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.
Where This Fits in the CCC DSA Map
- 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
- Related CP Weekly problems: CCC 2020 S3 Searching for Strings (coming soon, frequency signatures + sliding window), CCC 2022 J4/S2 Good Groups (counting and constraint checking), CPW-009
- Related Python / C++ foundations: Python Basics: Input, Operators, and Conditions , Python Lists: append() vs +
- Related DSA roadmap article: Counting Patterns (planned), PN-035 Sets and Dictionaries (coming soon)
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 achievebest.
No piece identities, no pairing lists — the answer is fully determined by the frequency table.
Algorithm Steps
- Read N and the N lengths, build
freq, and record the maximum length L. - Set
best = 0; ways = 0. - 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 addmin(freq[a], freq[b]); - If
pairs > best, update best and reset ways to 1; ifpairs == best, increment ways.
- Print
best 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 Solution
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++ Solution
#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 toways, handled by the else-if branch.
Therefore the printed best ways is exactly the requested longest fence length and the number of tied heights.
Complexity Analysis
- 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.)
Common Mistakes
- Enumerating piece pairs: O(N²) at N=10⁶ is about 5×10¹¹ operations — hopeless.
- Counting C(3,2)=3 boards from three equal pieces: a piece is used once; the a=b class contributes freq[a] // 2.
- Forgetting the a ≤ b constraint: (a,b) and (b,a) are one class, so every height doubles.
- Reusing the frequency table across heights: heights are independent plans; never mutate freq between them.
- 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
- 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.
- 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”?
- If boards could be built from any number of pieces, would complement-class counting still apply? Why or why not?
- What goes wrong if the
if b < a or b > max_len: continueguard is removed? By how much would every height’s count be wrong? - 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?)
Questions or feedback?
Have a question about this article or want to suggest an improvement? Send us an email.
