求平均值最小的环,如果平均值最小为x,则如果把每条边的权值都减(x+1),那么新图将会有负环,用bellman ford判断。
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; #define pb(a) push(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) {return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) {return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #elsefreopen("d:\\in1.txt","r",stdin);freopen("d:\\out1.txt","w",stdout); #endif } int getch() {int ch;while((ch=getchar())!=EOF) {if(ch!=' '&&ch!='\n')return ch;}return EOF; }struct Edge {int from,to;double dist; }; const int maxn=55; vector<int> g[maxn]; vector<Edge> edge; double d[maxn]; int inq[maxn]; int inq_cnt[maxn]; int n,m; void init() {for(int i=1;i<=n;i++)g[i].clear();edge.clear(); } void add(int u,int v,double w) {Edge e=(Edge){u,v,w};edge.push_back(e);g[u].push_back(edge.size()-1); } bool negativeCycle(int s) {queue<int> q;memset(inq,0,sizeof(inq));memset(inq_cnt,0,sizeof(inq_cnt));for(int i=1;i<=n;i++){d[i]=0;inq[i]=1;q.push(i);}while(!q.empty()){int u=q.front();q.pop();inq[u]=0;for(int i=0;i<g[u].size();i++){Edge &e=edge[g[u][i]];if(d[u]+e.dist<d[e.to]){d[e.to]=d[u]+e.dist;if(!inq[e.to]){inq[e.to]=1;q.push(e.to);if(++inq_cnt[e.to]>n)return true;}}}}return false; } bool check(double x) {for(int i=0;i<m;i++)edge[i].dist-=x;int flag=negativeCycle(1);for(int i=0;i<m;i++)edge[i].dist+=x;return flag; } int main() {int t;scanf("%d",&t);for(int ca=1;ca<=t;ca++){scanf("%d%d",&n,&m);init();for(int i=1;i<=m;i++){int u,v;double w;scanf("%d%d%lf",&u,&v,&w);add(u,v,w);}double l=0,r=10000002;//printf("%d\n%d\n",10000000,INF);while(r-l>10e-4){double mid=l+(r-l)/2;if(!check(mid))l=mid;else r=mid;}if(l>10000000)printf("Case #%d: No cycle found.\n",ca);elseprintf("Case #%d: %.2lf\n",ca,l);}return 0; }