差分约束

#include<bits/stdc++.h>
#define ll long long
#define db double
#define filein(a) freopen(#a".in","r",stdin)
#define fileot(a) freopen(#a".out","w",stdout)
#define sky fflush(stdout);
#define gc getchar
#define pc putchar
namespace IO{
	inline bool blank(const char &c){
		return c==' ' or c=='\n' or c=='\t' or c=='\r' or c==EOF;
	}
	inline void gs(char *s){
		char ch=gc();
		while(blank(ch) ) {ch=gc();}
		while(!blank(ch) ) {*s++=ch;ch=gc();}
		*s=0;
	}
	inline void gs(std::string &s){
		char ch=gc();s+='#';
		while(blank(ch) ) {ch=gc();}
		while(!blank(ch) ) {s+=ch;ch=gc();}
	}
	inline void ps(char *s){
		while(*s!=0) pc(*s++);
	}
	inline void ps(const std::string &s){
		for(auto it:s) 
			if(it!='#') pc(it);
	}
	template<class T>
	inline void read(T &s){
		s=0;char ch=gc();bool f=0;
		while(ch<'0'||'9'<ch) {if(ch=='-') f=1;ch=gc();}
		while('0'<=ch&&ch<='9') {s=s*10+(ch^48);ch=gc();}
		if(ch=='.'){
			db p=0.1;ch=gc();
			while('0'<=ch&&ch<='9') {s=s+p*(ch^48);p*=0.1;ch=gc();}
		}
		s=f?-s:s;
	}
	template<class T,class ...A>
	inline void read(T &s,A &...a){
		read(s);read(a...);
	}
};
using IO::read;
using IO::gs;
using IO::ps;
const int N=5e3+3;
const int M=1e4+3;
const int inf=1e9;
int n,m;
int head[N],nxt[M];
struct Edge{
	int u,v,w;
}to[M];
int Etot=-1;
inline void link(int u,int v,int w){
	nxt[++Etot]=head[u];
	head[u]=Etot;
	to[Etot]={u,v,w};
}
int dis[N],cnt[N];
bool inq[N];
std::queue<int>q;
inline bool spfa(){
	for(int i=1;i<=n;++i){
		dis[i]=inf;
		cnt[i]=inq[i]=0;
	}
	inq[0]=1;dis[0]=0;
	q.push(0);
	while(!q.empty() ){
		int u=q.front();q.pop();
		inq[u]=0;
		for(int i=head[u];~i;i=nxt[i]){
			int v=to[i].v,w=to[i].w;
			if(dis[v]>dis[u]+w){
				dis[v]=dis[u]+w;
				cnt[v]=cnt[u]+1;
				if(cnt[v]>=n+1) return 1;
				if(!inq[v]) q.push(v);
			}
		}
	}
	return 0;
}
int main(){
	filein(a);fileot(a);
	read(n,m);
	memset(head,-1,sizeof(head) );
	for(int i=1;i<=m;++i){
		int u,v,w;
		read(u,v,w);
		link(v,u,w);
	}
	for(int i=1;i<=n;++i) link(0,i,0);
	if(spfa() ) printf("NO\n");
	else{
		for(int i=1;i<=n;++i){
			printf("%d ",dis[i]);
		}
	}
	return 0;
}

posted @   cbdsopa  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示