城市交通路网
最短路 + 路径输出
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
//Mystery_Sky
//
#define M 1000100
#define INF 0x3f3f3f3f
struct Edge{
int to, next, w;
}edge[M];
int n, m;
int map[5000][5000];
int head[M], cnt, dis[M], vis[M];
inline void add_edge(int u, int v, int w)
{
edge[++cnt].to = v;
edge[cnt].next = head[u];
edge[cnt].w = w;
head[u] = cnt;
}
struct node {
int dis;
int pos;
inline bool operator <(const node &x) const{
return x.dis < dis;
}
};
priority_queue <node> q;
inline void dijkstra()
{
memset(dis, INF, sizeof(dis));
dis[1] = 0;
q.push((node){0, 1});
while(!q.empty()) {
node top = q.top();
q.pop();
int x = top.pos;
if(vis[x]) continue;
vis[x] = 1;
for(int i = head[x]; i; i = edge[i].next) {
int y = edge[i].to;
if(dis[y] > dis[x] + edge[i].w) {
dis[y] = dis[x] + edge[i].w;
if(!vis[y]) q.push((node){dis[y], y});
}
}
}
}
void print(int i) {
if(i == 1) return;
for(int k = 1; k <= n; k++) {
if(dis[k] + map[k][i] == dis[i]) {
print(k);
printf("%d ", k);
return;
}
}
}
int main() {
scanf("%d", &n);
int a;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) {
scanf("%d", &map[i][j]);
if(map[i][j]) add_edge(i, j, map[i][j]);
}
dijkstra();
printf("minlong=%d
", dis[n]);
print(n);
printf("%d
", n);
return 0;
}