UVA 11090 Going in Cycle!!

本文深入探讨了SPFA判负环算法及其与二分算法的结合运用,详细介绍了算法原理、实现步骤及实例分析,旨在解决实际问题中的复杂路径查找和优化难题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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[N];
int v[M],nxt[M];
double w[M];
int first[N],inq[N],cnt[N];
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值