蒟蒻求助
查看原帖
蒟蒻求助
1198194
zlqwq楼主2024/10/4 20:00

20pts20pts,求大佬调代码

#include<bits/stdc++.h>
#define int long long

using namespace std;
int t,n,m;
const int N=2e5+5;
vector<pair<int,int> > ed[N];
int dis[N],vis[N],cnt[N];
int read() {
    static int x,c,f; x=0,f=1;
    do c=getchar(),(c=='-'&&(f=-1)); while(!isdigit(c));
    do x=x*10+(c&15),c=getchar(); while(isdigit(c));
    return x*f;
} 
queue<int> q;
bool spfa(){
	q.push(1);
	dis[1]=0;
	while(q.size()){
		int f=q.front();
		q.pop();
		vis[f]=0;
		for(auto v:ed[f]){
			int to=v.first;
			int w=v.second;
			if(dis[to]>dis[f]+w){
				dis[to]=dis[f]+w;
				if(vis[to])continue;
				cnt[to]=cnt[f]+1;
				if(cnt[to]>n)return 1;
				vis[to]=1;
				q.push(to);
			}
		}
	}
	return 0;
}
int u,v,w;
signed main() {
	ios::sync_with_stdio(0);
	t=read();
	while(t--){
		n=read();
		m=read();
		memset(vis,0,sizeof(vis));
	    memset(cnt,0,sizeof(cnt));
	    memset(dis,0x7f,sizeof(dis));
		for(int i=1;i<=m;++i){
			u=read();
			v=read();
			w=read();
			if(w>=0){
				ed[u].push_back({v,w});
				ed[v].push_back({u,w});	
			}
			else ed[u].push_back({v,w});
		}
		if(spfa())cout<<"YES\n";
		else cout<<"NO\n";
	}
	return 0;
}
2024/10/4 20:00
加载中...