Contest problems rated 800 to 900 that say exactly what to do, but whose limits forbid doing it step by step. The move: size the literal simulation, then replace it with a count.
This tent holds contest problems rated 800 to 900, and each one describes a process in full. Halve an amount until it reaches zero. Print every number from 1 to n. Add up the batches of a stretch of routes.
So the first solution is always clear: do what the statement says. It is also always correct. The trouble is the limits, which make the literal process far too long.
| Problem | The literal process | Its size at the limits |
|---|---|---|
| Even or odd steps | apply the rule to each amount until it is 0 | 10^6 amounts, fewer than 60 steps each |
| Count the digits | print every number from 1 to n | 10^12 numbers |
| Palindromic number check | test every number in each range | 10^5 ranges of up to 10^6 numbers: 10^11 tests |
| Parity of the sum | add up each stretch, with huge powers | 10^5 stretches of up to 10^5 routes: 10^10 terms |
| Reverse and compare | compare every pair of codes | 10^5 codes: about 5 × 10^9 pairs |
Only the first row comes close to fitting in a second, and only in a fast language. The other four need an idea first.
Exercise · Predict the output: Count the steps of two payouts. Each amount is halved when it is even and lowered by 1 when it is odd, until it reaches 0. What does this print?
halvings = 0
set_asides = 0
for amount in [13, 8]:
while amount > 0:
if amount % 2 == 0:
amount //= 2
halvings += 1
else:
amount -= 1
set_asides += 1
print(halvings, set_asides)The move has two steps, and both happen before you write code.
First, multiply out the literal process from the limits, as in the table above. A judge runs about 10^8 simple steps a second. If your product is far above that, simulating is not an option, however tight the code.
Second, look for what repeats, and count it instead of doing it. The repeated work is usually one of three kinds.
When the literal process is far above 10^8 steps, find the work that repeats and compute it once per item, per block or per prefix.
For the digits, the blocks are 1 to 9, 10 to 99, 100 to 999 and so on. Up to 120 that is 9 + 180 + 63 = 252 digits. Up to 10^12 it is 11,888,888,888,902 digits, from only 13 blocks.
Size the literal process from the limits; far above 10^8 steps, count the repeated work by blocks instead.
Exercise · Find the bug: The block that loses a number. This counts the digits printed when you write every number from 1 to last_number. It adds one block of equal width at a time. Which line is wrong?
def digits_written(last_number):
total = 0
low, width = 1, 1
while low <= last_number:
high = low * 10 - 1
count = min(last_number, high) - low
total += count * width
low *= 10
width += 1
return totalThe Academy lesson Reading problems and constraints taught you to turn a limit into a budget. Counting operations taught you to count the steps of a loop, and How the judge works explained verdicts such as Time Limit Exceeded. This tent uses all three at once, under a clock.
Two things are new here. A contest statement is a story with a puzzle inside, so you must find the process before you can size it. And the shortcut is usually a small fact about numbers: a parity rule, a digit count or a block of equal width.
Facts like these hide edge cases. An exponent of 0 turns any base into 1, which is odd. A last block is cut short by the limit, and a code of one letter reads the same backwards.
Test the edges of each fact before you trust it.
A power has the parity of its base only for a positive exponent; any base to the power zero is one, which is odd.
Exercise · Break it: The power that forgets its exponent. Each route sends fans[i] to the power stages[i] people. This says whether the total of routes left to right is odd (1) or even (0). It uses "a power has the parity of its base". Find an input where it is wrong.
def total_parity(fans, stages, left, right):
odd = 0
for i in range(left, right + 1):
if fans[i] % 2 == 1:
odd += 1
return odd % 2On a contest site, read the input limits before the story. They tell you which running time you need, before you know what the problem is about.
| Largest n | Steps you can afford | What usually fits |
|---|---|---|
| 10^5 to 10^6 | about 10^8 | O(n) or O(n log n) |
| 10^12 or more | a few thousand | a formula or a loop over blocks or digits |
| 10^5 queries | about 10^3 per query | precompute, then O(1) or O(log n) a query |
In this course the judge passes the input to your function. On a contest site you read standard input yourself, and slow reading alone can exceed the limit. Read everything at once, and print once at the end.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
values = list(map(int, data[1:1 + n]))
sys.stdout.write(str(sum(values)) + "\n")
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));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(in.readLine());
long total = 0;
for (int i = 0; i < n; i++) total += Long.parseLong(st.nextToken());
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
out.println(total);
out.flush();
}
}#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
long long total = 0;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
total += x;
}
cout << total << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
let total = 0;
for (let i = 1; i <= n; i++) total += data[i];
process.stdout.write(String(total) + "\n");When there are many answers, collect them in a list and join them with newlines. One print of a long string is much faster than one print per line.
Keep the slow, literal solution: it is your reference. Write a generator for small random inputs, run both solutions on each one, and stop at the first difference.
import random
from fast import digits_written
from slow import digits_written as slow_digits
for seed in range(1000):
n = random.Random(seed).randint(1, 2000)
if digits_written(n) != slow_digits(n):
print("different at", n)
break
else:
print("all 1000 inputs agree")Small inputs find most bugs, and a small failing input is easy to trace by hand. The bug above, the block that loses a number, fails on the first random input, n = 1,730. Try n from 1 upwards instead, and it fails at n = 1, which takes one line to trace.
Problems rated 800 to 1,000 test careful reading and one small observation. You do not need a new algorithm, so an error is almost always a misread limit or a missed edge case. Aim to solve each one in about 15 minutes, with a stress test in the last five.
Most carry the rating 800, so their order follows the idea. The first two replace a process with a count, the next two answer many questions from a table, and the fifth counts pairs of strings. The last, rated 900, steps through the multiples of a number and looks each one up in a set.
For each problem, write the size of the literal process in one line before you code. If it is far above 10^8, write the count that replaces it in a second line.
Checkpoint · Implementation warm ups
Q1/5 A problem asks 10^5 questions, each about a range of up to 10^6 numbers. Can you test every number of every range?
Answer: B
Multiply the limits first: 10^5 × 10^6 = 10^11. Test each number once instead, and answer each range from prefix counts.
Q2/5 How many digits do you write for every number from 1 to 120?
Answer: C
The blocks give 9 × 1 + 90 × 2 + 21 × 3 = 252. 246 is what you get when every block loses one number.
Q3/5 Why does a contest solution read the whole input at once?
Answer: B
With 10^6 numbers, a slow reader spends more time on input than on the algorithm. One read of everything, then a split, is fast in every language.
Q4/5 Your fast solution and the slow one disagree on a random input of size 1,730. What do you do next?
Answer: B
The slow solution is the reference, because it does exactly what the statement says. A tiny failing input, such as n = 1, is quick to trace.
Q5/5 What does a rating of 800 to 1,000 usually ask of you?
Answer: B
These problems need no new algorithm. Wrong answers come from a misread limit or a missed edge case, such as an exponent of 0.
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.