解题思路:最短路的模板题,注意一个细节处理即可。
见代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 #define inf 0x3f3f3f3f 6 const int maxn = 1005; 7 int vis[maxn], w[maxn][maxn], d[maxn], t, n; 8 9 void Dijkstra() 10 { 11 for(int i = 1; i <= n; i++) d[i] = w[i][n]; 12 for(int i = 1; i <= n; i++) 13 { 14 int k = -1; 15 int min1 = inf; 16 for(int j = 1; j <= n; j++) 17 { 18 if(vis[j]) continue; 19 if(d[j] < min1) 20 { 21 min1 = d[j]; 22 k = j; 23 } 24 } 25 if(k == -1) break; 26 vis[k] = 1; 27 for(int j = 1; j <= n; j++) 28 { 29 30 if(vis[j]) continue; 31 if(d[j] > d[k] + w[k][j] && w[k][j] < inf) 32 { 33 d[j] = d[k] + w[k][j]; 34 } 35 } 36 } 37 return ; 38 } 39 40 int main() 41 { 42 int x, y, len; 43 while(~scanf("%d %d", &t, &n)) 44 { 45 for(int i = 1; i <= n; i++) 46 for(int j = 1; j <= n; j++) 47 { 48 if(i == j) w[i][j] = 0; 49 else w[i][j] = w[j][i] = inf; 50 } 51 memset(vis, 0, sizeof(vis)); 52 //for(int i = 1; i <= n; i++) d[i] = inf; 53 //d[n] = 0; 54 while(t-- ) 55 { 56 scanf("%d %d %d", &x, &y, &len); 57 //w[x][y] = w[y][x] = len; 刚开始没有进行if判断 58 if(w[x][y] > len) w[y][x] = w[x][y] = len; 59 } 60 Dijkstra(); 61 printf("%d ", d[1]); 62 } 63 return 0; 64 }