P3385 【模板】负环

题意:判断是否存在负环

思路:

bfs_spfa;就是判断一个节点的入队次数>=n,若是说明存在环

(个人觉得bfs跑不是很好,还是比较建议dfs跑)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 const int maxn=2005;
 5 int inf=0xfffffff;
 6 bool vis[maxn];
 7 int dis[maxn],cnt[maxn];
 8 int n,m,rot;
 9 struct node
10 {
11     int to,val;
12     node(){}
13     node(int xx,int yy):to(xx),val(yy){}
14 };
15 vector<node> v[maxn];
16 void init()
17 {
18     for(int i=1;i<=n;i++)
19     {
20         v[i].clear();
21         dis[i]=inf;
22         vis[i]=0;
23         cnt[i]=0;
24     }
25 }
26 int spfa()
27 {
28     queue<node>que;
29     que.push(node(1,0));
30     dis[1]=0;
31     cnt[1]=1;
32     vis[1]=1;
33     while(!que.empty())
34     {
35         node t=que.front();
36         que.pop();
37         vis[t.to]=0;
38         for(int i=0;i<v[t.to].size();i++)
39         {
40             node p=v[t.to][i];
41             if(dis[p.to]>dis[t.to]+p.val)
42             {
43                 dis[p.to]=dis[t.to]+p.val;
44                 if(!vis[p.to]){
45                     cnt[p.to]++;
46                     vis[p.to]=1;
47                     que.push(node(p.to,dis[p.to]));
48                     if(cnt[p.to]>=n){
49                         return 1;
50                     }
51                 }
52             }
53         }
54     }
55     return 0;
56 }
57 int main()
58 {
59     int t;
60     scanf("%d",&t);
61     while(t--)
62     {
63         scanf("%d%d",&n,&m);
64         init();
65         for(int i=1;i<=m;i++)
66         {
67             int a,b,c;
68             scanf("%d%d%d",&a,&b,&c);
69             v[a].push_back(node(b,c));
70             if(c>=0){
71                 v[b].push_back(node(a,c));
72             }
73         }
74         if(spfa()){
75             cout<<"YE5"<<endl;
76         }
77         else{
78             cout<<"N0"<<endl;
79         }
80     }
81     return 0;
82 }
纵使单枪匹马,也要勇闯天涯
原文地址:https://www.cnblogs.com/sj-gank/p/11498648.html