[ An Ac a Day ^_^ ] [kuangbin带你飞]专题四 最短路练习 POJ 3259 Wormholes

SPFA求负环 模板题

记得每组处理之前clear vector

  1 /* ***********************************************
  2 Author        :Sun Yuefeng
  3 Created Time  :2016/10/25 18:02:02
  4 File Name     :A.cpp
  5 ************************************************ */
  6 
  7 #include<cstdio>
  8 #include<iostream>
  9 #include<algorithm>
 10 #include<cmath>
 11 #include<cstring>
 12 #include<string>
 13 #include<bitset>
 14 #include<map>
 15 #include<set>
 16 #include<stack>
 17 #include<vector>
 18 #include<queue>
 19 #include<list>
 20 #define M(a,b) memset(a,b,sizeof(a))
 21 using namespace std;
 22 typedef long long ll;
 23 const int inf=0x3f3f3f3f;
 24 const int maxn=2e3+600;
 25 const int mod=1e7+7;
 26 int dx[8]= {0,0,1,-1,1,-1,1,-1};
 27 int dy[8]= {1,-1,0,0,-1,1,1,-1};
 28 
 29 struct edge
 30 {
 31     int v,value;
 32     edge(int _v=0,int _value=0):v(_v),value(_value){}
 33 };
 34 
 35 vector<edge>e[maxn];
 36 int n,m,w;
 37 bool vis[maxn];
 38 int cnt[maxn];
 39 int dist[maxn];
 40 
 41 bool SPFA()
 42 {
 43     M(vis,false);
 44     M(dist,inf);
 45     M(cnt,0);
 46     vis[1]=true;
 47     dist[1]=0;
 48     cnt[1]=1;
 49     queue<int>q;
 50     while(!q.empty()) q.pop();
 51     q.push(1);
 52     while(!q.empty())
 53     {
 54         int u=q.front();
 55         q.pop();
 56         vis[u]=false;
 57         for(int i=0;i<e[u].size();i++)
 58         {
 59             int v=e[u][i].v;
 60             if(dist[v]>dist[u]+e[u][i].value)
 61             {
 62                 dist[v]=dist[u]+e[u][i].value;
 63                 if(!vis[v])
 64                 {
 65                     vis[v]=true;
 66                     q.push(v);
 67                     cnt[v]++;
 68                     if(cnt[v]==n) return true;
 69                 }
 70             }
 71         }
 72     }
 73     return false;
 74 }
 75 
 76 void addedge(int u,int v,int w)
 77 {
 78     e[u].push_back(edge(v,w));
 79 }
 80 
 81 int main()
 82 {
 83     //freopen("in.txt","r",stdin);
 84     //freopen("out.txt","w",stdout);
 85     int T;
 86     scanf("%d",&T);
 87     while(T--)
 88     {
 89         for(int i=0;i<maxn;i++)
 90             e[i].clear();
 91         int u,v,l;
 92         scanf("%d%d%d",&n,&m,&w);
 93         while(m--)
 94         {
 95             scanf("%d%d%d",&u,&v,&l);
 96             addedge(u,v,l);
 97             addedge(v,u,l);
 98         }
 99         while(w--)
100         {
101             scanf("%d%d%d",&u,&v,&l);
102             addedge(u,v,-l);
103         }
104         if(SPFA()) printf("YES
");
105         else printf("NO
");
106     }
107     return 0;
108 }
原文地址:https://www.cnblogs.com/general10/p/5997838.html