CCC 2017 J5/S3 Nailed It! Solution: Count Pairs per Height with a Frequency Array



☰

开始北极星测评

CP 每周编程挑战

CCC 2017 J5/S3 Nailed It! Solution: Count Pairs per Height with a Frequency Array

Fix each fence height, count complement pairs with a frequency array, and track how many heights tie for the best fence.

竞赛编程每周挑战

CCC 2017 J5/S3 Nailed It! 题解:固定高度数配对,频率数组把 N² 压到 4 百万

固定栅栏高度,用频率数组统计互补木板对,并计算有多少个高度并列最优。

分享这篇文章

复制链接、使用手机分享、用微信扫码,或通过邮件发送。




邮箱

Tudor has N pieces of wood, each at most 2000 long. Two pieces nail into one board, and a fence requires all its boards to share one length — the "height". The fence's length is its number of boards. The questions: what is the longest fence possible, and how many different heights achieve it? CCC 2017 J5/S3 Nailed It! tempts everyone into enumerating all pairs of pieces — with N up to 10⁶, O(N²) is hopeless. The real unlock: piece lengths have only 2000 possible values. Move pair counting from the items to the value domain, and N² collapses into a constant.

本题在 CCC 数据结构与算法路线图中的位置

  • Level: Junior J5 ≡ Senior S3 (the same problem serves both levels)
  • Pattern: Frequency Array + Complement Pair Counting
  • Prerequisite: arrays and indexing, counting, loops, Big-O basics (Python basics: input, operators, and conditions, Python list fundamentals)
  • What this teaches: when items are many but kinds are few, move pairing from the item domain to the value domain — fix a height, count by complement classes, and sum independent classes
  • Where it appears again: the counting topic (planned), CPW-012 Searching for Strings (planned; the first two sessions of the same notebook build its prerequisites)

What to Study Next

What the Problem Is Asking

Input N (2 ≤ N ≤ 1,000,000) and N piece lengths (1 ≤ L_i ≤ 2000). A board uses exactly two pieces; its length L_i + L_j is the fence's height. A fence needs all boards at one height. Output two integers: the maximum number of boards in any fence, and how many different heights achieve that maximum.

Official sample 1: [1 2 3 4] → height 5 allows two boards (1+4, 2+3), output 2 1.

Official sample 2: [1 10 100 1000 2000] → the longest fence has one board, but 10 different heights work, output 1 10.

Note the question is not "how many pairings exist" but "which height maximizes the board count, and how many heights tie" — two different counting problems.

Where Beginners Often Get Stuck

  • Enumerating all piece pairs: at N=10⁶ there are about 5×10¹¹ pairs; hopeless under a 2-second limit. Pairs must be counted by length kind, not by piece identity.
  • Treating the board count as a combination count: three pieces of length 2 make exactly one board of height 4 (2+2 uses two pieces), not C(3,2)=3 — a piece cannot be reused.
  • Depleting stock between heights: heights are alternative plans, each counted on its own; deleting pieces from the frequency table after one height corrupts the next.
  • Double counting complements: (a,b) and (b,a) are one class; constrain to a ≤ b so each class is visited once.
  • Missing the a=b case: two equal pieces form a legal board, contributing freq[a] // 2, not min.

Core Algorithm Idea

Count by length: freq[x] = how many pieces have length x. The value domain L ≤ 2000, so freq is a table of size 2001.

Fix a height h; a piece of length a has exactly one possible partner: h−a. Lengths split into complement classes: (1, h−1), (2, h−2), … Each piece belongs to exactly one class, and classes share no pieces, so their board counts add directly:

  • Inside a class with a < b: pair the a-pieces with the b-pieces, contributing min(freq[a], freq[b]);
  • Inside a class with a = b: pair within one length, contributing freq[a] // 2.

Scan every height h from 2 to 2L, keep the running maximum best, and count how many heights tie it as ways. The inner scan visits only a ≤ b, for about L²/2 ≈ 2×10⁶ class checks in total — the N² disaster compressed into a constant.

State / Data Structure Design

  • freq[0..L]: piece counts per length, where L = max input length (≤ 2000).
  • best: the maximum board count over all heights.
  • ways: how many heights achieve best.

No piece identities, no pairing lists — the answer is fully determined by the frequency table.

Algorithm Steps

  1. Read N and the N lengths, build freq, and record the maximum length L.
  2. Set best = 0; ways = 0.
  3. For each height h from 2 to 2L:
  • Set pairs = 0; for each a from 1 to L, let b = h − a, skipping b < a or b > L;
  • If a = b, add freq[a] // 2; otherwise add min(freq[a], freq[b]);
  • If pairs > best, update best and reset ways to 1; if pairs == best, increment ways.
  1. printbest ways.

Sample Check with the Official Data

Verify with the notebook's hand-computed table (pieces [1,1,2,2,3,3], L=3):

Height h Complement classes (a≤b) Boards per class Total
2 (1,1) 2//2=1 1
3 (1,2) min(2,2)=2 2
4 (1,3)=2; (2,2)=2//2=1 2+1 3
5 (2,3) min(2,2)=2 2
6 (3,3) 2//2=1 1

The maximum 3 is reached by exactly one height, 4 → output 3 1. Both official samples check out too: [1 2 3 4] → 2 1, [1 10 100 1000 2000] → 1 10. Two more boundaries worth memorizing: [2 2] → 1 1 and [2 2 2] → 1 1 (three 2s still make one board).

Python 解法

n = int(input())
boards = list(map(int, input().split()))

max_len = max(boards)
freq = [0] * (max_len + 1)

for x in boards:
    freq[x] += 1

best = 0
ways = 0

for height in range(2, 2 * max_len + 1):
    pairs = 0

    for a in range(1, max_len + 1):
        b = height - a
        if b < a or b > max_len:
            continue

        if a == b:
            pairs += freq[a] // 2
        else:
            pairs += min(freq[a], freq[b])

    if pairs > best:
        best = pairs
        ways = 1
    elif pairs == best:
        ways += 1

print(best, ways)

This matches the curriculum notebook (p2005, Session 3) reference implementation.

C++ 解法

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;

    vector<int> boards(n);
    int maxLen = 0;
    for (int i = 0; i < n; i++) {
        cin >> boards[i];
        maxLen = max(maxLen, boards[i]);
    }

    vector<int> freq(maxLen + 1, 0);
    for (int x : boards) {
        freq[x]++;
    }

    int best = 0;
    int ways = 0;
    for (int height = 2; height <= 2 * maxLen; height++) {
        int pairs = 0;

        for (int a = 1; a <= maxLen; a++) {
            int b = height - a;
            if (b < a || b > maxLen) {
                continue;
            }

            if (a == b) {
                pairs += freq[a] / 2;
            } else {
                pairs += min(freq[a], freq[b]);
            }
        }

        if (pairs > best) {
            best = pairs;
            ways = 1;
        } else if (pairs == best) {
            ways++;
        }
    }

    cout << best << " " << ways << '\n';
    return 0;
}

Mirrors the curriculum pseudocode step by step; int suffices for counting (N ≤ 10⁶) and for the accumulated board counts; add <algorithm> explicitly if your toolchain does not pull min transitively.

Why the Algorithm Is Correct

  • Each piece belongs to exactly one complement class at a fixed height: classes are the unordered pairs {a, h−a}; scanning a from 1 to L visits each once without overlap; the a ≤ b constraint guarantees a single visit.
  • The per-class contribution is maximal: with a < b the two length groups pair one-to-one for at most min(freq[a], freq[b]) boards; with a = b the group pairs within itself for at most freq[a] // 2. No better is possible inside a class.
  • Class contributions can be summed: complement classes share no pieces, so pieces used by one class do not affect another; the maximum boards at this height equals the sum of class contributions.
  • Heights are exclusive; ties must be counted: different heights are different plans, each maximized independently into best; every height equal to best contributes to ways, handled by the else-if branch.

Therefore the printed best ways is exactly the requested longest fence length and the number of tied heights.

复杂度分析

  • Time O(N + L²): table building O(N); the full height scan is about L²/2 ≈ 2×10⁶ class checks (L ≤ 2000). At N=10⁶, reading takes about half the time.
  • Space O(N + L): the read buffer stores N lengths (stream reading would drop this to O(L)); the frequency table is O(L).
  • Measured on this machine: C++ finishes the N=10⁶ random case well under one second; the curriculum CPython version sits in the seconds range — under the official 2-second limit, submit C++; use Python to learn the algorithm. (Exact numbers in qa.md.)

常见错误

  1. Enumerating piece pairs: O(N²) at N=10⁶ is about 5×10¹¹ operations — hopeless.
  2. Counting C(3,2)=3 boards from three equal pieces: a piece is used once; the a=b class contributes freq[a] // 2.
  3. Forgetting the a ≤ b constraint: (a,b) and (b,a) are one class, so every height doubles.
  4. Reusing the frequency table across heights: heights are independent plans; never mutate freq between them.
  5. Output format: the task wants "longest length + number of tied heights" as two integers — not a list of plans, not the total pair count.

Review Questions

  1. Why does each length a need only the partner h−a at a fixed height h? Draw the 1..L number line to show why complement classes never overlap or miss.
  2. Why do three pieces of length 2 make one board of height 4, not three? Which line of code encodes "a piece is used at most once"?
  3. If boards could be built from any number of pieces, would complement-class counting still apply? Why or why not?
  4. What goes wrong if the if b < a or b > max_len: continue guard is removed? By how much would every height's count be wrong?
  5. If the length cap L grew from 2000 to 10⁵, would this algorithm still work? What would time and space become? (Hint: is O(L²) still affordable?)

Tudor 有 N 根木料,每根长度不超过 2000。把两根木料钉成一块板,所有板必须一样长(称为高度)才能围成一道栅栏;栅栏的"长度"是板的块数。问:最长能围多长的栅栏?有多少种高度可以达到这个最长?CCC 2017 的 J5/S3 Nailed It! 最容易让人去枚举所有木料配对——N 高达 10⁶,O(N²) 根本跑不动。真正的突破口是:木料的长度只有 2000 种。把"数配对"搬到值域上做,N² 瞬间变成常数级。

本题在 CCC DSA 地图里的位置

  • Level: Junior J5 ≡ Senior S3(同一道题,两个级别共用)
  • Pattern: Frequency Array + Complement Pair Counting(频率数组 + 互补配对计数)
  • Prerequisite: 数组与下标、计数、循环、Big-O 基础(Python 基础:输入、运算符与条件、Python 列表基础)
  • What this teaches: 当"物品很多、种类很少"时,把配对问题从物品域搬到值域:固定高度、按互补类计数、类间独立求和
  • Where it appears again: 计数模式专题 (planned)、CPW-012 Searching for Strings(planned,同一教案的前两个 Session 正好讲它的前置)

下一步推荐

如果你已经理解这道题,可以继续看:

题目要我们做什么

输入 N(2 ≤ N ≤ 1,000,000)和 N 根木料的长度(1 ≤ L_i ≤ 2000)。一块板由恰好两根木料组成,板长 = 两木料长度之和,也就是栅栏的"高度"。栅栏要求所有板同高。输出两个整数:最长栅栏的长度(板数),以及能围出这个最长长度的不同高度个数。

官方样例 1:[1 2 3 4] → 高度 5 可以做两块板(1+4、2+3),输出 2 1。

官方样例 2:[1 10 100 1000 2000] → 最长的栅栏只有一块板,但有 10 种高度都行,输出 1 10。

注意题目问的不是"有多少种配对方式",而是"哪个高度能做的板最多、并列的高度有几个"——这是两道不同的计数题。

初学者容易卡在哪里

  • 枚举所有木料对:N=10⁶ 时约有 5×10¹¹ 对,2 秒时限内毫无希望。配对必须按"长度种类"而不是"木料个体"来数。
  • 把板数当成组合数:三块长度都是 2 的木料,高度 4 只能做 1 块板(2+2 用掉两根),不是 C(3,2)=3——一根木料不能 reused。
  • 不同高度之间互相"扣库存":高度 4 和高度 5 是互斥方案,各算各的;如果算完高度 4 就把频率表里的木料删掉,高度 5 的计数就错了。
  • 互补对重复计数:a 和 b 配,扫到 (a,b) 又扫到 (b,a),同一类被算了两次。要约束 a ≤ b,每类只数一次。
  • 漏掉 a=b 的情形:两根等长木料拼一块板是合法高度,贡献是 freq[a] // 2 而不是 min。

核心算法概念

按长度计数:freq[x] 表示长度为 x 的木料有几根。值域 L ≤ 2000,所以 freq 只是一张长度为 2001 的表。

固定一个高度 h,木料 a 唯一可能的搭档是 h−a。把所有长度分成若干互补类:(1, h−1)、(2, h−2)… 每根木料恰好属于一个类,类与类之间不共享木料,所以各类能做出的板数可以直接相加:

  • 类内 a < b:a 类有 freq[a] 根、b 类有 freq[b] 根,两两配对,贡献 min(freq[a], freq[b]);
  • 类内 a = b:同类内部配对,贡献 freq[a] // 2。

对所有高度 h(2 到 2L)各扫一遍,得到每个高度的板数;维护最大值 best 和达到 best 的高度个数 ways,就是答案。内层只对 a ≤ b 扫,全部高度的总工作量约为 L²/2 ≈ 200 万次类检查——N² 的灾难被压缩成了常数。

状态定义

  • freq[0..L]:各长度木料的根数,L = 输入中的最大长度(≤ 2000)。
  • best:所有高度中最大的板数。
  • ways:达到 best 的高度个数。

不需要保存木料个体,也不需要保存配对清单——答案完全由频率表决定。

算法步骤

  1. 读入 N 与 N 个长度,建 freq 表,记下最大长度 L。
  2. best = 0; ways = 0。
  3. 对每个高度 h 从 2 到 2L:
  • pairs = 0;对每个 a 从 1 到 L,令 b = h − a,跳过 b < a 或 b > L 的情况;
  • a = b 时 pairs += freq[a] // 2,否则 pairs += min(freq[a], freq[b]);
  • pairs > best 则更新 best、ways 重置为 1;pairs == best 则 ways += 1。
  1. 输出 best ways。

官方样例核对

用教案中的手算表核对(木料 [1,1,2,2,3,3],L=3):

高度 h 互补类(a≤b) 各类板数 总板数
2 (1,1) 2//2=1 1
3 (1,2) min(2,2)=2 2
4 (1,3)=2;(2,2)=2//2=1 2+1 3
5 (2,3) min(2,2)=2 2
6 (3,3) 2//2=1 1

最大值 3 由唯一高度 4 取得,输出 3 1。两个官方样例同样复核通过:[1 2 3 4] → 2 1,[1 10 100 1000 2000] → 1 10。再记两个边界:[2 2] → 1 1,[2 2 2] → 1 1(三根 2 也只能做一块板)。

Python 解法

n = int(input())
boards = list(map(int, input().split()))

max_len = max(boards)
freq = [0] * (max_len + 1)

for x in boards:
    freq[x] += 1

best = 0
ways = 0

for height in range(2, 2 * max_len + 1):
    pairs = 0

    for a in range(1, max_len + 1):
        b = height - a
        if b < a or b > max_len:
            continue

        if a == b:
            pairs += freq[a] // 2
        else:
            pairs += min(freq[a], freq[b])

    if pairs > best:
        best = pairs
        ways = 1
    elif pairs == best:
        ways += 1

print(best, ways)

要点:代码与课程教案(p2005 Session 3)参考实现一致。读入用 sys.stdin.buffer——N=10⁶ 时这是 Python 能不能按时读完的分水岭;计数、逐高度求和、并列统计三段一一对应上面的算法步骤。

C++ 解法

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;

    vector<int> boards(n);
    int maxLen = 0;
    for (int i = 0; i < n; i++) {
        cin >> boards[i];
        maxLen = max(maxLen, boards[i]);
    }

    vector<int> freq(maxLen + 1, 0);
    for (int x : boards) {
        freq[x]++;
    }

    int best = 0;
    int ways = 0;
    for (int height = 2; height <= 2 * maxLen; height++) {
        int pairs = 0;

        for (int a = 1; a <= maxLen; a++) {
            int b = height - a;
            if (b < a || b > maxLen) {
                continue;
            }

            if (a == b) {
                pairs += freq[a] / 2;
            } else {
                pairs += min(freq[a], freq[b]);
            }
        }

        if (pairs > best) {
            best = pairs;
            ways = 1;
        } else if (pairs == best) {
            ways++;
        }
    }

    cout << best << " " << ways << '\n';
    return 0;
}

要点:与教案伪代码逐步对应;计数用 int 足够(N ≤ 10⁶),累加板数同理;min 在 <algorithm> 中,这里经 <vector>/iostream 链已可用,严谨起见可显式 #include <algorithm>。

正确性说明

  • 固定高度下每根木料恰好属于一个互补类:类由无序对 {a, h−a} 决定,a 从 1 到 L 的扫描不重不漏;约束 a ≤ b 保证每类只访问一次。
  • 类内贡献是最大板数:a < b 时两类木料一一配对,最多 min(freq[a], freq[b]) 块;a = b 时同类两两配对,最多 freq[a] // 2 块。同类内无法做得更好。
  • 类间可以相加:不同互补类没有共享木料,一类用掉的木料不影响另一类,因此该高度的最大板数就是各类贡献之和。
  • 高度之间互斥、并列需要计数:不同高度是不同方案,分别取最大值 best;所有等于 best 的高度都要计入 ways,扫描中的 else-if 分支完成统计。

因此输出的 best ways 就是题目所求的最长栅栏长度与并列高度数。

复杂度分析

  • 时间 O(N + L²):建表 O(N),全部高度扫描约 L²/2 ≈ 2×10⁶ 次类检查(L ≤ 2000)。N=10⁶ 时读入约占一半时间。
  • 空间 O(N + L):读入缓冲存 N 个长度(可改为流式读入降到 O(L)),频率表 O(L)。
  • 实测参考(本机):C++ 在 N=10⁶ 随机数据上远低于 1 秒;CPython 教案版约数秒级,官方时限 2 秒下建议 C++ 提交,Python 用于学习算法。(精确数字见 qa.md。)

常见错误

  1. 枚举木料对:O(N²) 在 N=10⁶ 下约 5×10¹¹ 次操作,必然超时。
  2. 把三块等长木料算成 C(3,2)=3 块板:一根木料只能用一次,a=b 类的贡献是 freq[a] // 2。
  3. 忘记 a ≤ b 约束:(a,b) 与 (b,a) 是同一类,重复计数使每个高度翻倍。
  4. 高度之间复用频率表:各高度是独立方案,计算下一个高度前不得修改 freq。
  5. 输出格式:题目要的是"最长长度 + 并列高度数"两个整数,不是方案列表,也不是配对总数。

复习问题

  1. 为什么固定高度 h 时,每个长度 a 只需考虑搭档 h−a?画 1..L 的数轴说明互补类为什么不重不漏。
  2. 三根长度都为 2 的木料,高度 4 为什么是 1 块板而不是 3 块?把"一根木料只能用一次"翻译成代码里的哪一行?
  3. 如果把题目改成"板可以由任意多根木料组成",互补类计数还适用吗?为什么?
  4. 内层循环里 if b < a or b > max_len: continue 去掉会怎样?各高度板数会错多少?
  5. 若长度上限 L 从 2000 改成 10⁵,本算法还行吗?时间和空间各变成多少?(提示:O(L²) 还扛得住吗。)

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

Back to CP Weekly Challenge
返回竞赛编程每周挑战

滚动至顶部