1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 505;
struct Node { int u, v, w; } node[MAXN];
int n, m, s, t; int dis[MAXN], pre[MAXN];
bool Bellman_Ford(int s, int t) { memset(dis, 0x3f, sizeof(dis)); dis[s] = 0; pre[s] = 0; for (int i = 1; i < n; i++) { for (int j = 1; j <= m; j++) { if (dis[node[j].u] + node[j].w < dis[node[j].v]) { dis[node[j].v] = dis[node[j].u] + node[j].w; pre[node[j].v] = node[j].u; } } } for (int i = 1; i <= m; i++) { if (dis[node[i].u] + node[i].w < dis[node[i].v]) { return false; } } return true; }
void print(int x) { if (pre[x] == 0) { printf("%d ", x); return; } print(pre[x]); printf("%d ", x); }
int main() { scanf("%d %d", &n, &m); for (int i = 1, ui, vi, wi; i <= m; i++) { scanf("%d %d %d", &ui, &vi, &wi); node[i].u = ui; node[i].v = vi; node[i].w = wi; pre[vi] = ui; } scanf("%d %d", &s, &t); if (Bellman_Ford(s, t)) { printf("%d\n", dis[t]); print(t); } else { printf("No Solution\n"); } return 0; }
|