Python貌似永远过不了...

P1342 请柬

SwordRain @ 2024-01-24 12:08:55

不是TLE就是MLE,我的代码如下,等大佬优化

import heapq
# import sys
# input = lambda: sys.stdin.readline().strip()
# print = lambda x, end='\n': sys.stdout.write(str(x) + str(end))
def Dijkstra(edges, s, n):
    distance = [float('inf')] * n
    distance[s] = 0
    vis = [False] * n
    pqueue = [(0, s)]
    i = 0
    while pqueue and i < n:
        dist, vertex = heapq.heappop(pqueue)
        if not vis[vertex]:
            vis[vertex] = True
            i += 1
            for edge in edges[vertex]:
                Dist = dist + edge[1]
                if Dist < distance[edge[0]]:
                    distance[edge[0]] = Dist
                    heapq.heappush(pqueue, (Dist, edge[0]))
    return distance
def solve():
    n, m = map(int, input().split())
    edges_shun = [[] for _ in range(n)]
    edges_ni = [[] for _ in range(n)]
    for _ in range(m):
        u, v, w = map(int, input().split())
        u -= 1
        v -= 1
        edges_shun[u].append([v, w])
        edges_ni[v].append([u, w])
    ans = 0
    dis = Dijkstra(edges_shun, 0, n)
    for i in range(n):
        ans += dis[i]
    dis = Dijkstra(edges_ni, 0, n)
    for i in range(n):
        ans += dis[i]
    print(ans)
solve()

|