/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <climits>
#include <iostream>
#define INF 0x3f3f3f3f
using namespace std;
/****************************************/
const int N = 10;
int n, m, tot, head[N], dis[N], fa[N];
bool inq[N];
struct Node
{
int u, v, w, next;
}edge[N*N];
void init()
{
memset(head, -1, sizeof(head));
tot = 0;
}
void add(int u, int v, int w)
{
edge[tot].u = u;
edge[tot].v = v;
edge[tot].w = w;
edge[tot].next = head[u];
head[u] = tot++;
}
void spfa(int st)
{
memset(dis, 0x3f, sizeof(dis));
memset(inq, 0, sizeof(inq));
queue <int> q;
q.push(st);
dis[st] = 0;
inq[st] = true;
while(!q.empty()) {
int u = q.front();
q.pop();
inq[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].v;
if(dis[v] > dis[u] + edge[i].w) {
dis[v] = dis[u] + edge[i].w;
fa[v] = u;
if(!inq[v]) {
q.push(v);
inq[v] = true;
}
}
}
}
}
int main()
{
#ifdef J_Sure
freopen("000.in", "r", stdin);
// freopen(".out", "w", stdout);
#endif
scanf("%d", &n);
init();
int a, b, c;
while(~scanf("%d%d%d", &a, &b, &c)) {
if(a == -1&&b == -1 && c == -1) break;
add(a, b, c);
}
spfa(0);
int dir[N];
for(int j = 1; j < n; j++) {
printf("%d\t", dis[j]);
int cnt = 0, x = j;
while(x != fa[x]) {
dir[cnt++] = x;
x = fa[x];
}
dir[cnt] = 0;
for(int k = cnt; k > 0; k--) {
printf("%d->", dir[k]);
}
printf("%d\n", dir[0]);
}
return 0;
}
SPFA模板
最新推荐文章于 2020-01-21 09:58:41 发布