一条最短路至多经过n-1条边 设cnt[s] = 0
每次松弛时,同样修改cnt[v] = cnt[u] + 1
因为有return操作 所以必须每次都清空队列
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 500000 + 10;
const int MAXM = 500000 + 10;
int n,m,last[MAXN],tot,dist[MAXN],s,vis[MAXN],cnt[MAXN],T;
bool flg;
queue<int> q;
struct Edge{
int u,v,w,to;
Edge(){}
Edge(int u, int v, int w, int to) : u(u), v(v), w(w), to(to) {}
}e[MAXM];
inline void add(int u, int v, int w) {
e[++tot] = Edge(u,v,w,last[u]);
last[u] = tot;
}
bool SPFA(int s) {
dist[s] = 0;
q.push(s);
vis[s] = 1;
cnt[s] = 0;
while(!q.empty()) {
int x = q.front();
q.pop();
vis[x] = 0;
for(int i=last[x]; i; i=e[i].to) {
int v = e[i].v;
int w = e[i].w;
if(dist[v] > dist[x] + w) {
dist[v] = dist[x] + w;
cnt[v] = cnt[x] + 1;
if(cnt[v] >= n) {
return 1;
}
if(!vis[v]) q.push(v), vis[v] = 1;
}
}
}
return 0;
}
int main() {
scanf("%d", &T);
while(T--) {
memset(dist, 0x3f, sizeof(dist));
memset(vis,0,sizeof(vis));
memset(last,0,sizeof(last));
while(!q.empty())
q.pop();
tot = 0;
scanf("%d %d",&n, &m);
for(int i=1; i<=m; i++) {
int u,v,w;
scanf("%d %d %d",&u, &v, &w);
if(w < 0)
add(u,v,w);
else
add(u,v,w), add(v,u,w);
}
if(SPFA(1)) printf("YE5\n");
else printf("N0\n");
}
return 0;
}