Six contest problems rated 800 to 900 whose algorithm is easy. The trouble is around it: reading input, the width of a total, ties, and a bug that only a rare input shows.
In this course the judge gives your function a list and takes a list back. On a contest site there is no function. Your program reads standard input, writes standard output, and must do both within the time limit.
The six problems in this tent are rated 800 to 900, so the algorithm in each is easy. What they test is everything around it.
| Problem | Where it bites |
|---|---|
| Sum of two numbers | a total of two balances up to 10^12 passes 32 bits |
| Read until the end of input | no line count, and blank lines in the middle |
| Sum of many lines fast | the whole file is one string, and its last line break may be missing |
| Find the maximum and its position | a tie must keep the earliest position |
| Stress test a wrong minimum | a bug that only some inputs show |
| Handling TLE with a faster loop | a loop over 10^8 numbers is too slow |
Three kinds of trouble repeat. The first is reading: the count of lines is missing, blank lines appear, or the file arrives as one string. The second is width: a total does not fit in the type you chose. The third is testing: the code passes the samples, and a rare input breaks it.
When the file arrives as one string, the usual tool is a scan over its characters. A number ends when a non-digit arrives, and that is where a last line without a break goes wrong.
Exercise · Predict the output: The last number of the file. Each line holds a received value and a sent value. This scan adds a number when a non-digit ends it. The text has no line break after its last line. What does it print?
text = "12 5\n7 30"
received = 0
sent = 0
number = 0
in_number = False
first_column = True
for ch in text:
if ch >= "0" and ch <= "9":
number = number * 10 + (ord(ch) - ord("0"))
in_number = True
elif in_number:
if first_column:
received += number
else:
sent += number
first_column = not first_column
number = 0
in_number = False
print(received, sent)The six problems need three habits, and each one is cheap when you do it first and costly when you add it after a failed submission.
Read the whole input in one pass and keep every total in 64 bits. Trust a fast solution only after it agrees with a slow twin on many small random inputs.
The width rule comes from numbers you can check. A 32-bit signed integer holds up to 2,147,483,647. Two balances of 2,000,000,000 add up to 4,000,000,000, and in Java an int prints -294,967,296 while a long prints 4,000,000,000.
Python integers never overflow, and JavaScript numbers are exact up to 9,007,199,254,740,991. In Java and C++ you choose the type, so choose long or long long every time.
Each problem also has one small rule that a single character decides: > against >=, a number left unfinished, a start value of 0. Ties are the clearest case, because the statement asks for the first position of the maximum.
Read the whole input at once and print once; one slow call per number or per answer can cost more than the algorithm.
Exercise · Find the bug: The tie that moves the position. This returns the highest height and the position of its first occurrence, counted from 1. Which line is wrong?
def highest_sample(heights):
best = heights[0]
position = 1
for i in range(1, len(heights)):
if heights[i] >= best:
best = heights[i]
position = i + 1
return [best, position]How the judge works showed that Submit also runs hidden tests, so a failure there was found for you. On a contest site you see the verdict and not the input. A line such as Wrong Answer on test 7 gives you a number and nothing to trace.
Hand tracing and debugging taught you to shrink a failure and trace it on paper. A stress test finds that failure first, so the habit there becomes a tool here. And Language toolkit covered the types and the string tools of each language, which now decide whether a total fits and whether reading is fast.
The last problem of the tent adds the time limit. A loop over 10^8 numbers is correct, but in Python it took 17.8 seconds in one run, against a limit of a second or two. The multiples of k up to limit are k, 2k, ..., m*k with m = limit // k, and they add up to k * m * (m + 1) / 2. For steps 3 and 5 and a limit of 10^8, that gives 2,333,333,416,666,668 in a few operations.
Two steps can share multiples, and that is the edge to test. A multiple of both is counted twice, so subtract the sum over the multiples of the least common multiple.
Adding the sums of two sets of multiples counts the shared multiples twice; subtract the sum over the least common multiple.
Exercise · Break it: The parcel that is checked twice. Parcels 1 to limit are checked when their number is a multiple of first_step or second_step. This adds up the two sets of multiples with a formula. Find an input where it is wrong.
def inspected_total(limit, first_step, second_step):
first = limit // first_step
second = limit // second_step
return first_step * first * (first + 1) // 2 + second_step * second * (second + 1) // 2Read the limits before the story. They tell you the running time you need and the type you need, before you know what the problem is about.
| Largest value | What it tells you |
|---|---|
| n up to 10^5 or 10^6 | a pass or a sort fits; a pair of loops does not |
| a total of up to 10^12 | a 64-bit type |
| a limit of 10^8 or more | no loop over the range: a formula or a count |
| the number of lines is not given | read until the input ends |
A contest program reads standard input itself. The slow way is one library call per number. In a run with a million numbers, one input() call per line took 1.8 seconds in Python, and one read of everything took 0.12. Printing one line per answer shows the same gap: 0.3 seconds against 0.15 for a million lines.
The first pattern is the usual one. The count comes first, and the values follow.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
total = 0
for i in range(1, n + 1):
total += int(data[i])
sys.stdout.write(str(total) + "\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());
System.out.println(total);
}
}#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 value;
cin >> value;
total += value;
}
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");The second pattern has no count. Each line holds two numbers, blank lines may appear, and the input ends without notice. Read until it does, skip what is not a pair, collect the answers and print once.
import sys
def main():
out = []
for line in sys.stdin.buffer:
parts = line.split()
if len(parts) < 2:
continue
out.append(str(int(parts[0]) + int(parts[1])))
if out:
sys.stdout.write("\n".join(out) + "\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));
StringBuilder out = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
if (st.countTokens() < 2) continue;
long a = Long.parseLong(st.nextToken());
long b = Long.parseLong(st.nextToken());
out.append(a + b).append('\n');
}
System.out.print(out);
}
}#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string out;
long long a, b;
while (cin >> a >> b) out += to_string(a + b) + "\n";
cout << out;
}const lines = require("fs").readFileSync(0, "utf8").split("\n");
const out = [];
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 2) continue;
out.push(String(Number(parts[0]) + Number(parts[1])));
}
if (out.length > 0) process.stdout.write(out.join("\n") + "\n");Reading a count and then the values is the same job as the function below, except that the whole input is a single string.
Exercise · Put it in order: Total the values after the count. Arrange the lines into a function that reads a count and then that many values from one string, and returns their total.
def sum_after_count(text):
tokens = text.split()
count = int(tokens[0])
total = 0
for i in range(1, count + 1):
total += int(tokens[i])
return total
for i in range(count):Keep a slow twin that you can check by reading it. Generate many small random inputs, run both programs, and stop at the first difference. Then shrink the input by dropping elements while the two still disagree, because a failing input of one number is easy to trace by hand.
import random
def fast_minimum(values):
smallest = 0
for x in values:
smallest = min(smallest, x)
return smallest
def slow_minimum(values):
return sorted(values)[0]
def shrink(values):
i = 0
while i < len(values) and len(values) > 1:
shorter = values[:i] + values[i + 1:]
if fast_minimum(shorter) != slow_minimum(shorter):
values = shorter
else:
i += 1
return values
for seed in range(1, 1001):
rng = random.Random(seed)
values = [rng.randint(-3, 3) for _ in range(rng.randint(1, 6))]
if fast_minimum(values) != slow_minimum(values):
print("different at seed", seed, values)
print("shrunk to", shrink(values))
break
else:
print("all 1000 inputs agree")The run prints different at seed 1 [1, 3] and then shrunk to [3]. The fast version starts its minimum at 0, so it fails whenever every value is positive. In 1,000 random lists of values from -3 to 3, 122 expose it. A sample with a negative number never does.
Problems rated 800 to 1,000 test careful reading and one small observation. A wrong answer here comes from the input, the width of a type or a tie rule, and almost never from the algorithm. Spend about ten minutes on each problem, and keep the last three for a stress test.
The first four are rated 800 and each one has a single trap: a width, a missing count, a missing break or a tie. The last two are rated 900. One finds a bug with a twin, and one beats the time limit with a formula.
For each problem, write the trap in one line before you code. After you pass, run the stress test of this tent against a slow twin, even when the samples agree.
Checkpoint · Fast I/O and stress testing
Q1/5 Two balances of 2,000,000,000 are added in a Java int. What does it print?
Answer: B
A 32-bit int holds at most 2,147,483,647, so the sum wraps around to -294,967,296. A long holds the true total, 4,000,000,000.
Q2/5 A log has no line count, and blank lines appear in the middle. How do you read it?
Answer: B
The input decides when to stop, so the loop runs until there are no lines left. A blank line changes nothing and is skipped.
Q3/5 Why does a contest solution collect its answers and print once at the end?
Answer: B
In a run with a million lines, printing each line took 0.3 seconds and printing the joined text once took 0.15.
Q4/5 A stress test of your fast solution against a slow twin finds a difference on a list of six numbers. What do you do next?
Answer: B
The slow twin is correct by reading. A failing input of one or two numbers is quick to trace.
Q5/5 Parcels 1 to 12 are checked when their number is a multiple of 3 or of 4. The formula adds the multiples of 3 and the multiples of 4. What is missing?
Answer: B
The sum of multiples of 3 is 30 and of 4 is 24. Parcel 12 is in both, so the true total is 54 - 12 = 42.
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.