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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include<bits/stdc++.h> using namespace std; #define MAX 1e9 #define ll long long struct edge { int to; int nextE; ll w; }; int head[2010]; int num_edge[2010]; int cnt=0; edge e[6010]; ll dis[2010]; int spfa(int n, int s) { bool vis[n + 1]; for (int i = 0; i <= n; i++) { vis[i]=false; num_edge[i]=0; dis[i] = MAX; }
dis[s] = 0; vis[s]=true; queue<int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = false; for (int i = head[u]; i; i = e[i].nextE) { int v = e[i].to; ll w = e[i].w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; num_edge[v] = num_edge[u] + 1; if (num_edge[v] >= n) return -1; if (!vis[v]) { q.push(v); vis[v] = true; } } } } return 1; } int main() { int t; cin>>t; while(t--) { int n,m; cin>>n>>m; cnt=0; for(int i=0; i<=n; i++) head[i]=0; for(int i=0; i<=m; i++) e[i].w=MAX; for(int i=0; i<m; i++) { int u,v,w; cin>>u>>v>>w; e[++cnt].to=v; e[cnt].w=w; e[cnt].nextE=head[u]; head[u]=cnt; } bool flag=false; for(int i=n; i>=1; i--) { if(spfa(n,i)==-1) { cout<<"boo how\n"; flag=true; break; } } if(!flag) { for(int i=1; i<=n; i++) cout<<dis[i]<<" "; cout<<"\n"; } } return 0; }
|