brain

tamnd's digital brain — notes, problems, research

43815 notes

constructive algorithmsdfs and similargraphsimplementation
binary searchgreedymathsortingsternary search
greedy
math
dpfftmath
brute forcegreedymath
dpstrings
mathsortingstwo pointers
dpstrings
*special
constructive algorithms
CF 1257F - Make Them Similar

We are given a fixed array of integers. We are allowed to choose a single integer x and apply it to every element using XOR. After this transformation, each original value ai becomes bi = ai XOR x.

codeforcescompetitive-programmingbitmasksbrute-forcehashingmeet-in-the-middle
CF 1257B - Magic Stick

We are given a starting integer and a target integer. From the starting value, we are allowed to repeatedly apply one of two transformations: if the current value is even, we may replace it with three halves of itself, and if the value is greater than one, we may reduce it by…

codeforcescompetitive-programmingmath
CF 1257C - Dominated Subarray

We are given several arrays, and for each one we need to find the shortest contiguous segment that has a strict majority element.

codeforcescompetitive-programminggreedyimplementationsortingsstringstwo-pointers
CF 1257D - Yet Another Monster Killing Problem

We are given a sequence of monsters that must be defeated strictly from left to right. Each monster has a required strength threshold, and none can be skipped or reordered. We also have a pool of heroes.

codeforcescompetitive-programmingbinary-searchdata-structuresdpgreedysortingstwo-pointers
CF 1251F - Red-White Fence

We are given a multiset of white boards, each with a fixed integer length, and a very small set of red boards. From these boards we want to form a “mountain shaped” fence. The fence uses exactly one red board, which must be the unique maximum element in the sequence.

codeforcescompetitive-programmingcombinatoricsfft
CF 1251E2 - Voting (Hard Version)

Each voter comes with two independent ways to make them support you. You may directly pay a fixed cost to activate any voter.

codeforcescompetitive-programmingbinary-searchdata-structuresgreedy
CF 1251D - Salary Changing

We are given several independent scenarios. In each scenario, there are an odd number of employees, and each employee has a salary interval from which their final salary must be chosen.

codeforcescompetitive-programmingbinary-searchgreedysortings
CF 1251E1 - Voting (Easy Version)

We are given a set of voters, and each voter can be activated in one of two ways. Either we directly pay a fixed cost to convince them, or we can exploit a dependency: if enough other voters are already convinced, they will join for free.

codeforcescompetitive-programmingdata-structuresdpgreedy
CF 1251A - Broken Keyboard

We are given a final string that appeared on a screen after someone pressed keyboard keys one by one. Each key corresponds to a lowercase Latin letter, and each key is either always healthy or always broken during the entire typing process.

codeforcescompetitive-programmingbrute-forcestringstwo-pointers
CF 1251C - Minimize The Integer

We are given a very long decimal string, but the digits are not free to move arbitrarily. The only allowed move is swapping two neighboring digits, and even that swap is restricted: the two digits must have different parity, meaning one is even and the other is odd.

codeforcescompetitive-programminggreedytwo-pointers
CF 1251B - Binary Palindromes

We are given several binary strings and allowed to repeatedly swap characters between any two positions in any strings.

codeforcescompetitive-programminggreedystrings
CF 1250H - Happy Birthday

We are given a collection of digit candles, where each digit from 0 to 9 appears a certain number of times. Each candle can be reused infinitely, so the counts do not deplete when we form numbers.

codeforcescompetitive-programmingmath
CF 1250F - Data Center

We are given a target area $n$, and we want to build a rectangle whose sides are integers and whose area is exactly $n$. Every valid rectangle corresponds to choosing two integers $a$ and $b$ such that $a cdot b = n$.

codeforcescompetitive-programmingbrute-forceimplementation
CF 1250A - Berstagram

We are simulating a social media feed where posts continuously swap positions based on incoming likes. Initially, posts are arranged in a fixed vertical order from top to bottom, with post 1 at the top and post n at the bottom.

codeforcescompetitive-programmingimplementation
CF 1249D2 - Too Many Segments (hard version)

We are given a collection of integer segments on a number line. Each segment covers every integer point between its endpoints. A point becomes problematic if it is covered by more than $k$ segments at the same time.

codeforcescompetitive-programmingdata-structuresgreedysortings
CF 1249A - Yet Another Dividing into Teams

We are given several independent scenarios. In each scenario there is a list of distinct integers representing student skill levels.

codeforcescompetitive-programmingmath
CF 1248A - Integer Points

We are given two families of straight lines on the plane. The first family consists of lines of the form $y = x + pi$, and the second family consists of lines of the form $y = -x + qj$. Every $pi$ is distinct within its own group, and every $qj$ is distinct within its own group.

codeforcescompetitive-programminggeometrymath
CF 1245F - Daniel and Spring Cleaning

We are given a range of integers from l to r, and we need to count ordered pairs (a, b) inside this range such that adding them behaves exactly like XOR. In other words, the usual addition of a and b produces the same result as their bitwise XOR.

codeforcescompetitive-programmingbitmasksbrute-forcecombinatoricsdp
CF 1245A - Good ol' Numbers Coloring

We are given two step sizes, a and b. Starting from zero, we paint every nonnegative integer in increasing order, but whether a number becomes white depends on whether it can be reached from already white numbers by repeatedly adding either a or b. Formally, zero starts as white.

codeforcescompetitive-programmingmathnumber-theory
CF 1245B - Restricted RPS

We are given a sequence of rock-paper-scissors moves played by Bob. Alongside this, Alice has a fixed inventory of moves: she must play exactly a specified number of Rocks, Papers, and Scissors across all rounds.

codeforcescompetitive-programmingconstructive-algorithmsdpgreedy
CF 1244D - Paint the Tree

We are given a tree where each node must be assigned one of three colors, and each assignment has a cost depending on the chosen color.

codeforcescompetitive-programmingbrute-forceconstructive-algorithmsdpgraphsimplementationtrees
Kvant Physics Problem 37

Two vertical cylinders of cross-sectional areas $S_1$ and $S_2$ are filled with water between two weightless, frictionless pistons.

kvantphysics
Kvant Physics Problem 32

A prismatic wooden block of constant square cross-section of side $a$ and length $L$ floats on the surface of water of density $\rho_w$.

kvantphysics
CF 1243A - Maximum Square

We are given several test cases, each consisting of a list of plank heights. Every plank has width 1 and some integer height.

codeforcescompetitive-programmingimplementation
Kvant Physics Problem 28

Two large parallel plates of area $S$ are separated by distance $L$, with $L$ much smaller than the lateral dimensions so edge effects are neglected.

kvantphysics
CF 1242A - Tile Painting

We are given a path of length n, where each position is a tile arranged in a straight line. We assign a color to every tile. The constraint is not local adjacency, but global structure tied to divisors of n.

codeforcescompetitive-programmingconstructive-algorithmsmathnumber-theory
Kvant Physics Problem 27

A rigid hemispherical bell of radius $R$ rests on a horizontal table with its rim in tight contact with the table, preventing fluid flow under the rim until lift-off.

kvantphysics
Kvant Physics Problem 26

A small block of mass $m$ moves without friction on a rigid surface consisting of two horizontal half-planes connected by a smooth spatial transition.

kvantphysics
Kvant Physics Problem 24

A body of mass $M$ is attached to an ideal spring of stiffness $k$, whose upper end is fixed.

kvantphysics
Kvant Physics Problem 23

Two identical thin-walled cylindrical tubes of mass $m$ and radius $R$ move on a horizontal rough plane.

kvantphysics
Kvant Physics Problem 21

Two identical direct current motors are rigidly connected by their shafts, so they share the same angular velocity $\omega$ and produce torques that add algebraically.

kvantphysics
Kvant Physics Problem 20

A long cylinder of radius $R$ and uniform material density contains a cylindrical hole parallel to its axis.

kvantphysics
Kvant Physics Problem 18

Two one-dimensional periodic structures represent the combs.

kvantphysics
Kvant Physics Problem 17

A parallel-plate capacitor with large identical plates of area $A$ is short-circuited, so both plates are connected by an external conducting wire and always remain at the same electric potential.

kvantphysics
Kvant Physics Problem 15

A refrigerator maintains its internal air at temperature $T_1 = 5^\circ\text{C}$ while it is placed in a room at temperature $T_2 = 20^\circ\text{C}$.

kvantphysics
Kvant Physics Problem 14

Two pistons of masses $m_1$ and $m_2$ move inside two rigid tubes of cross-sections $S_1$ and $S_2$.

kvantphysics
Kvant Physics Problem 12

Two identical steel balls of mass $m$ move on rigid, massless rods that constrain motion to circular trajectories of fixed radii $l$ and $2l$.

kvantphysics
Kvant Physics Problem 11

Three large open barrels contain water and have free surfaces located at fixed heights $H_1$, $H_2$, $H_3$ above a common reference level, with $H_1 > H_2 > H_3$, measured in meters.

kvantphysics
Kvant Physics Problem 9

A small mass $m$ is attached to a fixed point on a horizontal table by a spring of stiffness $k$.

kvantphysics
Kvant Physics Problem 6

A grounded conducting sphere of radius $r$ is fixed in vacuum.

kvantphysics
Kvant Physics Problem 4

A fixed mass $m = 1,\mathrm{kg}$ of an unknown gas is considered under two thermodynamic processes: heating at constant pressure and heating at constant volume.

kvantphysics
Kvant Physics Problem 3

Two helical springs are made from identical steel wire segments of equal total wire length $L_w$ and identical wire diameter.

kvantphysics
Kvant Physics Problem 1

Three identical communicating vessels contain water of density $\rho$ in a uniform gravitational field $g$.

kvantphysics
CF 1237E - Balanced Binary Search Trees

We are counting a very specific family of binary search trees built on the keys from 1 to n. The tree structure must satisfy the usual BST ordering, but that is not the main constraint that drives the solution. The real restriction comes from two additional rules.

codeforcescompetitive-programmingdpmath
CF 1237B - Balanced Tunnel

We are given a timeline of cars entering a tunnel and a separate timeline of the same cars exiting it. Every car appears exactly once in each list, so both sequences are permutations of the same set of identifiers. Inside the tunnel, overtaking is only detectable indirectly.

codeforcescompetitive-programmingdata-structuressortingstwo-pointers
CF 1236B - Alice and the List of Presents

We are given several kinds of items, where each kind is unlimited in supply. We also have several distinct boxes, each belonging to a different friend, so boxes are labeled and cannot be swapped. For each kind of item, Alice chooses a subset of boxes to place that kind into.

codeforcescompetitive-programmingcombinatoricsmath
CF 1234A - Equalize Prices Again

We are given several independent scenarios. In each one, a shop has a list of item prices. The goal is to replace all of these different prices with a single uniform price so that selling all items at this single price does not reduce the total revenue compared to the original…

codeforcescompetitive-programmingmath
CF 1228D - Complete Tripartite

We are given an undirected graph with up to 100,000 vertices and up to 300,000 edges. The task is to split all vertices into exactly three non-empty groups so that the structure between every pair of groups is perfectly regular.

codeforcescompetitive-programmingbrute-forceconstructive-algorithmsgraphshashingimplementation
CF 1228A - Distinct Digits

We are given a closed interval of integers from l to r, and we need to find any number inside this interval whose decimal representation does not repeat any digit. In other words, when writing the number as a string of digits, every character must be unique.

codeforcescompetitive-programmingbrute-forceimplementation
CF 1227F2 - Wrong Answer on test 233 (Hard Version)

We are given a length-n sequence of questions, and for each position i there is a correct answer h[i]. We construct another sequence a of length n, where each a[i] is chosen independently from 1 to k.

codeforcescompetitive-programmingcombinatoricsmath
CF 1227A - Math Problem

We are given several closed intervals on a number line. Each interval represents a set of integer or real points between its endpoints, and the endpoints themselves are included.

codeforcescompetitive-programmingmath
CF 1225A - Forgetting Things

We are asked to construct two positive integers $a$ and $b$ such that they differ by exactly one unit in the sense that $a + 1 = b$. We are not given the numbers themselves. Instead, we are only given the first digit of $a$ and the first digit of $b$.

codeforcescompetitive-programmingmath
CF 1225E - Rock Is Push

We are walking in a grid from the top-left cell to the bottom-right cell, moving only right or down. The grid is not empty in a passive sense: some cells contain rocks, and those rocks behave dynamically. When we step into a rock cell, the rock does not block us.

codeforcescompetitive-programmingbinary-searchdp
CF 1225B1 - TV Subscriptions (Easy Version)

We are given a schedule of TV shows over a sequence of days. Each day broadcasts exactly one show, and if we buy a subscription to a show, we gain access to all of its episodes for the entire timeline.

codeforcescompetitive-programmingimplementation
CF 1223D - Sequence Sorting

We are given multiple independent sequences, and for each one we want to transform it into a non-decreasing array using a very specific operation.

codeforcescompetitive-programmingdpgreedytwo-pointers
CF 1221C - Perfect Team

Each query describes a pool of students split into three groups. Some students are coders, some are mathematicians, and some have no specialization at all. A valid team must contain exactly three students and must include at least one coder and at least one mathematician.

codeforcescompetitive-programmingbinary-searchmath
CF 1220B - Multiplication Table

We are given an $n times n$ table that was originally generated from some hidden array $a1, a2, dots, an$. Every entry of the table was formed by multiplying two elements of this array, so the cell in row $i$, column $j$ equals $ai cdot aj$.

codeforcescompetitive-programmingmathnumber-theory
CF 1218F - Workout plan

Alan follows a fixed schedule of gym visits over $N$ days. On day $i$, he must lift exactly $X[i]$ grams, and he starts with a base strength $K$. He can permanently increase his strength by buying a pre-workout drink on any day he visits a gym.

codeforcescompetitive-programmingdata-structuresgreedy
CF 1218H - Function Composition

We are given a directed functional graph defined by an array A. From every node i, there is exactly one outgoing edge to A[i]. Repeated application of this mapping defines a process where starting from a node x, we move along the graph m times.

codeforcescompetitive-programmingdfs-and-similar
CF 1217B - Zmei Gorynich

We are given a creature with an initial number of heads, and a collection of attack types. Each attack type behaves in a very specific way: when used, it removes some number of heads, but after the strike, if the creature is still alive, it immediately regrows a fixed number…

codeforcescompetitive-programminggreedymath
CF 1216E1 - Numerical Sequence (easy version)

We are given a conceptual infinite string formed by concatenating blocks of digits. The first block is just the number “1”. The second block is “12”.

codeforcescompetitive-programmingbinary-searchbrute-forcemath
CF 1215D - Ticket Game

We are given a ticket represented by a string of even length. Each position corresponds to a digit from 0 to 9, except that some positions are unknown and marked with a question mark. The unknown positions must eventually be filled with digits.

codeforcescompetitive-programminggamesgreedymath
CF 1215B - The Number of Products

We are given a sequence of nonzero integers and asked to count how many subarrays produce a positive product and how many produce a negative product. A subarray is defined by choosing two indices $l le r$ and multiplying everything from $al$ to $ar$.

codeforcescompetitive-programmingcombinatoricsdpimplementation
CF 1214B - Badges

We are given three integers describing a small combinatorial setup. There are a fixed number of boys and girls in total, and exactly $n$ participants will attend an event, but we do not know how many of them are boys or girls.

codeforcescompetitive-programmingbrute-forcemath
CF 1213G - Path Queries

We are given a weighted tree where every edge has a cost, and we are asked multiple questions about how “expensive” paths between pairs of vertices can be. For any two vertices $u$ and $v$, there is exactly one simple path between them because the graph is a tree.

codeforcescompetitive-programmingdivide-and-conquerdsugraphssortingstrees
CF 1213D1 - Equalizing by Division (easy version)

We are given a list of integers, and we are allowed to repeatedly reduce any chosen number by replacing it with its half rounded down. Each such replacement costs one operation.

codeforcescompetitive-programmingbrute-forceimplementation
CF 1211I - Unusual Graph

We are given an undirected graph with up to 500 vertices. The graph is known to come from a very specific hidden labeling process: each vertex originally had a number between 0 and 15, and an edge existed between two vertices if and only if their labels differ in exactly one…

codeforcescompetitive-programming*specialgraphs
CF 1211D - Teams

We are given a multiset of player ratings. Each player can be used at most once, and our goal is to form as many disjoint teams as possible under a strict structure constraint. Every valid team consists of two homogeneous groups of players.

codeforcescompetitive-programming*specialbinary-searchgreedymath
LeetCode 3922 - Minimum Flips to Make Binary String Coherent

We are given a binary string s consisting only of '0' and '1'. A string is called coherent if it does not contain either of the following patterns as a subsequence: - "011" - "110" Recall that a subsequence does not need to occupy consecutive positions.

leetcodemediumstring
LeetCode 3924 - Minimum Threshold Path With Limited Heavy Edges

We are given an undirected weighted graph with n nodes and a list of weighted edges. We must travel from source to target. The key concept in this problem is the definition of a threshold.

leetcodehardbinary-searchbreadth-first-searchgraph-theory
LeetCode 3899 - Angles of a Triangle

We are given an array sides containing exactly three positive integers. Each integer represents the length of one side of a potential triangle. The task is to determine whether these three side lengths can form a triangle with positive area.

leetcodemedium
CF 1209B - Koala and Lights

Each light in this problem behaves like a binary switch that flips its state over time. You are given an initial configuration where each light is either on or off.

codeforcescompetitive-programmingimplementationmathnumber-theory
CF 1207A - There Are Two Types Of Burgers

We are given a small restaurant model where each query describes available ingredients and selling prices for two kinds of burgers. One burger requires buns plus beef, the other requires buns plus chicken.

codeforcescompetitive-programmingbrute-forcegreedyimplementationmath
CF 1206A - Choose Two Numbers

We are given two collections of positive integers. One collection represents the possible values we can pick as the first number, and the second collection represents the possible values we can pick as the second number.

codeforcescompetitive-programmingmathsortings
CF 1205F - Beauty of a Permutation

We are asked to build permutations of numbers from 1 to n such that a specific structural property holds on subarrays, and to control how many subarrays satisfy it.

codeforcescompetitive-programmingconstructive-algorithmsmath
CF 1205A - Almost Equal

We are asked to arrange the numbers from 1 to 2n around a circle. Once the circle is fixed, we look at every contiguous block of exactly n elements. Each such block produces a sum, and since the circle has 2n positions, there are 2n such blocks (wrapping around at the end).

codeforcescompetitive-programmingconstructive-algorithmsgreedymath
CF 1205C - Palindromic Paths

We are given an unknown binary grid of size $n times n$, where $n$ is odd. Each cell contains either 0 or 1. Two facts are guaranteed: the top-left cell is 1 and the bottom-right cell is 0. We cannot directly read the grid.

codeforcescompetitive-programmingimplementationinteractive
CF 1205D - Almost All

We are given a tree with $n$ nodes. Each edge must be assigned a non-negative integer. Once the edges are labeled, every pair of nodes defines a path, and each path has a sum obtained by adding the values on its edges.

codeforcescompetitive-programmingconstructive-algorithmstrees
CF 1204E - Natasha, Sasha and the Prefix Sums

We are looking at all possible sequences of length $n+m$ made of exactly $n$ ones and $m$ minus ones. Every arrangement is considered once, so this is a multiset permutation problem.

codeforcescompetitive-programmingcombinatoricsdpmathnumber-theory
CF 1204D2 - Kirk and a Binary String (hard version)

We are given a binary string and we are allowed to construct another binary string of the same length. The requirement is not local, it is global over all substrings: for every interval of positions, the value of the longest non-decreasing subsequence inside that interval must…

codeforcescompetitive-programmingdata-structuresgreedymathstrings
CF 1204D1 - Kirk and a Binary String (easy version)

We are given a binary string and asked to construct another binary string of the same length. The key requirement is not about matching the strings themselves, but about preserving a structural value computed on every substring: the length of the longest non-decreasing…

codeforcescompetitive-programmingbrute-forcegreedystrings
CF 1204B - Mislove Has Lost an Array

We are given a length n array of positive integers, but the array is not arbitrary. Every value in it must satisfy a strict structural rule: each number is either 1, or it is an even number whose half is also present somewhere in the array.

codeforcescompetitive-programminggreedymath
CF 1203F2 - Complete the Projects (hard version)

Each project can be thought of as an action that becomes available only when Polycarp’s current rating is high enough. Once he starts a project, his rating may go up or down, but it is never allowed to become negative at any point.

codeforcescompetitive-programmingdpgreedy
CF 1203D2 - Remove the Substring (hard version)

We are given two strings, s and t. The second string is guaranteed to already appear inside the first one as a subsequence, meaning we can pick characters from s in order and obtain t.

codeforcescompetitive-programmingbinary-searchgreedyimplementationtwo-pointers
CF 1203A - Circle of Students

We are given several independent scenarios. In each scenario, a group of students is arranged in a fixed circular order, and we are shown that order as a linear list representing clockwise traversal around the circle.

codeforcescompetitive-programmingimplementation
CF 1203D1 - Remove the Substring (easy version)

We are given a source string s and a target string t, where t is already guaranteed to be a subsequence of s. In other words, we can pick characters from s in order and obtain t without reordering anything.

codeforcescompetitive-programminggreedyimplementation
CF 1202A - You Are Given Two Binary Strings...

We are given two binary strings, which represent two integers. One of them, call it $x$, is fixed. The other, $y$, is effectively shifted left by some number of positions $k$, then added to $x$. After computing this sum, we take its binary representation and reverse it.

codeforcescompetitive-programmingbitmasksgreedy
CF 1201C - Maximum Median

We are given a list of numbers and allowed to repeatedly increase any single element by one. Each such increment has a cost of one operation, and we have a total budget of at most $k$ operations.

codeforcescompetitive-programmingbinary-searchgreedymathsortings
CF 1201D - Treasure Hunting

We are given a grid with rows increasing upward and columns increasing left to right. We start at the bottom-left cell and want to collect all treasures placed on various cells.

codeforcescompetitive-programmingbinary-searchdpgreedyimplementation