UVA11090 Going in Cycle!!

Posted zytwan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA11090 Going in Cycle!!相关的知识,希望对你有一定的参考价值。

给定一个N个点M条边的带权有向图,求平均值最小的回路

二分查找+bellmanford判负环

 1 #include<cstdio>
 2 #include<vector>
 3 #include<cstring>
 4 #include<queue>
 5 const int maxn=10000;
 6 using namespace std;
 7 struct Edge{
 8     int from,to;
 9     double dist;
10 };
11 struct bellmanford{
12     int n,m;
13     vector<Edge> edges;
14     vector<int> G[maxn];
15     bool inq[maxn];
16     double d[maxn];
17     int p[maxn];
18     int cnt[maxn];
19     
20     void init(int n){
21         this->n=n;
22         for(int i=0;i<n;++i) G[i].clear();
23         edges.clear();
24     }
25     
26     void addedges(int from,int to,int dist)
27     {
28         edges.push_back((Edge){from,to,dist});
29         m=edges.size();
30         G[from].push_back(m-1);
31     }
32     
33     bool negativecycle(){
34         queue<int> Q;
35         memset(inq,0,sizeof(inq));
36         memset(cnt,0,sizeof(cnt));
37         for(int i=0;i<n;++i) {d[i]=0;inq[0]=true;Q.push(i);}
38         while(!Q.empty())
39         {
40             int u=Q.front();Q.pop();
41             inq[u]=false;
42             for(int i=0;i<G[u].size();i++)
43             {
44                 Edge& e=edges[G[u][i]];
45                 if(d[e.to]>d[u]+e.dist)
46                 {
47                     d[e.to]=d[u]+e.dist;
48                     p[e.to]=G[u][i];
49                     if(!inq[e.to]) 
50                     {
51                         Q.push(e.to);inq[e.to]=true;if(++cnt[e.to]>n) return true;
52                     }
53                 }
54             }
55         }
56         return false;
57     }
58 };
59 bellmanford solver;
60 int test(double s)
61 {
62     for(int i=0;i<solver.m;++i) solver.edges[i].dist-=s;
63     bool ret=solver.negativecycle();
64     for(int i=0;i<solver.m;++i) solver.edges[i].dist+=s;
65     return ret;
66 }
67 int main()
68 {
69     int t;
70     scanf("%d",&t);
71     for(int kase=1;kase<=t;kase++)
72     {
73         int n,m,ub;
74         scanf("%d%d",&n,&m);
75         solver.init(n);
76         int zui=0;
77         while(m--)
78         {
79             int u,v,w;
80             scanf("%d%d%d",&u,&v,&w);
81             u--;v--;ub=max(ub,w);
82             solver.addedges(u,v,w);
83         }
84         printf("Case #%d: ",kase);
85         if(!test(ub+1)) printf("No cycle found.
");
86         else{
87             double l=0,r=ub;
88             while(r-l>0.0001)
89             {
90                 double m=(r+l)/2;
91                 if(test(m)) r=m;else l=m;
92             }
93             printf("%.2lf
",l);
94         }
95     }
96     return 0;
97 }

 

以上是关于UVA11090 Going in Cycle!!的主要内容,如果未能解决你的问题,请参考以下文章

UVA11090 Going in Cycle!! [spfa负环]

UVA - 11090 Going in Cycle!!

Going in Cycle!! UVA - 11090(二分+判断环路 )

UVA11090 Going in Cycle!!

H - Going in Cycle!! (UVA - 11090)

UVa 11090 Going in Cycle!! (Bellman_Ford)