题目描述:
description
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
题目分析:
从n个点,m条有向边,并有权值,求这个图是否有环,若有环,求这个图内环的最小权值(环内所有边的权除以环内点的个数)。
我们知道spfa法可以判定是否有负环回路,那么我们只要将这个图所有可能环的权值都进行spfa,就可以找到最小权值。(查找利用二分)
代码如下:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long ll;
const double INF = 0x3f3f3f3f*1.0;
const int MAXN=60;
struct Edge
{
int next,to;
double w;
}mp[MAXN*MAXN];
int head[MAXN];int id;
int T;
int n,m;
void init()
{
id=0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,double w)
{
mp[id].to=v;
mp[id].w=w;
mp[id].next=head[u];
head[u]=id++;
}
bool vis[MAXN];
double dis[MAXN];
int cnt[MAXN];
bool spfa(double mid)//spfa算法 用kuangbin的模板 根据题意略有改动
{
queue<int>q;
while(!q.empty()) q.pop();
for(int i=1; i<=n; i++)
{
q.push(i);
vis[i]=false;
cnt[i]=0;
dis[i]=INF;
}
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=false;
for(int i=head[u]; i!=-1; i=mp[i].next)
{
int v=mp[i].to;
if (dis[v]>dis[u]+mp[i].w-mid)//减mid是以mid为基准查找负环回路
{
dis[v]=dis[u]+mp[i].w-mid;
if (!vis[v])
{
vis[v]=true;
if (++cnt[v]>=n) return false;//有负环回路
q.push(v);
}
}
}
}
return true;//没有负环回路
}
int main()
{
scanf("%d",&T);
for(int t=1; t<=T; t++)
{
double ans=INF;
double high=0,low=0,mid;
init();
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int u,v;double w;
scanf("%d%d%lf",&u,&v,&w);
if(u==v) ans=min(ans,w);
addedge(u,v,w);
high=max(high,w);
}
printf("Case #%d: ",t);
if (spfa(high+10000)) {puts("No cycle found.");continue;}
while(high-low>1e-6)//二分(实数判断相等)
{
mid=(high+low)/2;
if(!spfa(mid))
{
ans=min(ans,mid);
high=mid;
}
else low=mid;
}
printf("%.2lf\n",ans);
}
return 0;
}