标签:
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 35493 Accepted Submission(s): 12983
1 #include <cstdio> 2 #include <iostream> 3 using namespace std; 4 5 const int INF = 10000000; 6 7 int n, m; 8 int map[210][210]; 9 10 void Floyd(){ 11 int i, j, k; 12 for(k=0; k<n; k++) 13 for(i=0; i<n; i++) 14 for(j=0; j<n; j++) 15 if(map[i][j] > map[i][k] + map[k][j]) 16 map[i][j] = map[i][k] + map[k][j]; 17 } 18 19 int main(){ 20 while(~scanf("%d %d", &n, &m)){ 21 int i, j; 22 for(i=0; i<n; i++) 23 for(j=0; j<n; j++) 24 map[i][j] = (i==j?0:INF); 25 int u, v, w; 26 for(i=0; i<m; i++){ 27 scanf("%d %d %d", &u, &v, &w); 28 if(map[u][v] > w) 29 map[u][v]=map[v][u]=w; 30 } 31 int a, c; 32 scanf("%d %d", &a, &c); 33 Floyd(); 34 if(map[a][c] != INF) 35 printf("%d\n", map[a][c]); 36 else 37 printf("-1\n"); 38 } 39 return 0; 40 }
//Dijkstra算法 → → 贪心思想,
1 #include <cstdio> 2 #include <iostream> 3 4 using namespace std; 5 6 const int INF = 0x3f3f3f3f; 7 const int N = 210; 8 9 int n, m, s, t; //点, 边; 10 int map[N][N], vis[N], dis[N]; //关系; 11 12 void Dijkstra(int cra) 13 { 14 int i; 15 for(i=0; i<n; i++) 16 { 17 dis[i] = map[cra][i]; 18 vis[i] = 0; 19 } 20 dis[cra] = 0; 21 vis[cra] = 1; 22 int j, k, temp; 23 for(i=0; i<n; i++) 24 { 25 temp = INF; 26 for(j=0; j<n; j++) 27 { 28 if(!vis[j] && temp > dis[j]) 29 { 30 temp = dis[j]; 31 k = j; 32 } 33 } 34 if(temp == INF) 35 break; 36 vis[k] = 1; 37 for(j=0; j<n; j++) 38 if(!vis[j] && dis[j] > dis[k] + map[k][j]) 39 dis[j] = dis[k] + map[k][j]; 40 } 41 } 42 43 int main() 44 { 45 while(~scanf("%d %d", &n, &m)) 46 { 47 int i, j; 48 for(i=0; i<n; i++) 49 for(j=0; j<n; j++) 50 map[i][j] = INF; 51 int u, v, w; 52 for(i=0; i<m; i++) 53 { 54 scanf("%d %d %d", &u, &v, &w); 55 if(map[u][v] > w) 56 map[u][v]=map[v][u]= w; 57 } 58 scanf("%d %d", &s, &t); 59 Dijkstra(s); 60 if(dis[t] == INF) 61 printf("-1\n"); 62 else 63 printf("%d\n",dis[t]); 64 } 65 return 0; 66 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4684030.html