brain

tamnd's digital brain — notes, problems, research

41777 notes

CF 409H - A + B Strikes Back

The task is to read a single line containing two non-negative integers separated by whitespace and output their arithmetic sum.

codeforcescompetitive-programming*specialbrute-forceconstructive-algorithmsdsuimplementation
CF 409F - 000001

We are given a single integer $a$, and we are asked to compute a certain count associated with binary strings of length $a$. Each position in such a string can be thought of as a switch that is either off or on, but the strings we are allowed to consider are not arbitrary.

codeforcescompetitive-programming*special
CF 409E - Dome

The problem presents a number x that represents a dome's height in some scaled system. Our task is to find two positive integers, a and b, both between 1 and 10 inclusive, that encode this height according to the formula $x = a cdot sqrt{b}$.

codeforcescompetitive-programming*special
CF 409B - Mysterious Language

This is one of Codeforces' April Fools problems. There is no real algorithmic input. The judge provides a special language called "Secret" through the custom invocation system. The task is to identify what that language actually is and submit a program written in that language.

codeforcescompetitive-programming*special
CF 409D - Big Data

At first glance, the problem seems almost absurdly simple: you are given an integer between 1 and 16, and you need to output a single integer corresponding to that input.

codeforcescompetitive-programming*special
CF 409A - The Great Game

We are given two short strings representing sequences of moves in a fictional duel between two teams. Each string is built from a small alphabet that visually looks like emoticon fragments, and each valid move is actually encoded using two characters.

codeforcescompetitive-programming*special
CF 409C - Magnum Opus

The problem gives us a list of integers representing quantities of some alchemical ingredients. The goal is to determine the greatest common divisor (GCD) of these quantities. In other words, we want to find the largest integer $d$ such that each given number is divisible by $d$.

codeforcescompetitive-programming*special
CF 407E - k-d-sequence

We are given an integer sequence of length $n$ and two additional parameters: $k$, the maximum number of elements we are allowed to insert, and $d$, the intended difference of an arithmetic progression.

codeforcescompetitive-programmingdata-structures
CF 407D - Largest Submatrix 3

We are given an integer matrix of size n by m. Each cell contains a positive integer. The task is to find the largest rectangular submatrix where all the elements are distinct. The “largest” is measured by area, meaning the number of cells inside the rectangle.

codeforcescompetitive-programmingdphashing
CF 407C - Curious Array

We are given an array and a sequence of range operations. Each operation picks a segment $[l, r]$ and a parameter $k$, and for every position $j$ inside that segment we add a value that depends on how far $j$ is from the left endpoint $l$.

codeforcescompetitive-programmingbrute-forcecombinatoricsimplementationmath
CF 407A - Triangle

We are given two positive integers, a and b, which are the lengths of the legs of a right triangle. The task is not to check whether such a triangle exists, it obviously does.

codeforcescompetitive-programmingbrute-forcegeometryimplementationmath
CF 407B - Long Path

We are given a linear maze with n+1 rooms, numbered from 1 to n+1. Each room 1 through n has two portals. The first portal always moves forward to the next room, i+1. The second portal moves backward to some previous room, p₁ through pₙ, where pᵢ ≤ i.

codeforcescompetitive-programmingdpimplementation
CF 405D - Toy Sum

We are given a large universe of numbered blocks from 1 to 1,000,000. Some subset of these blocks, called $X$, has been removed from Chris’s set. From the remaining blocks, we need to choose a non-empty subset $Y$ so that a very specific weighted balance condition holds.

codeforcescompetitive-programminggreedyimplementationmath
CF 405E - Graph Cutting

We are given a connected undirected graph, and we are asked to completely decompose its edges into length-2 paths.

codeforcescompetitive-programmingdfs-and-similargraphs
CF 405C - Unusual Product

We are given an n×n binary matrix, meaning every element is either 0 or 1. The "unusual square" of the matrix is defined as the sum over all rows of the dot product of row i with column i, computed modulo 2.

codeforcescompetitive-programmingimplementationmath
CF 405B - Domino Effect

We are given a row of dominoes, some of which are initially pushed to fall either left or right, while others are standing upright. Each second, a falling domino pushes its immediate neighbor in the same direction.

codeforcescompetitive-programming
CF 405A - Gravity Flip

We are given a row of vertical stacks of cubes. Each position in the row holds a column, and the input array describes how many cubes are stacked at each position. Then a “gravity switch” happens.

codeforcescompetitive-programminggreedyimplementationsortings
CF 404E - Maze 1D

We have a robot standing on an infinite 1D strip of cells indexed by integers, starting at cell 0. The robot is given a sequence of moves, each either left (L) or right (R). Before the robot starts, we can place obstacles on some cells, except cell 0.

codeforcescompetitive-programmingbinary-searchgreedyimplementation
CF 404D - Minesweeper 1D

We have a one-dimensional Minesweeper field represented as a string of length n. Each character can be a bomb '', an unknown '?', or a number 0, 1, or 2. The numbers indicate how many bombs are immediately adjacent to that cell.

codeforcescompetitive-programmingdpimplementation
CF 404C - Restore Graph

We are asked to reconstruct an undirected connected graph from a list of shortest distances from one vertex, under the constraint that each vertex can have at most k edges.

codeforcescompetitive-programmingdfs-and-similargraphssortings
CF 404A - Valera and X

We are given an odd-sized square grid of letters. Each cell contains a lowercase English letter. The task is to check whether the letters form a perfect "X" pattern.

codeforcescompetitive-programmingimplementation
CF 404B - Marathon

Valera runs around the perimeter of a square stadium. The square has side length a, and the route follows the boundary in counterclockwise order. The starting point is the bottom-left corner (0, 0).

codeforcescompetitive-programmingimplementationmath
CF 402E - Strictly Positive Matrix

We are given a square matrix $a$ of size $n times n$ whose elements are all non-negative integers. The matrix can be thought of as a weighted adjacency matrix of a graph with $n$ nodes, where $a{ij} 0$ indicates a direct edge from node $i$ to node $j$.

codeforcescompetitive-programminggraphsmath
CF 402C - Searching for Graph

We are asked to construct a special type of undirected graph. The graph has n vertices and a parameter p, and it must satisfy two global conditions. First, the total number of edges is exactly 2n + p. Second, no subgraph of k vertices may have more than 2k + p edges.

codeforcescompetitive-programmingbrute-forceconstructive-algorithmsgraphs
CF 402A - Nuts

We are asked to distribute a given number of nuts into boxes, but the boxes are not simple containers. Each box can be split into sections using “divisors,” and every section can hold at most a certain number of nuts.

codeforcescompetitive-programminggreedymath
CF 402B - Trees in a Row

We have a row of trees, each with a given height. The Queen wants the trees arranged in perfect arithmetic progression: the difference between consecutive tree heights must be exactly $k$.

codeforcescompetitive-programmingbrute-forceimplementation
CF 401C - Team

We are asked to arrange a set of cards, some marked with zero and some with one, in a line so that no two zeros are adjacent and no three ones are consecutive. We know the counts of each type of card upfront: n zeros and m ones.

codeforcescompetitive-programmingconstructive-algorithmsgreedyimplementation
CF 401A - Vanya and Cards

Vanya has found a subset of his playing cards, each card labeled with an integer between $-x$ and $x$. He wants the total sum of all his cards to be zero. We need to determine the minimum number of additional cards he should find to achieve that zero sum.

codeforcescompetitive-programmingimplementationmath
CF 353A - Domino

We have a row of domino tiles. Each tile has a number on its upper half and a number on its lower half. For every tile, we may either leave it as it is or rotate it by 180 degrees. Rotating a tile simply swaps its upper and lower values. Each rotation costs one second.

codeforcescompetitive-programmingimplementationmath
CF 353C - Find Maximum

We are given an array of non-negative integers a with length n and a number m in binary form. We want to select a subset of indices from 0 to n-1 and sum the corresponding a[i] values, but with a twist: the subset corresponds to the binary representation of some integer x…

codeforcescompetitive-programmingimplementationmathnumber-theory
CF 353E - Antichain

Codeforces 353E: Antichain

codeforcescompetitive-programmingdpgraph-matchingsgreedy
CF 353D - Queue

We are given a line of schoolchildren represented as a string of letters M and F, where M indicates a boy and F a girl. Each second, any boy standing immediately in front of a girl swaps positions with her. This process repeats until no boy is in front of a girl.

codeforcescompetitive-programmingconstructive-algorithmsdp
CF 353B - Two Heaps

Each cube contains a two digit number. We must split the 2n cubes into two heaps of exactly n cubes each. After the split, Valera may choose any cube from the first heap and any cube from the second heap.

codeforcescompetitive-programmingcombinatoricsconstructive-algorithmsgreedyimplementationmathsortings
CF 351C - Jeff and Brackets

We are asked to construct a bracket sequence of length n·m, where n is a small number up to 20 and m is much larger, up to 10^7, and is even. Each position in the sequence can be either an opening bracket ( or a closing bracket ).

codeforcescompetitive-programmingdpmatrices
CF 351A - Jeff and Rounding

Jeff has a list of 2n real numbers and he wants to round them in pairs so that the total sum changes as little as possible. Each operation consists of taking two unused numbers: one is rounded down (floor) and the other rounded up (ceiling).

codeforcescompetitive-programmingdpgreedyimplementationmath
CF 351E - Jeff and Permutation

We are given a sequence of integers, and we are allowed to flip the sign of any element. The goal is to minimize the number of inversions in the sequence. An inversion occurs whenever a larger number appears before a smaller number in the sequence.

codeforcescompetitive-programminggreedy
CF 351D - Jeff and Removing Periods

For each query we look at a subarray of the given array and ask for its beauty. A single operation chooses several equal values whose positions form an arithmetic progression, removes them, and then allows us to reorder everything that remains. That last sentence is the key.

codeforcescompetitive-programmingdata-structures
CF 351B - Jeff and Furik

We are asked to model a two-player game played on a permutation of integers from 1 to n. Jeff moves first and can swap any adjacent elements.

codeforcescompetitive-programmingcombinatoricsdpprobabilities
Kvant Math Problem 2867

Label the people around the circle as a cyclic sequence of 60 vertices, each colored either $B$ (boy) or $G$ (girl), with exactly 30 of each color.

kvantmathematicsolympiad
Kvant Math Problem 2738

Let

kvantmathematicsolympiad
Kvant Math Problem 1592

Let integers $a \le b$ be such that the required sum is

kvantmathematicsolympiad
Kvant Math Problem 1528

The relation

kvantmathematicsolympiad
CF 350C - Bombs

We are given a set of points on an infinite grid, each point containing a single bomb. A robot starts at the origin and must eventually destroy every bomb, but it cannot simply “teleport” to them.

codeforcescompetitive-programminggreedyimplementationsortings
CF 350E - Wrong Floyd

We are given an undirected, simple, connected graph with $n$ vertices and $m$ edges. In addition, a subset of vertices $a1, a2, dots, ak$ is designated as “special”.

codeforcescompetitive-programmingbrute-forceconstructive-algorithmsdfs-and-similargraphs
CF 350D - Looking for Owls

We are asked to count "owls" in a geometric picture composed of segments and circles. An owl is defined as a combination of two circles and a segment where the circles are reflections of each other across the segment, have identical radii, do not overlap, and the segment…

codeforcescompetitive-programmingbinary-searchdata-structuresgeometryhashingsortings
CF 350A - TL

We are asked to help Valera set a time limit for a programming problem. He has a set of correct solutions, each with a known runtime, and a set of wrong solutions, also with runtimes.

codeforcescompetitive-programmingbrute-forcegreedyimplementation
Kvant Math Problem 1487

Place the circumcenter $O$ as a reference point and represent the triangle on its circumcircle.

kvantmathematicsolympiad
CF 349B - Color the Fence

Igor wants to paint the largest possible number on a fence using a limited amount of paint. Each digit from 1 to 9 has a specific paint cost, and zero cannot be used.

codeforcescompetitive-programmingdata-structuresdpgreedyimplementation
CF 349A - Cinema Line

We are given a queue of people waiting to buy cinema tickets. Each person holds a bill worth 25, 50, or 100 rubles, and each ticket costs 25 rubles. The clerk starts with no money and must sell tickets in the exact order of the line, giving correct change if necessary.

codeforcescompetitive-programminggreedyimplementation
CF 348C - Subset Sums

We are given an array of integers and a collection of subsets, each referencing indices in the array. Two types of operations are performed repeatedly: querying the sum of the elements of a subset, and adding a value to all elements of a subset.

codeforcescompetitive-programmingbrute-forcedata-structures
Kvant Math Problem 1453

Let $n_k$ be the repunit of length $k$, so

kvantmathematicsolympiad
CF 348B - Apple Tree

We are given a rooted tree where only the leaves initially contain apples, while internal nodes are empty. Each leaf contributes a fixed number of apples, and the “weight” of any subtree is defined as the total number of apples in all leaves inside that subtree.

codeforcescompetitive-programmingdfs-and-similarnumber-theorytrees
CF 348E - Pilgrims

We are given a weighted tree with n towns. Some of these towns contain monasteries, and each monastery hosts exactly one pilgrim.

codeforcescompetitive-programmingdfs-and-similardptrees
CF 348D - Turtles

We are given a rectangular grid of size n by m, where each cell is either free or blocked. Two turtles start at the top-left corner, cell (1,1), and both want to reach the bottom-right corner, cell (n,m).

codeforcescompetitive-programmingdpmatrices
CF 348A - Mafia

We are given a group of friends who will repeatedly play a game. Each round of the game has exactly one person acting as a supervisor, while the remaining $n-1$ people participate as players.

codeforcescompetitive-programmingbinary-searchmathsortings
Kvant Math Problem 962

Let $P(x)\in\mathbb{Z}[x]$ and suppose there exist distinct integers $x_1,\dots,x_n$ with $n\ge 3$ such that

kvantmathematicsolympiad
CF 347A - Difference Row

We are given a list of n integers and need to arrange them in a row such that the sum of differences between consecutive numbers is maximized. Concretely, if the arrangement is $x1, x2, dots, xn$, the value is calculated as $(x1 - x2) + (x2 - x3) + dots + (x{n-1} - xn)$.

codeforcescompetitive-programmingconstructive-algorithmsimplementationsortings
Kvant Math Problem 873

The process can be encoded in terms of the coefficients $a$ and $b$ of the quadratic $x^2+ax+b$, starting from $(a,b)=(10,20)$ and ending at $(20,10)$.

kvantmathematicsolympiad
CF 347B - Fixed Points

We are given a permutation of numbers from 0 to n − 1, stored in an array where each index represents a position and the value at that index represents where that position “points”. A position i is called a fixed point if the value stored at that position is exactly i.

codeforcescompetitive-programmingbrute-forceimplementationmath
CF 346C - Number Transformation II

We start with a number a and want to reduce it down to b using two types of moves. One move simply decreases the current value by 1. The other move is more interesting: we pick one of the given numbers xi and subtract the remainder of the current value when divided by xi.

codeforcescompetitive-programminggreedymath
CF 346A - Alice and Bob

We start with a finite set of distinct positive integers. Two players alternate turns, and on each turn a player is allowed to take any two existing numbers, compute their absolute difference, and insert that value into the set if it is not already present.

codeforcescompetitive-programminggamesmathnumber-theory
Kvant Math Problem 803

Let $x,y \in \mathbb{Q}\setminus{0}$ satisfy

kvantmathematicsolympiad
CF 346E - Doodle Jump

We are given a sequence of platform heights generated by a modular arithmetic rule. The x-th platform sits at height (a · x) mod p, where a and p are coprime and we only consider the first n such positions.

codeforcescompetitive-programmingmathnumber-theory
CF 346D - Robot Control

We are given a directed graph representing a map a robot can traverse. The robot starts at a vertex s and must reach a target vertex t.

codeforcescompetitive-programmingdpgraphsshortest-paths
CF 346B - Lucky Common Subsequence

We are asked to build a sequence that appears as a subsequence of two given strings while avoiding a third string as a contiguous pattern.

codeforcescompetitive-programmingdpstrings
CF 345G - Suffix Subgroup

We are given a list of strings, and the task is to find the largest possible subset of these strings such that all strings in the subset are suffixes of some single string. In other words, there should exist a string t that ends with every string in our chosen subset.

codeforcescompetitive-programming*specialstrings
Kvant Math Problem 715

The rule replaces one chip by two chips placed one step north and one step east, provided those target cells are empty.

kvantmathematicsolympiad
CF 345B - Triskaidekaphobia

We are given a number $n le 10^5$. For every integer base $b ge 2$, we write $n$ in base $b$, but instead of usual digit symbols we represent each digit as a decimal number and concatenate them without separators.

codeforcescompetitive-programming*special
Kvant Math Problem 687

We model the configuration as follows.

kvantmathematicsolympiad
Kvant Math Problem 659

For the Fibonacci sequence $f_1=1$, $f_2=2$, $f_{k+1}=f_k+f_{k-1}$, the first terms are

kvantmathematicsolympiad
Kvant Math Problem 599

Let $A=4^{5^6}+6^{5^4}$.

kvantmathematicsolympiad
CF 345E - Black Cat Rush

We are moving along a straight line from (0, 0) to (a, 0) at a constant speed v. Around us, there are n black cats, each starting at a point (xi, yi). Each cat can move in any direction at speed at most u.

codeforcescompetitive-programming*special
Kvant Math Problem 580

Let $G$ be the graph whose vertices are parliamentarians and edges represent mutual enmity.

kvantmathematicsolympiad
CF 345D - Chain Letter

We are given a network of people, where every pair of people either knows each other in both directions or does not know each other at all.

codeforcescompetitive-programming*specialdfs-and-similargraphs
CF 345A - Expecting Trouble

We are given a string representing Fridays the 13th across some period of time. Each character in the string can be "0" for a normal day, "1" for a particularly bad day, or "?" for a day the user cannot recall.

codeforcescompetitive-programming*specialprobabilities
Kvant Math Problem 570

Let the squares have side lengths $a_1, a_2, \dots, a_n$, so that

kvantmathematicsolympiad
CF 343A - Rational Resistance

We are asked to construct a resistor network using only unit resistors to achieve a specific rational resistance $frac{a}{b}$.

codeforcescompetitive-programmingmathnumber-theory
Kvant Math Problem 559

Let

kvantmathematicsolympiad
CF 343C - Read Time

We are asked to simulate multiple read heads moving along a linear hard drive to read a set of target tracks as quickly as possible. Each head starts at a given track, can move left, right, or stay in place, and multiple heads can occupy the same track.

codeforcescompetitive-programmingbinary-searchgreedytwo-pointers
Kvant Math Problem 498

Consider small values of $n$.

kvantmathematicsolympiad
CF 343E - Pumping Stations

We are asked to maximize the total amount of water Mike can pump across a network of stations in a sequence of days. Each station is a node in an undirected graph, and pipes between stations are edges with capacities.

codeforcescompetitive-programmingbrute-forcedfs-and-similardivide-and-conquerflowsgraphsgreedytrees
Kvant Math Problem 480

The recurrence is

kvantmathematicsolympiad
CF 343D - Water Tree

We are given a rooted tree where every node behaves like a reservoir that can either contain water or be empty. The root is fixed at node 1, and all edges are directed conceptually away from it.

codeforcescompetitive-programmingdata-structuresdfs-and-similargraphstrees
Kvant Math Problem 467

The triangle is equilateral, so placing it in a coordinate system with one side horizontal allows algebraic control over all distances and angles.

kvantmathematicsolympiad
CF 343B - Alternating Current

We are given a sequence that describes how two wires, one called “plus” and the other “minus”, overlap as they run from the left side to the right side of a device. At each position along the path, exactly one of the wires is physically above the other.

codeforcescompetitive-programmingdata-structuresgreedyimplementation
Kvant Math Problem 448

Let the quadrilateral have diagonals intersecting at a point $O$.

kvantmathematicsolympiad
CF 342C - Cupboard and Balloons

The task is to determine how many spherical balloons of radius 1 can fit inside a cupboard shaped like a semicircle on top of a rectangle. The cupboard has a semicircular top with radius r and vertical walls of height h, forming a depth also equal to r.

codeforcescompetitive-programminggeometry
Kvant Math Problem 420

The allowed operations on a fraction $\frac{a}{b}$ replace the integer pair $(a,b)$ by one of $(a-b,b)$, $(a+b,b)$, or $(b,a)$.

kvantmathematicsolympiad
CF 342B - Xenia and Spies

A note starts at one spy positioned at index s in a line of n spies. The note must eventually reach another spy at position f.

codeforcescompetitive-programmingbrute-forcegreedyimplementation
Kvant Math Problem 402

From the condition with $n=m=1$ we obtain

kvantmathematicsolympiad
Kvant Math Problem 367

For three consecutive natural numbers $n, n+1, n+2$, the key structural feature is that any two of them are coprime.

kvantmathematicsolympiad
CF 342E - Xenia and Tree

We are working with a tree where every node represents a point in a connected acyclic graph. Initially only node 1 is colored red, while every other node starts blue. Over time, we perform two kinds of operations.

codeforcescompetitive-programmingdata-structuresdivide-and-conquertrees
Kvant Math Problem 243

Let the two given lines be denoted $l_1$ and $l_2$.

kvantmathematicsolympiad
CF 342D - Xenia and Dominoes

We are given a 3×n grid representing a puzzle board. Each cell can be forbidden, free, or marked with a special circle. Dominoes, which are 1×2 or 2×1 tiles, must be placed to cover exactly two non-forbidden cells.

codeforcescompetitive-programmingbitmasksdfs-and-similardp
CF 342A - Xenia and Divisors

We are given a sequence of positive integers, all between 1 and 7, and the length of the sequence is divisible by three.

codeforcescompetitive-programminggreedyimplementation
Kvant Math Problem 196

Work in the unit circle centered at $O$.

kvantmathematicsolympiad
CF 341D - Iahub and Xors

We are given an $n times n$ matrix initially filled with zeros. The problem asks us to handle two types of operations efficiently: one that computes the xor of all elements inside a submatrix, and another that xors a given value into every element of a submatrix.

codeforcescompetitive-programmingdata-structures
CF 341E - Candies Game

We are given a set of boxes, each containing some number of candies. The objective is to redistribute candies such that exactly two boxes contain all the candies, and every other box is empty.

codeforcescompetitive-programmingconstructive-algorithmsgreedy
CF 340B - Maximal Area Quadrilateral

We are given a set of $n$ points in the 2D Cartesian plane, and we are asked to select four of these points to form a quadrilateral with the maximal area. The quadrilateral does not need to be convex, but it must have four vertices from the given points and cannot self-intersect.

codeforcescompetitive-programmingbrute-forcegeometry
CF 340C - Tourist Problem

We have several destinations located on a straight line at positions $a1,a2,dots,an$, all strictly positive and distinct. A route is simply a permutation of these destinations.

codeforcescompetitive-programmingcombinatoricsimplementationmath