brain

tamnd's digital brain — notes, problems, research

41527 notes

CF 105020A - Mood

We are given multiple independent scenarios where a person has a fixed amount of money and wants to buy a drink with a known price. For each scenario, we need to determine how much additional money is required so that the available amount is enough to cover the cost.

codeforcescompetitive-programming
CF 105020B - Hungry

We are given a single queue of customers already lined up at a shop. Each customer in the queue requires a known amount of time to be served, and the shop processes them strictly one after another.

codeforcescompetitive-programming
CF 105020C - Ice Coffee

We are given two arrays of integers of the same length. We are allowed to repeatedly transform elements, but only in one direction: each operation replaces a value by its largest proper divisor, meaning the greatest divisor strictly smaller than the number itself.

codeforcescompetitive-programming
CF 105022L - Silver Wolf and IPC (Advanced)

We are given a permutation of size $N$. Then we are given a sequence of $Q$ operations, each operation taking a segment $[l, r]$ and rotating it cyclically to the right by one position. After all $Q$ operations are applied, we obtain a final permutation.

codeforcescompetitive-programming
CF 105022K - Turning Trucks

We are given a vertical stack of trucks, each truck contributing a fixed length segment. Initially, the stack is perfectly aligned on the y-axis starting from the origin, so the head of the top truck ends up at a point whose y-coordinate is the sum of all truck lengths and…

codeforcescompetitive-programming
CF 105022J - Not So Generous Genie

We are given a string consisting only of digits 1 and 2, and we are allowed to modify it using a limited budget of coins.

codeforcescompetitive-programming
CF 105022I - Find Iron Bundle

We are given a tree representing a metro network where every station is connected and there is exactly one simple path between any two stations. Two people matter: Psyduck, who starts at a uniformly chosen station, and Iron Bundle, who is located at some station.

codeforcescompetitive-programming
CF 105022H - One Step Closer To The AK

We are given a binary array that changes over time through two kinds of operations. One operation flips every value in a range, turning zeros into ones and ones into zeros. The other operation asks us to look at a subarray and play a deterministic removal game on it.

codeforcescompetitive-programming
CF 105022G - Just Visiting Relatives

We are given two length-N sequences, and we use them to define an N by N matrix where every entry is formed by multiplying a row weight from the first sequence with a column weight from the second sequence.

codeforcescompetitive-programming
CF 105022F - Sparkle's Stage

We are given a set of trucks placed on a number line, each with a starting position and a constant velocity. Every truck moves in a straight line, and whenever two trucks meet at the same point at the same time, they collide.

codeforcescompetitive-programming
CF 105022E - Distressed Driver

We are given a sequence of scheduled trips, each with a start time and an end time. Chad performs these trips in the given order. The key mechanic is that if a trip starts while he is still busy finishing a previous delayed trip, it does not start on its original time.

codeforcescompetitive-programming
CF 105022D - Air Taxi Game

We are given several independent test cases. In each test case, there is a list of distinct positive integers representing city populations.

codeforcescompetitive-programming
CF 105022C - Car Go or Not Car Go

We are looking at a deterministic process on a directed graph where every city has exactly one outgoing edge defined by doubling the index modulo $N$. Starting from city $1$, the car repeatedly follows this rule, producing a sequence of visited cities.

codeforcescompetitive-programming
CF 105022A - Truck-Kun

We are given a complete directed graph on up to 300 vertices, where every ordered pair of vertices has a weight, which can be positive, zero, or negative.

codeforcescompetitive-programming
CF 105022B - Twin Trucks

We are given a list of distinct truck lengths. From all possible pairs of different trucks, we assign a score based on two values: the sum of the lengths and the absolute difference between them.

codeforcescompetitive-programming
CF 105023L - One Step Closer To The AK

We are given a binary array that supports two kinds of operations over time. The first operation flips all bits in a segment, turning zeros into ones and ones into zeros. The second operation asks us to consider a subarray and play a deterministic two player game on it.

codeforcescompetitive-programming
CF 105023K - Silver Wolf and IPC (Novice)

We are given a permutation of size $N$, and then a long sequence of $Q$ operations. Each operation selects a segment $[l, r]$ and performs a left rotation on that segment, meaning the element at position $l$ moves to position $r$, and everything between shifts one step left.

codeforcescompetitive-programming
CF 105023J - Air Taxi Game

We are given multiple independent test cases. In each test case there is a list of distinct positive integers representing city populations.

codeforcescompetitive-programming
CF 105023I - What the heck is a kilometer?

We are given a one-dimensional road represented as a string of length $N$. Each character describes a unit cell: either a normal road segment denoted by a dot, or a traffic light denoted by an asterisk.

codeforcescompetitive-programming
CF 105023G - I-5 Drive

We are asked to count ordered pairs of primes $(p, q)$ such that a number formed as $N = p^2 + q^3$ has a very specific representation property in base $T$.

codeforcescompetitive-programming
CF 105023H - Sparkle's Stage

We are given a set of trucks placed on a one-dimensional line. Each truck starts at a distinct position and moves forever with a fixed velocity.

codeforcescompetitive-programming
CF 105023F - Twin Trucks

We are given a list of distinct positive integers, each representing the length of a truck. From these trucks, we choose two different ones and assign them a score based on both their sum and their absolute difference.

codeforcescompetitive-programming
CF 105023E - Car Go or Not Car Go

We are given a deterministic graph on the integers from 0 to N − 1 where each city has exactly one outgoing road, specifically from x to 2x modulo N. Starting from city 1, a car repeatedly follows these edges forever.

codeforcescompetitive-programming
CF 105023D - Airport Algorithm

Each plane occupies a gate during a continuous time interval from its arrival time to its departure time. While it is present at the airport, it blocks one gate, so overlapping intervals correspond to simultaneous gate usage.

codeforcescompetitive-programming
CF 105023C - Tree Trucks

We are given a multiset of truck lengths, and we want to assemble a special “tree-shaped structure” using some of them. The structure has a vertical spine made of trucks stacked one above another.

codeforcescompetitive-programming
CF 105023B - Truck Traffic

We are given a one-dimensional representation of what Bob sees along a freeway, encoded as a string of length $N$. Each position is either a truck segment marked as T or an empty road segment marked as ..

codeforcescompetitive-programming
CF 105023A - Toy Trucks

We are given a single integer that represents the length of a toy truck in inches. The task is to decide whether this truck can be placed inside a toy box. The only constraint for fitting is that the truck’s length must not exceed 10 inches.

codeforcescompetitive-programming
CF 105025I - Два друга

Two players build a single tower by alternately placing blocks on top. Each block has an integer weight between $l$ and $r$, and both players can reuse any weights as often as they want. The tower starts with total weight $0$.

codeforcescompetitive-programming
CF 105025G - Зачет по информатике

We are given a line of positions numbered from 1 to m, and a collection of weighted segments. Each segment covers a contiguous interval of these positions and has a cost if we choose to use it.

codeforcescompetitive-programming
CF 105025H - Шихан

We are working with a hidden “mountain” defined over a very large grid of size $n times m$. Somewhere on this grid there is a single special cell $(x0, y0)$, the peak.

codeforcescompetitive-programming
CF 105025E - Банановый бизнес Олега

We are given a sequence of banana prices arranged in a line. Each position holds one value, and we are allowed to perform exactly $k$ operations, where one operation swaps two adjacent elements.

codeforcescompetitive-programming
CF 105025D - Недовольство Марселя

We are given two ordered groups of cars positioned along a straight road at a fixed moment in time. One group moves away from the origin, the other moves toward it, all at identical speed.

codeforcescompetitive-programming
CF 105025F - Рэп игра

We are given a collection of text lines, and we are allowed to rearrange them in any order. The score of an arrangement is determined only by adjacent pairs: for every neighboring pair of strings, we compute how long their suffixes match character by character from the end…

codeforcescompetitive-programming
CF 105025C - Солнечная панель

We are given a sequence of heights representing consecutive segments of a roof. Each segment has a fixed height, and we want to place a solar panel on a contiguous interval of these segments.

codeforcescompetitive-programming
CF 105025A - Цифры помогают мыслить

We are given an integer a, which can be negative, zero, or positive. We are allowed to add a non-negative integer x to it. The goal is to make the resulting number a + x look like a valid time displayed on a digital clock.

codeforcescompetitive-programming
CF 105025B - Две монеты

We are given two positive integers $k$ and $n$. They describe a hidden pair of coin values $A$ and $B$ under two constraints at the same time. First, one coin value is a multiplicative scaling of the other: $A = k cdot B$.

codeforcescompetitive-programming
CF 105028D - Tree Merger

We are given a tree where every node carries an initial integer value. The only allowed operation is to pick an edge whose endpoints currently have the same value, merge those two endpoints into a single node, and assign that new node the sum of the two values.

codeforcescompetitive-programming
CF 105028E - RBS Score

We are given a bracket string that changes over time. After each update, we must compute how many substrings of the current string form a correct, fully balanced bracket sequence.

codeforcescompetitive-programming
CF 105028F - Too Many BSTs

We are given a fixed sequence of values that will always be inserted into a binary search tree in the same order, and then many queries, each introducing a different value that is inserted first before that fixed sequence.

codeforcescompetitive-programming
CF 105028A - Minimum Black Cells

We are working on an $n times n$ grid where movement is allowed in four directions, as long as we stay inside the grid. A traveler starts at the top-left cell and wants to reach the bottom-right cell.

codeforcescompetitive-programming
CF 105028C - Perfect Square Matrix

We are given an initially empty $n times n$ grid filled with zeros. We must choose exactly $n$ distinct cells and assign them the values $1, 2, ldots, n$, each used exactly once, leaving all other cells as zero. After placing these numbers, every square submatrix is examined.

codeforcescompetitive-programming
CF 105028B - Sequence Duplication

We are given two sequences. The first sequence a is the pattern we want to match, and the second sequence b is a base sequence that is repeated endlessly, but only a finite number of times. If we repeat b exactly k times, we get a long sequence made of k consecutive copies of b.

codeforcescompetitive-programming
CF 105030D - Песчаная буря

We are given a line of buildings, each with a fixed height. Over time, sandstorms partially “cover” some segment of buildings, and each building inside that segment is only visible up to a certain height limit.

codeforcescompetitive-programming
CF 105030B - Добыча пряности

We are modeling a production pipeline with three sequential stages that behave like a single constrained assembly line. Each final unit, a harvester, is composed of one unit from stage I and one unit from stage II, and both of these must first be produced by earlier stages.

codeforcescompetitive-programming
CF 105030C - Предательство Юэ

We are asked to count how many length $2n$ sequences can be formed using digits from 1 to 9 such that a very specific symmetry holds between the first half and the second half. Split any valid sequence into two parts of length $n$.

codeforcescompetitive-programming
CF 105030A - Распределение пряности

Each unit of spice is labeled with an integer topic. We must distribute all units among as few students as possible. A single student may receive several units, but any two topics assigned to that student must differ by more than k.

codeforcescompetitive-programming
CF 105043E - Ужин у лесника Янки

We are given an array of values, where each position has a number attached to it. For each query, we take a contiguous segment of this array and are allowed to freely permute the values inside that segment before evaluating a score.

codeforcescompetitive-programming
CF 105043D - Высадка двоичных яблонь на луну

I can't write a correct editorial or provide a correct solution for this problem because the prompt is missing essential information.

codeforcescompetitive-programming
CF 105043B - Двоичный паук плетёт паутину

We are given a sequence of pillar heights laid out in a straight line. Each position has a height, and we also have a threshold value x. The task is to find a contiguous segment of these pillars such that every pillar inside the segment has height at most x.

codeforcescompetitive-programming
CF 105043A - Петя и странные запросы

We are given a number $n$. Imagine writing all integers from $1$ to $n$ on a sheet. Two independent operations are performed on this set: every number divisible by 2 is marked in one color, and every number divisible by 3 is marked in another color.

codeforcescompetitive-programming
CF 105043C - Марсианские числа

We are given a fixed integer a and an interval [l, r]. A number x from that interval is considered compatible with a if gcd(a, x) = 1. The task is to count how many integers in the interval are coprime with a. The most striking constraint is that l and r can be as large as 10^18.

codeforcescompetitive-programming
CF 105046E - XORradas

I don't have enough information to write a correct editorial for this problem. The statement you've pasted is missing a critical part: the actual input format. As written, it says: "The first line of the input contains the number of cases T.

codeforcescompetitive-programming
CF 105046D - Differences

We are given several independent test cases. Each test case describes a rectangular grid with n rows and m columns, and a multiset of n·m integers.

codeforcescompetitive-programming
CF 105046B - Seats

We are given several disjoint blocks of free seats. Each block is a contiguous segment with a known length, and inside each block we can place teams, but only if a team occupies consecutive seats entirely inside that block.

codeforcescompetitive-programming
CF 105046C - Color Cycles

We are given an undirected graph and we must assign an integer color to every vertex. The coloring is constrained by two global conditions that interact in a nontrivial way.

codeforcescompetitive-programming
CF 105046A - Guess the Number

This request cannot be completed as written because the problem is interactive, not a standard input/output problem.

codeforcescompetitive-programming
CF 105047E - XOR Sorting

We are given an array of integers, and we are allowed to repeatedly apply a single destructive operation: pick two different positions, and replace the first position by the XOR of its current value with the second position’s value. The second position is never modified.

codeforcescompetitive-programming
CF 105047D - Resto

I'm missing the actual Codeforces problem details needed to write a correct editorial. The statement you pasted is corrupted in several places: - The sample input is malformed. It begins with 3 2 even though the format says the first number is T.

codeforcescompetitive-programming
CF 105047C - Rectangle

We are interacting with a hidden axis-aligned rectangle whose side lengths are two unknown integers $a$ and $b$, both at most 100. We cannot see these values directly.

codeforcescompetitive-programming
CF 105047B - Equalizing

We are given an array of integers. The goal is to raise every element so that it reaches at least a threshold value k. The only way to modify the array is through a very specific operation applied to a chosen index i.

codeforcescompetitive-programming
CF 105047A - Card Game

This request cannot be fulfilled as written because the problem is interactive, not a standard input/output problem.

codeforcescompetitive-programming
CF 105055N - Nim?

We start with a pile that initially contains $A times B$ stones. Two players alternate moves, with Machado always starting. On each turn, the current player changes the pile size by either adding or removing a number of stones, subject to restrictions that differ per player.

codeforcescompetitive-programming
CF 105055M - Dimly Lit

We are given a one-dimensional street segment from position 0 to position N, together with a set of lampposts placed at fixed integer coordinates along this segment.

codeforcescompetitive-programming
CF 105055L - Le Café

We are given a multiset of sprinkle packages, where each package contains a fixed positive number of sprinkles and must be used entirely or not at all.

codeforcescompetitive-programming
CF 105055J - Party Game

We are given a small group of at most seven players, each owning a “die” described indirectly through a string of length $M$.

codeforcescompetitive-programming
CF 105055I - DJ Interface

A circular vinyl disc is drawn on a square screen. The disc is centered in the square from the origin-aligned view, with its visible region being the set of points inside a circle of diameter $D$. A user clicks at one point on the disc, drags to another point, and releases.

codeforcescompetitive-programming
CF 105055A - Sticker Album

We are given a line of sticker packs, each pack having a cost and a multiset of stickers it contains. Each sticker has an identifier from 1 to M, and the goal is to acquire at least one copy of every identifier in this range.

codeforcescompetitive-programming
CF 105055F - Festa Junina

We are asked to construct a sequence of exactly $N$ positive integers such that the sequence is strictly increasing, and among all such sequences we want the one with minimum total cost. The cost structure is the key part.

codeforcescompetitive-programming
CF 105055B - Bit Tennis

We start with a binary string that represents an integer. Two players alternate turns, and on each turn a player is allowed to extend the string by adding exactly one bit either to the left or to the right.

codeforcescompetitive-programming
CF 105053L - LED Matrix

We are given a rectangular LED matrix and a rectangular pattern that is supposed to scroll across it from right to left. The matrix has fixed dimensions, and each cell is either functional or broken. A functional LED can be turned on, while a broken one can never light up.

codeforcescompetitive-programming
CF 105053H - Harmonic Operations

We are given a fixed string and a sequence of operations that repeatedly transform it. Each operation is either a full reversal of the string or a cyclic rotation by some amount to the left or right.

codeforcescompetitive-programming
CF 105053I - Insects, Mathematics, Accuracy, and Efficiency

We are given a set of points in the plane, all lying inside or on a fixed circle centered at the origin with radius $R$. These points represent existing crops.

codeforcescompetitive-programming
CF 105053K - KMOP

We are given a phrase split into several words, and we are allowed to build an acronym by taking a prefix from each word and concatenating these prefixes in order.

codeforcescompetitive-programming
CF 105051F - Искусственный интеллект

We are given a collection of strings built from a small alphabet of size at most 20. For each query string, we need to choose one string from the collection that is compatible with it in a very specific sense: the chosen string must not share any character with the query string.

codeforcescompetitive-programming
CF 105051D - Пирамида

Each input brick is a rectangle with fixed dimensions $wi times hi$. From any brick, you are allowed to “shrink” it into exactly one new rectangle $a times b$, as long as both sides do not increase, meaning $a le wi$ and $b le hi$.

codeforcescompetitive-programming
CF 105051E - Сложная игра

We are given a grid of size $n times m$, where each cell contains either a 0 or a 1. A 1 represents a cell with a candy, and a 0 means it is empty. A player starts at the top-left cell and can only move either one step right or one step down at each move.

codeforcescompetitive-programming
CF 105051C - Необычная шахматная доска

We are given a rectangular grid with n rows and m columns. Every cell is assigned one of three colors, but the coloring is not based on parity like a standard chessboard.

codeforcescompetitive-programming
TAOCP 7.1.3 Exercise 67

Work in the ring $\mathbb{F}_2[x]/(x^n + x^m + 1)$ with $0<m<n$, where $m$ and $n$ are odd.

taocpmathematicsalgorithmsvolume-4math-hard
TAOCP 7.1.3 Exercise 66

Let the binary polynomial $u(x)=u_0+u_1x+\cdots+u_{n-1}x^{n-1}\pmod 2$ be represented by the integer $u=(u_{n-1}\ldots u_1u_0)_2.$ For an integer $\delta \ge 0$, define $v = u \oplus (u \ll \delta) \o...

taocpmathematicsalgorithmsvolume-4math-hard
TAOCP 7.1.3 Exercise 65

Let u(x)=\sum_{i=0}^{n-1} u_i x^i \pmod 2,\qquad v(x)=\sum_{i=0}^{n-1} v_i x^i \pmod 2, and let the corresponding integers be

taocpmathematicsalgorithmsvolume-4math-medium
CF 105051B - Магический квадрат

We are given a partially filled 3×3 grid that is known to be a magic square. That means the grid contains the numbers from 1 to 9 exactly once, and every row, every column, and both diagonals sum to the same value.

codeforcescompetitive-programming
CF 105051A - Выборы в РИЛИ

Three candidates are receiving votes in an election. The first candidate currently has a votes, the second has b, and the third has c. More votes may still arrive, but only additional votes for the first candidate matter.

codeforcescompetitive-programming
TAOCP 7.1.3 Exercise 64

The proposed solution fails because it tries to treat the interleaving as if it were compatible with ordinary addition.

taocpmathematicsalgorithmsvolume-4medium
TAOCP 7.1.3 Exercise 63

Let $x = (\ldots x_2 x_1 x_0)_2$ and $y = (\ldots y_2 y_1 y_0)_2$.

taocpmathematicsalgorithmsvolume-4medium
CF 105053J - Joys of Trading

Each resource has two competing production technologies, one used by each village. For resource $i$, Apolyanka spends $Ai$ person-hours per unit, while Büddelsdorf spends $Bi$.

codeforcescompetitive-programming
TAOCP 7.1.3 Exercise 62

Let $N = 2^d$.

taocpmathematicsalgorithmsvolume-4medium
CF 105053G - Greek Casino

We start with a single pointer sitting on a slot labeled 1, and we repeatedly perform a randomized transition that depends on the current slot. At each step, we sample a value $y$ from $1$ to $N$ with given weighted probabilities.

codeforcescompetitive-programming
CF 105053F - Fair Distribution

Each blueprint describes a type of building. If a child receives a blueprint with parameters $G$ and $R$, they construct a building with one ground floor of height $G$ and then choose how many residential floors to add, each contributing height $R$.

codeforcescompetitive-programming
CF 105053D - DiviDuelo

We are given a number $N$. From this number we construct a set consisting of all its positive divisors. Two players then take turns picking elements from this set until nothing remains. The starting player is interested only in the divisors they personally pick.

codeforcescompetitive-programming
CF 105053E - Expanding STACKS!

We are given a chronological log of events involving N customers. Each customer appears exactly once when they enter the restaurant and exactly once when they leave.

codeforcescompetitive-programming
TAOCP 7.1.3 Exercise 61

The previous argument fails because it assumes that the recursion of Fig.

taocpmathematicsalgorithmsvolume-4research
CF 105053C - Clever Cell Choices

We are given a grid where some cells are blocked and the rest are free. A game starts when the first player chooses any free cell and places a stone there.

codeforcescompetitive-programming
CF 105053B - Beating the Record

We are simulating a repeated attempt to clear a sequence of at most four game levels, where each full attempt either succeeds or fails depending on independent probabilistic choices made inside each level.

codeforcescompetitive-programming
CF 105053A - Almost Aligned

Each meteor starts at a known point in the plane and moves in a fixed direction with constant velocity. After time $t ge 0$, meteor $i$ is at $$(xi(t), yi(t)) = (xi + v{x,i} t,; yi + v{y,i} t).

codeforcescompetitive-programming
CF 105055O - Another Trip

The situation is a simple road trip with a mistake in direction. Two distances are relevant: the first is how far the travelers went after taking the wrong direction, and the second is the remaining distance from their starting point to the destination along the correct route.

codeforcescompetitive-programming
TAOCP 7.1.3 Exercise 60

Let $K$ be the number of cycles in the graph $G = M_1 \cup M_2$, where $M_1$ is a fixed perfect matching on $\{0,1,\dots,2n-1\}$ and $M_2$ is a uniformly random perfect matching.

taocpmathematicsalgorithmsvolume-4hm-hard
CF 105055K - Knock Code

Each uppercase letter must be translated into its position inside the fixed 5 by 5 Knock Code matrix. Every letter is represented by a pair consisting of its row and column. The numbers themselves are encoded as consecutive asterisks, so row 3 becomes and column 5 becomes .

codeforcescompetitive-programming
CF 105055H - Hawarma

We are given an integer parameter $N$ and a rational function $$f(x) = frac{5xN^2}{x^2 + 3xN - 5N^2}.$$ The task is to find all real values $a$ such that plugging $a$ into the function returns the same value, meaning $f(a) = a$.

codeforcescompetitive-programming
CF 105055G - Genie in the Lamp

We are given a string of length $N$ consisting of three kinds of characters: fixed opening parentheses, fixed closing parentheses, and wildcard positions written as ?. Each wildcard can independently be replaced by either ( or ).

codeforcescompetitive-programming
CF 105055E - Email

We are given a string made only of the characters a and b. This string is not arbitrary: it is supposed to be an encoding of a binary password where each 0 was replaced by the block ab and each 1 was replaced by the block aba.

codeforcescompetitive-programming