图论


预计阅读时间:3 分钟

图论

图论一类题的合集,随训练持续补完。用 Python 打 CF,除了算法本身,还得和语言特性过几招——这类实战经验也一并记录在此。

DFS 与建图

CF 29C - Mail Stamps(唯一路径重建)

题意:给出无序的边集,它们构成一条链,从端点按序输出这条唯一路径。

思路本身朴素:度为 1 的点是端点,从任一端点 dfs 走到底即可。这题真正的收获是两条 Python 实战经验:

  • 交上去一直 RE,根因不是算法:Python 默认递归深度限制只有 1000,链长 $10^5$ 的 dfs 直接爆栈。当时用 sys.setrecursionlimit(int(2 * 10**5)) 把递归深度扩到题目规模。但只调上限不一定够:在 CPython 3.11 之前的版本上,这么深的递归会先撑爆 C 栈、直接段错误($10^5$ 的链在 Python 3.9 上实测段错误)。这题链上每个点最多只有一个未访问的邻居,改成 while 循环往下走最稳,代码如下。
  • 邻接表建图用字典的 setdefault 初始化空列表最简洁。
n = int(input())
graph = {}
for _ in range(n):
    c1, c2 = map(int, input().split())
    graph.setdefault(c1, []).append(c2)
    graph.setdefault(c2, []).append(c1)
# an endpoint of the chain has degree 1
start = next(k for k, v in graph.items() if len(v) == 1)
path = [start]
prev, cur = None, start
while True:
    # each city has at most one neighbour other than the one we came from
    nxt = [c for c in graph[cur] if c != prev]
    if not nxt:
        break
    prev, cur = cur, nxt[0]
    path.append(cur)
print(*path)

未完待续,本合集随训练进度持续补完。


本文由 aboom 原创,转载请注明出处。

📖相关推荐