Six contest problems rated 1,000 to 1,100 that describe an exact process on a huge input. The move: find what repeats, then jump over it with arithmetic and implement the jump with care.
This tent holds six problems rated 1,000 to 1,100. Each one describes a process in full: players queue and take turns, a display scrolls, a robot follows a route, a calendar counts days. The process is simple to state, and the input is huge.
So the literal replay is clear, and it is far too slow. The risk moves from the idea to the care. Once you know the jump, a wrong sign or a missing century rule still fails the hidden tests.
| Problem | The literal replay | Its size at the limits |
|---|---|---|
| Simulate the queue of players | one question at a time | 10^11 questions |
| Rotate the string k times | one letter per step | 10^14 steps |
| Day of the week from a date | one day at a time | about 3.65 million days a date |
| Lexicographically smallest rotation | build and compare every rotation | 10^10 letters |
| Grid walk with turns | follow every command | 10^14 commands |
| Largest rectangle of equal symbols | test every rectangle | 2,038,522,500 rectangles |
A calendar is the clearest case of a process with a hidden pattern. Count the days before a date, take them modulo 7, and the weekday follows. The count must follow the century rules.
Exercise · Predict the output: The calendar after 400 years. Year 1 starts on a Monday. This counts the days before 1 January of a year, using whole division, and turns the count into a weekday from 1 (Monday) to 7. What does it print?
year = 401
before = year - 1
days = 365 * before + before // 4 - before // 100 + before // 400
print(days, days % 7 + 1)The move has two parts, and the second is the one that fails.
First, say what is true after each step of the process. After a pass of the robot, its position and its facing describe everything that follows. After a press of the display, only the total shift matters. After a round of the queue, every player still waiting has had the same number of visits.
Second, find what repeats and replace it with arithmetic. A total modulo n, a cycle of four passes, a sort by two keys, a day count modulo 7: each one is a jump. Then write the jump with care, because it fails at the edges and not in the middle.
State what is true after every step. Replace the repeated part with arithmetic on one period, and test the edges of the arithmetic: negatives, zero, the last partial step and the century rules.
A leap year is the edge that most calendars miss. A year is a leap year when it is divisible by 4, except when it is divisible by 100, unless it is also divisible by 400.
A year divisible by 100 is a leap year only when it is also divisible by 400; a test that stops at the hundreds gets 2000 wrong.
Exercise · Find the bug: The century that is a leap year. This returns the number of days in a year. Which line is wrong?
def days_in_year(year):
if year % 4 == 0 and year % 100 != 0:
return 366
return 365Hand tracing and debugging taught you to follow a program with a table of values. Here the table is how you check a jump. Strings and builders taught how to cut and join a string, which is all a rotation needs. Bits and maths covered remainders and divisibility.
Monotonic stack is the tool of the last problem, and Comparators covers the sort by two keys behind the queue. What changes in a contest is that nothing names the tool. The statement tells a story, and you find the repeat yourself.
The grid walk shows how a repeat hides. A robot follows a route, and each pass may turn it. After four passes it always faces the way it started, so every further block of four passes moves it by the same amount. With a route repeated 10^9 times, you follow the route 4 times at most, and then multiply.
A shortcut can be right in the middle and wrong at the turn. Taking one pass and multiplying it by the rounds works only when the robot never turns.
After four passes a route returns the robot to its starting facing, so follow the route four times and multiply the block.
Exercise · Break it: The route that turns. A robot starts at (0, 0) facing north. F moves it forward, L and R turn it 90 degrees. It follows the route rounds times. This takes the move of one pass and multiplies it by rounds. Find an input where it is wrong.
def final_cell(route, rounds):
x, y = 0, 0
dx, dy = 0, 1
for command in route:
if command == "F":
x += dx
y += dy
elif command == "L":
dx, dy = -dy, dx
else:
dx, dy = dy, -dx
return [x * rounds, y * rounds]In this band the limits name the jump before you find it.
| Limit | What it rules out | The jump |
|---|---|---|
| a repeat count of 10^9 | a replay | a cycle, or a total modulo n |
| a shift of up to 10^9 in each of 10^5 presses | a total in 32 bits | a 64-bit total, then a remainder |
| 10^5 players with up to 10^6 turns | one question at a time | a sort by visits |
| a floor of 300 by 300 | every rectangle: 2,038,522,500 | a pass per row with a stack |
The full treatment is in Fast I/O and stress testing. A mixed input, a word and then a list of numbers, needs one token at a time from a single read.
import sys
def main():
data = sys.stdin.read().split()
text = data[0]
count = int(data[1])
total = sum(int(x) for x in data[2:2 + count])
start = total % len(text)
sys.stdout.write(text[start:] + text[:start] + "\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());
String text = st.nextToken();
int count = Integer.parseInt(st.nextToken());
long total = 0;
while (count > 0) {
while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
total += Long.parseLong(st.nextToken());
count--;
}
int n = text.length();
int start = (int) (((total % n) + n) % n);
System.out.println(text.substring(start) + text.substring(0, start));
}
}#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string text;
int count;
cin >> text >> count;
long long total = 0;
for (int i = 0; i < count; i++) {
long long move;
cin >> move;
total += move;
}
long long n = text.size();
int start = (int)(((total % n) + n) % n);
cout << text.substr(start) + text.substr(0, start) << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean);
const text = data[0];
const count = Number(data[1]);
let total = 0;
for (let i = 0; i < count; i++) total += Number(data[2 + i]);
const n = text.length;
const start = ((total % n) + n) % n;
console.log(text.slice(start) + text.slice(0, start));The remainder line decides the answer. In Python, % of a negative number is never negative. In Java, C++ and JavaScript it is, so add n and take the remainder again.
Exercise · Put it in order: Rotate by the total shift. Arrange the lines into a function that scrolls the text left by the total of all presses. A negative total scrolls right.
def rotate_text(text, moves):
n = len(text)
total = 0
for move in moves:
total += move
start = total % n
return text[start:] + text[:start]
start = abs(total) % nThe slow twin scrolls one letter at a time. The fast version below reduces the total, but it takes the absolute value of the total, a slip that works for positive totals. Because the twin is slow, keep the presses small.
import random
def fast_rotate(text, moves):
start = abs(sum(moves)) % len(text)
return text[start:] + text[:start]
def slow_rotate(text, moves):
letters = list(text)
for move in moves:
for _ in range(abs(move)):
if move > 0:
letters.append(letters.pop(0))
else:
letters.insert(0, letters.pop())
return "".join(letters)
bad = 0
first = None
for seed in range(1000):
rng = random.Random(seed)
text = "".join(rng.choice("abc") for _ in range(rng.randint(1, 6)))
moves = [rng.randint(-8, 8) for _ in range(rng.randint(1, 4))]
if fast_rotate(text, moves) != slow_rotate(text, moves):
bad += 1
if first is None:
first = (seed, text, moves)
print("first difference", first)
print(bad, "of 1000 inputs differ")The run prints first difference (13, 'bcc', [-1, -4]) and 207 of 1000 inputs differ. Dropping the first press leaves a single press of -4, and the fast version still disagrees. A negative total is the whole bug.
Problems rated 1,000 to 1,200 hide a jump in a long story. The idea is known, and the care decides the verdict: signs, wrap-around, the century rule and the last partial step. Spend about 20 minutes on each, and keep a third of it for a tiny stress test.
The first three replace a long replay with a number: a sort key, a shift, a day count. The next three need a sharper idea: two candidates, a cycle of four passes and a stack per row.
For each problem, write one line for the repeat and one for the jump before you code. When the jump is clear, write a slow literal version first, and use it as your twin.
Checkpoint · Careful implementation
Q1/5 A process repeats 10^9 times over a long input. What do you look for first?
Answer: B
A replay of 10^9 steps is too slow in any language. Arithmetic on one period replaces it.
Q2/5 Which of these years is a leap year?
Answer: C
A year divisible by 100 is a leap year only when it is also divisible by 400. So 2000 is a leap year, and 1900 and 2100 are not.
Q3/5 In Java, the total of the presses is -1. What does total % 6 give, and how do you get a valid start?
Answer: B
In Java, C++ and JavaScript the remainder of a negative number is negative. Adding n and taking the remainder again gives a start from 0 to n - 1.
Q4/5 A robot repeats a route of turns and moves 10^9 times. How many passes do you follow?
Answer: B
Following one pass and multiplying works only when a pass leaves the facing unchanged. Four passes always restore it.
Q5/5 Your fast rotation and the slow twin disagree on seed 13. What do you do next?
Answer: B
The slow twin does exactly what the statement says. A tiny failing input is quick to trace.
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.