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

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

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

方法思路

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

    import heapqdef 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/

    你可能感兴趣的文章
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>
    org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
    查看>>
    org/hibernate/validator/internal/engine
    查看>>
    SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
    查看>>
    ORM sqlachemy学习
    查看>>
    Ormlite数据库
    查看>>
    orm总结
    查看>>
    os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
    查看>>
    os.system 在 Python 中不起作用
    查看>>
    OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
    查看>>
    OSCACHE介绍
    查看>>
    SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
    查看>>
    OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
    查看>>
    OSChina 周四乱弹 ——程序员为啥要买苹果手机啊?
    查看>>
    OSChina 技术周刊第十期,每周技术抢先看!
    查看>>