题目大意:给一个地区的地图,上面有若干路口,每个路口因为红灯的缘故要耽误一些时间,给出起点和终点,找出最短路径使得耽误时间最短。
单源最短路问题,Dijkstra算法。同时还要打印路径。
1 #include <cstdio> 2 #include <vector> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 #define INF 1e9 7 typedef pair<int, int> ii; 8 typedef vector<ii> vii; 9 10 int p[20]; 11 12 void print_ans(int x) 13 { 14 if (p[x] != -1) print_ans(p[x]); 15 printf(" %d", x); 16 } 17 18 int main() 19 { 20 #ifdef LOCAL 21 freopen("in", "r", stdin); 22 #endif 23 int n, kase = 0; 24 while (scanf("%d", &n) && n) 25 { 26 vector<vii > AdjList(n+1); 27 for (int u = 1; u <= n; u++) 28 { 29 int k; 30 scanf("%d", &k); 31 int v, w; 32 for (int i = 0; i < k; i++) 33 { 34 scanf("%d%d", &v, &w); 35 AdjList[u].push_back(make_pair(v, w)); 36 } 37 } 38 int src, dest; 39 scanf("%d%d", &src, &dest); 40 memset(p, -1, sizeof p); 41 vector<int> dist(n+1, INF); 42 dist[src] = 0; 43 priority_queue<ii, vector<ii>, greater<ii> > pq; 44 pq.push(make_pair(dist[src], src)); 45 while (!pq.empty()) 46 { 47 ii top = pq.top(); 48 pq.pop(); 49 int d = top.first, u = top.second; 50 if (u == dest) break; 51 if (d == dist[u]) 52 for (int j = 0; j < AdjList[u].size(); j++) 53 { 54 int v = AdjList[u][j].first, w = AdjList[u][j].second; 55 if (dist[u] + w < dist[v]) 56 { 57 dist[v] = dist[u] + w; 58 pq.push(make_pair(dist[v], v)); 59 p[v] = u; 60 } 61 } 62 } 63 printf("Case %d: Path =", ++kase); 64 print_ans(dest); 65 printf("; %d second delay ", dist[dest]); 66 } 67 return 0; 68 }
看到书上说,由于节点数目较少,可以使用Bellman Ford算法,但是要打印路径,这个...Bellman Ford还没用过呢,打印路径...就免了吧,以后再说