【模板】拓扑排序 (nowcoder.com)
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
g = [ [] for _ in range(n + 1)]
vis = [0] * (n + 1)
de = [0] * (n + 1)
for _ in range(m):u, v = map(int, input().split())g[u].append(v)de[v] += 1
q = deque()
for i in range(1, n + 1):if de[i] == 0:q.append(i)
ans = []
while q:x = q.popleft()ans.append(x)vis[x] = 1for y in g[x]:de[y] -= 1if de[y] == 0:q.append(y)
if len(ans) == n:print(*ans)
else:print(-1)
【模板】单源最短路1 (nowcoder.com)
没有理解5000
和n
之间的联系。
import sys,heapq
input = sys.stdin.readline
n,m = map(int,input().split())
g = [ [] for _ in range(5000+1) ]
dist = [ float('inf') ] * (5000+1)
vis = [0] * (5000+1)
for _ in range(m):u,v = map(int,input().split())g[u].append(v)g[v].append(u)
q = []
heapq.heappush(q,(0,1))
dist[1] = 0
while q:d,u = heapq.heappop(q)if vis[u]: continuevis[u] = 1for v in g[u]:if not vis[v] and dist[v] > d+1:dist[v] = d+1heapq.heappush(q,(dist[v],v))
print(dist[n] if dist[n] != float('inf') else -1)
【模板】单源最短路2 (nowcoder.com)
import sys, heapq
input = sys.stdin.readline
n,m = map(int, input().split())
N = 5000 + 21
g = [ [] for i in range(N) ]
vis = [0] * N
dist = [ float('inf') ] * N
for _ in range(m):u,v,w = map(int, input().split())g[u].append((v,w))g[v].append((u,w))
hq = []
dist[1] = 0
heapq.heappush(hq, (0,1))
while hq:d,u = heapq.heappop(hq)if vis[u]: continuevis[u] = 1for v,w in g[u]:if dist[v] > d+w:dist[v] = d+wheapq.heappush(hq, (dist[v],v))
print(dist[n] if dist[n] != float('inf') else -1)
【模板】多源最短路径 (nowcoder.com)
超时。
import sys
input = sys.stdin.readline
n = int(input())
g = [ [0] * (n + 1)] + [ [0] + list(map(int, input().split())) for _ in range(n)]
g = [ [x if x != -1 else float('inf') for x in t] for t in g]
for k in range(1, n + 1):for i in range(1, n + 1):for j in range(1, n + 1):g[i][j] = min(g[i][j], g[i][k] + g[k][j])
for i in range(1, n + 1):print(' '.join([str(x) if x != float('inf') else '-1' for x in g[i][1:]]))