标签:hdu2066
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18484 Accepted Submission(s): 6429
6 2 3 1 3 5 1 4 7 2 8 12 3 8 4 4 9 12 9 10 2 1 2 8 9 10
9
Dijkstra 31ms
//Dijkstra #include <stdio.h> #include <string.h> #define INF -1 #define maxn 1002 int map[maxn][maxn]; int dist[maxn]; bool vis[maxn], exis[maxn]; int getNext(int n) { int u = -1, tmp = 100000000; for(int i = 0; i <= n; ++i) if(!vis[i] && exis[i] && dist[i] != INF && dist[i] < tmp){ tmp = dist[i]; u = i; } return u; } void Dijkstra(int v, int n) { int i, tmp; dist[v] = 0; while(v != -1){ for(i = 1; i <= n; ++i){ if(map[v][i] != -1){ tmp = dist[v] + map[v][i]; if(dist[i] == INF || tmp < dist[i]) dist[i] = tmp; } } vis[v] = 1; v = getNext(n); } } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int t, s, d, a, b, c, i, ans; while(scanf("%d%d%d", &t, &s, &d) != EOF){ memset(map, -1, sizeof(map)); memset(dist, -1, sizeof(dist)); memset(vis, 0, sizeof(vis)); memset(exis, 0, sizeof(exis)); for(i = 0; i <= 1000; ++i) map[i][i] = 0; for(i = 0; i < t; ++i){ scanf("%d%d%d", &a, &b, &c); if(map[a][b] == INF || c < map[a][b]) map[a][b] = map[b][a] = c; exis[a] = exis[b] = 1; } for(i = 0; i < s; ++i){ scanf("%d", &a); map[0][a] = map[a][0] = 0; } Dijkstra(0, 1000); ans = 100000000; while(d--){ scanf("%d", &a); if(dist[a] != INF && dist[a] < ans) ans = dist[a]; } printf("%d\n", ans); } return 0; }
Floyd 593ms 需要适当的剪枝,第14行若不剪会超时
//Floyd #include <stdio.h> #include <string.h> #define maxn 1002 #define INF -1 int map[maxn][maxn]; void Floyd(int n) { int i, j, k; for(k = 0; k <= n; ++k) for(i = 0; i <= n; ++i) for(j = 0; j <= n && map[i][k] != -1; ++j) if(map[i][k] != -1 && map[k][j] != -1 && (map[i][k] + map[k][j] < map[i][j] || map[i][j] == -1)) map[i][j] = map[i][k] + map[k][j]; } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int t, s, d, a, b, c, i, ans; while(scanf("%d%d%d", &t, &s, &d) != EOF){ memset(map, -1, sizeof(map)); for(i = 0; i <= 1000; ++i) map[i][i] = 0; for(i = 0; i < t; ++i){ scanf("%d%d%d", &a, &b, &c); if(map[a][b] == -1 || c < map[a][b]) map[a][b] = map[b][a] = c; } for(i = 0; i < s; ++i){ scanf("%d", &a); map[0][a] = map[a][0] = 0; } Floyd(1000); ans = 100000000; for(i = 0; i < d; ++i){ scanf("%d", &a); if(map[0][a] != -1 && map[0][a] < ans) ans = map[0][a]; } printf("%d\n", ans); } return 0; }
HDU2066 一个人的旅行 【Dijkstra】【Floyd】,布布扣,bubuko.com
HDU2066 一个人的旅行 【Dijkstra】【Floyd】
标签:hdu2066
原文地址:http://blog.csdn.net/chang_mu/article/details/38232855