萌新WA了求助!WA on Test 9
#include<bits/stdc++.h>
#define inf 100000000
#define N 2009
#define M 3009
using namespace std;
int ans[N],flag[N],vis[N];
int head[N],last[N],tot;
struct node {
int next,to,val;
} q[M<<1];
void add_edge(int u,int v,int val,int id) {
if(head[u] == 0) head[u] = id;
else q[last[u]].next = id;
last[u] = id , q[id].to = v , q[id].val = val;
}
int n,m,T;
bool spfa() {
queue<int> f;
f.push(1),flag[1] = 1;
while(!f.empty()) {
int u = f.front();
f.pop();
flag[u] = 0;
for(int i = head[u]; i != 0; i = q[i].next) {
int v = q[i].to;
if(flag[v] || ans[v] <= q[i].val + ans[u]) continue;
++vis[v] , ans[v] = q[i].val + ans[u] , flag[v] = 1 , f.push(v);
if(vis[v] > n) return true;
}
}
return false;
}
int main() {
scanf("%d",&T);
while(T--) {
int U,V,VAL;
scanf("%d%d",&n,&m),tot=0;
for(int i = 1; i <= m*2; i++) q[i].next = q[i].to = q[i].val = 0;
for(int i = 1; i <= n; i++) head[i] = last[i] = 0;
for(int i = 1; i <= m; i++) {
scanf("%d%d%d",&U,&V,&VAL);
if(VAL>=0) add_edge(U,V,VAL,tot+1),add_edge(V,U,VAL,tot+2),tot+=2;
else add_edge(U,V,VAL,tot+1),tot++;
}
for(int i = 1; i <= n; i++) ans[i] = inf , vis[i] = flag[i] = 0;
ans[1] = 0;
if(spfa()) printf("YES\n");
else printf("NO\n");
}
return 0;
}