UVA11090 Going in Cycle!! (二分+SPFA推断有无负权)

本文介绍了一种通过二分搜索和SPFA算法寻找有向图中平均边权重最小的环的方法。通过不断调整候选平均距离并检测是否存在负权环来确定最小平均距离。

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

0 6

Problem G: Going in Cycle!!

Input: standard input

Output: standard output

 

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, NN test cases follow. Each one starts with two numbers n and mm 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

Output for Sample Input

2
2 1
1 2 1
2 2
1 2 2
2 1 3

Case #1: No cycle found.
Case #2: 2.50

 

Problemsetter: Mohammad Tavakoli Ghinani

Alternate Solution: Cho

 


题意:

在一个有向图中找一个平均距离最小的环。


思路:

二分枚举平均最小距离,每次每条边减去这个距离,然后spfa(或者bellmanFord找负环)假设找到,说明平均最小距离比这个值要小。假设没找到。则说明平均最小距离比这个值大。

注意可能是不连通图~


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define INF 0x3f3f3f3f
#define eps 1e-6
#define maxn 55
#define MAXN 10005
using namespace std;

int n,m,ans,cnt,sx;
double le,ri,mid,res;
bool vis[maxn];
double dist[maxn];
int head[maxn],num[maxn];
struct Node
{
    int v,next;
    double w;
}edge[MAXN];

void addedge(int u,int v,double w)
{
    cnt++;
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt;
}
bool SPFA(int k)
{
    int i,j,nx,v;
    memset(vis,0,sizeof(vis));
    memset(num,0,sizeof(num));
    for(i=1;i<=n;i++) dist[i]=INF;
    sx=k;
    queue<int>q;
    dist[sx]=0;
    vis[sx]=num[sx]=1;
    q.push(sx);
    while(!q.empty())
    {
        nx=q.front();
        vis[nx]=0;
        q.pop();
        for(i=head[nx];i;i=edge[i].next)
        {
            v=edge[i].v;
            if(dist[v]>dist[nx]+edge[i].w-mid)
            {
                dist[v]=dist[nx]+edge[i].w-mid;
                if(!vis[v])
                {
                    num[v]++;
                    if(num[v]>n) return true ;
                    vis[v]=1;
                    q.push(v);
                }
            }
        }
    }
    return false ;
}
int main()
{
    int i,j,u,v,t,test=0;
    double w;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        cnt=0;
        memset(head,0,sizeof(head));
        for(i=1;i<=m;i++)
        {
            scanf("%d%d%lf",&u,&v,&w);
            addedge(u,v,w);
        }
        le=0; ri=10000005;
        int flag;
        while(ri-le>eps)
        {
            mid=(le+ri)/2.0;
            flag=0;
            for(i=1;i<=n;i++)
            {
                if(SPFA(i))
                {
                    flag=1; break ;
                }
            }
            if(flag) ri=mid;
            else le=mid;
        }
        res=le;
        if(res<=10000001) printf("Case #%d: %.2f\n",++test,res);
        else printf("Case #%d: No cycle found.\n",++test);
    }
    return 0;
}




### SPFA算法检测环的实现及原理 SPFA(Shortest Path Faster Algorithm)是一种用于解决单源最短路径问题的有效算法,尤其适用于含有边但不包含环的情况。然而,在实际应用中,如果图中存在环,SPFA可能陷入无限循环,因此需要一种机制来检测这种特殊情况。 #### 环的存在条件 环指的是在一个图中存在一条回路,该回路上所有边的重之和为数。由于每次经过这条回路都会使路径长度变得更小,理论上可以不断绕圈从而得到无穷小的距离值[^1]。 #### SPFA算法的工作方式 SPFA的核心思想是利用队列进行广度优先搜索(BFS),并通过松弛操作更新节点到起点之间的距离。具体来说,对于每一个从队列弹出的顶点u,遍历它所有的邻接点v,并尝试用当前已知的最佳路径加上(u,v)这条边的成本去改进到达v点的距离。一旦发现新的更优解,则将v重新放入队列等待进一步探索[^3]。 #### 检测环的关键技术 尽管标准版SPFA不具备内置功能自动识别环,但可以通过增加额外计数器变量`cnt[]`记录每个结点被访问(即入队)的最大次数来间接完成此任务: - **初始化阶段**: 设置数组 `dis[]` 表示各顶点至源点间的最小估计成本;设初值均为正无穷大(+&infin;),除了起始位置设置成零外(`dis[s]=0`)。另外定义辅助数组 `inQueue[]`,用来标记哪些顶点正处于队列之中以防重复插入相同元素浪费时间资源。 - **核心逻辑修改**: - 当某顶点再次进入队列前检查它的累计入队数目是否已经超过整个网络中的总定点数量V; 如果满足上述条件则立即终止运算并报告发现了不可接受状况—存在至少一个闭合链表结构[^2]. 以下是具体的伪代码描述如何扩展基础版本以支持环探测: ```python from collections import deque def spfa_with_negative_cycle_detection(graph, start_node, num_nodes): dis = [float('inf')] * (num_nodes + 1) cnt = [0] * (num_nodes + 1) in_queue = [False] * (num_nodes + 1) queue = deque() dis[start_node] = 0 queue.append(start_node) in_queue[start_node] = True while queue: u = queue.popleft() in_queue[u] = False for v, weight in graph[u]: if dis[v] > dis[u] + weight: dis[v] = dis[u] + weight if not in_queue[v]: cnt[v] += 1 # If a node is relaxed more than the number of nodes times, # then there must be a negative cycle. if cnt[v] >= num_nodes: return "Negative Cycle Detected" queue.append(v) in_queue[v] = True return "No Negative Cycles Found" ``` 在这个增强型函数里,我们引入了一个名为`cnt[]`的新列表跟踪各个节点经历过的放松迭代轮次。每当某个特定节点准备第二次加入工作序列之前都要先核查其对应统计数值是不是已经达到了预设界限——也就是等于总的节点个数N。如果是的话就意味着系统内部必然隐藏着某种形式上的面反馈闭环现象发生,此时应该立刻停止后续计算动作并向外界发出警告信号表明遇到了非法情形[^4]。 ### 结论 综上所述,虽然原始形态下的SPFA并不自带针对环形拓扑结构的有效甄别手段,不过借助简单的附加措施比如设立专门监控指标就可以轻松弥补这项缺陷进而构建更加健壮可靠的解决方案出来供人们日常开发实践当中选用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值