
CP Weekly Challenge
USACO 2020 December Bronze Daisy Chains Solution: Bounded Enumeration with Exact Average Checks
Enumerate every interval, test whether its average is an integer, and check whether that average appears inside the interval.
竞赛编程每周挑战
USACO 2020 December Bronze Daisy Chains 题解:有界枚举 + 整除判定,N=100 时立方也是满分解法
枚举所有连续区间,先判断平均值是否为整数,再检查区间内是否存在这朵“平均花”。
A row of N daisies, flower i with p_i petals. Bessie photographs every contiguous interval [i, j] — how many photos contain an "average flower": one whose petal count equals the exact average of the interval? USACO 2020 December Bronze Problem 2, Daisy Chains, is a gentle enumeration lesson. What it teaches is not a clever optimization but something more important: read the bounds before choosing an algorithm. N ≤ 100, so there are only about 5050 intervals — "cubic" is a legal, full-marks solution here.
Where This Fits in the USACO / CP DSA Map
- Level: USACO Bronze, Difficulty Band L1
- Pattern: Bounded Enumeration + Exact Average Check
- Prerequisite: nested loops, the modulo operator
%, interval sums (Python basics: input, operators, and conditions, Python list fundamentals) - What this teaches: estimate the work from the stated bounds — 5050 intervals × 100 checks ≈ 5×10⁵, so cubic complexity still scores full marks; correctness first, elegance second
- Where it appears again: the USACO Bronze simulation line (unit B2-00), the Mixing Milk sibling (in production review), and as the mirror image of CPW-011 Nailed It! — there N=10⁶ forced a move to the value domain, here N=100 allows plain enumeration
What to Study Next
- Related CP Weekly problems: USACO 2018 December Bronze Mixing Milk (in production review), CCC 2017 J5/S3 Nailed It! (the value-domain counterpart when N is huge)
- Related Python / C++ foundations: Python Basics: Input, Operators, and Conditions, Python Lists: append() vs +
- Related DSA note: brute force and complexity intro (planned)
What the Problem Is Asking
The first line gives N (1 ≤ N ≤ 100), the second N petal counts p_i (1 ≤ p_i ≤ 1000). Every interval [i, j] gets one photo. A photo has an "average flower" if some flower in the interval has exactly P petals, where P is the interval's average. Output the number of qualifying photos.
Official sample: N=4, petals [1 1 2 3] → output 6: the 4 single-flower photos qualify; interval (1,2) averages 1 and a 1 is present; (2,4), i.e. [1,2,3], averages 2 and a 2 is present.
Two tests, both required: the average must be an integer (the sum divisible by the length), and some flower in the interval must equal it.
Where Beginners Often Get Stuck
- Overthinking: seeing "average" triggers prefix-sum optimizations, sliding windows, or math — and traps you. N=100; a correct brute force is already full marks.
- Skipping the "average must be present" test: counting on
total % length == 0alone. Averages like 4 in the interval [2,4,6] do not qualify, because no 4 is in the photo. - Floating-point averages: comparing with
total / lengthinvites precision bugs (especially in C++). Test divisibility first, then use integer division. - Off-by-one enumeration: left from 0 to N−1, right from left to N−1; single-flower intervals (i,i) count too.
Core Algorithm Idea
All photos = all contiguous intervals, N(N+1)/2 of them. Answer two questions per interval:
Is the sum divisible by the length? -> total % length == 0
Does some flower equal that average? -> average appears in petals[i..j]
Both yes → count the photo. The complexity ledger is the point: at N=100 there are ~5050 intervals; each needs one divisibility test plus at most 100 lookups, about 5×10⁵ operations in total — milliseconds in any language. That is why Bronze problems keep N small: they test whether you can write a clean enumeration, not whether you can optimize.
One detail worth keeping: compute the average, then scan the interval for it. Since p_i ≥ 1 and the average ≥ 1, you can stop at the first hit — a micro-optimization that is irrelevant at this scale.
State / Data Structure Design
total: the sum of [left, right], updated in O(1) as right advances.length = right - left + 1: the interval size.photos: the qualifying-photo counter.
Algorithm Steps
- Read N and the petal array.
- Set
photos = 0. - For each left from 0 to N−1:
- Set
total = 0; - For each right from left to N−1: add
petals[right]into total; compute length; iftotal % length == 0, let average = total // length; if average appears inpetals[left..right], increment photos.
- Print
photos.
Sample Check with the Official Data
Verifying the sample [1 1 2 3] interval by interval (✓ = has an average flower):
| Interval | Content | Sum | Len | Avg | Present? | Counts |
|---|---|---|---|---|---|---|
| (1,1) | [1] | 1 | 1 | 1 | ✓ | 1 |
| (2,2) | [1] | 1 | 1 | 1 | ✓ | 1 |
| (3,3) | [2] | 2 | 1 | 2 | ✓ | 1 |
| (4,4) | [3] | 3 | 1 | 3 | ✓ | 1 |
| (1,2) | [1,1] | 2 | 2 | 1 | ✓ | 1 |
| (2,3) | [1,2] | 3 | 2 | 1.5 | not integer | 0 |
| (3,4) | [2,3] | 5 | 2 | 2.5 | not integer | 0 |
| (1,3) | [1,1,2] | 4 | 3 | 4/3 | not integer | 0 |
| (2,4) | [1,2,3] | 6 | 3 | 2 | ✓ | 1 |
| (1,4) | [1,1,2,3] | 7 | 4 | 1.75 | not integer | 0 |
Total 6, matching the official output. This table also models a dry run: hand-check it before submitting.
Python Solution
n = int(input())
petals = list(map(int, input().split()))
photos = 0
for left in range(n):
total = 0
for right in range(left, n):
total += petals[right]
length = right - left + 1
if total % length != 0:
continue
average = total // length
if average in petals[left:right + 1]:
photos += 1
print(photos)
The outer-left, inner-right loops cover every interval; total accumulates inside the inner loop so sums are never recomputed; the divisibility test runs before the slice membership test — cheapest condition first.
C++ Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> petals(n);
for (int i = 0; i < n; i++) {
cin >> petals[i];
}
int photos = 0;
for (int left = 0; left < n; left++) {
int total = 0;
for (int right = left; right < n; right++) {
total += petals[right];
int length = right - left + 1;
if (total % length != 0) {
continue;
}
int average = total / length;
for (int k = left; k <= right; k++) {
if (petals[k] == average) {
photos += 1;
break;
}
}
}
}
cout << photos << '\n';
return 0;
}
Mirrors the Python version step by step; break on the first matching flower; integer arithmetic throughout, no floating point anywhere.
Why the Algorithm Is Correct
- Intervals are enumerated exactly once: left runs 0..N−1 and right runs left..N−1, generating each of the N(N+1)/2 contiguous intervals exactly once.
- The divisibility test is exact: total % length == 0 holds if and only if the average is an integer; a fractional average can never equal a petal count, which is an integer.
- The membership test matches the definition: some petals[k] == average is exactly the statement "the photo contains an average flower"; stopping at the first hit does not change correctness.
- The count is correct: each interval is judged independently and contributes one when both tests pass, so photos equals the number of qualifying photos.
Complexity Analysis
- Time O(N³) in the worst case (O(N²) intervals × O(N) membership scan); at N=100 that is about 5×10⁵ operations — measured in milliseconds for both languages.
- Space O(N): the petal array only.
- Contrast for learning: CCC's Nailed It! pushes N to 10⁶ and brute force dies instantly — "read the bounds first" is only half the lesson until you have seen both problems.
Common Mistakes
- Forgetting single-flower intervals: (i,i) are photos too, and always qualify, contributing N.
- Skipping the "average must be present" test: divisibility alone is not enough.
- Floating-point averages: use integer division after the divisibility check.
- Enumeration off-by-one: right starting at 0 or missing right == left duplicates or drops intervals.
- Over-optimizing: reaching for sliding-window math first often writes bugs; at Bronze's N=100, brute force is the intended solution.
Review Questions
- Why is O(N³) full marks here? Compute the operation count at N=100.
- If N became 10⁵ with the same petal bounds, would this algorithm survive? What would you change?
- Which of the two tests should run first, and why is the order cheaper?
- Why does a single-flower interval always qualify? What does that say about the definition of average?
- Hand-compute the answer for
[1 2 1 2], then verify by running. (Hint: count singletons first, then pairs.)
一排 N 朵雏菊,每朵有 p_i 片花瓣。Bessie 给每一个连续区间 [i, j] 拍一张照片——问有多少张照片里存在"平均花":某朵花的花瓣数恰好等于区间内所有花的平均数。USACO 2020 年 12 月 Bronze 第 2 题 Daisy Chains 是道温柔的枚举题,它教的不是巧妙优化,而是更重要的一课:先看清数据上限,再决定算法。N ≤ 100,所有区间只有约 5050 个,"立方"在这里是合法且满分的做法。
本题在 USACO / CP DSA 地图里的位置
- Level: USACO Bronze, Difficulty Band L1
- Pattern: Bounded Enumeration + Exact Average Check(有界枚举 + 整除判定)
- Prerequisite: 嵌套循环、整除
%、区间求和(Python 基础:输入、运算符与条件、Python 列表基础) - What this teaches: 用题目给出的上限估算运算量——5050 个区间 × 100 次检查 ≈ 5×10⁵,立方复杂度也能满分;写对先于写好
- Where it appears again: USACO Bronze 模拟线(B2-00 单元)、Mixing Milk 姊妹篇(production 复核中)、与 CPW-011 Nailed It! 构成对照——那边 N=10⁶ 必须搬值域,这边 N=100 直接枚举
下一步推荐
如果你已经理解这道题,可以继续看:
- 相关 CP Weekly 真题:USACO 2018 December Bronze Mixing Milk 题解(production 复核中)、CCC 2017 J5/S3 Nailed It! 题解(N 很大时的值域压缩对照)
- 相关 Python / C++ 基础:Python 基础:输入、运算符与条件、Python 列表 append() 和 + 的区别
- 相关 DSA 专题:暴力与复杂度入门短笔记(计划中)
题目要我们做什么
第一行 N(1 ≤ N ≤ 100),第二行 N 个花瓣数 p_i(1 ≤ p_i ≤ 1000)。对每个满足 1 ≤ i ≤ j ≤ N 的区间拍一张照。一张照片有"平均花",当且仅当区间内某朵花的花瓣数 P 恰好等于区间平均值。输出有平均花的照片数。
官方样例:N=4,花瓣 [1 1 2 3] → 输出 6:4 张单花照片都合格;区间 (1,2) 平均 1,花 1 在场;(2,4) 即 [1,2,3] 平均 2,花 2 在场;其余区间平均值不是整数或平均值不在区间内。
注意两个判定缺一不可:平均值必须是整数(总和能被长度整除),且区间内必须有花恰好等于这个平均值。
初学者容易卡在哪里
- 想复杂了:看到"平均数"就去想前缀和优化、滑窗、数学推导,结果把自己绕进去。这题 N=100,先把暴力写对就是满分。
- 漏掉"平均值必须在区间内":只判
total % length == 0就去计数,忘了照片里得有那朵花。样例区间 (1,4)=[1,1,2,3] 平均 1.75,不整除;但若换成 [2,4,6] 平均 4,4 不在区间里也不算。 - 平均值算成浮点数:用
total / length得浮点数再比较,精度会咬人(尤其 C++)。先判整除,再用整数除法。 - 区间漏数或重复:左端点 i 从 1 到 N、右端点 j 从 i 到 N,单花区间 (i,i) 也必须计入。
核心算法概念
全部照片 = 全部连续区间,数量是 N(N+1)/2。对每个区间回答两个判断:
总和能被区间长度整除吗? -> total % length == 0
区间内有没有花等于这个平均值? -> average 在 petals[i..j] 中
两个都"是",这张照片计入答案。关键在复杂度账:N=100 时区间约 5050 个,每个区间一次整除判断加最多 100 次查找,合计约 5×10⁵ 次基本运算——任何语言都在毫秒级。这就是为什么 Bronze 题目常给很小的 N:它在考你能不能干净地把枚举写出来,而不是考优化技巧。
另一个值得记的细节是"平均值存在性"的检查方式:先算 average,再线性扫一遍区间。因为 p_i ≥ 1 且平均值 ≥ 1,扫到就停(早退)还能再省一点——不过在这个量级下,省不省都满分。
状态定义
total:当前区间 [left, right] 的花瓣总和,随 right 右移累加(O(1) 更新)。length = right - left + 1:区间长度。photos:合格照片计数。
算法步骤
- 读入 N 和花瓣数组。
photos = 0。- 对每个 left 从 0 到 N−1:
total = 0;- 对每个 right 从 left 到 N−1:
total += petals[right];length = right - left + 1;若total % length == 0,令average = total // length,若 average 出现在petals[left..right]中则photos += 1。
- 输出
photos。
官方样例核对
用样例 [1 1 2 3] 逐区间核对(✓ = 有平均花):
| 区间 | 内容 | 和 | 长度 | 平均 | 平均花在区间? | 计入 |
|---|---|---|---|---|---|---|
| (1,1) | [1] | 1 | 1 | 1 | ✓ | 1 |
| (2,2) | [1] | 1 | 1 | 1 | ✓ | 1 |
| (3,3) | [2] | 2 | 1 | 2 | ✓ | 1 |
| (4,4) | [3] | 3 | 1 | 3 | ✓ | 1 |
| (1,2) | [1,1] | 2 | 2 | 1 | ✓ | 1 |
| (2,3) | [1,2] | 3 | 2 | 1.5 | 不整除 | 0 |
| (3,4) | [2,3] | 5 | 2 | 2.5 | 不整除 | 0 |
| (1,3) | [1,1,2] | 4 | 3 | 4/3 | 不整除 | 0 |
| (2,4) | [1,2,3] | 6 | 3 | 2 | ✓ | 1 |
| (1,4) | [1,1,2,3] | 7 | 4 | 1.75 | 不整除 | 0 |
合计 6,与官方输出一致。这张表也示范了 dry run 的用法:写完代码先照表手算一遍再提交。
Python 解法
n = int(input())
petals = list(map(int, input().split()))
photos = 0
for left in range(n):
total = 0
for right in range(left, n):
total += petals[right]
length = right - left + 1
if total % length != 0:
continue
average = total // length
if average in petals[left:right + 1]:
photos += 1
print(photos)
要点:外层 left、内层 right 的双循环覆盖所有区间;total 在内层累加,避免重复求和;average in petals[left:right+1] 是切片查找,N=100 下毫无压力;整除判断放在切片查找之前,把最便宜的条件放前面。
C++ 解法
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> petals(n);
for (int i = 0; i < n; i++) {
cin >> petals[i];
}
int photos = 0;
for (int left = 0; left < n; left++) {
int total = 0;
for (int right = left; right < n; right++) {
total += petals[right];
int length = right - left + 1;
if (total % length != 0) {
continue;
}
int average = total / length;
for (int k = left; k <= right; k++) {
if (petals[k] == average) {
photos += 1;
break;
}
}
}
}
cout << photos << '\n';
return 0;
}
要点:结构与 Python 版一一对应;找到平均花立即 break;全程整数运算,没有浮点精度问题。
正确性说明
- 区间不重不漏:left 取遍 0..N−1,right 取遍 left..N−1,恰好生成全部 N(N+1)/2 个连续区间各一次。
- 整除判断正确:total % length == 0 当且仅当平均值是整数;非整数平均值不可能等于任何一朵花的花瓣数(花瓣数是整数)。
- 成员判断正确:区间内存在 petals[k] == average,正是"照片里有平均花"的定义;扫描到即停不影响正确性。
- 计数正确:每个区间独立判定,合规则 photos 加一,因此 photos 等于合格照片总数。
复杂度分析
- 时间 O(N³) 上界(区间数 O(N²),每区间成员查找 O(N)),N=100 时约 5×10⁵ 次基本运算,实测双解法毫秒级。
- 空间 O(N):只存花瓣数组。
- 对照学习:同样考"区间平均",CCC 的 Nailed It! 把 N 给到 10⁶,暴力立刻失效——先看上限再选算法这句话,两道题合起来才完整。
常见错误
- 忘记单花区间:(i,i) 也算照片,且必然合格,贡献 N 张。
- 漏判"平均值在场":只判整除就计数。
- 浮点平均:用
total / length浮点比较,边界出错;整数题全程用整数。 - 区间枚举错位:right 从 0 开始或漏掉 right == left,导致区间重复或缺失。
- 过度优化:先想滑窗数学推导反而写错;Bronze 的 N=100 下,暴力就是正解。
复习问题
- 为什么这题用 O(N³) 是满分?把 N=100 时的运算量算出来。
- 如果 N 改成 10⁵、花瓣数不变,这个算法还成立吗?你会怎么改?
- "平均值必须是整数"和"区间内要有这朵花"两个条件,哪个放前面判断更省?为什么?
- 单花区间为什么必然合格?这和"平均值定义"有什么关系?
- 用样例
[1 2 1 2]手算答案,再运行验证。(提示:先数单花,再看两两区间。)
Questions or feedback?
Have a question about this article or want to suggest an improvement? Send us a private message.
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。