前面讲到了spfa,然后有一个判断负环的操作,这个判断负环有更好的思路。

\(cnt[i]\)\(s\)\(i\)的最短路中已经经过的路径条数,如果超过 \(n\) 个边,那就说明有 \(n-1\) 个点,必产生了负环,如果没有负环绝对是不会找到回路的。

洛谷P3385

emm直接给标程吧,就是最朴实无华的 \(spfa\) 负环判断。

标程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<bits/stdc++.h>
#define maxn 2005
using namespace std;
struct eee{
int next;
int to;
int w;
}edge[maxn<<2];
int root[maxn],dis[maxn],e_cnt[maxn],in_que[maxn],cnt;
int n,m;
void add(int x,int y,int w){
edge[++cnt].to=y;
edge[cnt].w=w;
edge[cnt].next=root[x];
root[x]=cnt;
}
void sync(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}

int spfa(int s){
memset(dis,0x3f,sizeof(dis));
memset(e_cnt,0,sizeof(e_cnt));
memset(in_que,0,sizeof(in_que));
queue<int>q;
dis[s]=0;
q.push(s);
e_cnt[s]=0;
while(q.size()){
int u=q.front();
q.pop();
in_que[u]=0;
for(int i=root[u];i;i=edge[i].next){
int v=edge[i].to,w=edge[i].w;
if(dis[v]>dis[u]+w){
dis[v]=dis[u]+w;
if(!in_que[v]){
q.push(v);
e_cnt[v]++;
if(e_cnt[v]>n){
return false;
}
in_que[v]=1;
}
}
}
}
return true;
}
int main(){
//freopen("P3385_9.in","r",stdin);
sync();
int t;
cin>>t;
while(t--){
cnt=0;
memset(root,0,sizeof(root));
memset(edge,0,sizeof(edge));
cin>>n>>m;
for(int i=1;i<=m;i++){
int x,y,w;
cin>>x>>y>>w;
add(x,y,w);
if(w>=0){
add(y,x,w);
}
}
if(!spfa(1)){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
return 0;
}