Holy Grail Bellman-Ford/spfa
Bellman-Ford
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 305, maxm = 505; 4 const int inf = 0x3f3f3f3f; 5 struct edge { 6 int v, w; 7 }; 8 vector<edge> maps[maxn]; 9 int dis[maxn], n, m; 10 11 bool BellmanFord(int s) { // s为源点 12 fill(dis, dis+n, inf); 13 dis[s] = 0; 14 for (int i = 0; i < n-1; i++) { 15 for (int u = 0; u < n; u++) { 16 for (int j = 0; j < maps[u].size(); j++) { 17 int v = maps[u][j].v; 18 int w = maps[u][j].w; 19 if (dis[u] + w < dis[v]) { 20 dis[v] = dis[u] + w; 21 } 22 } 23 } 24 } 25 for (int u = 0; u < n; u++) { 26 for (int j = 0; j < maps[u].size(); j++) { 27 int v = maps[u][j].v; 28 int w = maps[u][j].w; 29 if (dis[u] + w < dis[v]) 30 return false; 31 } 32 } 33 return true; 34 } 35 int main() { 36 int t; scanf("%d",&t); 37 while (t--) { 38 scanf("%d%d",&n,&m); 39 for (int i = 0; i < n; i++) maps[i].clear(); 40 41 for (int i = 1; i <= m; i++) { 42 int u, v, w; scanf("%d%d%d",&u,&v,&w); 43 maps[u].push_back(edge{v,w}); 44 } 45 for (int i = 1; i <= 6; i++) { 46 int u, v; scanf("%d%d",&u,&v); 47 bool flag = BellmanFord(v); 48 printf("%d\n",-dis[u]); 49 50 //if (flag == false) continue; 51 maps[u].push_back(edge{v,-dis[u]}); 52 } 53 } 54 }
spfa
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 305, maxm = 505; 4 struct edge { 5 int v, w; 6 }; 7 vector<edge> maps[maxn]; 8 int dis[maxn], n, m; 9 bool vis[maxn]; 10 11 void add(int u, int v, int w) { 12 maps[u].push_back(edge{v,w}); 13 } 14 void spfa(int s) { 15 memset(dis, 0x3f3f3f3f, sizeof(dis)); 16 memset(vis,0,sizeof(vis)); 17 queue<int> que; 18 que.push(s), dis[s] = 0, vis[s] = true; 19 while(!que.empty()) { 20 int u = que.front(); 21 que.pop(); 22 vis[u] = false; 23 for(int i = 0; i < maps[u].size(); i++) { 24 int v = maps[u][i].v; 25 int w = maps[u][i].w; 26 if(dis[v] > dis[u]+w) { 27 dis[v] = dis[u] + w; 28 if(vis[v] == false) { 29 que.push(v); 30 vis[v] = true; 31 } 32 } 33 } 34 } 35 } 36 int main() { 37 int t; scanf("%d",&t); 38 while(t--) { 39 scanf("%d%d",&n,&m); 40 for (int i = 0; i < n; i++) maps[i].clear(); 41 for(int i = 1; i <= m; i++) { 42 int u, v, w; scanf("%d%d%d",&u,&v,&w); 43 add(u,v,w); 44 } 45 for(int i = 1; i <= 6; i++) { 46 int u, v; scanf("%d%d",&u,&v); 47 spfa(v); 48 add(u,v,-dis[u]); 49 printf("%d\n",-dis[u]); 50 } 51 } 52 return 0; 53 }