最优比例生成环(dfs判正环或spfa判负环)

本文介绍了一种基于有向图的最优旅行计划算法,旨在帮助游客找到一条从起点出发,访问至少两个不同景点后回到起点的路径,使得单位时间内获得的乐趣值最大化。通过将问题转化为寻找加权图中的正环值问题,并利用二分搜索与深度优先搜索的方法来解决。

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

http://poj.org/problem?id=3621

Sightseeing Cows
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7649 Accepted: 2567

Description

Farmer John has decided to reward his cows for their hard work by taking them on a tour of the big city! The cows must decide how best to spend their free time.

Fortunately, they have a detailed city map showing the L (2 ≤ L ≤ 1000) major landmarks (conveniently numbered 1.. L) and the P (2 ≤ P ≤ 5000) unidirectional cow paths that join them. Farmer John will drive the cows to a starting landmark of their choice, from which they will walk along the cow paths to a series of other landmarks, ending back at their starting landmark where Farmer John will pick them up and take them back to the farm. Because space in the city is at a premium, the cow paths are very narrow and so travel along each cow path is only allowed in one fixed direction.

While the cows may spend as much time as they like in the city, they do tend to get bored easily. Visiting each new landmark is fun, but walking between them takes time. The cows know the exact fun values Fi (1 ≤ Fi ≤ 1000) for each landmark i.

The cows also know about the cowpaths. Cowpath i connects landmark L1i to L2i (in the direction L1i -> L2i ) and requires time Ti (1 ≤ Ti ≤ 1000) to traverse.

In order to have the best possible day off, the cows want to maximize the average fun value per unit time of their trip. Of course, the landmarks are only fun the first time they are visited; the cows may pass through the landmark more than once, but they do not perceive its fun value again. Furthermore, Farmer John is making the cows visit at least two landmarks, so that they get some exercise during their day off.

Help the cows find the maximum fun value per unit time that they can achieve.

Input

* Line 1: Two space-separated integers: L and P
* Lines 2..L+1: Line i+1 contains a single one integer: Fi
* Lines L+2..L+P+1: Line L+i+1 describes cow path i with three space-separated integers: L1i , L2i , and Ti

Output

* Line 1: A single number given to two decimal places (do not perform explicit rounding), the maximum possible average fun per unit time, or 0 if the cows cannot plan any trip at all in accordance with the above rules.

Sample Input

5 7
30
10
10
5
10
1 2 3
2 3 2
3 4 5
3 5 2
4 5 5
5 1 3
5 2 2

Sample Output

6.00

题意:有n个景点和一些单项道路,到达一个顶点会获得一定的快乐值,经过道路会消耗一定的时间,一个人可以任意选择一个顶点作为开始的地方,然后经过一系列的景点返回原地;每个景点可以经过多次,但是只有经过第一次景点的时候才可以获得欢乐值,并且要旅游至少两个顶点,以保证得到足够的锻炼;问单位时间的欢乐值最大是多少;

分析:该题思路和最优比例生成树有些类似,设第i个点的欢乐值f[i],边权值是w[u][v];

对于一个环比率:r=(f[1]*x1+f[2]*x2+f[3]*x3+……f[n]*xn)/(w[1][2]*x1+w[2][3]*x2+……w[n][1]*xn);

构造一个函数z(l)=(f[1]*x1+f[2]*x2+f[3]*x3+……f[n]*xn)-l*(w[1][2]*x1+w[2][3]*x2+……w[n][1]*xn);

简化为z(l)=sigma(f[i]*xi)-l*sigma(w[i][j]*xi);

变形得:r=sigma(f[i]*xi)/sigma(w[i][j]*xi)=l+z(l)/sigma(w[i][j]*xi);

当存在比l还大的比率的冲要条件是z(l)>0;即z(l)存在正环值就行,所以转化成了求正环的问题;

应该把点权和边权融合成关于边的量:K=f[u]-mid*w[u][v];然后用二分枚举比率mid,当有向连通图中存在正环,就把mid增大,否者减小;

程序:

#include"stdio.h"
#include"string.h"
#include"queue"
#include"stdlib.h"
#include"iostream"
#include"algorithm"
#include"string"
#include"iostream"
#include"map"
#include"math.h"
#define M 1005
#define eps 1e-8
#define inf 100000000
using namespace std;
struct node
{
    int v;
    double w;
    node(int vv,double ww)
    {
        v=vv;
        w=ww;
    }
};
vector<node>edge[M];
double dis[M],f[M];
int use[M],n;
double mid;
int dfs(int u)
{
    use[u]=1;
    for(int i=0;i<(int)edge[u].size();i++)
    {
        int v=edge[u][i].v;
        if(dis[v]<dis[u]+f[u]-mid*edge[u][i].w)
        {
            dis[v]=dis[u]+f[u]-mid*edge[u][i].w;
            if(use[v])
                return 1;
            if(dfs(v))
                return 1;
        }
    }
    use[u]=0;
    return 0;
}
int ok()
{
    memset(dis,0,sizeof(dis));
    memset(use,0,sizeof(use));
    for(int i=1;i<=n;i++)
        if(dfs(i))
        return 1;
    return 0;
}
int main()
{
    int m,i;
    while(scanf("%d%d",&n,&m)!=-1)
    {
        for(i=1;i<=n;i++)
            scanf("%lf",&f[i]);
        for(i=1;i<=n;i++)
            edge[i].clear();
        for(i=1;i<=m;i++)
        {
            int a,b;
            double c;
            scanf("%d%d%lf",&a,&b,&c);
            edge[a].push_back(node(b,c));
        }
        double left,right;
        left=0;
        right=100000;
        while(right-left>eps)
        {
            mid=(right+left)/2;
            if(ok())
                left=mid;
            else
                right=mid;
        }
        printf("%.2lf\n",left);
    }
    return 0;
}



### SPFA算法检测图中的方法和原理 SPFA(Shortest Path Faster Algorithm)是一种用于求解单源最短路径问题的算法,尤其适合处理带有权边的图结构。然而,在实际应用中,SPFA可能遇到一种特殊情况——的存在。这种情况下,SPFA无法常终止计算,因此需要额外机制来检测。 #### 的概念 指的是在一个有向图中存在一条回路,该回路上所有边的权重之和小于零。由于每次经过这条回路都会使路径长度变得更小,理论上可以无限次通过此降低路径成本,从而导致最短路径不存在的情况[^3]。 #### SPFA算法的工作方式 SPFA的核心思想是对每一个顶点维护一个距离数组 `dist[]` 表示从起点到当前节点的距离,并利用队列实现动态更新这些距离值的过程。每当某个节点的距离发生变化时,就将其相邻节点重新入队以便进一步优化它们的距离估计值[^1]。 #### 检测的具体方法 为了能够识别出是否存在这样的有害循即所谓的“”,可以在执行标准版SPFA的同时增加计数器记录每个结点被访问者说被尝试放松操作的最大次数: - **引入辅助变量**:定义一个数组 `cnt[]` ,其中 `cnt[i]` 记录到达第 i 个节点所需经历的最大松弛次数。 - **初始化条件设置**:对于初始状态下的各个位置来说,默认其尚未经历过任何改变所以都赋初值0;同时把起始点加入待处理集合当中并将对应项设为已知数值比如置成0表示它自己到自己的路程当然是恒定不变的就是原地不动而已无需消耗资源者时间代价等等因素考虑进去即可满足需求了。 - **核心逻辑修改** - 当前在考察某特定目标对象k的时候,假设我们已经知道如何抵达它的前置依赖关系链上的另一端j处的最佳方案是什么样子的话(也就是知道了d[j]),那么就可以试着看看能否借助这个新发现的信息去改善关于前往目的地K的知识水平(d[k]). 如果确实发现了更优的选择途径可供采纳,则除了常规意义上的调整之外还需要同步提升与之关联的那个统计指标c[k]+=1. 接下来就是最关键的一步节啦!一旦观察到任意单一实体i所累积起来的历史改动记录数目超出了整个网络规模范围内所能容纳的数量极限V (这里指代的是总的定点数量),那就意味着必然存在着至少一组相互纠缠交错在一起形成闭效应的现象发生于此系统内部之中咯~于是乎便可以直接断言说啊,“哎呀不得了啦同志们注意啦!!我们的输入数据里面藏匿着危险分子----那个讨厌至极的‘权圈’跑出来捣乱喽!”随即果断采取措施予以妥善处置吧😊 ```python def spfa(graph, start_node): n = len(graph) dist = [float('inf')] * n cnt = [0] * n in_queue = [False] * n queue = deque([start_node]) dist[start_node] = 0 cnt[start_node] += 1 in_queue[start_node] = True while queue: u = queue.popleft() in_queue[u] = False for v, weight in graph[u]: if dist[v] > dist[u] + weight: dist[v] = dist[u] + weight if not in_queue[v]: queue.append(v) in_queue[v] = True cnt[v] += 1 if cnt[v] >= n: # Detect negative cycle return "Negative Cycle Detected" return dist ``` 上述代码片段展示了如何在SPFA框架下集成探测功能。通过追踪各节点被松弛的频率,一旦发现任一节点的松弛次数达到超过总节点数n,立即报告存在。 ### 结论 尽管SPFA本身不具备内置的检测能力,但通过对节点松弛次数加以监控的方式,可有效弥补这一缺陷。这种方法不仅简单易行,而且能很好地融入现有的SPFA流程之中,成为解决此类复杂问题的有效工具之一。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值