您的位置:首页 > 编程语言 > Go语言

UVA 11090 Going in Cycle!!

2015-08-25 10:32 573 查看
SPFA判负环+二分

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <vector>
#define N 55
#define M 100015
using namespace std;
int n,m,maxn=0,e=0;
double d
;
int v[M],nxt[M];
double w[M];
int first
,inq
,cnt
;
void add_edge(int a,int b,double c)
{
v[e] = b;nxt[e] = first[a];w[e] = c;first[a] = e++;
}
bool negativeCycle()
{
queue<int> q;
memset(cnt,0,sizeof(cnt));
memset(inq,0,sizeof(inq));
int i;
for(i = 1;i <= n;i++){
q.push(i);
d[i] = 0;
}
inq[1] = 1;
while(!q.empty()){
int ith = q.front();
q.pop();
inq[ith] = 0;
for(i = first[ith];i != -1;i = nxt[i]){
if(d[v[i]] > d[ith] + w[i]){
d[v[i]] = d[ith] + w[i];
if(!inq[v[i]]){
q.push(v[i]);
inq[v[i]] = 1;
if(++cnt[v[i]] > n) return true;
}
}
}
}
return false;
}
bool isok(double x){
bool ret;
for(int i = 0;i < e;i++)
w[i] -= x;
ret = negativeCycle();
for(int i = 0;i < e;i++)
w[i] += x;
return ret;
}
int main()
{
int t,x=1;
scanf("%d",&t);
while(x<=t)
{
maxn=0,e=0;
memset(first,-1,sizeof(first));
scanf("%d%d",&n,&m);
while(m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
maxn=max(c,maxn);
add_edge(a,b,c);
}
if(!isok(maxn+1))
printf("Case #%d: No cycle found.\n",x++);
else
{
double left=0,right=maxn;
double mid=(left+right)/2;
while(right-left>1e-3)
{
if(isok(mid))
right = mid;
else
left = mid;
mid=(left+right)/2;
}
printf("Case #%d: %.2f\n",x++,left);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: