1 #include <iostream> 2 3 using namespace std; 4 5 #define MAX_VERTEXT 250 6 const int MAX_WEIGHT= 0x7f7f7f7f; 7 8 int map[MAX_VERTEXT][MAX_VERTEXT]; 9 int path[MAX_VERTEXT]; 10 11 void Init() 12 { 13 memset(map,MAX_WEIGHT,sizeof(map)); 14 memset(path,MAX_WEIGHT,sizeof(path)); 15 } 16 17 void Input(int m) 18 { 19 int start,end,weight; 20 for (int i=0;i<m;i++) 21 { 22 cin>>start>>end>>weight; 23 //这里太BT了。。。 24 if (weight<map[start][end]) 25 map[start][end]=map[end][start] 26 =weight; 27 if(start==end) 28 map[start][end]=0; 29 } 30 } 31 32 template<typename T> 33 T min(const T& x,const T& y) 34 { 35 return x<y ? x:y; 36 } 37 38 int Dijkstra(int n,int s,int e) 39 { 40 int i,j,k; 41 int v[MAX_VERTEXT]={0}; 42 for (path[s]=0,i=0;i<n;i++) 43 { 44 //把顶点分成两个集合S,U(U为剩余顶点集) 45 //一开始S中只有s顶点(开始点) 46 //从剩余的顶点中挑选路径最短的加入S 47 for(k=-1,j=0;j<n;j++) 48 if(!v[j]&&(k==-1||path[j]<path[k])) 49 k=j; 50 51 for(v[k]=1,j=0;j<n;j++) 52 if(!v[j]&&(map[k][j]!=MAX_WEIGHT)) 53 path[j]=::min(path[k]+map[k][j],path[j]); 54 } 55 if(path[e]>=MAX_WEIGHT) 56 return -1; 57 else 58 return path[e]; 59 } 60 61 int main() 62 { 63 int N,M,start,end; 64 while(cin>>N>>M) 65 { 66 Init(); 67 Input(M); 68 cin>>start>>end; 69 if(start==end) 70 cout<<"0"<<endl; 71 else 72 cout<<Dijkstra(N,start,end)<<endl; 73 } 74 return 0; 75 }
相关文章: