#include <cstdlib> #include <iostream> #define LENGTH 100 #define Maxint 1000000 using namespace std; int main(int argc, char *argv[]) { //图G的点数N和边数M int N,M,i,j; //边的起点和终点 int E[LENGTH][2]; //边的权值 int Value[LENGTH]; //分别是当前选边的权值‘选边的编号和树的长度 // int Min,MinE,ValueT; //读入图G,图G采用边目录表示法 cin>>N>>M; int c[LENGTH][LENGTH]; for( i = 0; i <= N; i++) for(j = 0; j <= N; j++) c[i][j] = Maxint; //初始化 for (i=0;i<M;i++) { cin>>E[i][0]>>E[i][1]>>Value[i]; c[E[i][0]][E[i][1]] = Value[i]; } // for( i = 0; i <= N; i++) // for(j = 0; j <= N; j++) // cout << c[i][j] << endl; int dist[LENGTH]; int prev[LENGTH]; bool s[Maxint]; int v = 1; for(i = 1; i <= N; i++) { dist[i] = c[v][i]; s[i] = false; if(dist[i] == Maxint) prev[i] = 0; else prev[i] = v; } dist[v] = 0; s[v] = true; for(i = 1; i < N; i++) { int temp = Maxint; int u = v; for(j = 1; j <= N; j++) if((!s[j])&&(dist[j] < temp)) {u = j; temp = dist[j];} s[u] = true; for(j = 1; j <= N; j++) if((!s[j]) && (c[u][j] < Maxint)) { int newdist = dist[u] + c[u][j]; if(newdist < dist[j]) { dist[j] = newdist; prev[j] = u; } } } cout << "The shortest path: " <<endl; for(i = 1; i <= N; i++) { if(i != 1) cout << "1 -> " << i <<": " << dist[i] << endl; } system("PAUSE"); return EXIT_SUCCESS; }