20pt
查看原帖
20pt
317400
Foggy_night楼主2023/10/27 12:40
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
const int N = 10005;
struct Node{
	int to, weight, next;
}edge[N];
//vector<Node> G[N];
int dis[N];
int n, m, cnt[N], head[N];
bool vis[N], tot;
void add(int u, int v, int w){
	edge[++tot].to = v;
	edge[tot].weight = w;
	edge[tot].next = head[u];
	head[u] = tot;
}
bool SPFA(){
	queue<int> q;
	vis[1] = 1;
	dis[1] = 0;
	q.push(1);
	while(!q.empty()){
		int t = q.front(); q.pop();
		vis[t] = false;
		for(int i = head[t]; i; i = edge[i].next){
			int x = edge[i].to, w = edge[i].weight;
			if(dis[x] > dis[t] + w){
				dis[x] = dis[t] + w;
				//cnt[x] = cnt[t] + 1;
				if(++cnt[x] >= n)
					return true;
				if(!vis[x]){
					vis[x] = 1;
					q.push(x);
				}	
			}
		}
	}
	return false;
}
int main(){
	int t;
	scanf("%d", &t);
	while(t--){
		tot = 0;
		for(int i = 0; i < N; i++)
			edge[i].next = 0, head[i] = 0;
		memset(dis,0x7f,sizeof(dis));
		memset(vis,0,sizeof(vis));
		memset(cnt,0,sizeof(cnt));
		scanf("%d%d", &n, &m);
		for(int i = 1; i <= m; i++){
			int u, v, w;
			scanf("%d%d%d", &u, &v, &w);
			//G[u].push_back({v, w});
			add(u, v, w);
			if(w >= 0)
				add(v, u, w);//G[v].push_back({u, w});
		} 
		printf(SPFA()?"YES\n":"NO\n");
	}
	return 0;
}
2023/10/27 12:40
加载中...