算法思路:Dijkstra算法,简单的模板题。
刚开始没有吧w数组初始化,WA了三次,改过来之后成功AC。
//模板开始
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include<iomanip>
#include<string.h>
#define SZ(x) (int(x.size()))
using namespace std;
int toInt(string s){
istringstream sin(s);
int t;
sin>>t;
return t;
}
template<class T> string toString(T x){
ostringstream sout;
sout<<x;
return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
istringstream sin(s);
int64 t;
sin>>t;
return t;
}
template<class T> T gcd(T a, T b){
if(a<0)
return gcd(-a, b);
if(b<0)
return gcd(a, -b);
return (b == 0)? a : gcd(b, a % b);
}
//模板结束(通用部分)
#define ifs cin
#define MAX_LEN 105
int w[MAX_LEN][MAX_LEN];
int n, m;
int a, b, c;
int v[MAX_LEN];
int d[MAX_LEN];
#define INF 1<<30
//【图论01】最短路 1001 最短路
int main()
{
//ifstream ifs("shuju.txt", ios::in);
while(ifs>>n>>m && !(n == 0 && m == 0))
{
for(int i = 0; i < MAX_LEN; i++)
{
for(int j = 0; j < MAX_LEN; j++)
{
w[i][j] = INF;
}
}
for(int i = 0; i < m; i++)
{
ifs>>a>>b>>c;
w[a][b] = c;
w[b][a] = c;
}
memset(v, 0, sizeof(v));
for(int i = 1; i <= n; i++)
{
if(i == 1)
{
d[i] = 0;
}
else
{
d[i] = INF;
}
}
for(int i = 0; i < n; i++) //计数
{
int x, m = INF;
for(int y = 1; y <= n; y++)
{
if(!v[y] && d[y] <= m)
{
m = d[x = y];
}
}
v[x] = 1;
for(int y = 1; y <= n; y++)
{
if(d[y] > d[x] + w[x][y])
{
d[y] = d[x] + w[x][y];
}
}
}
cout<<d[n]<<endl;
}
return 0;
}
另转载一位大牛的博客,
Title:“Dijkstra分析与实现”
链接地址:http://www.wutianqi.com/?p=1890