You are given a weighted directed graph with n vertices and m edges. Each cycle in the graph has a weight, which equals to sum of its edges. There are so many cycles in the graph with different weights. In this problem we want to find a cycle with the minimum mean.
Input
The first line of input gives the number of cases, N. N test cases follow. Each one starts with two numbers n and m. m lines follow, each has three positive number a,b,c which means there is an edge from vertex a to b with weight of c.
Output
For each test case output one line containing Case #x: followed by a number that is the lowest mean cycle in graph with 2 digits after decimal place, if there is a cycle. Otherwise print No cycle found..
Constraints • n ≤ 50 • a,b ≤ n • c ≤ 10000000
Sample Input
2
2 1
1 2 1
2 2
1 2 2
2 1 3
Sample Output
Case #1: No cycle found. Case #2: 2.50
解题报告
这道题的题意是让我们求一个值,使得每一条边的边权减去这一个值后的图中有负环。
显然,我们只需要二分这一个值,再跑SPFA判负环就行了。
代码如下:
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N=100;
const int inf=0x3f3f3f3f;
struct edge
{
int v,next;
double w;
}ed[N*N+5];
int head[N+5],num;
int n,m;
int T,Case;
int flag[N+5],cnt[N+5];
double dis[N+5];
inline void build(int u,int v,double w)
{
ed[++num].v=v;
ed[num].w=w;
ed[num].next=head[u];
head[u]=num;
}
bool SPFA(int s)
{
queue<int>q;
for(int i=0;i<=n;i++)
{
dis[i]=inf;
cnt[i]=0;
}
memset(flag,0,sizeof(flag));
dis[s]=0;
flag[s]=1;
q.push(s);
while(!q.empty())
{
int u=q.front();q.pop();
flag[u]=0;
for(int i=head[u];i!=-1;i=ed[i].next)
{
int v=ed[i].v;
if(dis[v]>dis[u]+ed[i].w)
{
dis[v]=dis[u]+ed[i].w;
if(!flag[v])
{
flag[v]=1;
q.push(v);
if(++cnt[v]>=n)return false;
}
}
}
}
return true;
}
bool check(double x)
{
bool ret=false;
for(int i=1;i<=n;i++)
for(int j=head[i];j!=-1;j=ed[j].next)ed[j].w-=x;
for(int i=1;i<=n;i++)if(!SPFA(i))ret=true;
for(int i=1;i<=n;i++)
for(int j=head[i];j!=-1;j=ed[j].next)ed[j].w+=x;
return ret;
}
int main()
{
scanf("%d",&T);
while(T--)
{
double lf=inf*1.0,rg=0;
memset(head,-1,sizeof(head));
num=0;
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int u,v;
double w;
scanf("%d%d%lf",&u,&v,&w);
build(u,v,w);
lf=min(w,lf);
rg=max(w,rg);
}
printf("Case #%d: ",++Case);
if(!check(rg+1))printf("No cycle found.\n");
else
{
double s=1e-8;
while(rg-lf>s)
{
double mid=(lf+rg)/2.0;
if(check(mid))rg=mid;
else lf=mid;
}
printf("%.2lf\n",rg);
}
}
return 0;
}