
CP 每周编程挑战
CCC 2013 J5/S3 Chances of Winning Solution: Enumerate Every Remaining Result
Model every unplayed game as a three-way decision, then count all complete futures where the favourite team finishes strictly first.
竞赛编程每周挑战
CCC 2013 J5/S3 Chances of Winning 题解:枚举剩余比赛的所有结果
把每场未完成比赛建模为三选一决定,再统计支持队伍严格第一的所有完整未来。
This problem looks like a standings calculation, but its real question is about the future: how can we count every possible set of remaining results without missing or duplicating one?
Treat each unplayed game as a three-way decision: the first team wins, the second team wins, or the game is tied. There are at most six unplayed games, so the complete search tree has at most 3^6 = 729 leaves. A direct recursive search is clear, reliable, and easily fast enough.
The Core Idea
Compute the points from games already played, list the remaining games, try all three outcomes for each one, and count leaves where the favourite team finishes strictly above all three opponents.
本题在 CCC 数据结构与算法路线图中的位置
| Item | Description |
|---|---|
| Level | CCC Junior J5 / introductory Senior S3 search |
| Pattern | Complete search, recursive enumeration, apply-recurse-undo |
| Prerequisites | Lists, sets, functions, recursion, exponential growth |
| What this teaches | Translate “all possibilities” into a state tree and prove coverage |
| Where it appears again | Permutations, backtracking, game states, constraint search, dynamic programming |
What to Study Next
- Read “Why Should You Write Brute Force First?” to practise defining a complete search space.
- Compare this recursive decision tree with the interval loops in Daisy Chains.
- Later, study CCC 2015 J5 Pi Day to see how repeated states lead from search to dynamic programming.
Problem Restatement
Four teams play a six-game round robin. A win gives 3 points to the winner, a loss gives 0, and a tie gives 1 point to each team. Some games have already been played. Count how many assignments of results to the remaining games make the favourite team finish with strictly more points than every other team. A tie for first is not enough.
The six possible games are:
(1,2) (1,3) (1,4) (2,3) (2,4) (3,4)
Price the Search Before Coding
If G games have been played, then R = 6 - G remain. Each remaining game has three possible point outcomes, so there are 3^R complete futures. In the worst case, R = 6, giving only 729 leaves.
That small bound is the key constraint. Complete search is not a desperate fallback here; it is the intended shape of a dependable solution.
Define the State
The future depends only on:
- the index
iof the next remaining game; - the current point totals of the four teams.
We can write the state as (i, p1, p2, p3, p4). Two paths that reach the same state have exactly the same possible completions, so memoization is safe.
The Three Branches
For a current game (a, b), try (3,0), (0,3), and (1,1). Each branch follows the same discipline:
apply the points -> recurse -> undo the points
The undo step matters. Without it, one branch changes the starting state of the next branch.
Terminal Test and Safe Pruning
At a leaf, the favourite must have more points than every opponent. Use strict > because a tie for first does not count.
We can also reject a state early. If the favourite has p points and appears in q remaining games, its final score is at most p + 3q. If an opponent already has at least that many points, the favourite can never finish strictly first. The comparison is >=, because equality would still be only a tie.
Python and C++ Implementations
The English page includes complete standalone implementations as well. These baseline versions keep the same remaining-game model and apply-recurse-undo search, without requiring memoization to fit the official limits.
Python
favourite = int(input())
played_count = int(input())
all_games = [
(1, 2), (1, 3), (1, 4),
(2, 3), (2, 4), (3, 4)
]
points = [0] * 5
played = []
# Process games already played
for i in range(played_count):
a, b, score_a, score_b = map(int, input().split())
played.append((min(a, b), max(a, b)))
if score_a > score_b:
points[a] += 3
elif score_b > score_a:
points[b] += 3
else:
points[a] += 1
points[b] += 1
# Find remaining games
remaining = []
for game in all_games:
if game not in played:
remaining.append(game)
# Start with current standings
states = [points]
# Simulate all possible outcomes
for a, b in remaining:
new_states = []
for state in states:
# Team A wins
p = state.copy()
p[a] += 3
new_states.append(p)
# Team B wins
p = state.copy()
p[b] += 3
new_states.append(p)
# Tie
p = state.copy()
p[a] += 1
p[b] += 1
new_states.append(p)
states = new_states
# Count outcomes where favourite wins outright
answer = 0
for state in states:
wins = True
for team in range(1, 5):
if team != favourite and state[team] >= state[favourite]:
wins = False
break
if wins:
answer += 1
print(answer)
C++
#include <iostream>
using namespace std;
int allGames[6][2] = {
{1, 2}, {1, 3}, {1, 4},
{2, 3}, {2, 4}, {3, 4}
};
int favourite, playedCount;
int points[5];
int remainingGames[6][2];
int remainingCount;
int search(int i) {
if (i == remainingCount) {
for (int team = 1; team <= 4; team++) {
if (team != favourite && points[favourite] <= points[team]) {
return 0;
}
}
return 1;
}
int a = remainingGames[i][0];
int b = remainingGames[i][1];
int total = 0;
points[a] += 3;
total += search(i + 1);
points[a] -= 3;
points[b] += 3;
total += search(i + 1);
points[b] -= 3;
points[a]++;
points[b]++;
total += search(i + 1);
points[a]--;
points[b]--;
return total;
}
int main() {
cin >> favourite >> playedCount;
bool played[5][5] = {};
for (int i = 0; i < playedCount; i++) {
int a, b, scoreA, scoreB;
cin >> a >> b >> scoreA >> scoreB;
played[a][b] = true;
if (scoreA > scoreB) points[a] += 3;
else if (scoreB > scoreA) points[b] += 3;
else {
points[a]++;
points[b]++;
}
}
for (auto &game : allGames) {
if (!played[game[0]][game[1]]) {
remainingGames[remainingCount][0] = game[0];
remainingGames[remainingCount][1] = game[1];
remainingCount++;
}
}
cout << search(0) << '\n';
}
Why the Algorithm Is Correct
The remaining-game list contains every unplayed pair exactly once. At each level the search tries all three legal outcomes for the next game, so every complete future appears exactly once. The leaf test matches the statement's strictly-first rule. Memoization combines only states with identical remaining games and scores, and the ceiling prune removes only states whose best possible finish already fails. Therefore the returned count is exactly the number of winning result assignments.
Complexity
With R remaining games, the baseline search takes O(3^R) time and O(R) recursion space. Since R <= 6, there are at most 729 leaves. Memoization and pruning reduce the actual work further but are not required to make the official limits feasible.
常见错误
- Accepting a tie for first by using
>=at the leaf. - Forgetting to undo one or both score changes after recursion.
- Trying only two outcomes and omitting ties.
- Adding the raw game score instead of tournament points.
- Using
>instead of>=in the ceiling prune.
Review Questions
- Why are there at most
3^6leaves? - Why must the state include both the game index and all four point totals?
- What goes wrong if an update is not undone?
- Why does the leaf use
>while the prune uses>=? - Why might the same search become too large with eight teams?
这道题看起来像积分计算,真正的难点却是:未来还没有发生,我们怎样把所有未来都数一遍,而且一个也不漏?
答案是把每场未进行的比赛看成一个三选一决定:第一队赢、第二队赢、平局。最多只剩 6 场,因此完整搜索树最多有 3^6 = 729 个叶子。这个规模非常小,直接递归枚举就是可靠、清楚而且足够快的解法。
一句话结论
先计算已完成比赛的积分,列出剩余比赛;递归为每场剩余比赛尝试三种结果,到叶子时检查支持的队伍是否严格高于另外三队。
这道题在 CCC DSA Map 中的位置
| 项目 | 内容 |
|---|---|
| Level | CCC Junior J5 / Senior S3 入门搜索 |
| Pattern | Complete Search、递归枚举、apply-recurse-undo |
| Prerequisite | 列表、集合、函数、递归、指数规模估算 |
| What this teaches | 把“所有可能”翻译成状态树,并证明没有漏掉或重复 |
| Where it appears again | 排列组合、回溯、游戏状态、约束搜索、动态规划状态设计 |
下一步推荐
- 先读 DSA 短文《为什么要先写 brute force?》,学会定义完整搜索空间。
- 复习
CPW-USACO-002Daisy Chains,比较“循环枚举区间”和“递归枚举决定”。 - 之后挑战 CCC 2015 J5 Pi Day,观察状态搜索如何进一步变成动态规划。
题意
四支队伍进行单循环比赛,一共有 6 场:
(1,2) (1,3) (1,4) (2,3) (2,4) (3,4)
计分规则:
- 胜者得 3 分,负者得 0 分;
- 平局双方各得 1 分;
- 只有当你支持的队伍最终积分严格高于其他三队时,才算夺冠;并列第一不算。
输入会告诉我们支持哪支队伍,以及已经完成的比赛和比分。输出剩余比赛的所有可能结果中,有多少种会让支持的队伍夺冠。
先把搜索空间算清楚
设已经完成 G 场,还剩:
R = 6 - G
每场剩余比赛有三种积分结果,因此叶子数量是:
3^R
最坏情况 G = 0,所以只有:
3^6 = 729
729 个完整未来很小。这里不需要贪心,也不需要猜公式;把全部未来枚举完,反而是最稳的方案。
搜索状态是什么?
递归过程中,未来只取决于两件事:
- 当前准备处理第几场剩余比赛;
- 四支队伍当前各有多少分。
可以把状态写成:
(i, p1, p2, p3, p4)
其中 i 是下一场比赛的位置。只要这五个值相同,后面可以产生的未来就完全相同。
三个递归分支
假设当前比赛是 (a, b):
| 结果 | a 的积分变化 |
b 的积分变化 |
|---|---|---|
a 胜 |
+3 |
+0 |
b 胜 |
+0 |
+3 |
| 平局 | +1 |
+1 |
每个分支都遵循同一套动作:
修改积分 → 递归下一场 → 恢复积分
最后一步叫 undo。如果忘记恢复,下一条分支会继承上一条分支的分数,搜索树就被污染了。
叶子条件
当 i == R,所有剩余比赛都已经分配结果。此时检查:
points[T] > points[other]
必须对另外三支队伍都成立。这里是 >,不能写成 >=,因为并列第一不算夺冠。
一个安全剪枝
假设支持的队伍当前有 p 分,并且还会参加 q 场比赛。即使全部获胜,它最多也只能得到:
ceiling = p + 3q
如果某个对手当前已经有至少 ceiling 分,那么支持的队伍不可能严格超过它,这个子树可以立即返回 0。
注意比较符号是 >=:对手等于上限时,最好情况也只是并列第一,仍然失败。
Python 参考实现
favourite = int(input())
played_count = int(input())
all_games = [
(1, 2), (1, 3), (1, 4),
(2, 3), (2, 4), (3, 4)
]
points = [0] * 5
played = []
# Process games already played
for i in range(played_count):
a, b, score_a, score_b = map(int, input().split())
played.append((min(a, b), max(a, b)))
if score_a > score_b:
points[a] += 3
elif score_b > score_a:
points[b] += 3
else:
points[a] += 1
points[b] += 1
# Find remaining games
remaining = []
for game in all_games:
if game not in played:
remaining.append(game)
# Start with current standings
states = [points]
# Simulate all possible outcomes
for a, b in remaining:
new_states = []
for state in states:
# Team A wins
p = state.copy()
p[a] += 3
new_states.append(p)
# Team B wins
p = state.copy()
p[b] += 3
new_states.append(p)
# Tie
p = state.copy()
p[a] += 1
p[b] += 1
new_states.append(p)
states = new_states
# Count outcomes where favourite wins outright
answer = 0
for state in states:
wins = True
for team in range(1, 5):
if team != favourite and state[team] >= state[favourite]:
wins = False
break
if wins:
answer += 1
print(answer)
C++ 参考实现
#include <cstring>
#include <iostream>
using namespace std;
int allGames[6][2] = {
{1, 2}, {1, 3}, {1, 4},
{2, 3}, {2, 4}, {3, 4}
};
int favourite, playedCount;
int points[5];
int remainingGames[6][2];
int remainingCount;
int memo[7][10][10][10][10];
int search(int i) {
int &answer = memo[i][points[1]][points[2]][points[3]][points[4]];
if (answer != -1) return answer;
if (i == remainingCount) {
for (int team = 1; team <= 4; team++) {
if (team != favourite && points[favourite] <= points[team]) {
return answer = 0;
}
}
return answer = 1;
}
int gamesLeftForFavourite = 0;
for (int game = i; game < remainingCount; game++) {
if (remainingGames[game][0] == favourite ||
remainingGames[game][1] == favourite) {
gamesLeftForFavourite++;
}
}
int ceiling = points[favourite] + 3 * gamesLeftForFavourite;
for (int team = 1; team <= 4; team++) {
if (team != favourite && points[team] >= ceiling) {
return answer = 0;
}
}
int a = remainingGames[i][0];
int b = remainingGames[i][1];
int total = 0;
points[a] += 3;
total += search(i + 1);
points[a] -= 3;
points[b] += 3;
total += search(i + 1);
points[b] -= 3;
points[a]++;
points[b]++;
total += search(i + 1);
points[a]--;
points[b]--;
return answer = total;
}
int main() {
cin >> favourite >> playedCount;
bool played[5][5] = {};
for (int i = 0; i < playedCount; i++) {
int a, b, scoreA, scoreB;
cin >> a >> b >> scoreA >> scoreB;
played[a][b] = true;
if (scoreA > scoreB) points[a] += 3;
else if (scoreB > scoreA) points[b] += 3;
else {
points[a]++;
points[b]++;
}
}
remainingCount = 0;
for (auto &game : allGames) {
if (!played[game[0]][game[1]]) {
remainingGames[remainingCount][0] = game[0];
remainingGames[remainingCount][1] = game[1];
remainingCount++;
}
}
memset(memo, -1, sizeof(memo));
cout << search(0) << '\n';
}
正确性说明
- 六场比赛的队伍对固定,程序准确删除已经完成的比赛,所以
remaining恰好包含所有未完成比赛。 - 每场未完成比赛只有三种积分结果,递归对每场都建立三个分支,因此每一种未来结果组合都会出现。
- 每层只为当前比赛选择一次结果,所以同一种结果组合不会重复出现。
- 叶子检查与题目“严格高于其他三队”的定义完全一致。
- 记忆化只合并
i和四队积分都相同的状态;这样的状态拥有相同的剩余比赛和相同的未来。 - 剪枝只在支持队伍的理论最高分也无法严格超过对手时发生,因此被删除的所有叶子都必然失败。
所以算法统计的恰好是支持队伍最终夺冠的结果组合数。
复杂度
设剩余比赛数为 R:
- 基础枚举时间:
O(3^R); R <= 6,最多 729 个叶子;- 递归空间:
O(R); - 记忆化状态上界很小,四队积分都只在
0..9。
常见错误
1. 把并列第一算成夺冠
叶子必须检查严格大于。>= 会错误接受并列。
2. 忘记撤销积分
每次递归返回后,都要准确减掉刚才增加的积分。
3. 漏掉平局
一场比赛不是只有两种结果。平局双方各得 1 分,是第三个分支。
4. 用实际比分直接累加
比分只决定胜、负、平;积分是 3、0 或 1、1,不是把进球数加入排名。
5. 剪枝写成 >
对手积分等于支持队伍的最高可能积分时,支持队伍仍无法严格第一,所以必须用 >=。
复习问题
- 为什么最多只有
3^6个叶子? - 状态为什么必须同时包含比赛位置和四队积分?
apply-recurse-undo中,undo 少一步会发生什么?- 为什么叶子比较使用
>,剪枝比较却使用>=? - 如果扩展到 8 支队伍,为什么同样的直接枚举可能不再可行?
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。