hdu 2066 一个人的旅行 最短路
这题简单的最短路,一开始我还傻傻地去用bfs写,WA了几次后,发现用错方法了,用bfs求最短路,是对每条边权值都相同的图才可以的,后来改用单源最短路径, 这题数据规模比较大(a,b去到1000)不能用floyd算法。
#include <iostream> #include <cstring> using namespace std; const int MAX = 1005; const int INF = 1000000000; int arcs[MAX][MAX]; int S,T,D; int start_place[MAX]; int size; bool isfound[MAX]; int cost[MAX]; int goal_place[MAX]; int shortest(int v) { memset(isfound, false, sizeof(isfound)); for (int i = 1; i <= size; i++) cost[i] = arcs[v][i]; isfound[v] = true; int index; int _min; for (int i = 1; i < size; i++) { _min = INF; for (int j = 1; j <= size; j++) if (!isfound[j] && _min > cost[j]) _min = cost[index = j]; if (_min == INF) break; isfound[index] = true; for (int j = 1; j <= size; j++) if (!isfound[j] && cost[j] > cost[index] + arcs[index][j]) cost[j] = cost[index] + arcs[index][j]; } _min = INF; for (int i = 0; i < D; i++) _min = min(_min, cost[goal_place[i]]); return _min; } int main() { int a, b, c; int num; int ans; while (cin >> T >> S >> D) { for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) arcs[i][j] = INF; arcs[i][i] = 0; } for (int i = 0; i < T; i++) { cin >> a >> b >> c; arcs[a][b] = min(arcs[a][b], c); arcs[b][a] = arcs[a][b]; size = max(size,max(a,b)); } for (int i = 0; i < S; i++) cin >> start_place[i]; for (int i = 0; i < D; i++) cin >> goal_place[i]; ans = INF; for (int i = 0; i < S; i++) ans = min(ans, shortest(start_place[i])); cout << ans << endl; } return 0; }