☰
Start NorthStar
CP Weekly Challenge
CCC 2018 J5 Choose your own path Solution: BFS for Reachability and the Shortest Ending
Model each page as a vertex and solve both tasks with one BFS.
竞赛编程每周挑战
CCC 2018 J5 Choose your own path 题解:用 BFS 检查可达性与最短结局
把页面建模为节点,用一次 BFS 解决两个问题。
The story gives us pages and choices, but the underlying structure is a directed graph. Once that model is clear, one breadth-first search answers both required questions.
Problem in Plain Language
We start on page 1. Each page lists the pages that can be read next. A page with no next choice is an ending.
We must print:
Yif every page can be reached from page 1, otherwiseN.- The minimum number of pages read before reaching any ending.
The official constraints allow up to 10,000 pages and 10,000 total choices, so we should process each page and choice only a constant number of times.
DSA Map
| Story idea | Graph idea | Implementation |
|---|---|---|
| page | vertex | integer index |
| choice to another page | directed edge | adjacency list |
| first page | source | page 1 |
| page with no choices | terminal vertex | empty adjacency list |
| pages read | BFS distance + 1 | initialize source to 1 |
The crucial word is directed. A choice from page 2 to page 5 does not imply that page 5 can return to page 2.
Why BFS?
BFS explores vertices layer by layer. Every page at distance 1 from the start is processed before every page at distance 2, and so on. Therefore, the first ending removed from the queue has the smallest number of pages read.
There is one detail that often causes an off-by-one error: the problem counts pages, not edges. We have already read page 1 at the start, so set distance[1] = 1.
Algorithm
- Store every page's choices in an adjacency list.
- Set page 1's distance to 1 and put it in the queue.
- Pop one page at a time.
- If it has no outgoing choices and no ending has been recorded, save its distance.
- Enqueue every unvisited next page and set its distance.
- Continue until the queue is empty, even after finding an ending.
- Compare the number of visited pages with
N.
Sample Walkthrough
3
2 2 3
0
0
Page 1 points to pages 2 and 3. Both are endings. The BFS layers are:
Layer 1: page 1
Layer 2: pages 2, 3
All three pages are reachable, and an ending is reached after reading two pages. The output is:
Y
2
Python Solution
from collections import deque
n = int(input())
graph = []
for _ in range(n):
row = list(map(int, input().split()))
graph.append([page - 1 for page in row[1:]])
distance = [-1] * n
distance[0] = 1
queue = deque([0])
visited_count = 0
shortest_ending = -1
while queue:
page = queue.popleft()
visited_count += 1
if not graph[page] and shortest_ending == -1:
shortest_ending = distance[page]
for next_page in graph[page]:
if distance[next_page] == -1:
distance[next_page] = distance[page] + 1
queue.append(next_page)
print("Y" if visited_count == n else "N")
print(shortest_ending)
distance == -1 means unvisited. We mark a page when it is enqueued, preventing duplicate queue entries.
C++ Solution
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> graph(n);
for (int page = 0; page < n; ++page) {
int count;
cin >> count;
graph[page].resize(count);
for (int &nextPage : graph[page]) {
cin >> nextPage;
--nextPage;
}
}
vector<int> distance(n, -1);
queue<int> q;
distance[0] = 1;
q.push(0);
int visitedCount = 0;
int shortestEnding = -1;
while (!q.empty()) {
int page = q.front();
q.pop();
++visitedCount;
if (graph[page].empty() && shortestEnding == -1) {
shortestEnding = distance[page];
}
for (int nextPage : graph[page]) {
if (distance[nextPage] == -1) {
distance[nextPage] = distance[page] + 1;
q.push(nextPage);
}
}
}
cout << (visitedCount == n ? "Y" : "N") << '\n';
cout << shortestEnding << '\n';
}
Correctness Proof
Claim 1: The algorithm visits exactly the pages reachable from page 1.
Page 1 is visited initially. Whenever a visited page has an edge to an unvisited page, that next page is enqueued and visited. Thus every reachable page is eventually visited. The algorithm never adds a page without following an edge from a reachable page, so no unreachable page is visited.
Claim 2: shortest_ending is the minimum number of pages needed to reach an ending.
BFS processes pages in nondecreasing distance from page 1. Since the source distance starts at 1, each stored distance equals the number of pages on that route. Therefore the first ending removed from the queue has minimum page count.
Together, the two claims prove that both outputs are correct.
Complexity
Each reachable vertex enters the queue once, and each outgoing edge is examined once.
- Time:
O(N + E) - Space:
O(N + E)
Common Mistakes
- Starting the source distance at 0 and printing an edge count instead of a page count.
- Treating choices as undirected edges.
- Marking a page only after it leaves the queue, allowing duplicate entries.
- Stopping the entire BFS at the first ending, so unreachable pages are never detected.
- Counting only ending pages when checking whether every page is reachable.
Review Questions
- Why can the first ending in BFS be trusted, but the first ending in DFS cannot?
- Why do we continue after finding the shortest ending?
- What would change if the question counted choices instead of pages?
Next Steps
Next, study why BFS's layer order guarantees shortest paths, then practise explaining the graph model before touching the code.
Sources
- Official CEMC problem set: https://cemc.uwaterloo.ca/sites/default/files/documents/2018/2018CCCJrProblemSet.html
- Python
collections.deque: https://docs.python.org/3/library/collections.html#collections.deque
Read Next
这道题表面上是在读故事,底层结构却是一个有向图。模型确定后,一次广度优先搜索就能回答题目的两个问题。
题意简述
我们从第 1 页开始。每一页列出接下来可以跳转到哪些页面;没有后续选择的页面就是结局页。
我们需要输出:
- 如果从第 1 页可以到达所有页面,输出
Y,否则输出N。 - 到达任意结局页时,最少读过多少页。
官方数据最多有 10,000 页,所有选择的总数也不超过 10,000,因此我们需要近似线性的算法。
数据结构地图
| 故事元素 | 图论概念 | 实现 |
|---|---|---|
| page | vertex / 节点 | integer index |
| choice to another page | directed edge / 有向边 | adjacency list |
| first page | source / 起点 | page 1 |
| page with no choices | terminal vertex / 终点 | empty adjacency list |
| pages read | BFS distance + 1 | initialize source to 1 |
最关键的词是“有向”。第 2 页可以跳到第 5 页,并不代表第 5 页可以回到第 2 页。
为什么使用 BFS?
BFS 按层搜索:距离起点 1 条边的页面先于距离 2 条边的页面处理。因此,第一个出队的结局页一定对应最少阅读页数。
这里最容易出现差一错误:题目计算的是“读过的页面数”,不是边数。开始时已经读了第 1 页,所以应设置 distance[1] = 1。
算法步骤
步骤如下:
- 用邻接表保存每一页的后续选择。
- 将第 1 页距离设为 1,并放入队列。
- 每次从队首取出一个页面。
- 如果它没有出边,并且还没记录结局,就保存当前距离。
- 把所有未访问的下一页加入队列并设置距离。
- 找到结局后仍然继续,直到队列为空。
- 用访问页面数与
N比较,判断是否所有页面都可达。
样例推演
3
2 2 3
0
0
第 1 层:第 1 页
第 2 层:第 2、3 页
Y
2
第 1 页可以前往第 2、3 页,而这两页都是结局。所有页面均可达,最短阅读路径包含两页,所以输出 Y 和 2。
Python 解法
from collections import deque
n = int(input())
graph = []
for _ in range(n):
row = list(map(int, input().split()))
graph.append([page - 1 for page in row[1:]])
distance = [-1] * n
distance[0] = 1
queue = deque([0])
visited_count = 0
shortest_ending = -1
while queue:
page = queue.popleft()
visited_count += 1
if not graph[page] and shortest_ending == -1:
shortest_ending = distance[page]
for next_page in graph[page]:
if distance[next_page] == -1:
distance[next_page] = distance[page] + 1
queue.append(next_page)
print("Y" if visited_count == n else "N")
print(shortest_ending)
distance == -1 表示尚未访问。页面入队时立刻标记,避免同一页面重复进入队列。
C++ 解法
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> graph(n);
for (int page = 0; page < n; ++page) {
int count;
cin >> count;
graph[page].resize(count);
for (int &nextPage : graph[page]) {
cin >> nextPage;
--nextPage;
}
}
vector<int> distance(n, -1);
queue<int> q;
distance[0] = 1;
q.push(0);
int visitedCount = 0;
int shortestEnding = -1;
while (!q.empty()) {
int page = q.front();
q.pop();
++visitedCount;
if (graph[page].empty() && shortestEnding == -1) {
shortestEnding = distance[page];
}
for (int nextPage : graph[page]) {
if (distance[nextPage] == -1) {
distance[nextPage] = distance[page] + 1;
q.push(nextPage);
}
}
}
cout << (visitedCount == n ? "Y" : "N") << '\n';
cout << shortestEnding << '\n';
}
正确性证明
结论 1:算法恰好访问从第 1 页可达的页面。
第 1 页首先被访问;每当已访问页面指向一个未访问页面时,后者会被加入队列。因此所有可达页面最终都会被访问。算法只沿着已访问页面的边扩展,所以不会访问不可达页面。
结论 2:shortest_ending 是到达结局所需的最少页面数。
BFS 按距离非递减顺序处理页面。起点距离设为 1 后,每个距离正好等于路径上的页面数。因此,第一个出队的结局页具有最小页面数。
两个结论共同证明了两个输出均正确。
复杂度
每个可达节点只入队一次,每条出边只检查一次,因此时间复杂度为 O(N + E),空间复杂度为 O(N + E)。
常见错误
对应地,要注意:起点距离应为 1;选择是有向边;页面入队时就要标记;找到最短结局后仍需完成搜索;全可达性要统计所有页面。
复习问题
- 为什么 BFS 第一个遇到的结局可信,而 DFS 不一定?
- 为什么找到最短结局后还要继续搜索?
- 如果题目计算“选择次数”而不是“页面数”,初始化应如何改变?
下一步
下一步可以深入理解 BFS 为什么保证最短路径,再练习在写代码之前先把图模型讲清楚。
来源及延伸阅读
- Official CEMC problem set: https://cemc.uwaterloo.ca/sites/default/files/documents/2018/2018CCCJrProblemSet.html
- Python
collections.deque: https://docs.python.org/3/library/collections.html#collections.deque
延伸阅读
Questions or feedback?
Have a question about this article or want to suggest an improvement? Send us a private message.
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。