1. 对于节点数量超过1e3(达到1e5)是要用邻接表来储存的;
2. 步骤为:
2.1从(0,1)加入小根堆开始,(distance = 0, i = 1),每一次枚举i可以到达的边,对他们进行距离更新并加入堆中,只到把每一个节点都枚举过
2.2 注意:1.5e5是很大的,有必要计入优化才能AC.(优化 : 开state数组,对于每一次的取出的节点进行标记 ---------》不是对于每一次加入进行标记,对于取出标记可以每一次都continue,更快)
题目:
from queue import PriorityQueue
N = int(1.5e5 +10)
e = [0 for i in range(N)]
w = [float('inf') for i in range(N)]
ne= [0 for i in range(N)]
h = [0 for i in range(N)]
idx = 1
def add(a,b,c):
global idx
e[idx]=b
w[idx]=c
ne[idx] = h[a]
h[a] = idx
idx+=1
n , m =map(int,input().split())
d = [float('inf') for i in range(n+1)]
for i in range(m):
a,b,c = map(int,input().split())
add(a,b,c)
if a==1: d[b] = min(d[b] , c)
a = PriorityQueue()
state = [False for i in range(N)]
a.put((0,1))
#
d[1] = 0
#
#print(d)
while not a.empty():
distance,head = a.get()
tt = h[head]
if state[tt] : continue#这里要加continue掉
while True:
if not state[tt]:
d[e[tt]] = min(d[e[tt]],distance + w[tt])
a.put((d[e[tt]],e[tt]))
#state[h[head]] = True
if e[tt] == 0:break
tt = ne[tt]
#print(distance,head)
state[h[head]] = True
if d[n] == float('inf') :print(-1)
else:print(d[n])
就可以AC了。