博客
关于我
牛客练习赛61 D 最短路变短了(spfa+思维)
阅读量:388 次
发布时间:2019-03-05

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

为了解决这个问题,我们需要判断将某一条有向边反向后,从城市1到达城市n的最短路径是否会变短。我们可以通过计算原始图中从城市1到城市n的最短路径,并检查反转边后是否存在更短的路径来实现这一点。

方法思路

  • 计算最短路径:首先,我们需要计算从城市1出发到所有其他城市的最短路径(记为d1),以及从城市n出发到所有其他城市的最短路径(记为d2)。
  • 检查反转边的影响:对于每一条边u→v,反转后变为v→u。我们需要检查是否存在一条经过反转边的路径,使得从城市1到城市n的最短路径变短。具体来说,检查d2[u] + d1[v] + c是否小于d1[n],其中c是原边的权重。
  • 解决代码

    import heapq
    def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    idx = 0
    n = int(data[idx])
    idx += 1
    m = int(data[idx])
    idx += 1
    edges = []
    adj = [[] for _ in range(n + 1)]
    for _ in range(m):
    u = int(data[idx])
    idx += 1
    v = int(data[idx])
    idx += 1
    c = int(data[idx])
    idx += 1
    edges.append((u, v, c))
    adj[u].append((v, c))
    # Compute d1: from 1
    d1 = [float('inf')] * (n + 1)
    d1[1] = 0
    heap = []
    heapq.heappush(heap, (0, 1))
    while heap:
    dist_u, u = heapq.heappop(heap)
    if dist_u > d1[u]:
    continue
    for v, c in adj[u]:
    if d1[v] > d1[u] + c:
    d1[v] = d1[u] + c
    heapq.heappush(heap, (d1[v], v))
    # Compute d2: from n
    d2 = [float('inf')] * (n + 1)
    d2[n] = 0
    heap = []
    heapq.heappush(heap, (0, n))
    while heap:
    dist_u, u = heapq.heappop(heap)
    if dist_u > d2[u]:
    continue
    for v, c in adj[u]:
    if d2[v] > d2[u] + c:
    d2[v] = d2[u] + c
    heapq.heappush(heap, (d2[v], v))
    q = int(data[idx])
    idx += 1
    output = []
    for _ in range(q):
    x = int(data[idx])
    idx += 1
    u, v, c = edges[x]
    if d2[u] == float('inf') or d1[v] == float('inf'):
    output.append("NO")
    else:
    total = d2[u] + d1[v] + c
    if total < d1[n]:
    output.append("YES")
    else:
    output.append("NO")
    print('\n'.join(output))
    if __name__ == '__main__':
    main()

    代码解释

  • 读取输入:使用sys.stdin.read读取所有输入数据,提高读取效率。
  • 构建邻接表:读取边信息并构建邻接表,用于后续的最短路径计算。
  • 计算最短路径:使用Dijkstra算法分别从城市1和城市n出发,计算到达各城市的最短路径,存储在d1和d2数组中。
  • 处理查询:对于每条边,反转后检查是否存在更短的路径,输出结果。
  • 该方法通过预处理计算最短路径,然后在线查询每条边的影响,确保了高效处理大规模数据。

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

    你可能感兴趣的文章
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>