leetcode(33)图系列题目
1615. 最大网络秩
直接模拟即可
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
adjs = defaultdict(set) # 注意是集合
for u, v in roads:
adjs[u].add(v)
adjs[v].add(u)
res = 0
for i in range(n):
for j in range(i + 1, n):
cur = len(adjs[i]) + len(adjs[j]) # 注意是当前节点边数之和
if j in adjs[i]:
cur -= 1
res = max(res, cur)
return res
Dijkstra 算法相关题目
882. 细分图中的可到达节点
heappush(q,(newd, y))比heappush(q,(y, newd))效率快一些,可能因为默认为小根堆,大的newd会直接放在下面,不用排序
class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
g = [[] for _ in range(n)]
for u, v, cnt in edges:
g[u].append((v, cnt + 1))
g[v].append((u, cnt + 1))
dist = self.dijkstra(g, 0)
# 原始图可到达的节点数
res = sum(d <= maxMoves for d in dist)
for u, v, cnt in edges:
# 到达原始图中的节点后剩余的步数
a = max(0, maxMoves - dist[u])
b = max(0, maxMoves - dist[v])
# 每条边中可到达的新节点数
res += min(a + b, cnt)
return res
def dijkstra(self, g, start):
dist = [inf] * len(g)
dist[start] = 0
q = [(0, start)]
while q:
d, x = heappop(q)
if dist[x] < d: # 已经是最短路径,如果=说明有一条新的最短路,还是要进行下面的操作
continue
for y, w in g[x]:
newd = dist[x] + w
if newd < dist[y]:
dist[y] = newd
heappush(q,(newd, y))
return dist