博客
关于我
【SSL 2206&洛谷 P1576】最小花费【最短路 Dijkstra】【图论】
阅读量:309 次
发布时间:2019-03-03

本文共 1698 字,大约阅读时间需要 5 分钟。

为了解决这个问题,我们需要找到从A到B的最优转账路径,使得转账后B最终收到100元所需的最小初始金额。这个问题可以通过图论中的最长路径问题来解决,通过反向转换并使用Dijkstra算法来求解。

方法思路

  • 问题分析:我们需要找到从A到B的路径,使得在扣除手续费后,B最终收到100元。每一步转账都会扣除一定的百分比手续费,因此我们需要最大化每一步的转账效率。
  • 反向转换:将每条转账路径的权重取倒数,转化为从B到A的最短路径问题。这样,我们可以使用Dijkstra算法来找到最短路径,这相当于在原图中找到最长路径。
  • Dijkstra算法:使用优先队列来处理节点,找到从B到A的最短路径。每条边的权重是转换后的汇率。
  • 计算初始金额:找到最长路径的乘积,然后用100除以这个乘积,得到A的最小初始金额。
  • 解决代码

    import heapqdef main():    import sys    input = sys.stdin.read().split()    idx = 0    n = int(input[idx])    idx += 1    m = int(input[idx])    idx += 1    INF = float('inf')    graph = [[] for _ in range(n + 1)]  # 1-based indexing    for _ in range(m):        x = int(input[idx])        idx += 1        y = int(input[idx])        idx += 1        z = float(input[idx])        idx += 1        rate = 1.0 / ((100 - z) / 100)        graph[x].append((y, rate))        graph[y].append((x, rate))    A = int(input[idx])    idx += 1    B = int(input[idx])    idx += 1    # Dijkstra from B to A    dist = [INF] * (n + 1)    dist[B] = 1.0    heap = []    heapq.heappush(heap, (0, B))    while heap:        current_dist, u = heapq.heappop(heap)        if u == A:            break        if current_dist > dist[u]:            continue        for v, w in graph[u]:            if dist[v] < dist[u] * w:                dist[v] = dist[u] * w                heapq.heappush(heap, (dist[v], v))    total_rate = dist[A]    min_A = 100.0 / total_rate    print("{0:.8f}".format(min_A))if __name__ == "__main__":    main()

    代码解释

  • 读取输入:从标准输入读取数据,包括总人数、转账对数、转账手续费、以及起始和结束节点。
  • 建立图:使用邻接表表示图,每条边的权重是转换后的汇率(1 / ((100 - 手续费%) / 100))。
  • Dijkstra算法:从B出发,使用优先队列处理节点,更新每个节点的最短路径。
  • 计算结果:找到从B到A的最短路径的总汇率,然后计算A的初始金额并输出结果,精确到小数点后8位。
  • 这个方法通过反向转换和Dijkstra算法高效地解决了问题,确保了找到最优转账路径并计算最小初始金额。

    转载地址:http://ebim.baihongyu.com/

    你可能感兴趣的文章
    Oracle 11g忘记sys、system、scott密码该这样修改!
    查看>>
    Oracle 11g数据库安装和卸载教程
    查看>>
    Oracle 11g数据库成功安装创建详细步骤
    查看>>
    Oracle 11g超详细安装步骤
    查看>>
    Oracle 12c中的MGMTDB
    查看>>
    Oracle 12c安装报错Installation failed to access the temporary location(无法访问临时位置)...
    查看>>
    Oracle 9i数据库管理教程
    查看>>
    ORACLE Active dataguard 一个latch: row cache objects BUG
    查看>>
    oracle avg、count、max、min、sum、having、any、all、nvl的用法
    查看>>
    Oracle BEQ方式连接配置
    查看>>
    oracle Blob保存方式,oracle 存储过程操作blob
    查看>>
    Oracle BMW Racing sailing vessel帆船图
    查看>>
    ORACLE Bug 4431215 引发的血案—原因分析篇
    查看>>
    Oracle Business Intelligence Downloads
    查看>>
    Oracle cmd乱码
    查看>>
    Oracle Corp甲骨文公司推出Oracle NoSQL数据库2.0版
    查看>>
    【Docker知识】将环境变量传递到容器
    查看>>
    uniapp超全user-agent判断 包括微信开发工具 hbuilder mac windows 安卓ios端及本地识别
    查看>>
    Oracle DBA课程系列笔记(20)
    查看>>
    oracle dblink 创建使用 垮库转移数据
    查看>>