题目:负环
思路:
注意初始化。
吸氧可过,不吸氧TLE一个点。
代码:
#include<bits/stdc++.h>
using namespace std;
#define maxn 2000
#define read(x) scanf("%d",&x)
struct Edge {
int x,y,z;
Edge() {}
Edge(int xx,int yy,int zz) {
x=xx,y=yy,z=zz;
}
};
int n,m;
vector<Edge> a[maxn+5];
queue<int> que;
int cnt[maxn+5],dist[maxn+5];
bool inque[maxn+5];
bool spfa() {
queue<int> emp;
que=emp;
for(int i=1; i<=n; i++) {
que.push(i);
inque[i]=true;
dist[i]=0;
cnt[i]=0;
}
while(!que.empty()) {
int h=que.front();
que.pop();
inque[h]=false;
for(int i=0; i<a[h].size(); i++) {
int x=a[h][i].y;
if(dist[x]>dist[h]+a[h][i].z) {
dist[x]=dist[h]+a[h][i].z;
if(inque[x]) continue;
inque[x]=true;
que.push(x);
cnt[x]++;
if(cnt[x]>n) return true;
}
}
}
return false;
}
int main() {
int T;
read(T);
while(T--) {
read(n),read(m);
for(int i=1;i<=n;i++) a[i].clear();
for(int i=1; i<=m; i++) {
int x,y,z;
read(x),read(y),read(z);
if(z>=0) a[x].push_back(Edge(x,y,z)),a[y].push_back(Edge(y,x,z));
else a[x].push_back(Edge(x,y,z));
}
if(spfa()) printf("YE5\n");
else printf("N0\n");
}
return 0;
}