SPFA
与djkstra比可判断负环,处理负权边
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10100;
const int maxm = 500500;
const int inf = 0x3f3f3f3f;
struct edge{
int to,next,w;
}e[maxm];
int using_v[maxn],using_times[maxn];
int head[maxn],dis[maxn];
int cnt=0;
int n,m;
void addedge(int u,int v,int w){
e[++cnt].to = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
}
int spfa(int start){
queue<int>q;
dis[start] = 0;
using_v[start] = 1;
q.push(start);
while(!q.empty()){
int top=q.front();
q.pop();
using_v[top] = 0;
using_times[top]++;
if(using_times[top]>n) return 0;
for(int i = head[top];i;i=e[i].next){
if(dis[e[i].to]>dis[top]+e[i].w){
dis[e[i].to] = dis[top]+e[i].w;
if(!using_v[e[i].to]){
using_v[e[i].to] = 1;
q.push(e[i].to);
}
}
}
}
return 1;
}
int main()
{
int u,v,w,s;
cin >> n >> m >> s;
memset(dis,inf,sizeof(dis));
for(int i = 0;i < m;i++){
cin >> u >> v >> w;
addedge(u,v,w);
}
spfa(s);
for(int i = 1;i <= n;i++){
if(dis[i] != inf)
cout << dis[i] << " ";
else
cout << "inf" << " ";
}
return 0;
}