//spfa algorithm template (adjacency matrix): //c++ code: void spfa(int s){ for(int i=0; i<=n; i++) dis[i]=99999999; //Initialize the distance from each point i to s dis[s]=0; vis[s]=1; q[1]=s; Queue initialization, s is the starting point int i, v, head=0, tail=1; while (head<tail){ queue is not empty head++; v=q[head]; take the first element of the queue vis[v]=0; Release the first node of the team, because this node may be used to relax other nodes next time and re-enter the team for(i=0; i<=n; i++) for all vertices if (a[v][i]>0 && dis[i]>dis[v]+a[v][i]){ dis[i] = dis[v]+a[v][i]; modify the shortest path if (vis[i]==0){ If the extension node i is not in the queue, enter the queue tail++; q[tail]=i; show [i] = 1; } } } }
Reprinted from https://blog.csdn.net/xunalove/article/details/70045815
The above is the spfa algorithm of BFS, which may time out
DFS spfa
#include <iostream> using namespace std; int q[10001], dis[201], a[201][201], b[201][201]; bool fish [201]; int n, m, s, t; bool flag=false; void spfa(int s){ if(flag) return; if(vis[s])//If there is an edge that has experienced twice, there is a negative cycle { flag=true; return; } else vis [s] = 1; for(int i=1; i<=b[s][0]; i++) if (dis[b[s][i]] > dis[s]+a[s][b[s][i]]){ dis[b[s][i]] = dis[s]+a[s][b[s][i]]; spfa(b[s][i]); if(flag) return; } } int main(){ int x, y, z,w; int t; cin>>t; while(t--){ flag=false; cin >> n >> m>> w; for(int i=0; i<m; i++){ cin >> x >> y >> z; //if (a[x][y]!=0 && z>a[x][y]) continue; b[x][0]++; b[x][b[x][0]]=y; a[x][y]=z; b[y][0]++; b[y][b[y][0]]=x; a[y][x]=z; } for(int i=0;i<w;i++) { cin >> x >> y >> z; //if (a[x][y]!=0 && z>a[x][y]) continue; b[x][0]++; b[x][b[x][0]]=y; a[x][y]=-z;//b[x][0] means from vertex x How many edges are there from the start b[x][b[x][0]]=y stores the end point of the b[x][0]th edge starting from x b[y][0]++; b[y][b[y][0]]=x; a[y][x]=-z; } for(int i=0; i<=n; i++) dis[i]=99999999; dis[1]=0; spfa(s); if (flag) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }