Seven contest problems rated 1,000 to 1,200 that count pairs or build an answer. The move: count groups instead of listing pairs, and build greedily with a check that the rest can still be finished.
This tent holds seven problems rated 1,000 to 1,200. Some ask how many. How many pairs of payments add to an even number, how many bundles of two items exist, and how many pairs of plays differ by a given gap. The others ask you to build something: the smallest list, the smallest string, the best arrangement.
Listing the options works on a page of samples and fails at the limits. A list of 100,000 items has 4,999,950,000 pairs, and 10 items already have 3,628,800 orders.
| Problem | The literal way | What replaces it |
|---|---|---|
| Pairs with an even sum | test every pair | count odd and even amounts |
| Number of ways to choose two items | list every bundle | a running total of earlier categories |
| Construct a permutation with a property | try every order | keep the fixed points, swap neighbours |
| Build a string with no equal neighbours | try every arrangement | smallest letter that still lets the rest finish |
| Minimum moves to make all equal | try every target | the median of the sorted list |
| Arrange the numbers to maximise the sum | try every order | count reads per slot, pair largest with most read |
| Count the pairs with a given difference | test every pair | a count for each value |
The first idea in a counting problem is to find the groups. Two numbers add to an even total exactly when they have the same parity, so the groups are the odd amounts and the even ones.
Exercise · Predict the output: Pairs inside each parity. A pair of payments is counted when its total is even. This counts the odd and the even amounts, then the pairs inside each group. What does it print?
amounts = [3, 8, 5, 2, 7]
odd = 0
even = 0
for amount in amounts:
if amount % 2 == 1:
odd += 1
else:
even += 1
print(odd * (odd - 1) // 2 + even * (even - 1) // 2)The two kinds of problem share one habit. Do not handle the options one by one. Handle them as groups, or as a choice that you can justify.
For counting, find a property that splits the items into groups, and count the answer as a sum or product over the groups. For building, make the smallest valid choice at each step, and test that the rest can still be finished.
Count the answer as a sum or product over groups of items. Or build it one smallest valid choice at a time, checking that the rest can still be completed.
The median is the clearest case of a justified choice. Pair the smallest value with the largest. Any target between them costs the same for that pair, and the middle value lies between every such pair. So it serves all pairs at once, but only in a sorted list.
To make all stocks equal with the fewest moves, sort them and move every stock to the middle value; it lies between every smallest and largest pair.
Exercise · Find the bug: The middle of an unsorted list. One move changes one warehouse by one unit. This makes all stocks equal by moving every stock to the middle value. Which line is wrong?
def min_moves(stock):
ordered = stock
target = ordered[len(ordered) // 2]
moves = 0
for x in ordered:
moves += abs(x - target)
return movesGreedy choices and Greedy by sorting taught you to justify a choice with an exchange argument. Seen set and complement taught the count for each value, and Difference arrays taught how to count reads over ranges. Bits and maths covered parity and divisibility.
What a contest adds is the overlap between groups. In the pairs with a given difference, a play b has two partners, b - gap and b + gap. When the gap is 0, both partners are the same value, and counting both doubles the answer.
The same care applies to a pair and itself. A play never pairs with itself, so record it in the table only after you look up its partners. For a gap of 0 and plays 3 and 3, the answer is 1 pair, and a double count gives 2.
The count also needs 64 bits. A list of 100,000 plays can have 4,999,950,000 pairs, which is above 2,147,483,647.
With a gap of zero, the value minus the gap and the value plus the gap are the same value, so counting both partners doubles the answer.
Exercise · Break it: The partner that is the same value. A pair is two plays at different positions whose counts differ by exactly gap. This looks up the plays before each one, at value - gap and at value + gap. Find an input where it is wrong.
def earlier(plays, j, value):
count = 0
for i in range(j):
if plays[i] == value:
count += 1
return count
def count_pairs_with_gap(plays, gap):
total = 0
for j in range(len(plays)):
total += earlier(plays, j, plays[j] - gap)
total += earlier(plays, j, plays[j] + gap)
return totalThe limits tell you to count by groups, and which type the count needs.
| Limit | What it rules out | What fits |
|---|---|---|
| 10^5 items, count the pairs | every pair: 4,999,950,000 | groups, and a 64-bit count |
| build the smallest list or string | every order: 10! is 3,628,800 | a greedy build with a check |
| a target up to 10^9 | a loop over every target | the median of the sorted list |
| 10^5 queries over ranges of slots | adding up each range | a difference array of reads |
The full treatment is in Fast I/O and stress testing. For a count of pairs, read the numbers once and count by parity in the same pass.
import sys
def main():
data = sys.stdin.read().split()
n = int(data[0])
odd = 0
for i in range(1, n + 1):
odd += int(data[i]) % 2
even = n - odd
print(odd * (odd - 1) // 2 + even * (even - 1) // 2)
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine().trim());
StringTokenizer st = new StringTokenizer(in.readLine());
long odd = 0;
for (int i = 0; i < n; i++) odd += Long.parseLong(st.nextToken()) % 2;
long even = n - odd;
System.out.println(odd * (odd - 1) / 2 + even * (even - 1) / 2);
}
}#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
long long odd = 0;
for (int i = 0; i < n; i++) {
long long amount;
cin >> amount;
odd += amount % 2;
}
long long even = n - odd;
cout << odd * (odd - 1) / 2 + even * (even - 1) / 2 << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
let odd = 0;
for (let i = 1; i <= n; i++) odd += data[i] % 2;
const even = n - odd;
console.log(odd * (odd - 1) / 2 + even * (even - 1) / 2);For 100,000 payments the answer reaches 4,999,950,000, so the Java and C++ counts are 64-bit.
Exercise · Put it in order: Count the bundles of two items. Arrange the lines into a function that counts the sets of two items taken from two different categories. Counts holds the number of items in each category.
def ways_to_pick_two(counts):
seen = 0
total = 0
for count in counts:
total += count * seen
seen += count
return total
total += count * (seen + count)A median is easy to replace by something close. The slow twin tries every target from 0 to the largest stock. The fast version below moves everything to the mean instead of the median.
import random
def fast_moves(stock):
target = sum(stock) // len(stock)
return sum(abs(x - target) for x in stock)
def slow_moves(stock):
return min(sum(abs(x - t) for x in stock) for t in range(max(stock) + 1))
def shrink(stock):
changed = True
while changed:
changed = False
for i in range(len(stock)):
shorter = stock[:i] + stock[i + 1:]
if shorter and fast_moves(shorter) != slow_moves(shorter):
stock, changed = shorter, True
break
return stock
bad = 0
first = None
for seed in range(1000):
rng = random.Random(seed)
stock = [rng.randint(1, 20) for _ in range(rng.randint(1, 6))]
if fast_moves(stock) != slow_moves(stock):
bad += 1
if first is None:
first = (seed, stock)
print("first difference", first, "shrunk to", shrink(first[1]))
print(bad, "of 1000 inputs differ")The run prints first difference (5, [9, 12, 17, 1, 15]) shrunk to [17, 1, 15] and 350 of 1000 inputs differ. The mean of 17, 1 and 15 is 11, which costs 20 moves, and the median 15 costs 16.
Problems rated 1,000 to 1,200 combine a counting or building idea with one overlap or one check. Spend about 20 minutes on each. The statement often hides the group: ask which property splits the items into groups that do not interact.
The first two count by groups with a sum or a running total. The next three build an answer: a list, a string and a target. The last two combine sorting or counting with an overlap.
For each problem, write one line: either the groups and the count over them, or the choice and the check that justifies it. If you cannot write the line, you are not ready to code.
Checkpoint · Counting and constructive starters
Q1/5 Payments of 3, 8, 5, 2 and 7 units. How many pairs of payments have an even total?
Answer: B
The three odd amounts make 3 pairs and the two even amounts make 1 pair. A pair is even only when both amounts share a parity.
Q2/5 Categories hold 2 and 3 items. How many sets of two items come from two different categories?
Answer: C
Each of the 2 items of the first category pairs with each of the 3 items of the second: 2 x 3 = 6.
Q3/5 Which target makes the total number of moves smallest when all stocks must become equal?
Answer: B
Any target between the smallest and the largest costs the same for that pair, and the middle value lies between every such pair. The mean can cost more: for 17, 1 and 15 the mean 11 costs 20 moves and the median 15 costs 16.
Q4/5 Plays 3 and 3 with a gap of 0 give how many pairs, and what goes wrong if both partners value - gap and value + gap are counted?
Answer: B
With a gap of 0 the two partners are the same value, so each pair is counted twice. Only count the second partner when the gap is not 0.
Q5/5 A fast solution and a slow twin differ on seed 5 with five stocks. What helps most?
Answer: B
The shrunk list [17, 1, 15] is short enough to trace by hand, and it shows the mean is the wrong target.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.