蒟蒻代码求调,SPFA,链式前向星存图仅AC后两点,其余全T
查看原帖
蒟蒻代码求调,SPFA,链式前向星存图仅AC后两点,其余全T
901562
ysq20110325楼主2023/7/13 13:16
#include<bits/stdc++.h>
using namespace std;
struct Edge{
	int next,to,w;
}edge[13111];
int t,tot,head[13111],n,m,cnt[13111],vis[13111],dis[13111];
void add(int x,int y,int z){
	tot++;
	edge[tot].to=y;
	edge[tot].w=z;
	edge[tot].next=head[x];
	head[x]=tot;
	return;
}
queue<int> q;
bool spfa(){
	while(q.size()){
		int x=q.front();
		q.pop();
		vis[x]=0;
		for(int i=head[x];i;i=edge[i].next){
			int y=edge[i].to;
			int z=edge[i].w;
			if(dis[y]>dis[x]+z){
				dis[y]=dis[x]+z;
				cnt[y]=cnt[x]+1;
				if(cnt[y]>=n){
					cout<<"YES"<<endl;
					return 0;
				}
				if(!vis[y]){
					vis[y]=1;
					q.push(y);
				} 
			}
		}
	}
	return 1;
}
int main(){
	cin.tie(0);
	cout.tie(0);
	cin>>t;
	while(t--){
		memset(dis,0x3f,sizeof dis);
		memset(vis,0,sizeof vis);
		memset(cnt,0,sizeof cnt);
//		memset(edge,0,sizeof edge);
		cin>>n>>m;
		while(q.size())q.pop();
		tot=0;
		for(int i=1;i<=m;i++){
			int x,y,z;
			cin>>x>>y>>z;
			add(x,y,z);
			if(z>=0)add(y,x,z);
		}
		dis[1]=0;
		vis[1]=1;
		q.push(1);
		if(spfa())cout<<"NO\n";
	} 
	return 0;
}


2023/7/13 13:16
加载中...