跳到正文

剪贴板

剪贴板 pfy5pceq

原文
剪贴板信息

剪贴板信息

收录
更新

用来传代码用的

spfa判负环模板

C++
#include<bits/stdc++.h>
#define int long long
#define endl '\n'

using namespace std;
const int N=1010,M=1010;
int d[N],pre[N],k,cnt[N];
bool f[N];
int n,m,s;
queue<int> q;

struct node{
	int next,to,len;
}a[M];

void add(int u,int v,int l){
	k++;
	a[k].to=v;
	a[k].next=pre[u];
	a[k].len=l;
	pre[u]=k;
}

bool check(){
	for(int i=1;i<=n;i++){
		q.push(i);
		f[i]=true;
	}
//	memset(d,0x3f,sizeof d);
	while(!q.empty()){
		int h=q.front();
		q.pop();
		f[h]=false;
		for(int i=pre[h];i;i=a[i].next){
			int to=a[i].to;
			if(d[h]+a[i].len<d[to]){
				d[to]=d[h]+a[i].len;
				cnt[to]=cnt[h]+1;
				if(cnt[to]==n){
					return true;
				}
				if(!f[to]){
					q.push(to);
					f[to]=true;
				}
			}
		}
	}
	return false;
}

void spfa(){
	while(!q.empty()) q.pop();
	memset(d,0x3f,sizeof d);
	memset(f,false,sizeof f);
	d[s]=0;
	q.push(s);
	f[s]=true;
	while(!q.empty()){
		int h=q.front();
		q.pop();
		f[h]=false;
		for(int i=pre[h];i;i=a[i].next){
			int to=a[i].to;
			if(d[h]+a[i].len<d[to]){
				d[to]=d[h]+a[i].len;
				if(!f[to]){
					q.push(to);
					f[to]=true;
				}
			}
		}
	}
	for(int i=1;i<=n;i++){
		if(d[i]==0x3f3f3f3f3f3f3f3f){
			cout<<"NoPath";
		}else{
			cout<<d[i];
		}
		cout<<'\n';
	}
	return ;
}

signed main(){
	cin>>n>>m>>s;
	for(int i=1,a,b,c;i<=m;i++){
		cin>>a>>b>>c;
		add(a,b,c);
	}
	if(check()){
		cout<<-1;
		return 0;
	}
	spfa();
	return 0;
}
C++
inline int read(){
	int tot=0,f=1;
	char ch=getchar();
	while(ch>'9' || ch<'0'){
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while(ch>='0' && ch<='9'){
		tot=tot*10+ch-'0';
		ch=getchar();
	}
	return tot*f;
}

inline void write(int x){
	if(x>9) write(x/10);
	putchar(x%10+'0');
	return;
}