题目大意:给一个地区的地图,上面有若干路口,每个路口因为红灯的缘故要耽误一些时间,给出起点和终点,找出最短路径使得耽误时间最短。
单源最短路问题,Dijkstra算法。同时还要打印路径。
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
#define INF 1e9
typedef pair<int, int> ii;
typedef vector<ii> vii; int p[]; void print_ans(int x)
{
if (p[x] != -) print_ans(p[x]);
printf(" %d", x);
} int main()
{
#ifdef LOCAL
freopen("in", "r", stdin);
#endif
int n, kase = ;
while (scanf("%d", &n) && n)
{
vector<vii > AdjList(n+);
for (int u = ; u <= n; u++)
{
int k;
scanf("%d", &k);
int v, w;
for (int i = ; i < k; i++)
{
scanf("%d%d", &v, &w);
AdjList[u].push_back(make_pair(v, w));
}
}
int src, dest;
scanf("%d%d", &src, &dest);
memset(p, -, sizeof p);
vector<int> dist(n+, INF);
dist[src] = ;
priority_queue<ii, vector<ii>, greater<ii> > pq;
pq.push(make_pair(dist[src], src));
while (!pq.empty())
{
ii top = pq.top();
pq.pop();
int d = top.first, u = top.second;
if (u == dest) break;
if (d == dist[u])
for (int j = ; j < AdjList[u].size(); j++)
{
int v = AdjList[u][j].first, w = AdjList[u][j].second;
if (dist[u] + w < dist[v])
{
dist[v] = dist[u] + w;
pq.push(make_pair(dist[v], v));
p[v] = u;
}
}
}
printf("Case %d: Path =", ++kase);
print_ans(dest);
printf("; %d second delay\n", dist[dest]);
}
return ;
}
看到书上说,由于节点数目较少,可以使用Bellman Ford算法,但是要打印路径,这个...Bellman Ford还没用过呢,打印路径...就免了吧,以后再说