Accel Thinking

CP Weekly Challenges

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.

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

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

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:

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

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:
  1. 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

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

Complexity Analysis

Common Mistakes

  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?)