contest_id
stringlengths
1
4
index
stringclasses
43 values
title
stringlengths
2
63
statement
stringlengths
51
4.24k
tutorial
stringlengths
19
20.4k
tags
listlengths
0
11
rating
int64
800
3.5k
⌀
code
stringlengths
46
29.6k
⌀
1195
E
OpenStreetMap
Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size $n \times m$ cells on a map (rows of grid are numbered from $1$ to $n$ from north to south, and columns are numbered from $1$ to $m$ from west to east). After that he measured the average h...
There is almost nothing to say about this problem. It is pretty standard data structure problem. Let $mn_{i, j}$ be the minimum value over all values $h_{i, j}, h_{i - 1, j}, \dots, h_{i - a + 1}{j}$. If $i$ is less than $a$ then its value does not matter for us because the corresponding submatrix is not counted in the...
[ "data structures", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; long long n, m, a, b, g, x, y, z; vector<deque<long long> > deq; vector<vector<long long> > mi; vector<int> power; const long long MAX_V = 1000000000000000ll; void ins(deque<long long>& de, long long val) { while(!de.empty() && de.back() > val) { de.pop_back(...
1195
F
Geometers Anonymous Club
Denis holds a Geometers Anonymous Club meeting in SIS. He has prepared $n$ convex polygons numbered from $1$ to $n$ for the club. He plans to offer members of the club to calculate Minkowski sums of these polygons. More precisely, he plans to give $q$ tasks, the $i$-th of them asks to calculate the sum of Minkowski of ...
Suppose we want to compute the Minkowski sum of two polygons $a$ and $b$. Let's denote two sequences of free vectors: $u_1$, $u_2$, ..., $u_{k_a}$ such that free vector $u_i$ is congruent to the bound vector starting in $i$-th vertex of the first polygon and ending in the $(i + 1)$-th vertex of this polygon (if $i = k_...
[ "data structures", "geometry", "math", "sortings" ]
2,500
// Created by Nikolay Budin #ifdef LOCAL # define _GLIBCXX_DEBUG #else # define cerr __get_ce #endif #include <bits/stdc++.h> #define ff first #define ss second #define szof(x) ((int)x.size()) using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef unsigned long long u...
1196
A
Three Piles of Candies
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
The answer is always $\lfloor\frac{a + b + c}{2}\rfloor$. Let's understand why it is so. Let $a \le b \le c$. Then let Bob take the pile with $a$ candies and Alice take the pile with $b$ candies. Then because of $b \le a + c$ we can see that Bob's pile always can reach size of Alice's pile (and remaining candies can be...
[ "brute force", "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { long long a, b, c; cin >> a >> b >> c; cout << (a + b + c) / 2 << endl; } return 0; }
1196
B
Odd Sum Segments
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. You want to split it into exactly $k$ \textbf{non-empty non-intersecting subsegments} such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearra...
Firstly, let $cnt$ be the number of odd elements in the array. Note that even elements are don't matter at all because they cannot change the parity of the sum. If $cnt < k$ then it is obviously impossible to split the given array into $k$ subsegments with odd sum. And if $cnt \% 2 \ne k \% 2$ then it is impossible to ...
[ "constructive algorithms", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n, k; cin >> n >> k; vector<int> a(n); int cntodd = 0; for (int j = 0; j < n; ++j) { cin >> a[j...
1196
C
Robot Breakout
$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the loc...
In fact, we have some restrictions on $OX$ axis and $OY$ axis (for example, if some robot stays at the position $x$ and cannot move to the left, then the answer point should have $X \ge x$). So we can take the minimum among all $y$-coordinates of robots that cannot go up and save it into $maxy$, maximum among all $y$-c...
[ "implementation" ]
1,500
#include <algorithm> #include <iostream> using namespace std; const int MAXC = 1e5; int main() { int q; cin >> q; while (q--) { int n; cin >> n; int mnx = -MAXC, mxx = MAXC; int mny = -MAXC, mxy = MAXC; while (n--) { int x, y, f1, f2, f3, f4; ...
1196
D1
RGB Substring (easy version)
\textbf{The only difference between easy and hard versions is the size of the input}. You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'. You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the chang...
You can just implement what is written in the problem statement and solve this problem this way. Let's iterate over all starting positions of the substring $i$ from $0$ to $n-k+1$ and over all possible offsets of the string $t$ = "RGB" $offset$ from $0$ to $2$ inclusive. Then let's iterate over all position of the curr...
[ "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif const string t = "RGB"; int q; cin >> q; for (int i = 0; i < q; ++i) { int n, k; string s; cin >> n >> k >> s; int ans = 1e9; for (int j = 0; j < n...
1196
D2
RGB Substring (hard version)
\textbf{The only difference between easy and hard versions is the size of the input}. You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'. You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the chang...
In this problem you should make the same as in the previous one but faster. Let's consider three offsets of string "RGB": "RGB", "GBR" and "BRG". Let's copy the current offset of the string so that it will has the length $n$ (possibly, without some trailing characters) and save it in the string $t$. Then let's compare ...
[ "data structures", "dp", "implementation", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif const string t = "RGB"; int q; cin >> q; for (int i = 0; i < q; ++i) { int n, k; string s; cin >> n >> k >> s; int ans = 1e9; for (int offset = 0; ...
1196
E
Connected Component on a Chessboard
You are given two integers $b$ and $w$. You have a chessboard of size $10^9 \times 10^9$ with the top left cell at $(1; 1)$, the cell $(1; 1)$ is painted \textbf{white}. Your task is to find a connected component on this chessboard that contains exactly $b$ black cells and exactly $w$ white cells. Two cells are called...
I'll consider the case when $b \ge w$, the other case is symmetric and the answer I construct is the same but shifted by $1$ to the right. Consider the given field as a matrix where $x$ is the number of row and $y$ is the number of column. Firstly, let's build the line of length $2w-1$ from the cell $(2, 2)$ to the cel...
[ "constructive algorithms", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int b, w; cin >> b >> w; vector<pair<int, int>> res; bool need = b < w; if (need) swap(w, b); int x ...
1196
F
K-th Path
You are given a connected undirected weighted graph consisting of $n$ vertices and $m$ edges. You need to print the $k$-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one). More formally, if $d$ is the matrix of shorte...
The main observation is that you don't need more than $min(k, m)$ smallest by weight edges (among all edges with the maximum weights you can choose any). Maybe there will be a proof later, but now I ask other participant to write it. So you sort the initial edges and after that you can construct a graph consisting of n...
[ "brute force", "constructive algorithms", "shortest paths", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; const long long INF64 = 1e18; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, k; scanf("%d %d %d", &n, &m, &k); vector<pair<int, pair<int, int>>> e; for (int i = 0; i < m; ++i) { int x, y, w; ...
1197
A
DIY Wooden Ladder
Let's denote a $k$-step ladder as the following structure: exactly $k + 2$ wooden planks, of which - two planks of length \textbf{at least} $k+1$ — the base of the ladder; - $k$ planks of length \textbf{at least} $1$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be...
Since all planks have length at least $1$ so we can take any $n - 2$ planks as steps. So, all we need is to maximize the length of base planks. We can take the first and second maximum as base, then the answer is minimum among second maximum - 1 and $n - 2$.
[ "greedy", "math", "sortings" ]
900
fun main(args: Array<String>) { val T = readLine()!!.toInt() for (tc in 1..T) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() }.sortedDescending() println(minOf(a[1] - 1, n - 2)) } }
1197
B
Pillars
There are $n$ pillars aligned in a row and numbered from $1$ to $n$. Initially each pillar contains exactly one disk. The $i$-th pillar contains a disk having radius $a_i$. You can move these disks from one pillar to another. You can take a disk from pillar $i$ and place it on top of pillar $j$ if all these condition...
Suppose we have a disk that is smaller than both of its neighbours. Then it's impossible to collect all the disks on the same pillar: eventually we will put this disk on the same pillar with one of its neighbours, and then we can't put the other neighbouring disk on the same pillar since it is greater than the middle d...
[ "greedy", "implementation" ]
1,000
#include<bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); int pos = max_element(a.begin(), a.end()) - a.begin(); bool res = true; for(int i = 0; i < pos; i++) res &= (a[i] < a[i + 1]); for(int i = pos; i < n - 1; i+...
1197
C
Array Splitting
You are given a \textbf{sorted} array $a_1, a_2, \dots, a_n$ (for each index $i > 1$ condition $a_i \ge a_{i-1}$ holds) and an integer $k$. You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $max(i)$ be equal to the m...
Let's carefully look at the coefficients with which the elements of the array will be included in the answer. If pair of adjacent elements $a_i$ and $a_{i+1}$ belong to different subarrays then element $a_i$ will be included in the answer with coefficient $1$, and element $a_{i+1}$ with coefficient $-1$. So they add va...
[ "greedy", "sortings" ]
1,400
#include<bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int n, k; int a[N]; int main(){ cin >> n >> k; for(int i = 0; i < n; ++i) cin >> a[i]; vector <int> v; for(int i = 1; i < n; ++i) v.push_back(a[i - 1] - a[i]); sort(v.begin(), v.end()); int res = a[n - 1] - a[0]; for(int i = 0;...
1197
D
Yet Another Subarray Problem
You are given an array $a_1, a_2, \dots , a_n$ and two integers $m$ and $k$. You can choose some subarray $a_l, a_{l+1}, \dots, a_{r-1}, a_r$. The cost of subarray $a_l, a_{l+1}, \dots, a_{r-1}, a_r$ is equal to $\sum\limits_{i=l}^{r} a_i - k \lceil \frac{r - l + 1}{m} \rceil$, where $\lceil x \rceil$ is the least in...
At first let's solve this problem when $m = 1$ and $k = 0$ (it is the problem of finding subarray with maximum sum). For each position from $1$ to $n$ we want to know the value of $maxl_i = \max\limits_{1 \le j \le i + 1} sum(j, i)$, where $sum(l, r) = \sum\limits_{k = l}^{k \le r} a_k$, and $sum(x+1, x) = 0$. We will ...
[ "dp", "greedy", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int n, m, k; int a[N]; long long bst[N]; long long psum[N]; long long sum(int l, int r){ l = max(l, 0); return psum[r] - (l == 0? 0 : psum[l - 1]); } int main() { cin >> n >> m >> k; for(int i = 0; i < n; ++i){ cin >> a[i]; psum[...
1197
E
Culture Code
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $n$ different matryoshkas. Any matryoshka is a figure of volume $out_i$ with an empty space inside of volume $in_i$ (of course, $out_i > in_i$). You don't have much f...
Let's, at first, sort all matryoshkas by increasing its inner volume $in_i$. Then each nested subset will appear as subsequence in its "canonical" order. Now we'll write the DP with $d[i] = (x, y)$ - the minimum extra space $x$ and number of such subsequences $y$ among all nested subsets, where the $i$-th doll is minim...
[ "binary search", "combinatorics", "data structures", "dp", "shortest paths", "sortings" ]
2,300
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9) + 555; const li INF64 = li(1e18); const ld EPS = 1...
1197
F
Coloring Game
Alice and Bob want to play a game. They have $n$ colored paper strips; the $i$-th strip is divided into $a_i$ cells numbered from $1$ to $a_i$. Each cell can have one of $3$ colors. In the beginning of the game, Alice and Bob put $n$ chips, the $i$-th chip is put in the $a_i$-th cell of the $i$-th strip. Then they tak...
Suppose there is only one strip and we want to count the number of ways to paint it. We can do it with some dynamic programming: let $dp_{i, r_1, r_2, r_3}$ be the number of ways to paint first $i$ cells of the strip so that $r_1$ denotes the result of the game if it starts in the last cell ($r_1 = 0$ if the player tha...
[ "dp", "games", "matrices" ]
2,700
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { return (x + y) % MOD; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } typedef vector<int> vec; typedef vector<vec> mat; vec mul(const mat& a, const vec& b) { int n = a.size(); int m = b.size(); vector<int>...
1198
A
MP3
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers. If there are exactly $K$ distinct values in the array, then we need $k = \lcei...
First let's calculate how many different values we can have. Maximal $k$ is $\frac{8I}{n}$, maximal $K$ is $2^{k}$. We have to be careful not to overflow, let's use $K=2^{\min(20, k)}$ ($2^{20}$ is bigger than any $n$). Let's sort the array and compress equal values. Now we have to choose no more than $K$ consecutive v...
[ "sortings", "two pointers" ]
1,600
null
1198
B
Welfare State
There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the g...
For every citizen only the last query of type $1$ matters. Moreover, all queries before don't matter at all. So the answer for each citizen is maximum of $x$ for last query of type $1$ for this citizen and maximum of all $x$ for queries of type $2$ after that. We can calculate maximum $x$ for all suffices of queries of...
[ "binary search", "brute force", "data structures", "sortings" ]
1,600
null
1198
C
Matching vs Independent Set
You are given a graph with $3 \cdot n$ vertices and $m$ edges. You are to find a matching of $n$ edges, \textbf{or} an independent set of $n$ vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge.
Let's try to take edges to matching greedily in some order. If we can add an edge to the matching (both endpoints are not covered), then we take it. It is easy to see that all vertices not covered by the matching form an independent set - otherwise we would add an edge to the matching. Either matching or independent se...
[ "constructive algorithms", "graphs", "greedy", "sortings" ]
2,000
null
1198
D
Rectangle Painting 1
There is a square grid of size $n \times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\max(h, w)$ to color a rectangle of size $h \times w$. You are to make all cells white for minimum total cost.
Let's solve the problem for rectangle $W \times H$ ($W \ge H$). Of course, we can cover all rectangle with itself for cost $W$. To get something smaller than $W$ we have to leave at least one column uncovered - otherwise we pay at least sum of $w$ over all rectangles which is at least $W$. This gives us an idea to use ...
[ "dp" ]
2,300
null
1198
E
Rectangle Painting 2
There is a square grid of size $n \times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\min(h, w)$ to color a rectangle of size $h \times w$. You are to make all cells white for minimum total cost. The sq...
If we use some rectangle $[x_{1};x_{2}) \times [y_{1};y_{2})$ ($x_{2}-x_{1} \le y_{2}-y_{1}$), then we can change it to $[x_{1};x_{2}) \times [0, n)$ without changing the cost. Also we can choose $w$ rectangles of width $1$ instead of one rectangle of width $w$, it will not change the cost. So, we have to choose minima...
[ "flows", "graph matchings", "graphs" ]
2,500
null
1198
F
GCD Groups 2
You are given an array of $n$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one. The GCD of a group of integers is the largest non-negative integer that divides all the integers in ...
All numbers have no more than $k=9$ different prime divisors. If there exist a solution, then for every number there exist a solution in which this number is in group of size not more than $(k+1)$, because all we have to do is to "kill" all prime numbers from this number, and to do it we only need one number for each p...
[ "greedy", "number theory", "probabilities" ]
2,900
null
1199
A
City Day
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $n$ days of summer. On the $i$-th day, $a_i$ millimeters of rain will fall. All values $a_i$ are distinct. The...
$x$ and $y$ are small, so we can explicitly check every day. Complexity $O(n(x+y))$.
[ "implementation" ]
1,000
null
1199
B
Water Lily
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $H$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $L$ centimeters. Exactly at this point the flower touched the water su...
We can use Pythagorean theorem and get the equation $x^{2} + L^{2} = (H+x)^{2}$. Its solution is $x=\frac{L^{2}-H^{2}}{2H}$.
[ "geometry", "math" ]
1,000
null
1200
A
Hotelier
Amugae has a hotel consisting of $10$ rooms. The rooms are numbered from $0$ to $9$ from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. S...
Make an array of size 10 filled with 0. Then for each character from the input: L : Find the first position containing 0, then change it to 1. R : Find the last position containing 0, then change it to 1. 0 9 : array[x] = 0. Time complexity: $O(n)$
[ "brute force", "data structures", "implementation" ]
800
null
1200
B
Block Adventure
Gildong is playing a video game called Block Adventure. In Block Adventure, there are $n$ columns of blocks in a row, and the columns are numbered from $1$ to $n$. All blocks have equal heights. The height of the $i$-th column is represented as $h_i$, which is the number of blocks stacked in the $i$-th column. Gildong...
We can easily see that it's always optimal to have as many blocks as possible in the bag before getting to the next column. Therefore, if the character is currently on the top of the $i$-th column, Gildong just needs to make $h_i$ become $max(0, h_{i+1} - k)$ by repeating the $1$-st or the $2$-nd action. In other words...
[ "dp", "greedy" ]
1,200
null
1200
C
Round Corridor
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $n$ sectors, and the outer area is equally divided by $m$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. ...
Denote the corridor's length as $1$. Then, there is a wall at $(1, \frac{1}{n}), (1, \frac{2}{n}), \cdots, (1, \frac{n}{n}), (2, \frac{1}{m}), (2, \frac{2}{m}), \cdots (2, \frac{m}{m})$. For some value $x$, If there are walls at $(1, x)$ and $(2, x)$ at the same time, we can't move from $y$ to $z$ for $y \lt x$ and $z ...
[ "math", "number theory" ]
1,400
null
1200
D
White Lines
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $n$ rows and $n$ columns of square cells. The rows are numbered from $1$ to $n$, from top to bottom, and the columns are numbered from $1$ to $n$, from left to right. The position of a cell at row $r$ and...
Let's consider a single row that contains at least one black cell. If the first appearance of a black cell is at the $l$-th column and the last appearance of a black cell is at the $r$-th column, we can determine whether it becomes a white line when a certain cell $(i, j)$ is clicked in $O(1)$, after some preprocessing...
[ "brute force", "data structures", "dp", "implementation", "two pointers" ]
1,900
null
1200
E
Compress Words
Amugae has a sentence consisting of $n$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "...
Denote the words from left to right as $W_1, W_2, W_3, \cdots, W_n$. If we define string $F(k)$ as the result of merging as described in the problem $k$ times, we can get $F(k+1)$ by the following process: If length of $F(k)$ > length of $W_{k+1}$ Assume the length of $F(K)$ is $x$, and the length of $W_{k+1}$ is $y$. ...
[ "brute force", "hashing", "implementation", "string suffix structures", "strings" ]
2,000
null
1200
F
Graph Traveler
Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of $n$ vertices numbered from $1$ to $n$. The $i$-th vertex has $m_i$ outgoing edges that are labeled as $e_i[0]$, $e_i[1]$, $\ldots$, $e_i[m_i-1]$, each representing the destination vertex of th...
Since a travel will never end, it is clear that every travel will eventually get into an infinite loop. But we should consider more than just the vertices, since $c$ could be different every time he visits the same vertex. Since the number of outgoing edges of each vertex is at most $10$, we can see a state can be redu...
[ "brute force", "data structures", "dfs and similar", "dp", "graphs", "implementation", "math", "number theory" ]
2,300
null
1201
A
Important Exam
A class of students wrote a multiple-choice test. There are $n$ students in the class. The test had $m$ questions, each of them had $5$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $i$ worth $a_i$ points. Incorrect answers are graded with ze...
For each of the question let's count the number of answers of different type. Let $cnt[i][A]=$The number of A answers to the i-th question. The maximum score for that answer is $a[i]\cdot max(cnt[i][A], cnt[i][B], cnt[i][C], cnt[i][D], cnt[i][E])$. The answer is the sum of the maximum answer for the $m$ questions.
[ "implementation", "strings" ]
900
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, m; string s[1005]; ll a[1005]; ll ans; ll b[1005][5]; ll ma; int main() { ios_base::sync_with_stdio(false); cin>>n>>m; for (ll i=1; i<=n; i++) { cin>>s[i]; } for (ll i=0; i<m; i++) { cin>>a[i]; } ...
1201
B
Zero Array
You are given an array $a_1, a_2, \ldots, a_n$. In one operation you can choose two elements $a_i$ and $a_j$ ($i \ne j$) and decrease each of them by one. You need to check whether it is possible to make all the elements equal to zero or not.
There are 2 things needed to be possible to make all elements zero: 1: The sum of the elements must be even. 2: The biggest element have to be less or equal than the sum of all the other elements. If both are true, the answer is "YES", otherwise "NO".
[ "greedy", "math" ]
1,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, m, a, s; int main() { ios_base::sync_with_stdio(false); cin>>n; for (ll i=1; i<=n; i++) { cin>>a; s+=a; m=max(m, a); } if (s%2==1 || s<2*m) { cout<<"NO"; return 0; } cout<...
1201
C
Maximum Median
You are given an array $a$ of $n$ integers, where $n$ is odd. You can make the following operation with it: - Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$). You want to make the median of the array the largest possible using at most $k$ operati...
Sort the array in non-decreasing order. In the new array $b_1, b_2, \ldots, b_n$ you can make binary search with the maximum median value. For a given median value ($x$), it is required to make $\sum_{i=(n+1)/2}^{n} max(0,x-b_i)$ operations. If this value is more than $k$, $x$ can't be median, otherwise it can. Time co...
[ "binary search", "greedy", "math", "sortings" ]
1,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, k; ll x; vector < ll > a; bool check(ll x) { ll moves=0; for (int i=n/2; i<n; i++) { if (x-a[i]>0) moves+=x-a[i]; if (moves>k) return false; } if (moves<=k) return true; else return false; } int main() { ...
1201
D
Treasure Hunting
You are on the island which can be represented as a $n \times m$ table. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are $k$ treasures on the island, the $i$-th of them is located at the position $(r_i, c_i)$. Initially you stand at the lower left corner of the island, at t...
Make two arrays: left and right. $left[i]$ is the treasure in the leftmost position in row i (0 if there are no treasures in row $i$). $right[i]$ is the treasure in the rightmost cell in row $i$ (0 if there are no treasures in row $i$). We can simply take out rows where there is no treasure (and add 1 to the result if ...
[ "binary search", "dp", "greedy", "implementation" ]
2,100
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, m, k, q; ll tleft[300005]; ll tright[300005]; ll safeleft[300005]; ll saferight[300005]; ll a[300005][4]; ll b[4]; ll ans; vector < ll > safe; ll dis(ll pa, ll pb) { return abs(pa-pb); } ll solve(ll i, ll x, ll y) { ll ansa=dis(x, tright[i...
1201
E2
Knightmare (hard)
This is an interactive problem. Alice and Bob are playing a game on the chessboard of size $n \times m$ where $n$ and $m$ are \textbf{even}. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are two knights on the chessboard. A white one initially is on the position $(x_1, y_1)$...
First calculate the number of moves needed to reach (without capturing) positions $(a_1;b_1)$ and $(a_2;b_2)$. If one of the knights can reach it's goal at least 2 moves faster than the other can and faster than the other can reach it's goal, than there is a winning strategy with it. Just go the shortest path. The othe...
[ "graphs", "interactive", "shortest paths" ]
3,000
/** * This line was copied from template * This is nk_n4.cpp * * @author: Nikolay Kalinin * @date: Sun, 04 Aug 2019 03:59:47 +0300 */ #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif using ll = long long...
1202
A
You Are Given Two Binary Strings...
You are given two binary strings $x$ and $y$, which are binary representations of some two integers (let's denote these integers as $f(x)$ and $f(y)$). You can choose any integer $k \ge 0$, calculate the expression $s_k = f(x) + f(y) \cdot 2^k$ and write the binary representation of $s_k$ in \textbf{reverse order} (let...
Multiplying by power of $2$ is "shift left" binary operation (you, probably, should know it). Reverse $x$ and $y$ for the simplicity and look at leftmost $1$ in $y$ (let's denote its position as $pos_y$). If you move it to $0$ in $x$ then you make the $rev_k$ lexicographically bigger than the reverse of $x$. So you sho...
[ "bitmasks", "greedy" ]
1,100
fun main(args: Array<String>) { val T = readLine()!!.toInt() for (tc in 1..T) { val x = readLine()!!.reversed() val y = readLine()!!.reversed() val posY = y.indexOf('1') val posX = x.indexOf('1', posY) println(posX - posY) } }
1202
B
You Are Given a Decimal String...
Suppose you have a special $x$-$y$-counter. This counter can store some value as a decimal number; at first, the counter has value $0$. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $x$ or $y$ to its value. So all sequences this counter generates are starting fro...
All you need to know to solve this task is the minimal number of steps to move from any digit $a$ to any digit $b$ for fixed $x$ and $y$ (let's denote it as $ds[a][b]$). Shortest path? BFS? Floyd? Of course, you can use it, but you can think a little harder and save nerves and time. Since order of choosing operations $...
[ "brute force", "dp", "shortest paths" ]
1,700
const val INF = 1e9.toInt() fun main(args: Array<String>) { val s = readLine()!!.map { it - '0' } val cf = Array(10) {Array(10) {0}} for (i in 1 until s.size) cf[s[i - 1]][s[i]]++ for (x in 0..9) { for (y in 0..9) { val ds = Array(10) {Array(10) {INF + 7}} for ...
1202
C
You Are Given a WASD-string...
You have a string $s$ — a sequence of commands for your toy robot. The robot is placed in some cell of a \textbf{rectangular} grid. He can perform four commands: - 'W' — move one cell up; - 'S' — move one cell down; - 'A' — move one cell left; - 'D' — move one cell right. Let $Grid(s)$ be the grid of minimum possible...
The problem asks us to maintain the bounding box while inserting the character of one of $4$ types between every adjacent characters in $s$. Of course, we can do it, but do we really need to do it in such cumbersome way? Let's think a little. Inserting 'W' or 'S' doesn't affect the width of the bounding box, and 'A' or...
[ "brute force", "data structures", "dp", "greedy", "implementation", "math", "strings" ]
2,100
const val INF = 1e9.toInt() fun main(args: Array<String>) { val T = readLine()!!.toInt() for (tc in 1..T) { val s = readLine()!! val alp = arrayOf("WS", "AD") val aDir = arrayOf( s.filter { alp[0].indexOf(it) != -1 }, s.filter { alp[1].indexOf(it) != -1 }...
1202
D
Print a 1337-string...
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given an integer $n$. You have to find a sequence $s$ consisting of digits $\{1, 3, 7\}$ such that it has exactly $n$ subsequences equal to $1337$. For examp...
Let's consider the following string $1333 \dots 3337$. If digit $3$ occurs $x$ times in it, then string have $\frac{x (x-1)}{2}$ subsequences $1337$. Let's increase the number of digits $3$ in this string while condition $\frac{x (x-1)}{2} \le n$ holds ($x$ is the number of digits $3$ in this string). The length of thi...
[ "combinatorics", "constructive algorithms", "math", "strings" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int tc = 0; tc < t; ++tc){ int n; cin >> n; int len = 2; while(len * (len + 1) / 2 <= n) ++len; n -= len * (len - 1) / 2; assert(n >= 0); assert(n <= 45000); string s = ...
1202
E
You Are Given Some Strings...
You are given a string $t$ and $n$ strings $s_1, s_2, \dots, s_n$. All strings consist of lowercase Latin letters. Let $f(t, s)$ be the number of occurences of string $s$ in string $t$. For example, $f('\text{aaabacaa}', '\text{aa}') = 3$, and $f('\text{ababa}', '\text{aba}') = 2$. Calculate the value of $\sum\limits...
Let's look at any occurrence of arbitrary pair $s_i + s_j$. There is exactly one special split position, where the $s_i$ ends and $s_j$ starts. So, instead of counting occurrences for each pair, we can iterate over the position of split and count the number of pairs. This transformation is convenient, since any $s_i$, ...
[ "brute force", "string suffix structures", "strings" ]
2,400
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9) + 7...
1202
F
You Are Given Some Letters...
You are given $a$ uppercase Latin letters 'A' and $b$ letters 'B'. The period of the string is the smallest such positive integer $k$ that $s_i = s_{i~mod~k}$ ($0$-indexed) for each $i$. Note that this implies that $k$ won't always divide $a+b = |s|$. For example, the period of string "ABAABAA" is $3$, the period of ...
Let's introduce the slightly naive solution. Iterate over all values for periods and check the possibility of each one being correct. The conditions for some period $k$ can be formulated the following way. $g = n / k$ ($n = a + b$ is the total length of the string) is the number of full periods of length $k$. Let's fin...
[ "binary search", "implementation", "math" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int a, b; scanf("%d%d", &a, &b); int n = a + b; int ans = 0; int l = 1; while (l <= n){ int g = n / l; if (a < g || b < g){ l = n / g + 1; continue; } int r = n / g; int a_l...
1203
A
Circle of Students
There are $n$ students standing in a circle in some order. The index of the $i$-th student is $p_i$. It is guaranteed that all indices of students are distinct integers from $1$ to $n$ (i. e. they form a permutation). Students want to start a round dance. A \textbf{clockwise} round dance can be started if the student ...
We just need to find the position of the $1$ in the array and then check if the sequence $2, 3, \dots, n$ is going counterclockwise or clockwise from the position $pos-1$ or $pos+1$ correspondingly. We can do this by two cycles. Total complexity: $O(n)$.
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> a(n); int pos = -1; for (int j = 0; j < n; ++j) { cin >> a[j]; if (...
1203
B
Equal Rectangles
You are given $4n$ sticks, the length of the $i$-th stick is $a_i$. You have to create $n$ rectangles, each rectangle will consist of exactly $4$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be us...
After sorting $a$ we can observe that if the answer is "YES" then the area of each rectangle is $area = a_{1} \cdot a_{4n}$. Then we just need to check for each $i$ from $1$ to $n$ that $a_{2i-1} = a_{2i}$ and $a_{4n-2i+1} = a_{4n-2i+2}$ and $a_{2i-1} \cdot a_{4n-2i+2} = area$. If all conditions are satisfied for all $...
[ "greedy", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> a(4 * n); for (int j = 0; j < 4 * n; ++j) { cin >> a[j]; } sort(a.be...
1203
C
Common Divisors
You are given an array $a$ consisting of $n$ integers. Your task is to say the number of such positive integers $x$ such that $x$ divides \textbf{each} number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array $a$ will be $[2, 4, 6, 2...
Let $g = gcd(a_1, a_2, \dots, a_n)$ is the greatest common divisor of all elements of the array. You can find it by Euclidean algorithm or some standard library functions. Then the answer is just the number of divisors of $g$. You can find this value in $\sqrt{g}$.
[ "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; long long g = 0; for (int i = 0; i < n; ++i) { long long x; cin >> x; g = __gcd(g, x); } int ans = 0; for (int i = 1; i * 1ll * i ...
1203
D1
Remove the Substring (easy version)
\textbf{The only difference between easy and hard versions is the length of the string}. You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) fro...
In this problem we can just iterate over all possible substrings and try to remove each of them. After removing the substring we can check if $t$ remains the subsequence of $s$ in linear time. Let we remove the substring $s[l; r]$. Let's maintain a pointer $pos$ (the initial value of the pointer is $1$) and iterate ove...
[ "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s, t; cin >> s >> t; int ans = 0; for (int i = 0; i < int(s.size()); ++i) { for (int j = i; j < int(s.size()); ++j) { int pos = 0; for (int p =...
1203
D2
Remove the Substring (hard version)
\textbf{The only difference between easy and hard versions is the length of the string}. You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) fro...
Let $rg_i$ be such rightmost position $x$ in $s$ that the substring $t[i;|t|]$ is the subsequence of $s[x;|s|]$. We need values $rg_i$ for all $i$ from $1$ to $|t|$. We can calculate it just iterating from right to left over all characters of $s$ and maintaining the pointer to the string $t$ as in easy version. Then le...
[ "binary search", "greedy", "implementation", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s, t; cin >> s >> t; vector<int> rg(t.size()); for (int i = int(t.size()) - 1; i >= 0; --i) { int pos = int(s.size()) - 1; if (i + 1 < int(t.size...
1203
E
Boxers
There are $n$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the ...
Let $lst$ be the last weight of the boxer taken into the team. Initially $lst = \infty$. Let's sort all boxers in order of non-increasing their weights and iterate over all boxers in order from left to right. If the current boxer has the weight $w$ then let's try to take him with weight $w+1$ (we can do it if $w+1<lst$...
[ "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); int lst = a[0] + 2; int ans = 0; for (int i = 0; i < n; ++i) { int cur = -1; for (int dx = 1; dx >= -1; --dx) { if (a[i] + dx > 0 && ...
1203
F1
Complete the Projects (easy version)
\textbf{The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version}. Polycarp is a very famous freelancer. His current rating is $r$ units. Some very rich customers asked him to complete some projects for their companies. T...
Firstly, let's divide all projects into two sets: all projects giving us non-negative rating changes (let this set be $pos$) and all projects giving up negative rating changes (let this set be $neg$). Firstly let's take all projects from the set $pos$. How do we do that? Let's sort them by $a_i$ in non-decreasing order...
[ "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; bool comp(const pair<int, int>& a, const pair<int, int>& b) { return a.first + a.second > b.first + b.second; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, r; cin >> n >> r; vector<pair<int, ...
1203
F2
Complete the Projects (hard version)
\textbf{The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version}. Polycarp is a very famous freelancer. His current rating is $r$ units. Some very rich customers asked him to complete some projects for their companies. T...
To view the main idea of the problem, read the editorial of easy version. The only difference is that for non-negative $b_i$ we don't need to print "NO" if we cannot take the project, we just need to skip it because we cannot take it at all. And for negative $b_i$ we need to write the knapsack dynamic programming to ta...
[ "dp", "greedy" ]
2,300
#include <bits/stdc++.h> using namespace std; bool comp(const pair<int, int>& a, const pair<int, int>& b) { return a.first + a.second > b.first + b.second; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, r; cin >> n >> r; vector<pair<int, ...
1204
A
BowWow and the Timetable
In the city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \geq 0$. Team BowWow has arrived at the station at the time $s$ and i...
Basically, the problem asks you to count $\lceil \log_4 s \rceil$, which is equal to $\Bigl\lceil \dfrac{\log_2 s}{\log_2 4} \Bigr\rceil = \Bigl\lceil \dfrac{\log_2 s}{2} \Bigr\rceil$. If we denote $l$ as a length of the input number, then $\lceil \log_2 s \rceil$ is either equal to $l-1$ if $s$ is the power of two (it...
[ "math" ]
1,000
null
1204
B
Mislove Has Lost an Array
Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it: - The number of different numbers in the array is not less than $l$ and is not greater than $r$; - For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there ...
Any array that satisfies statements' conditions contains only powers of two from $2^0$ to $2^{k-1}$, where $l \leq k \leq r$, so the minimal sum is achieved when we take powers of two from $2^0$ to $2^{l-1}$ and set the other $n-l$ elements equal to $2^0$; the maximal sum is achieved when we take powers of two from $2^...
[ "greedy", "math" ]
900
null
1204
C
Anna, Svyatoslav and Maps
The main characters have been omitted to be short. You are given a directed unweighted graph without loops with $n$ vertexes and a path in it (that path is not necessary simple) given by a sequence $p_1, p_2, \ldots, p_m$ of $m$ vertexes; for each $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$. Define the seq...
Firstly, find the matrix of the shortest paths using Floyd-Warshall algortihm or running dfs from all vertexes; then a greedy approach works here: add $p_1$ to the answer and then go along the path; if the distance from the last vertex in the answer to the current vertex $p_i$ is shorter than in given path, add the ver...
[ "dp", "graphs", "greedy", "shortest paths" ]
1,700
null
1204
D2
Kirk and a Binary String (hard version)
\textbf{The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.} Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find...
Solution 1: Let's call a string $p$ fixed if there isn't another string $t$ of the same length which satisfies the first condition of the statement (it was about the same lengths of the longest nondecreasing subsequences on substrings). The following statements are obivous: string $10$ is fixed; if strings $p$ and $q$ ...
[ "data structures", "greedy", "math", "strings" ]
2,100
null
1204
E
Natasha, Sasha and the Prefix Sums
Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ elements are equal to $-1$. For each such array they counted its maximal pref...
Let's count a dp $k[x][y]$ - the number of arrays consisting of $x$ ones and $y$ minus ones such that their maximal prefix sum is equal to $0$: if $x=0$ then $k[x][y] = 1$, else if $x>y$ then $k[x][y] = 0$, else $k[x][y] = k[x-1][y] + k[x][y-1]$, because if we consider any array consisting of $x$ ones and $y-1$ minus o...
[ "combinatorics", "dp", "math", "number theory" ]
2,300
null
1205
A
Almost Equal
You are given integer $n$. You have to arrange numbers from $1$ to $2n$, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every $n$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $2n$ numbers differ n...
Consider a valid arrangement for some $n$. We denote $S_i = a_i + a_ {i + 1} + a_ {i + 2} + \dots + a_ {i + n-1}$ for each $i$ from $1$ to $2n$, where $a_ {t + 2n} = a_ {t}$. Then we have: $S_ {i + 1} -S_i = (a_ {i + 1} + a_ {i + 2} + a_ {i + 3} + \dots + a_ {i + n}) - (a_i + a_ {i + 1} + a_ {i + 2} + \dots + a_ {i + n...
[ "constructive algorithms", "greedy", "math" ]
1,200
null
1205
B
Shortest Cycle
You are given $n$ integer numbers $a_1, a_2, \dots, a_n$. Consider graph on $n$ nodes, in which nodes $i$, $j$ ($i\neq j$) are connected if and only if, $a_i$ AND $a_j\neq 0$, where AND denotes the bitwise AND operation. Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at al...
The most important thing in this task is to notice that if any bit is contained at least $3$ numbers, then they will form a cycle of length $3$, and the answer is $3$. Suppose now that each bit is in no more than two numbers. It follows that each bit can be shared by at most one pair of numbers. From here we get that i...
[ "bitmasks", "brute force", "graphs", "shortest paths" ]
1,900
null
1205
C
Palindromic Paths
\textbf{This is an interactive problem} You are given a grid $n\times n$, where $n$ is \textbf{odd}. Rows are enumerated from $1$ to $n$ from up to down, columns are enumerated from $1$ to $n$ from left to right. Cell, standing on the intersection of row $x$ and column $y$, is denoted by $(x, y)$. Every cell contains...
Denote $ask ((x_1, y_1), (x_2, y_2)) = 1$ if there is a palindromic path between them, and $0$ otherwise. We also denote by $grid [i] [j]$ the number written in the cell $(i, j)$. Firstly, make an observation: if the Manhattan distance is $| x_2-x_1 | + | y_2-y_1 | =$ 2, then $ask ((x_1, y_1), (x_2, y_2)) = 1 \iff boar...
[ "implementation", "interactive" ]
2,400
null
1205
D
Almost All
You are given a tree with $n$ nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes $i$, $j$, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer...
First we prove the following lemma: Suppose that there are $n$ vertices in the tree $G$ with the root $v$. Let also $0 <a_1 <a_2 \dots <a_ {n-1}$ be any $n-1$ different positive numbers. Then we can arrange non-negative integers on the edges of $G$ so that the distances from $v$ to the remaining vertices of the tree ar...
[ "constructive algorithms", "trees" ]
2,700
null
1205
E
Expected Value Again
You are given integers $n$, $k$. Let's consider the alphabet consisting of $k$ different elements. Let \textbf{beauty} $f(s)$ of the string $s$ be the number of indexes $i$, $1\le i<|s|$, for which prefix of $s$ of length $i$ equals to suffix of $s$ of length $i$. For example, beauty of the string $abacaba$ equals $2$...
Let $f_i (s)$ be a function of the string $s$ equal to $1$ if the prefix and suffix of length $i$ are equal, and equal to $0$ otherwise. We need to calculate $E ((f_1 (s) + f_2 (s) + \dots + f_{n-1}(s))^2) =$ (using linearity of expectation) $\sum_{i = 1}^{n-1} E(f_i (s) ^ 2) + \sum_{1 \le i, j \le n-1, i \neq j} E (f_...
[ "combinatorics", "strings" ]
3,100
null
1205
F
Beauty of a Permutation
Define the beauty of a permutation of numbers from $1$ to $n$ $(p_1, p_2, \dots, p_n)$ as number of pairs $(L, R)$ such that $1 \le L \le R \le n$ and numbers $p_L, p_{L+1}, \dots, p_R$ are consecutive $R-L+1$ numbers in some order. For example, the beauty of the permutation $(1, 2, 5, 3, 4)$ equals $9$, and segments, ...
We will denote $(a, b)$ if there exists a permutation of length $a$ with beauty equal to $b$. To begin with, it is obvious that the beauty of a permutation of length $a$ is at least $a + 1$ for $a> 1$: indeed, you can take each element individually and the entire permutation completely. ** Statement 1 **: if $(a_1, b_1...
[ "constructive algorithms", "math" ]
3,400
null
1206
A
Choose Two Numbers
You are given an array $A$, consisting of $n$ positive integers $a_1, a_2, \dots, a_n$, and an array $B$, consisting of $m$ positive integers $b_1, b_2, \dots, b_m$. Choose some element $a$ of $A$ and some element $b$ of $B$ such that $a+b$ doesn't belong to $A$ and doesn't belong to $B$. For example, if $A = [2, 1, ...
Let $a$ be the largest number in the array $A$, $b$ be the largest number in the array $B$. Then the number $a + b$ isn't present neither in the array $A$ nor in the array $B$. Indeed, $a + b> a$, and $a$ is the largest number in the array $A$, so $a + b$ is not included in $A$. Similarly, $a + b$ is not included in $B...
[ "math", "sortings" ]
800
null
1206
B
Make Product Equal One
You are given $n$ numbers $a_1, a_2, \dots, a_n$. With a cost of one coin you can perform the following operation: Choose one of these numbers and add or subtract $1$ from it. In particular, we can apply this operation to the same number several times. We want to make the product of all these numbers equal to $1$, i...
The product of several integers is equal to one if and only if each of these numbers is $1$ or $-1$, and there must be an even number of $-1$. Then: we will have to reduce every positive $a_i$ at least to one, and we have to spend at least $a_i - 1$ coin on this. Similarly, we will have to increase every negative $a_i$...
[ "dp", "implementation" ]
900
null
1207
A
There Are Two Types Of Burgers
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $b$ buns, $p$ beef patties and $f$ chicken cutlets in your restaurant. You can sell one hamburger...
In this task you just can iterate over the numbers of hamburgers and chicken burgers you want to assemble, check that you have enough ingredients and update the answer. If you want to sell $x$ hamburgers and $y$ chicken burgers then you need $x$ beef patties, $y$ chicken cutlets and $2(x+y)$ buns.
[ "brute force", "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int t; int b, p, f; int h, c; int main() { cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> b >> p >> f; cin >> h >> c; b /= 2; if(h < c){ swap(h, c); swap(p, f); } int res = 0; int...
1207
B
Square Filling
You are given two matrices $A$ and $B$. Each matrix contains exactly $n$ rows and $m$ columns. Each element of $A$ is either $0$ or $1$; each element of $B$ is initially $0$. You may perform some operations with matrix $B$. During each operation, you choose any submatrix of $B$ having size $2 \times 2$, and replace ev...
It is quite obvious that we can't choose any submatrix that contains at least one zero in $A$. The contrary is also true - if a submatrix of $A$ consists of only ones, then there's no reason not to choose it (suppose there is an answer that does not choose it - then choosing this submatrix won't affect it). So we may p...
[ "constructive algorithms", "greedy", "implementation" ]
1,200
n, m = map(int, input().split()) a = [[] for i in range(n)] for i in range(n): a[i] = list(map(int, input().split())) ans = [] for i in range(n - 1): for j in range(m - 1): if(a[i][j] * a[i][j + 1] * a[i + 1][j] * a[i + 1][j + 1] > 0): a[i][j] = 2 a[i + 1][j] = 2 a[i...
1207
C
Gas Pipeline
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $[0, n]$ on $OX$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $(x, x + 1)$ with integer $x$. So we can represent the road as a binary string...
This task was designed as a simple dynamic programming problem, but it also can be solved greedily. The dp solution is following: when we have already built some prefix of the pipeline all we need to know is the length of the prefix the height of the pipeline's endpoint ($1$ or $2$). So we can calculate the following d...
[ "dp", "greedy" ]
1,500
const val INF64 = 1e18.toLong() fun main(args: Array<String>) { val tc = readLine()!!.toInt() for (t in 1..tc) { val (n, a, b) = readLine()!!.split(' ').map { it.toInt() } val s = readLine()!! val d = Array(n + 1) { arrayOf(INF64, INF64) } d[0][0] = b.toLong() for (pos...
1207
D
Number Of Permutations
You are given a sequence of $n$ pairs of integers: $(a_1, b_1), (a_2, b_2), \dots , (a_n, b_n)$. This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequenc...
Let's suppose that all $n!$ permutation are good. We counted the permutations giving the sequences where the first elements are sorted (we denote the number of such permutations as $cnt_1$) and the permutations giving the sequences where the second elements are sorted (we denote the number of such permutations as $cnt_...
[ "combinatorics" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; const int MOD = 998244353; int mul(int a, int b){ return (a * 1LL * b) % MOD; } int sum(int a, int b){ return (a + b) % MOD; } int n; pair<int, int> a[N]; int f[N]; int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) ...
1207
E
XOR Guessing
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentati...
Suppose all integers we input in some query have the same value in the $k$-th bit. Then no matter which $i$ is chosen by the jury, we can always deduce whether the $k$-th bit in $x$ is $0$ or $1$. This leads us to a simple solution: divide $14$ bits of $x$ into two groups of size $7$. In the first query, submit $100$ i...
[ "bitmasks", "interactive", "math" ]
1,900
#include<bits/stdc++.h> using namespace std; int main() { cout << "?"; for(int i = 1; i <= 100; i++) cout << " " << i; cout << endl; cout.flush(); int res1; cin >> res1; cout << "?"; for(int i = 1; i <= 100; i++) cout << " " << (i << 7); cout << endl; cout.flush...
1207
F
Remainder Problem
You are given an array $a$ consisting of $500000$ integers (numbered from $1$ to $500000$). Initially all elements of $a$ are zero. You have to process two types of queries to this array: - $1$ $x$ $y$ — increase $a_x$ by $y$; - $2$ $x$ $y$ — compute $\sum\limits_{i \in R(x, y)} a_i$, where $R(x, y)$ is the set of al...
Let's notice that if we process the queries of type $2$ naively, then each such query consumes $O(\frac{N}{x})$ time (where $N$ is the size of the array). So queries with large $x$ can be processed naively. For queries with small $x$ ($x \le K$), we may notice two things: there are only $O(K^2)$ possible queries; each ...
[ "brute force", "data structures", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 500043; const int K = 750; int a[N]; int sum[K][K]; int main() { int q; scanf("%d", &q); for(int i = 0; i < q; i++) { int t, x, y; scanf("%d %d %d", &t, &x, &y); if(t == 1) { a[x] += y; ...
1207
G
Indie Album
Mishka's favourite experimental indie band has recently dropped a new album! Songs of that album share one gimmick. Each name $s_i$ is one of the following types: - $1~c$ — a single lowercase Latin letter; - $2~j~c$ — name $s_j$ ($1 \le j < i$) with a single lowercase Latin letter appended to its end. Songs are numbe...
There is a common approach for the problem "you are given a lot of strings and texts, count the number of occurences of the strings in the texts" - build an Aho-Corasick automaton on the given strings and somehow process the texts with it. Let's see if it can handle this problem. The names of the songs can be represent...
[ "data structures", "dfs and similar", "hashing", "string suffix structures", "strings", "trees" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int AL = 26; const int N = 400 * 1000 + 13; struct node{ int nxt[AL]; node(){ memset(nxt, -1, sizeof(nxt)); } int& operator [](int x){ return nxt[x]; } }; struct node_at{ ...
1208
A
XORinacci
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: - $f(0) = a$; - $f(1) = b$; - $f(n) = f(n-1) \oplus f(n-2)$ when $n > 1$, where ...
The sequence is $a$, $b$, $a\oplus b$, $a$, $b$, $a\oplus b$ $\cdots$ Since, the sequence has a period of $3$, $f[i] = f[i \mod 3]$.
[ "math" ]
900
#include<bits/stdc++.h> using namespace std; int main() { int test,a,b,n; cin>>test; while(test--){ cin>>a>>b>>n; switch (n%3){ case 0: cout<<a<<endl; break; case 1: cout<<b<<endl; break; default: ...
1208
B
Uniqueness
You are given an array $a_{1}, a_{2}, \ldots, a_{n}$. You can remove \textbf{at most one} subsegment from it. The remaining elements should be pairwise distinct. In other words, \textbf{at most one} time you can choose two integers $l$ and $r$ ($1 \leq l \leq r \leq n$) and delete integers $a_l, a_{l+1}, \ldots, a_r$ ...
After removing a sub-segment, a prefix and a suffix remain, possibly of length $0$. Let us fix the prefix which does not contain any duplicate elements and find the maximum suffix we can get without repeating the elements. We can use map/set to keep track of the elements. Time complexity: $O(n^2 \cdot log(n))$
[ "binary search", "brute force", "implementation", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 2e3 + 5; int a[N]; int main(){ int n; scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d", &a[i]); } int ans = n - 1; map<int, int> freq; for(int i = 0; i < n; ++i){ bool validPrefix = true; for(int ...
1208
C
Magic Grid
Let us define a magic grid to be a square matrix of integers of size $n \times n$, satisfying the following conditions. - All integers from $0$ to $(n^2 - 1)$ inclusive appear in the matrix \textbf{exactly once}. - Bitwise XOR of all elements in a row or a column must be the same for each row and column. You are give...
Divide the grid into four quadrants. Assign distinct integers to the first quadrant from $0$ to $(\frac{N^2}{4} - 1)$. Copy this quadrant to the other three. This way XOR of each row and column becomes $0$. Now, to make numbers distinct among the quadrants, multiply the numbers by $4$. Add $1$, $2$, and $3$ to the numb...
[ "constructive algorithms" ]
1,800
#include <bits/stdc++.h> using namespace std; #define int long long #define ld long double #define pii pair<int ,int> #define pld pair<ld ,ld> #define F first #define S second #define mod 1000000007 #define pb push_back #define mp make_pair #define all(x) x.begin(),x.end() #d...
1208
D
Restore Permutation
An array of integers $p_{1},p_{2}, \ldots,p_{n}$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3,1,2], [1], [1,2,3,4,5]$ and $[4,3,1,2]$. The following arrays are not permutations: $[2], [1,1], [2,3,4]$. There is a hidden permutat...
Let us fill the array with numbers from $1$ to $N$ in increasing order. $1$ will lie at the last index $i$ such that $s_{i} = 0$. Find and remove this index $i$ from the array and for all indices greater than $i$, reduce their $s_{i}$ values by $1$. Repeat this process for numbers $2, 3, ...N$. In the $i^{th}$ turn, re...
[ "binary search", "data structures", "greedy", "implementation" ]
1,900
#include<bits/stdc++.h> using namespace std; const int N = 2e5 + 5; long long BIT[N], s[N]; int n; int ans[N]; void update(int x, int delta){ for(; x <= n; x += x&-x) BIT[x] += delta; } long long query(int x){ long long sum = 0; for(; x > 0; x -= x&-x) sum += BIT[x]; return sum; ...
1208
E
Let Them Slide
You are given $n$ arrays that can have different sizes. You also have a table with $w$ columns and $n$ rows. The $i$-th array is placed horizontally in the $i$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table. You need to find the max...
For every array $i$ from $1$ to $N$, let us maintain 2 pointers $L[i]$ and $R[i]$, representing the range of elements in $i_{th}$ array, that can be accessed by the current column index $j$. Initially all $L[i]$ and $R[i]$ would be set equal to 0. As we move from $j_{th}$ index to $(j+1)_{th}$ index, some $L[i]$ and $R...
[ "data structures", "implementation" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = 1e6 + 5; long long ans[N]; vector<pair<int, int> > add_element[N], remove_element[N]; multiset<int> global_ms[N]; int main(){ int n,w; scanf("%d %d", &n, &w); for(int i = 0; i < n; ++i){ int cnt; scanf("%d", &cnt); for(int j = 0; j < cnt; ++j){ in...
1208
F
Bits And Pieces
You are given an array $a$ of $n$ integers. You need to find the maximum value of $a_{i} | ( a_{j} \& a_{k} )$ over all triplets $(i,j,k)$ such that $i < j < k$. Here $\&$ denotes the bitwise AND operation, and $|$ denotes the bitwise OR operation.
The idea is to first fix some $a[i]$ and try to get the bits which are off in $a[i]$ from any $2$ elements to the right of $i$. Since, we need to maximize the value, we will try to get higher bits first. What we need now is, for every number $x$ from $0$ to $2^{21}-1$, the $2$ right most positions such that the bits pr...
[ "bitmasks", "dfs and similar", "dp", "greedy" ]
2,600
#include <bits/stdc++.h> #define ll long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define vii vector<pii> #define mi map<int,int> #define mii map<pii,int> #define all(a) (a).begin(),(a).end() #define x first #d...
1208
G
Polygons
You are given two integers $n$ and $k$. You need to construct $k$ regular polygons having same circumcircle, with \textbf{distinct} number of sides $l$ between $3$ and $n$. \begin{center} {\small Illustration for the first example.} \end{center} You can rotate them to minimize the total number of distinct points on ...
If we choose a polygon with side length $l$, it is profitable to choose polygons with side lengths as divisors of $l$ as well, because this will not increase the answer. So our final set would be such that for every polygon with side length $l$, we would have polygons with side length as divisors of $l$ as well. All po...
[ "greedy", "math", "number theory" ]
2,800
#include <bits/stdc++.h> using namespace std; int phi[1000006]; void process_phis(int n){ iota(phi,phi+n+1,0); for(int i = 2 ; i<=n;i++){ if(phi[i]==i){ phi[i]=i-1; for(int j=2*i;j<=n;j+=i){ phi[j]=(phi[j]/i)*(i-1); } } } } int main(){ ...
1208
H
Red Blue Tree
You are given a tree of $n$ nodes. The tree is rooted at node $1$, which is not considered as a leaf regardless of its degree. Each leaf of the tree has one of the two colors: red or blue. Leaf node $v$ initially has color $s_{v}$. The color of each of the internal nodes (including the root) is determined as follows....
Transform queries into two types: "change color of a leaf", and "answer color of some vertex if k is given". Note that when $k = -\infty$ all internal vertices are red. When increasing $k$, each vertex will change its color exactly once, let's call this value of $k$ as boundary value for this vertex. If we can keep bou...
[ "data structures", "implementation", "trees" ]
3,500
/** * This line was copied from template * This is nk_sqrt_300.cpp * * @author: Nikolay Kalinin * @date: Fri, 23 Aug 2019 22:28:23 +0300 */ #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif using ll = long ...
1209
A
Paint the Numbers
You are given a sequence of integers $a_1, a_2, \dots, a_n$. You need to paint elements in colors, so that: - If we consider any color, all elements of this color must be divisible by the minimal element of this color. - The number of used colors must be minimized. For example, it's fine to paint elements $[40, 10, 6...
Consider the smallest element $x$ in the array. We need to paint it in some color, right? Observe, that we can paint all elements divisible by $x$ in that color as well. So we can perform the following while the array is not empty: find the minimum element $x$, assign new color and remove all elements divisible by $x$ ...
[ "greedy", "implementation", "math" ]
800
null
1209
B
Koala and Lights
It is a holiday season, and Koala is decorating his house with cool lights! He owns $n$ lights, all of which flash periodically. After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $a_i$ and $b_i$. Light with parameters $a_i$ and $b_i$ will toggle (on to off...
Because each individual light flashes periodically, all the lights together are periodic as well. Therefore, we can simulate the lights up to the period to get the answer. The actual period can be calculated as follows: If a light toggles every $t$ seconds, its period is $2t$. The overall period is the least common mul...
[ "implementation", "math", "number theory" ]
1,300
null
1209
C
Paint the Digits
You are given a sequence of $n$ digits $d_1d_2 \dots d_{n}$. You need to paint all the digits in two colors so that: - each digit is painted either in the color $1$ or in the color $2$; - if you write in a row from left to right all the digits painted in the color $1$, and then after them all the digits painted in the...
The sequence must split into two non-decreasing where the end of the first $\le$ start of the second. Let's bruteforce the value $x$, so that all elements $< x$ go to the color $1$, all elements $> x$ go to the color $2$, and for $=x$ we are not sure. Actually, we can say that all elements equal to $x$, which go before...
[ "constructive algorithms", "greedy", "implementation" ]
1,500
null
1209
D
Cow and Snacks
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo! There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flav...
Since every animal has exactly two favorite snacks, this hints that we should model the problem as a graph. The nodes are the snacks, and the edges are animals with preferences connecting snack nodes. Let's consider a connected component of the graph with size greater than $1$. The first animal (edge) in that component...
[ "dfs and similar", "dsu", "graphs" ]
1,700
null
1209
E1
Rotate Columns (easy version)
This is an easier version of the next problem. The difference is only in constraints. You are given a rectangular $n \times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this o...
There many approaches possible, let's describe one of them. Let's change the problem to the following: Rotate columns any way you want. Select in each row one value, maximizing the sum. This can be done with a dp, states are (prefix of columns, mask of taken columns). Basically at each step we are rotating the current ...
[ "bitmasks", "brute force", "dp", "greedy", "sortings" ]
2,000
null
1209
E2
Rotate Columns (hard version)
This is a harder version of the problem. The difference is only in constraints. You are given a rectangular $n \times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operati...
The previous solution is slightly too slow to pass the large constraints. Let's sort columns by the maximum element in them. Observe, that it is surely unoptimal to use columns which go after first $n$ columns in sorted order (we could've replaced them with some unused column). So we can solve the hard version with pre...
[ "bitmasks", "dp", "greedy", "sortings" ]
2,500
null
1209
F
Koala and Notebook
Koala Land consists of $m$ bidirectional roads connecting $n$ cities. The roads are numbered from $1$ to $m$ by order in input. It is guaranteed, that one can reach any city from every other city. Koala starts traveling from city $1$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't...
First split all edges into directed edges with single digit labels, creating $\mathcal{O}(m\log{m})$ dummy vertices if necessary. Since the first edge will not be zero (no leading zeros), longer paths are always greater. With a BFS, this reduces the problem to finding lexicographical minimal paths in a DAG. To avoid ne...
[ "data structures", "dfs and similar", "graphs", "shortest paths", "strings", "trees" ]
2,600
null
1209
G1
Into Blocks (easy version)
This is an easier version of the next problem. In this version, $q = 0$. A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible...
Let's solve easier version first (we will reuse core ideas in hard version as well). Clearly, if some two integers are ``hooked'' like in $1 \ldots 2 \ldots 1 \ldots 2$, then they will end up being turned into the same integer. So when we see integer $x$ with first occurrence at $a$ and last at $b$, let's mark segment ...
[ "data structures", "dsu", "greedy", "implementation", "two pointers" ]
2,000
null
1209
G2
Into Blocks (hard version)
This is a harder version of the problem. In this version $q \le 200\,000$. A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possib...
To adjust the solution for many queries we need to create some sophisticated data structure. E.g. we all know that mentioned above "+= 1 on a segment" is easily done with a segtree. If we maintain for every value $a_i$ the corresponding set of occurrences, it's easy to update mentioned above ``number of occurrences in ...
[ "data structures" ]
3,200
null
1209
H
Moving Walkways
Airports often use moving walkways to help you walking big distances faster. Each such walkway has some speed that effectively increases your speed. You can stand on such a walkway and let it move you, or you could also walk and then your effective speed is your walking speed plus walkway's speed. Limak wants to get f...
Some minor tips: Everything is a walkway. When there is no walkway, it is a walkway of speed $0$. You can increase all speeds by $1$ and assume that you own speed is in $[-1; +1]$ Energy is an entity which is $\delta$ speed $\times$ time, which is distance. Also if you spend $x$ energy per segment of len $l$ and speed ...
[ "data structures", "greedy", "math" ]
3,300
null
1210
A
Anadi and Domino
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every $a$ and $b$ such that $1 \leq a \leq b \leq 6$, there is exactly one domino with $a$ dots on one half and $b$ dots on the other half. The set contains exactly $21$ dominoes. Here is an exact illustration of his set: Al...
We can imagine writing an integer from $1$ to $6$ in each vertex - if we write an integer $x$ in vertex $v$, then we want each half of the domino directed toward vertex $v$ to have exactly $x$ dots. Then, it's easy to calculate the result - we should place as many different dominoes as possible according to the written...
[ "brute force", "graphs" ]
1,700
null
1210
B
Marcin and Training Camp
Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other. Let's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two intege...
If there are multiple people with the same set of skills (i.e., the same values of $a$), it's optimal to take each of them to the camp as they won't think they're better than everyone else. Now consider a person $i$ which has a different set of skills than everyone else. If they have a strictly smaller set of skills th...
[ "brute force", "greedy" ]
1,700
null
1210
C
Kamil and Making a Stream
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $100$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him? You're given a tree — a connected undirected graph consisting of $n$ vertices c...
Let's prove the following observation: Fix a vertex $v$ (the bottom end of the path), and consider all its ancestors $u$. The number of distinct values of $f(u,v)$ is at most $\log_2(10^{12})$. To prove this observation, consider the ancestors of $v$ in the order from the bottom-most to top-most: $v=u_0, u_1, u_2, u_3,...
[ "math", "number theory", "trees" ]
2,000
null
1210
D
Konrad and Company Evaluation
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company. There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company — ...
Let's imagine that the graph is directed as in the sample explanation (and edge $u\to v$ exists if $u$ brags to $v$). We have to deal with two kinds of queries: Count the number of three-vertex directed paths. Change the direction of a single edge in the graph. If we remember indegrees $\mathrm{indeg}$ and outdegrees $...
[ "graphs" ]
2,400
null
1210
E
Wojtek and Card Tricks
Wojtek has just won a maths competition in Byteland! The prize is admirable — a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!' The first chapter of the book is 'How to Shuffle $k$ Cards in Any Order You W...
Let's first enumerate all permutations by integers from $0$ to $k!-1$. Now, we can memoize all possible compositions of two permutations in an $k! \times k!$ array. This will allow us to compose any two permutations in constant time. Let $l$ and $r$ be the left and right ends of any interval. We'll compute the sum in t...
[ "math" ]
2,700
null
1210
F1
Marek and Matching (easy version)
This is an easier version of the problem. In this version, $n \le 6$. Marek is working hard on creating strong testcases to his new algorithmic problem. You want to know what it is? Nah, we're not telling you. However, we can tell you how he generates the testcases. Marek chooses an integer $n$ and $n^2$ integers $p_...
Let's first discuss one of possible solutions for the easy subtask. Let's assume that $n=6$ (all smaller $n$'s can be easily reduced to this case). There are two layers of vertices: left $L = \{\ell_1, \ell_2, \dots, \ell_6\}$ and right $R = \{r_1, r_2, \dots, r_6\}$. Let's do meet-in-the-middle on the right layer: $R_...
[ "brute force", "probabilities" ]
3,100
null
1210
F2
Marek and Matching (hard version)
This is a harder version of the problem. In this version, $n \le 7$. Marek is working hard on creating strong test cases to his new algorithmic problem. Do you want to know what it is? Nah, we're not telling you. However, we can tell you how he generates test cases. Marek chooses an integer $n$ and $n^2$ integers $p_...
Let's consider another approach that can solve the hard subtask as well. In the algorithm above, we computed all $k$-element subsets of $L$, $|L|=n$, that can match perfectly with some fixed $k$ vertices on the right. It turns out that not all families of subsets can be generated - for instance, if two sets: $\{\ell_1,...
[ "brute force", "probabilities" ]
3,200
null
1210
G
Mateusz and Escape Room
Mateusz likes to travel! However, on his $42$nd visit to Saint Computersburg there is not much left to sightsee. That's why he decided to go to an escape room with his friends! The team has solved all riddles flawlessly. There is only one riddle remaining — a huge circular table! There are $n$ weighing scales lying on...
Let's introduce the variables $x_1, x_2, \dots, x_n$ where $x_i$ is the number of coins passed from the $i$-th to the $(i+1)$-th scale (or, $x_i < 0$, it means that $-x_i$ coins are passed from the $(i+1)$-th to the $i$-th scale). We can now create the following conditions regarding the final number of stones on each s...
[ "dp" ]
3,500
null
1213
A
Chips Moving
You are given $n$ chips on a number line. The $i$-th chip is placed at the integer coordinate $x_i$. Some chips \textbf{can have equal coordinates}. You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: - Move the chip $i$ by $2$ to the left or $2$ to the right \te...
We can see that the only information we need is the parity of the coordinate of each chip (because we can move all chips that have the same parity to one coordinate for free). So if the number of chips with odd coordinate is $cnto$ then the answer is $min(cnto, n - cnto)$.
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; int cnto = 0; for (int i = 0; i < n; ++i) { int x; cin >> x; cnto += x & 1; } cout << min(cnto, n - cnto) << endl; return 0; }
1213
B
Bad Prices
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $n$ last days: $a_1, a_2, \dots, a_n$, where $a_i$ is the price of berPhone on the day $i$. Polycarp considers the price on the day $i$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For ...
Let $minPrice_i$ be the minimum price of the berPhone during days $i, i + 1, \dots, n$. We can precalculate this array moving from right to left and carrying the minimum price we met (in other words, if we iterate over all $i$ from $n$ to $1$ then $minPrice_i = a_i$ if $i = n$ otherwise $minPrice_i = min(a_i, minPrice_...
[ "data structures", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; int ans = 0; int right_min = INT_MAX; ...
1213
C
Book Reading
Polycarp is reading a book consisting of $n$ pages numbered from $1$ to $n$. Every time he finishes the page with the number divisible by $m$, he writes down the last digit of this page number. For example, if $n=15$ and $m=5$, pages divisible by $m$ are $5, 10, 15$. Their last digits are $5, 0, 5$ correspondingly, the...
Let $k = \lfloor\frac{n}{m}\rfloor$ be the number of integers from $1$ to $n$ divisible by $m$. We can notice that because we write down only the last digit of each number divisible by $m$ then the length of the "cycle" of digits does not exceed $10$. In fact, we can always suppose that it is $10$ because $i \cdot m \%...
[ "math" ]
1,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int q; cin >> q; forn(i, q) { long long n, m; cin >> n >> m; n = n / m; vector<int> digits(10); forn(i, 10) digits[i] = ((i + 1) * m) % 10; ...
1213
D1
Equalizing by Division (easy version)
\textbf{The only difference between easy and hard versions is the number of elements in the array}. You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$). You can per...
Let $x$ be the number such that after some sequence of moves there will be at least $k$ elements $x$ in the array. We can see that there is always $O(n \log n)$ possible candidates because all values $x$ are among all possible values of $\lfloor\frac{a_i}{2^m}\rfloor$ for some $m$ from $0$ to $18$. So we need to check ...
[ "brute force", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<int> poss; for (int i = 0; i < n; ++i) { int x = a[i];...
1213
D2
Equalizing by Division (hard version)
\textbf{The only difference between easy and hard versions is the number of elements in the array}. You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$). You can per...
In this problem we need to write almost the same solution as in the previous one (easy version) but faster. Observe that we calculate the value of $\lfloor\frac{a_i}{2^m}\rfloor$ too many times. Let $vals_x$ for all $x$ from $1$ to $2 \cdot 10^5$ be the array of numbers of divisions we need to obtain $x$ from every pos...
[ "brute force", "math", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<vector<int>> vals(200 * 1000 + 11); for (int i = 0; i < ...
1213
E
Two Small Strings
You are given two strings $s$ and $t$ \textbf{both of length $2$} and both consisting only of characters 'a', 'b' and 'c'. Possible examples of strings $s$ and $t$: "ab", "ca", "bb". You have to find a string $res$ consisting of $3n$ characters, $n$ characters should be 'a', $n$ characters should be 'b' and $n$ chara...
We can check the following solution by stress-testing (or maybe prove it somehow): let's iterate over all possible permutations of the string "abc". Let the first character of the current permutation be $c_1$, the second one be $c_2$ and the third one be $c_3$. Then let's add the following two candidates to the answer:...
[ "brute force", "constructive algorithms" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s, t; cin >> n >> s >> t; string abc = "abc"; vector<string> res; do { string cur; for (int i = 0; i < n; ++i) cur += abc; res.push_back...