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
985
A
Chess Placing
You are given a chessboard of size $1 × n$. It is guaranteed that \textbf{$n$ is even}. The chessboard is painted like this: "BWBW$...$BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to $\frac{n t}{2}$. ...
Firstly let's sort our array $p$ (pay the attention that there are $\frac{n t}{2}$ elements in this array, not $n$). Then for 0-indexed array $p$ answer will be equal to $m i n{\Bigl(}\sum_{i=0}^{n/2-1}|p_{i}-(i\cdot2+1)|,\sum_{i=0}^{n/2-1}|p_{i}-(i\cdot2+2)|{\Bigr)}$, where $|a - b|$ is an absolute value of difference...
[ "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> pos(n / 2); for (int i = 0; i < n / 2; ++i) cin >> pos[i]; sort(pos.begin(), pos.end()); int ans1 = 0, ans2 = 0; for (int i = 0; i < n / 2; ++i) { ans1 += abs(pos[i] - (i * 2 + 1)); ans2 += abs(pos[i] - (i * 2 + 2))...
985
B
Switches and Lamps
You are given $n$ switches and $m$ lamps. The $i$-th switch turns on some subset of the lamps. This information is given as the matrix $a$ consisting of $n$ rows and $m$ columns where $a_{i, j} = 1$ if the $i$-th switch turns on the $j$-th lamp and $a_{i, j} = 0$ if the $i$-th switch is not connected to the $j$-th lamp...
Let's maintain an array $cnt$ of size $m$, where $cnt_{i}$ will be equal to the number of switches that are connected to the $i$-th lamp. Then answer will be "YES" if and only if there exists some switch such that for each lamp $i$ that is connected to this switch $cnt_{i} > 1$. Otherwise the answer will be "NO".
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<string> s(n); vector<int> cnt(m); for (int i = 0; i < n; ++i) { cin >> s[i]; for (int j = 0; j < m; ++j) if (s[i][j] == '1') ++cnt[j]; } for (int i = 0; i < n; ++i) { bool ok = true; for (int j = 0; j < m; +...
985
C
Liebig's Barrels
You have $m = n·k$ wooden staves. The $i$-th stave has length $a_{i}$. You have to assemble $n$ barrels consisting of $k$ staves each, you can use any $k$ staves to construct a barrel. Each stave must belong to exactly one barrel. Let volume $v_{j}$ of barrel $j$ be equal to the length of the \textbf{minimal} stave in...
At first, sort all $a_{i}$ in non-decreasing order. Let $rg$ be first position that $a_{rg} > a_{1} + l$ (if $a_{m} \le a_{1} + l$, $rg = m + 1$). Then each barrel should have at least one stave from segment $[1, rg)$. So if $rg - 1 < n$ answer is $0$. Otherwise, for each $i$ from $1$ to $n$ let's take no more than $...
[ "greedy" ]
1,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) typedef long long li; int n, k, l, m; vector<li> a; inline bool read() { if(!(cin >> n >> k >> l)) return false; m = n * k; a.assign(m, 0); fore(i, 0, m) assert(scanf("%lld", &a[i]) == 1); return true; ...
985
D
Sand Fortress
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered $1$ through infinity from left to right. Obviously, there is not enough sand ...
Let's consider the optimal answer to always look like $h_{1} \le h_{2} \le ... \le h_{k} \ge h_{k + 1} \ge ...$ $k$ will be the leftmost position of a pillar with maximum height. We will heavily use the fact that all integers from $1$ to $h_{k} - 1$ appear in this sequence to the right of $k$. If you are able...
[ "binary search", "constructive algorithms", "math" ]
2,100
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) typedef long long li; using namespace std; const int INF = 2e9; li n, h; bool check(li maxh){ li k = min(h, maxh); li cnt = maxh * maxh - k * (k - 1) / 2; return (cnt <= n); } li get(li maxh){ li k = min(h, maxh); li cnt = maxh * ma...
985
E
Pencils and Boxes
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence $a_{1}, a_{2}, ..., a_{n}$ of $n$ integer numbers — saturation of the color of each pencil. Now Mis...
At first you need to sort the sequence. Then if there exists some answer, there also exists an answer such that every box in it contains some segment of pencils. Now it's pretty standard dp approach. Let $dp_{i}$ be $1$ if it's possible to distribute the first $i$ pencils into boxes correctly, $0$ otherwise, $dp_{0} = ...
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int N = 500 * 1000 + 13; int f[N]; void upd(int x){ for (int i = x; i < N; i |= i + 1) ++f[i]; } int sum(int x){ int res = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) res += ...
985
F
Isomorphic Strings
You are given a string $s$ of length $n$ consisting of lowercase English letters. For two given strings $s$ and $t$, say $S$ is the set of distinct characters of $s$ and $T$ is the set of distinct characters of $t$. The strings $s$ and $t$ are isomorphic if their lengths are equal and there is a one-to-one mapping (bi...
Yes, authors also implemented hashes. Note that if substrings $s$ and $t$ are isomophic, then position $pos$ of first encounter of some character $s_{i}$ in $s$ must be position of first encounter of some character $t_{j}$ in $t$. More over, if we sort all positions $pos_{i}^{s}$ for all distict characters in $s$ and s...
[ "hashing", "strings" ]
2,300
#include <bits/stdc++.h> #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 using namespace std; const int B = 2; typedef array<int, B> ht; ht MOD, BASE; inline int norm(int a, const int &MOD) { while(a >= MOD) a -= MOD; while(a < 0) a +=...
985
G
Team Players
There are $n$ players numbered from $0$ to $n-1$ with ranks. The $i$-th player has rank $i$. Players can form teams: the team should consist of three players and \textbf{no pair} of players in the team should have a conflict. The rank of the team is calculated using the following algorithm: let $i$, $j$, $k$ be the ra...
Let's solve this task in several steps. At first, let's calculate $all$ - sum of all triples. For each player $i$ consider three cases: $j<k<i$ - there are exactly ${i}\choose{2}$ ways to choose triple; $j<i<k$ - there are $i \cdot (n-i-1)$ ways; $i<j<k$ - there are ${n-i-1}\choose{2}$ ways. At second, let's calculate ...
[ "combinatorics" ]
2,700
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int(a.size()) using namespace std; typedef unsigned long long uli; const int N = 200 * 1000 + 555; int n, m; uli a, b, c; vector<int> g[N]; inline bool read() { if(!(cin >> n >> m)) return false; assert(cin >> a ...
986
A
Fair
Some company is going to hold a fair in Byteland. There are $n$ towns in Byteland and $m$ two-way roads between towns. Of course, you can reach any town from any other town using roads. There are $k$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $s...
Let's find a cost to bring a good $t$ in each town. To do this we will run BFS from all towns producing good $t$ at once. Just add all that towns in queue and run usual BFS. Complexity of BFS is $O(n+m)$, so total complexity of $k$ BFSs will be $O(k(n+m))$. Now for each town we should choose $s$ cheapest goods. We can ...
[ "graphs", "greedy", "number theory", "shortest paths" ]
1,600
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
986
B
Petr and Permutations
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr ...
Each swap change the parity of permutation. $3n$ and $7n+1$ always have different parities, so the solution is just to calculate the parity of the given permutation and check if it is equal to parity of $3n$ or to parity of $7n+1$. To calculate the parity you can just calculate the number of inversions with your favori...
[ "combinatorics", "math" ]
1,800
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
986
C
AND Graph
You are given a set of size $m$ with integer elements between $0$ and $2^{n}-1$ inclusive. Let's build an undirected graph on these integers in the following way: connect two integers $x$ and $y$ with an edge if and only if $x \& y = 0$. Here $\&$ is the bitwise AND operation. Count the number of connected components i...
Let's build directed graph on $m+2^n$ vertices. There will be two types of vertices: $(x, 1)$ is a vertex for $x$ from input and $(x, 2)$ is a vertex for all $x$ between $0$ and $2^{n}-1$. There will be edges of three classes: $(x, 1) \rightarrow (x, 2)$ for all $x$ from input $(x, 2) \rightarrow (x | (1 \ll k), 2)$ fo...
[ "bitmasks", "dfs and similar", "dsu", "graphs" ]
2,500
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
986
D
Perfect Encoding
You are working as an analyst in a company working on a new system for big data storage. This system will store $n$ different objects. Each object should have a unique ID. To create the system, you choose the parameters of the system — integers $m \ge 1$ and $b_{1}, b_{2}, \ldots, b_{m}$. With these parameters an ID o...
The problem asks to find integers $b_i$ such that $\prod b_i \ge n$ and $\sum b_i$ is minimized. Let's suppose that in optimal solution there is $x \ge 4$ among $b_i$. It is better to split it to $2$ and $(x-2)$: the sum remains the same and the product is increased (or stays the same). So we will use only $2$ and $3$ ...
[ "fft", "math" ]
3,100
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
986
E
Prince's Problem
Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervi...
Let's solve the problem offline and independently for all primes, then multiply the answers. The sum of powers of all primes is $O((n+q) \log C)$. To factorize numbers we will precalculate smallest prime divisor for all numbers using sieve. For fixed prime $p$ let's write its power $b_v$ in every vertex. Then if $p$ is...
[ "brute force", "data structures", "math", "number theory", "trees" ]
2,800
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
986
F
Oppa Funcan Style Remastered
Surely you have seen insane videos by South Korean rapper PSY, such as "Gangnam Style", "Gentleman" and "Daddy". You might also hear that PSY has been recording video "Oppa Funcan Style" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find origina...
Let's understand the problem first. The rule $f(x)$ must be bijective, because otherwise some platforms will be empty in $k$ seconds. So we are looking for permutations $p$ of size $n$. Let's say that cycles of the permutation have lengths $c_1, c_2, \ldots, c_m$. $p^k$ is an identity permutation if and only if $c_i$ d...
[ "graphs", "math", "number theory", "shortest paths" ]
3,300
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
987
A
Infinity Gauntlet
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: - the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color. Using colors of Ge...
Just do what is written in the statement. Convenient way is to use map in C++ or dict in Python.
[ "implementation" ]
800
d = {"purple":"Power", "green":"Time", "blue":"Space", "orange":"Soul", "red":"Reality", "yellow":"Mind"} s = set() n = int(input()) for _ in range(n): w = input() s.add(w) print(6 - n) for (key, value) in d.items(): if key not in s: print(value)
987
B
High School: Become Human
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl...
We need to compare $x^y$ with $y^x$. Let's take logarithms of both sides. Now we need to compare $y \ln x$ with $x \ln y$. If you will compare this numbers with appropriate epsilon, it will get AC, but let's analyze a bit more and get solution in integers. Let's divide both sides by $xy$, now we need to compare $\frac{...
[ "math" ]
1,100
def main(): x, y = map(int, input().split()) if x == y: print('=') return if x == 1: print('<') return if y == 1: print('>') return if x + y == 6: print('=') return if x == 3: print('>') return if y == 3: print('<') return if x < y: print('>') else: print('<') main()
987
C
Three displays
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent ...
Let's fix $j$. Now we can see that $i$ and $k$ are independent, so we can find best $i$ by iterating over all $i < j$, checking if $s_i < s_j$ holds and choosing the one with smallest $c_i$. Then do the same for $k$. There are $O(n)$ options for $j$, for each of them we will do $O(n)$ operations. Total complexity is $O...
[ "brute force", "dp", "implementation" ]
1,400
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace st...
988
A
Diverse Team
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members \textbf{are distinct}. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise pr...
Let's write our "unique" function. Keep the array of the taken elements $used$. Iterate over all elements in the array $a$ and if the current element is not used ($used[a_i] = false$) then add its index $i$ to the answer and set $used[a_i] := true$. When finished, check the number of distinct values (that is the size o...
[ "brute force", "implementation" ]
800
#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; set<int> el; vector<int> ans; for (int i = 0; i < n; ++i) { int x; cin >> x; if (!el.count(x)) { ans.push_back(i); el.in...
988
B
Substrings Sort
You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in su...
Firstly, sort all the strings by their lengths (if there are several strings of the same length, their order does not matter because if the answer is "YES" then all the strings of the same length should be equal). Then for each $i \in [1..n - 1]$ check that $s_i$ is a substring of $s_{i + 1}$. If it doesn't hold for so...
[ "sortings", "strings" ]
1,100
#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; vector<string> s(n); for (int i = 0; i < n; ++i) cin >> s[i]; sort(s.begin(), s.end(), [&] (const string &s, const string &t) { retur...
988
C
Equal Sums
You are given $k$ sequences of integers. The length of the $i$-th sequence equals to $n_i$. You have to choose exactly two sequences $i$ and $j$ ($i \ne j$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $i$ (its length will be equal to $n_i - 1$) equals...
Let's calculate the array of triples $t$. Triple $t_i = (sum_i, seq_i, el_i)$ means that the sum of the sequence $seq_i$ without the element at position $el_i$ will be equal to $sum_i$. Triples can be easily calculated in a following manner: for each sequence find its sum, then iterate over all its elements and subtrac...
[ "implementation", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int k; cin >> k; vector<pair<int, pair<int, int>>> a; for (int i = 0; i < k; ++i) { int n; cin >> n; vector<int> x(n); for (int j = 0; j < n; ++j) ...
988
D
Points and Powers of Two
There are $n$ distinct points on a coordinate line, the coordinate of $i$-th point equals to $x_i$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any sub...
Firstly, let's prove that the size of the answer is not greater than $3$. Suppose that the answer equals to $4$. Let $a, b, c, d$ be coordinates of the points in the answer (and $a < b < c < d$). Let $dist(a, b) = 2^k$ and $dist(b, c) = 2^l$. Then $dist(a, c) = dist(a, b) + dist(b, c) = 2^k + 2^l = 2^m$ (because of the...
[ "brute force", "math" ]
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 n; cin >> n; vector<int> x(n); for (int i = 0; i < n; ++i) { cin >> x[i]; } sort(x.begin(), x.end()); vector<int> res = { x[0] }; for (int i = 0...
988
E
Divisibility by 25
You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes. In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, \textbf{after each move} the number you have cannot contain any leading zeroes. What ...
Let's iterate over all pairs of digits in the number. Let the first digit in the pair be at position $i$ and the second at position $j$. Let's place these digits to the last two positions in the number. The first greedily goes to the last position and then the second goes to the position next to that. Now the number ca...
[ "brute force", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; const int INF = 1000 * 1000 * 1000; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif long long n; cin >> n; string s = to_string(n); int ans = INF; int len = s.size(); for (int i = 0; i < len; ++i) ...
988
F
Rain and Umbrellas
Polycarp lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments,...
Any experienced contestant can easily guess that the problem can be solved with dynamic programming. Coordinates are not really large so you can precalculate the array $rain_0, rain_1, \dots, rain_{a -1 }$, where $rain_i$ is a boolean value - $True$ if there exists some segment of rain to cover the segment between posi...
[ "dp" ]
2,100
//#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") //#pragma GCC optimize("unroll-loops") #include <stdio.h> #include <bits/stdc++.h> #define uint unsigned int #define ll long long #define ull unsigned long lo...
989
A
A Blend of Springtime
\begin{quote} When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead."What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, ar...
A cell can get its colours from at most three cells: itself and its two neighbouring cells (if they exist). In order to collect all three colours, all these three cells should contain a blossom, and their colours must be pairwise different. Therefore, the answer is "Yes" if and only if there are three consecutive cells...
[ "implementation", "strings" ]
900
puts gets.codepoints.each_cons(3).any?{|x,y,z|x*y*z==287430}?'Yes':'No'
989
B
A Tide of Riverscape
\begin{quote} Walking along a riverside, Mino silently takes a note of something."Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think ...
Our very first observation is that when $p \leq \frac n 2$, the answer can never be "No". Under this case, find any dot $s_i = \texttt{"."}$. At least one of $s_{i-p}$ and $s_{i+p}$ exists because $p \leq \frac n 2$ and $1 \leq i \leq n$. We want to make $s_i$ different from this character. In case this character is $\...
[ "constructive algorithms", "strings" ]
1,200
#include <algorithm> #include <cstdio> static const int MAXN = 2005; static int n, p; static char s[MAXN]; static int dots_ct = 0, dots[MAXN]; int main() { scanf("%d%d%s", &n, &p, s); for (int i = 0; i < n; ++i) if (s[i] == '.') { dots[dots_ct++] = i; s[i] = '0'; } for (int i = 1; ...
989
C
A Mist of Florescence
\begin{quote} As the boat drifts down the river, a wood full of blossoms shows up on the riverfront."I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" \end{quote} There are four k...
A picture is worth a thousand words. There are enormous ways to solve this problem. What's yours? Fine-tune your input and parameters, depict your woods here and share with us in the comments! (Remember to clip and scale the image, though. You can surround the image with a spoiler tag to avoid taking up too much space....
[ "constructive algorithms", "graphs" ]
1,800
#include <cstdio> #include <cstdlib> #include <algorithm> #include <string> #include <utility> #include <vector> static const int MAXM = 50; int main() { srand(1); int a[4]; scanf("%d%d%d%d", &a[0], &a[1], &a[2], &a[3]); int M = std::max(2, std::min(MAXM, *std::max_element(a, a + 4))); std::vect...
989
D
A Shade of Moonlight
\begin{quote} Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river."To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can...
There are some ways to play around with formulae of kinematics, but here's an intuitive way. With the concept of relative motion, let's not change the velocities of clouds, but the velocity of the moon instead. Namely, under a wind speed of $w$, consider the moon to be moving at a velocity of $-w$ (seriously). This doe...
[ "binary search", "geometry", "math", "sortings", "two pointers" ]
2,500
#include <cstdio> #include <algorithm> #include <vector> static const int MAXN = 1e5 + 3; static const int INF32 = 0x7fffffff; typedef long long int64; static int n, l, w; static int x[MAXN], v[MAXN]; static std::vector<int> pos, neg; inline int div_floor(int64 a, int b) { if (b == 0) return (a > 0 ? +INF32 : -I...
989
E
A Trance of Nightfall
\begin{quote} The cool breeze blows gently, the flowing water ripples steadily."Flowing and passing like this, the water isn't gone ultimately; Waxing and waning like that, the moon doesn't shrink or grow eventually." "Everything is transient in a way and perennial in another." Kanno doesn't seem to make much sense o...
Is this a graph theory problem? Yes. Let's consider a graph $G = (V, E)$, where there is a vertex for each point in $S$ (the terms "vertices" and "points" are used interchangeably hereafter), and an edge $(u, v)$ of weight $w$ whenever $v$ can be reached from $u$ in one move with a probability of $w$. Finding out all t...
[ "dp", "geometry", "matrices", "probabilities" ]
2,700
#include <cassert> #include <cstdio> #include <algorithm> #include <utility> #include <vector> static const int MAXN = 202; static const int LOGM = 15; static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } struct point { int x, y; point(int x = 0, int y = 0) : x(x), y(y) { } }; struct line { ...
990
A
Commentary Boxes
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations wil...
Notice that you need to check just two numbers: the closest one less or equal to $n$ and the closest one greater than $n$. Distances to them are $(n \mod m)$ and $(m - (n \mod m))$ respectively. Now you should multiply the first result by $b$, the second result by $a$ and compare the products. Overall complexity: $O(1)...
[ "implementation", "math" ]
1,000
#include <bits/stdc++.h> #define forn(i, n) for(int i = 0; i < int(n); i++) using namespace std; int main() { long long n, m; int a, b; cin >> n >> m >> a >> b; cout << min(n % m * b, (m - n % m) * a) << endl; return 0; }
990
B
Micro-World
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer c...
It can be proved that the optimal answer equals to a number of bacteria which can't be eaten by any other bacteria. So for each bacteria $i$ you need to check existence of any bacteria $j$ satisfying condition $a_i < a_j \le a_i + K$. There plenty of ways to check this condition. One of them is to sort array $a$ and fo...
[ "greedy", "sortings" ]
1,200
#include<bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 555; int n, k, a[N]; inline bool read() { if(!(cin >> n >> k)) return false; for(int i = 0; i < n; i++) assert(scanf("%d", &a[i]) == 1); return true; } inline void solve() { sort(a, a + n); a[n++] = int(2e9); int ans = 0, u = 0; fo...
990
C
Bracket Sequences Concatenation Problem
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are reg...
Let $f(s)$ be the mirror reflection of the string $s$. For example: $f$("((") = "))", $f$("))(") = ")((", $f$("()") = "()". Let string be good if it does not have a prefix, which have more closing brackets than opening ones. For example, "((", "(())(", "()()" are good, and "())", ")((", "()())" are not. The balance $ba...
[ "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 7; int n; string s[N]; char buf[N]; int cnt[N]; int getBalance(string &s){ int bal = 0; for(int i = 0; i < s.size(); ++i){ if(s[i] == '(') ++bal; else --bal; if(bal < 0) return -1; } return bal; } string rev(string &s){ ...
990
D
Graph And Its Complement
Given three numbers $n, a, b$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $a$, and the number of components in its complement is $b$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes. In an undirected graph loops (edg...
Let's prove that if $a > 1$, then $b = 1$. Let $G$ be the original graph, and $H$ - the complement of the graph $G$. Let's look at each pair of vertices $(u, v)$. If $u$ and $v$ belong to different components of the graph $G$, then there is an edge between them in the graph $H$. Otherwise, $u$ and $v$ belong to the sam...
[ "constructive algorithms", "graphs", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = int(1e3) + 7; int n, a, b; bool mat[N][N]; int main(){ scanf("%d %d %d", &n, &a, &b); if(min(a, b) > 1){ puts("NO"); return 0; } if(a == 1 && b == 1){ if(n == 2 || n == 3){ puts("NO"); return 0; } puts("YES"); for(int i = 1; i < n;...
990
E
Post Lamps
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has $n$ positions to install lamps, they correspond to the integer numbers from $0$ to $n - 1$ on the OX axis. However, some positions are bloc...
Let's start with learning how to place lamps of fixed power to cover the segment with the minimal number of them. The following greedy strategy works: find the rightmost non-blocked position that is covered by lamps and place lamp there until either everything is covered or rightmost free position is to the left of the...
[ "brute force", "greedy" ]
2,100
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; const long long INF64 = 1e18; const int N = 1000 * 1000 + 13; int n, m, k; bool pos[N]; int lst[N], s[N], a[N]; int get(int l){ int r = 0, i = -1, res = 0; while (r < n){ if (lst[r] <= i) r...
990
F
Flow Control
You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$. The only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe w...
The answer is "Impossible" if and only if the sum of values is not equal to $0$. Writing some number on edge does not change the total sum and the goal of the problem is to make $0$ in each vertex, thus getting $0$ in total. The algorithm is simple: you get an arbitrary spanning tree (with dfs or dsu), output the diffe...
[ "dfs and similar", "dp", "greedy", "trees" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; mt19937 rnd(time(NULL)); const int N = 1'000'013; int n, m; pair<int, int> e[N]; int a[N], rk[N]; long long sum[N], ans[N]; int p[N]; int getP(int a){ return (a == p[a] ? a : p[a] = getP(p[a])); } bool merge(int a...
990
G
GCD Counting
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$. Let's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vert...
Firstly, for every $i \in [1, 2 \cdot 10^5]$ we can calculate the number of paths such that $g(x, y)$ is divisible by $i$. We can do it as follows: generate all divisors of numbers $a_i$ (numbers not exceeding $2 \cdot 10^5$ have at most $160$ divisors, so this will be fast enough), and then for every $i \in [1, 2 \cdo...
[ "divide and conquer", "dp", "dsu", "number theory", "trees" ]
2,400
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream &out, const pair<A, B> &p) { return out << "(" <...
991
A
If at first you don't succeed...
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of them...
There are 4 groups of students - those who visited only the first restaurant, who visited only the second, who visited both places and who stayed at home. One of the easiest ways to detect all the incorrect situations is to calculate number of students in each group. For the first group it is $A - C$, for the second: $...
[ "implementation" ]
1,000
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint a, b, c, n;\n\tcin >> a >> b >> c >> n;\n\n\tint n1 = a - c;\n\tint n2 = b - c;\n\tint n3 = c;\n\tint n4 = n - n1 - n2 - n3;\n\n\tif (n1 >= 0 && n2 >= 0 && n3 >= 0 && n4 > 0)\n\t\tcout << n4;\n\telse\n\t\tcout << -1;\n}"
991
B
Getting an A
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that...
It is necessary to use the greedy approach: of course Vasya should redo the lowest grades firstly. So we have to sort the values in the ascending order and begin to replace the values by 5 until we get the desired result. In order to check whether the current state is suitable we may calculate the mean value after each...
[ "greedy", "sortings" ]
900
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool check(int sum, int n) {\n\t// integer representation of sum / n >= 4.5\n\treturn sum * 10 >= n * 45;\n}\n\nint main() {\n\tvector<int> v;\n\tint sum = 0;\n\n\tint n;\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\tv.push_back(x);\n\...
991
C
Candies
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself. This means the process of eating candies is the following: in the beginning Vasya cho...
It is easy to check that if for some value $k$ the necessary condition is met (Vasya eats at least half of the candies), then it is met for each integer greater $k$. Let's consider the number of candies remaining at the evening of each day for some selected $k_{1}$ - let $a_{i}$ candies remain at day $i$. If Vasya will...
[ "binary search", "implementation" ]
1,500
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool check(long long k, long long n) {\n\tlong long sum = 0;\n\tlong long cur = n;\n\twhile (cur > 0) {\n\t\tlong long o = min(cur, k);\n\t\tsum += o;\n\t\tcur -= o;\n\t\tcur -= cur / 10;\n\t}\n\treturn sum * 2 >= n;\n}\n\nint main() {\n\tlong long n;\n\tcin >> n;\n\...
991
D
Bishwock
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states: \begin{center} \begin{verbatim} XX XX .X X. X. .X XX XX \end{verbatim} \end{center} Bishwocks don't attack any squares and can even occupy on the ...
In this problem we may use the greedy approach. Let's go through columns from left to right. If we are currently considering column $i$ and we may place a figure occupying only cells at columns $i$ and $i + 1$, we have to place this figure. Really if the optimal solution doesn't contain a bishwock at column $i$ then co...
[ "dp", "greedy" ]
1,500
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tstring s[2];\n\n\tint n = 2;\n\tint m;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s[i];\n\t\tm = s[i].length();\n\t}\n\n\tint ans = 0;\n\tint previous = 0;\n\tfor (int i = 0; i < m; i++) {\n\t\tint current = (s[0][i] == '0') + (s[1][i] == '0');\n\n\...
991
E
Bus Number
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all. ...
According to the statement, digits of original bus number form a subset of digits of the number seen by Vasya. It is possible to iterate through all the subsets in $2^{k}$ operations (where $k$ is length of $n$). For each subset we need to check whether it is correct (contains all necessary digits) and transform it to ...
[ "brute force", "combinatorics", "math" ]
1,800
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long fact[20];\n\nset<string> was;\nint c0[10];\nint c[10];\n\nvoid split(string s, int *c) {\n\tfor (int i = 0; i < 10; i++)\n\t\tc[i] = 0;\n\tfor (char ch : s)\n\t\tc[ch - 48]++;\n}\n\nlong long getCount() {\n\tlong long ans = fact[accumulate(c, c + 10, 0)];\n...
991
F
Concise and clear
Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the ...
All the problem numbers (except for $10^{10}$, which is given in the samples) contain at most 10 digits. It means that we have to use at most 9 digits if we want to find a shorter representation. Notice that the length of sum of two integers is not greater than sum of the lengths of these integers, so in the optimal re...
[ "brute force", "greedy", "implementation", "math" ]
2,700
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long n;\nlong long p10[10];\nmap<long long, string> m;\nset<long long> s[10];\n\ntemplate<class T> string toString(T x) {\n\tostringstream sout;\n\tsout << x;\n\treturn sout.str();\n}\n\nint getlen(long long x) {\n\tint ans = 0;\n\twhile (x) {\n\t\tx /= 10;\n\t\...
992
A
Nastya and an Array
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: - In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zer...
Let's notice that after one second we aren't able to decrease the number of distinct non-zero elements in the array more than by 1. It means that we can't make all elements equal to zero faster than after $X$ seconds, where $X$ is the number of distinct elements in the array initially. And let's notice that we are able...
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; set <int> ms; for (int i = 0; i < n; ++i) { int x; cin >> x; if (x) ms.insert(x); } cout << ms.size() << '\n'; return 0; }
992
B
Nastya Studies Informatics
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well. We define a pair of integers $(a, b)$ good, if $GCD(a, b) = x$ and $LCM(a, b) = y$, where $GCD(a, b)$ denotes the greates...
Let's consider some suitable pair $(a,b)$. As $G C D(a,b)=x$, we can present number ${\boldsymbol{Q}}$ as $c\cdot x$, and number ${\boldsymbol{b}}$ as $d\cdot x$, where we know that $c,d\geq1$ and $G C D(c,d)=1$. Let's consider too that from the restriction from the problem $l\leq a,b\leq r$ we surely know the restrict...
[ "math", "number theory" ]
1,600
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int l, r, x, y; cin >> l >> r >> x >> y; if (y % x != 0){ cou...
992
C
Nastya and a Wardrobe
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month). Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with ...
Let's present we have initially $X=Y+{\frac{1}{2}}$ dresses. What does occur in the first month? Initially the number of dresses is multiplied by 2, that is becomes $2\cdot Y+1$. Then with probability $\mathbf{z}=\mathbf{z}(\mathbf{z})^{(y)}{\mathcal{V}}$ the wardrobe eats a dress, that is expected value of the number ...
[ "math" ]
1,600
#include <bits/stdc++.h> using namespace std; #define int long long const int MOD = 1000 * 1000 * 1000 + 7; int mod(int n) { return (n % MOD + MOD) % MOD; } int fp(int a, int b) { if (b == 0) return 1; int t = fp(a, b / 2); if (b % 2 == 0) return mod(t * t); else return mod(mod(t * t) * a); ...
992
D
Nastya and a Game
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that $\overset{p}{s}=k$, where $p$ is the product of all integers on the given array, $s$ is their sum, and $k$ is a ...
Let's call numbers which are more than 1 as good. Notice the following fact: If a subsegment is suitable, it contains not more than 60 good numbers. Indeed, let's assume that a subsegment contains more than 60 good numbers. In this subsegment $p\geq2^{61}>2\cdot10^{18}$. At the same time, as $k\leq10^{5}$, and $s\leq n...
[ "brute force", "implementation", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; #define int long long const int MAXN = 2e5 + 7; const int INF = 1e18 + 2007; int a[MAXN]; int go[MAXN]; signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; for (int i = 0; i < n; ++i) cin >> a[i]; go[n -...
992
E
Nastya and King-Shamans
Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were $n$ shamans in total enumerated with integers fr...
This problem was inspired by idea which was offered by my unbelievable girlfriend :) Solution I In this problem we maintain two segment trees - with maximum and with sum. After every query we recalculate these trees in $O(l o g N)$ for a query. Now we only have to understand, how to answer for a query? Let's call a pre...
[ "binary search", "data structures" ]
2,500
#include <iostream> #include <cstdio> #include <vector> #include <set> template <class T> class FenwickTree { public: void init(int n) { this->n = n; bit.assign(n + 1, 0); } void init(const std::vector<T> &a) { n = a.size(); bit.assign(n + 1, 0); for(int i = 1; i <= n; i++) { bit[i] += a[i - 1]; ...
993
A
Two Squares
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ...
It can be shown that if two squares intersect, then at least for one of the squares it is true that either one of its corners lies within the other square, or its center lies within the other square. It is very easy to check if any corner or the center of the square rotated by 45 degrees lies within the square with sid...
[ "geometry", "implementation" ]
1,600
null
993
B
Open Communication
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set ...
One way to approach this problem is to 1. Iterate over each pair $p1$ communicated by the first participant, and do the following: Iterate over all pairs $p2$ of the second participant that are not equal to $p1$ and count whether the first number of $p1$ appears in any of them and whether the second number of $p1$ appe...
[ "bitmasks", "brute force" ]
1,900
null
993
C
Careful Maneuvering
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $-100$, while the second group is positioned in suc...
One way to solve the problem is to fix one spaceship in the left half and one spaceship in the right half, and assume that they shoot each other by the means of shooting towards one of the small spaceships. This gives us a coordinate of one small spaceship. Once we have it, iterate over all the large spaceships, mark t...
[ "bitmasks", "brute force", "geometry" ]
2,100
null
993
D
Compute Power
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task ca...
First observe that if for some threshold there's a way to assign tasks in a way that they will finish computation, it is also possible for all higher thresholds. Because of that, we can use binary search to find the threshold. Now the problem is reduced to figuring out if for a given threshold the tasks can be assigned...
[ "binary search", "dp", "greedy" ]
2,500
null
993
E
Nikita and Order Statistics
Nikita likes tasks on order statistics, for example, he can easily find the $k$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $x$ is the $k$-th number in increasing order on this segment. In other words, you should find th...
First, we can find amount of numbers that less than $x$ for each prefix of $a$ (including empty prefix). We get array $s$ of this values. You can see that for each $i,j, i < j$ the truth that $s[i] \leq s[j]$ and if $s[i]<s[j]$ then $i<j$. Let's count array $r$ such that $r[i]$ is number of occurences $i$ in $s$. Then ...
[ "chinese remainder theorem", "fft", "math" ]
2,300
null
993
F
The Moral Dilemma
Hibiki and Dita are in love with each other, but belong to communities that are in a long lasting conflict. Hibiki is deeply concerned with the state of affairs, and wants to figure out if his relationship with Dita is an act of love or an act of treason. Hibiki prepared several binary features his decision will depen...
First lets observe that for the original and the inverted circuit to return the same value for each input, for each possible input one of the two conditions must be met: either in the original circuit all the gates in the second layer return 0, or in the inverted circuit all the gates in the second layer return 0. This...
[]
3,200
null
994
A
Fingerprints
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
The problem can be solved by iterating over every number of the sequence, then iterating over the sequence of fingerprints to check if the number corresponds to a key with a fingerprint, resulting in an $O(n \times m)$ solution.
[ "implementation" ]
800
null
994
B
Knights of a Polygonal Table
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no mo...
Sort the knights by increasing the power. Now we can iterate over an array and greedy store set of $k$ prevous knights with maximum if coins. After handling knight, if set contains less than $k$ elements, we add current knight in set. Else if number of coins from current knight greater than from knight with minimum coi...
[ "greedy", "implementation", "sortings" ]
1,400
null
995
A
Tesla
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be repres...
First, whenever any cars are directly to their parking spot, we should move them into the correct parking spot. Now, we can view rows $2$ and $3$ as a cycle. In at most $k$ moves, we can spin the entire cycle of cars counterclockwise. By repeating this $2n$ times, each car will have been adjacent to each parking space,...
[ "constructive algorithms", "implementation" ]
2,100
null
995
B
Suit and Tie
Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the pic...
We describe a greedy algorithm that achieves the minimum number of swaps. If the leftmost person is in pair $a$, swap the other person in pair $a$ left, to the second position. Now the first two people are both in pair $a$, and we repeat the process on the remaining $n-1$ pairs of people recursively. We now prove that ...
[ "greedy", "implementation", "math" ]
1,400
null
995
C
Leaving the Bar
For a vector $\vec{v} = (x, y)$, define $|v| = \sqrt{x^2 + y^2}$. Allen had a bit too much to drink at the bar, which is at the origin. There are $n$ vectors $\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$. Allen will make $n$ moves. As Allen's sense of direction is impaired, during the $i$-th move he will either move in th...
We first prove a claim which will help us significantly. The claim is that among any three vectors $\vec{v_1}, \vec{v_2}, \vec{v_3}$ of lengths at most $r$, then some sum $\vec{v_i} + \vec{v_j}$ or difference $\vec{v_i} - \vec{v_j}$ has at length at most $r$. Draw a circle with radius $r$ centered at the origin. If we ...
[ "brute force", "data structures", "geometry", "greedy", "math", "sortings" ]
2,300
null
995
D
Game
Allen and Bessie are playing a simple number game. They both know a function $f: \{0, 1\}^n \to \mathbb{R}$, i. e. the function takes $n$ binary arguments and returns a real value. At the start of the game, the variables $x_1, x_2, \dots, x_n$ are all set to $-1$. Each round, with equal probability, one of Allen or Bes...
One can show by induction that the expected value of the game is $\mathbb{E}[f] = 2^{-n} \sum_{x \in \{0, 1\}^n} f(x)$. Consider the first turn. For notation, let $v_{i, 0}$ be the expected value of the game when $x_i$ is set to $0$, and let $v_{i, 1}$ be the expected value of the game when $x_i$ is set to $1$. By indu...
[ "math" ]
2,500
null
995
E
Number Clicker
Allen is playing Number Clicker on his phone. He starts with an integer $u$ on the screen. Every second, he can press one of 3 buttons. - Turn $u \to u+1 \pmod{p}$. - Turn $u \to u+p-1 \pmod{p}$. - Turn $u \to u^{p-2} \pmod{p}$. Allen wants to press at most 200 buttons and end up with $v$ on the screen. Help him!
Our first observation is that the game can be modeled the following way. Construct an undirected graph on $\{0, 1, \dots, p-1\}$ such that $i$ is connected to $i-1, i+1,$ and $i^{p-2} \pmod{p}.$ We want to find a path of length at most 200 between $u$ and $v$ in this graph. Running a BFS will take too long, so we need ...
[ "divide and conquer", "graphs", "meet-in-the-middle", "number theory" ]
2,700
null
995
F
Cowmpany Cowmpensation
Allen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires $n-1$ other employees, each of which is assigned a direct superior. If $u$ is a superior of $v$ and $v$ is a superior of $w$ then also $u$ is a superior of $w$. Additionally, ...
A immediate simple observation is that we can compute the answer in $O(nD)$ with a simple dynamic program. How to speed it up though? To speed it up, we need the following lemma. Lemma 1: For a tree with $n$ vertices, the answer is a polynomial in $D$ of degree at most $n$. We can prove this via induction, and the fact...
[ "combinatorics", "dp", "math", "trees" ]
2,700
null
996
A
Hit the Lottery
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
The problem is to minimize $x_1 + x_2 + x_3 + x_4 + x_5$ given that $x_1 + 5x_2 + 10x_3 + 20x_4 + 100x_5 = n.$ It is pretty simple to see that we can operate greedily: take as many $100$ as we can, then $20$, then $10$, etc. The solutions works because each number in the sequence $1, 5, 10, 20, 100$ is a divisor of the...
[ "dp", "greedy" ]
800
null
996
B
World Cup
Allen wants to enter a fan zone that occupies a round square and has $n$ entrances. There already is a queue of $a_i$ people in front of the $i$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute. Allen uses the following strategy to enter the fan zone: - Initially he sta...
For gate $k$ (where $1 \le k \le n$) we visit the gate at times $k, k+n, k+2n, \cdots$ Therefore, the earliest Allen could enter from gate $k$ is the time $k + tn$ such that $k + tn \ge a_k.$ Now, for each $k$, compute the minimal integer $b_k = k+tn$ such that $k+tn \ge a_k$. Now, find the integer $k$ with minimum $b_...
[ "binary search", "math" ]
1,300
null
997
A
Convert to Ones
You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones. Let's call a sequence of consecutive elements $a_i, a_{i + 1}, \ldots, a_j$ ($1\leq i\leq j\leq n$) a substring of string $a$. You can apply the following operations any number of times: - Choose some substring of string $a$ (for example, you ...
Let's partite consecutive elements of the same color into groups. For example, we will split <<00011001110>> into <<000>> + <<11>> + <<00>> + <<111>> + <<0>>. Then it is obvious that it is useless to make moves within one group, and then (if we have at least two groups of color $0$) for one move we can reduce by one (a...
[ "brute force", "greedy", "implementation", "math" ]
1,500
null
997
B
Roman Digits
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence s...
TL; DR - among all the sequences, select the one, which contains the maximum number of $50$, in case of tie, select one with largest number of $9$. Bruteforce all configurations in such way, that each number is counted only in it's "maximum" configuration. Since the length of sequence is fixed, we can solve problem not...
[ "brute force", "combinatorics", "dp", "greedy", "math" ]
2,000
null
997
C
Sky Full of Stars
On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game. It is well known that one month on this planet consists of $n^2$ days, so calendars, represented as square matrix $n$ by $n$ are extremely popular. Weather conditions are even more unusual. Due to the unique composi...
Let $A_i$ be the set of all colorings, where $i$-th line contains only one color, and $B_i$ be the set of colorings, where $i$-th column contains only one color. This way, you need to calculate $|A_1 \cup A_2 \ldots A_n \cup B_1 \cup B_2 \ldots B_n|$. As usual, we can use inclusion-exclusion formula to reduce the calcu...
[ "combinatorics", "math" ]
2,500
null
997
D
Cycles in product
Consider a tree (that is, an undirected connected graph without loops) $T_1$ and a tree $T_2$. Let's define their cartesian product $T_1 \times T_2$ in a following way. Let $V$ be the set of vertices in $T_1$ and $U$ be the set of vertices in $T_2$. Then the set of vertices of graph $T_1 \times T_2$ is $V \times U$, ...
Consider an arbitrary cycle in a graph product. Due to the definition of the product, the adjacent vertices in the cycle correspond to the transition by the edge either in the first tree or in the second tree. This way, if you write the edges corresponding to one tree in a separate list, you will get a cycle in this tr...
[ "combinatorics", "divide and conquer", "trees" ]
2,900
null
997
E
Good Subsegments
A permutation $p$ of length $n$ is a sequence $p_1, p_2, \ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \leq p_i \leq n$) . Let's call the subsegment $[l,r]$ of the permutation \textbf{good} if all numbers from the minimum on it to the maximum on this subsegment occur among the num...
Let's look at two solutions for all array, and each of them can be upgraded to subquadratic time for queries on subsegments. First solution is Divide&Conquer. Let's take a middle of the array and find number of segments, that contain it. If minimum and maximum are at one side of middle, then by the end on the half wher...
[ "data structures" ]
3,000
null
998
A
Balloons
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons insi...
It is easy to show, that if at least one solution exists, than it is possible to use the answer, which contains only one, minimal, element. Suppose, that this set is not valid. Then one of the following holds: Either $n = 1$, and then there is no solution Or $n = 2$, and other element is equal to minimum, in this case ...
[ "constructive algorithms", "implementation" ]
1,000
null
998
B
Cutting
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers. There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti...
It is possible to proof, that cut after $i$-th number can be done if and only if the prefix of length $i$ contains equal number of odd and even numbers. This way each cut can be done or not done independently of all other cuts (except the budget issue). Why it is true? Let's proof that criterion is sufficient. If you m...
[ "dp", "greedy", "sortings" ]
1,200
null
999
A
Mishka and Contest
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses ...
You can iterate over all the elements of the array from left to right. Count the number of problems Mishka will solve from the left end of the list and break if he cannot solve the next one. Let's denote the number of problems Mishka will solve from the left end of the list by $\mathit{lf}$. Do the same thing independe...
[ "brute force", "implementation" ]
800
#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]; int ans = 0; while (!a.empty() && a.back() <= k) { ++ans; a.pop_...
999
B
Reversing Encryption
A string $s$ of length $n$ can be encrypted by the following algorithm: - iterate over all divisors of $n$ in decreasing order (i.e. from $n$ to $1$), - for each divisor $d$, reverse the substring $s[1 \dots d]$ (i.e. the substring which starts at position $1$ and ends at position $d$). For example, the above algorit...
To solve the problem, we can implement the encryption algorithm with a single change: we have to iterate over all divisors of $n$ in increasing order. Time complexity - $O(n~ \cdot d(n))$, where $d(n)$ is a divisor count function for $n$. For example, $\max\limits_{i = 1}^{10^6}d(i) = 240$.
[ "implementation" ]
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; cin >> n >> s; for (int i = 1; i <= n; ++i) { if (n % i == 0) { reverse(s.begin(), s.begin() + i); } } cout << s << endl; return ...
999
C
Alphabetic Removals
You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \le n$) from the string $s$. Polycarp uses the following algorithm $k$ times: - if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item...
Let the lowercase Latin letters be indexed from $0$ to $25$. There are exists at least two different solutions: If $k = n$ exit the program. Otherwise, count the number of occurrences of each letter $i$ from $0$ to $25$. Let it be $\mathit{cnt}$. Now, find the (alphabetically) smallest letter that will be in the result...
[ "implementation" ]
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 n, k; cin >> n >> k; string s; cin >> s; vector<pair<char, int>> c(n); for (int i = 0; i < n; ++i) c[i] = make_pair(s[i], i); sort(c.begin(), c.end(...
999
D
Equalize the Remainders
You are given an array consisting of $n$ integers $a_1, a_2, \dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$. In a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$. Let's calculate $c_r$ ($0 \le r \le m-1)$ — the number of elements havin...
For each $i$ from $0$ to $m - 1$, find all elements of the array that are congruent to $i$ modulo $m$, and store their indices in a list. Also, create a vector called $\mathit{free}$, and let $k$ be $\frac{n}{m}$. We have to cycle from $0$ to $m - 1$ twice. For each $i$ from $0$ to $m - 1$, if there are in list too man...
[ "data structures", "greedy", "implementation" ]
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, m; cin >> n >> m; int k = n / m; vector<int> a(n); vector<vector<int>> val(m); for (int i = 0; i < n; ++i) { cin >> a[i]; val[a[i] % m].push_back...
999
E
Reachability from the Capital
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way. What is the minimum number of new roads that need to be built to make all the cities reachable from the capital? New roads will also be one-way.
This problem is (almost) equivalent to the following: count the number of sources (the vertices with indegree equal to $0$) in the given graph's condensation. Thus, there exist solutions with complexity $O(n + m)$. However, the constraints in the problem are small, so solutions with complexity $O(n \cdot m)$ also pass....
[ "dfs and similar", "graphs", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 5010; int n, m, s; vector<int> g[N]; vector<int> tg[N]; vector<int> cg[N]; vector<int> ord; int indeg[N]; bool ucomp[N]; bool used[N]; int comp[N]; int cnt; void dfs1(int v) { used[v] = true; for (auto to : g[v]) if (!used[to]) dfs1(to); ord.push_b...
999
F
Cards and Joy
There are $n$ players sitting at the card table. Each player has a favorite number. The favorite number of the $j$-th player is $f_j$. There are $k \cdot n$ cards on the table. Each card contains a single integer: the $i$-th card contains number $c_i$. Also, you are given a sequence $h_1, h_2, \dots, h_k$. Its meaning...
It is obvious that we can solve the problem separately for each favorite number because each player has only one favorite number, and if the player gets a card not having his favorite number, his joy will not change. Let $\mathit{dp}[x][y]$ be the maximum possible total joy of $x$ players with the same favorite number ...
[ "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 520; const int K = 12; const int C = 100 * 1000 + 11; int n, k; int c[C]; int f[C]; vector<int> h; int dp[N][K * N]; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n >> k; h = vector<...
1000
A
Codehorses T-shirts
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from $0$ to $3$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. ...
At first, let's remove all coinciding entries of both lists. The most convinient way is to use map/hashmap but it's not the only option. Now divide entries into categories by their length. You can notice that it takes exactly one second to remove an entry in each category (to make it equal to an entry of the opposing l...
[ "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n; cin >> n; vector<string> a(n), b(n); forn(i, n) cin >> a[i]; forn(i, n) cin >> b[i]; map<string, int> cnta, cntb; forn(i, n) ++cnta[a[i]]; forn(i, n) ++cntb[b[i]]; int ans = n; for (...
1000
B
Light It Up
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunate...
At first, let's insert $0$ and $M$ in array $a$, so all possible positions for inserting will always belong to $(a_i, a_{i + 1})$. At second, let $x$ be value to insert and $a_i < x < a_{i + 1}$. It can be proven, that it's always optimal to move $x$ to $a_i$ or to $a_{i + 1}$. So, for each $(a_i, a_{i + 1})$ we need t...
[ "greedy" ]
1,500
#include<bits/stdc++.h> using namespace std; int n, M; vector<int> a; inline bool read() { if(!(cin >> n >> M)) return false; a.assign(n, 0); for(int i = 0; i < n; i++) scanf("%d", &a[i]); return true; } vector<int> f[2]; inline void solve() { a.insert(a.begin(), 0); a.push_back(M); f[0].assign(a.size...
1000
C
Covered Points Count
You are given $n$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every $k \in [1..n]$, calculate the number of points with in...
This problem with small coordinates can be solved using partial sums and some easy counting. Let's carry an array $cnt$, where $cnt_i$ will be equal to the number of segments that cover the point with coordinate $i$. How to calculate $cnt$ in $O(n + maxX)$? For each segment ($l_i, r_i$) let's add $+1$ to $cnt_{l_i}$ an...
[ "data structures", "implementation", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<pair<long long, long long>> a(n); vector<long long> cval; for (auto &i : a) { scanf("%lld %lld", &i.first, &i.second); cva...
1000
D
Yet Another Problem On a Subsequence
The sequence of integers $a_1, a_2, \dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 > 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ — are not. A sequence of integers is called good if it can be divided into a positive number of ...
The problem is solved by the dynamic programming. Let $dp_i$ be the answer for the prefix of the array starting at $i$ (it contains the indices $i, i + 1, \dots, n$). If $a_i \le 0$, then $dp_i = 0$. Otherwise, let's go over the position $j$, with which the next good array begins. Then we need to select $a_i$ positions...
[ "combinatorics", "dp" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 1009; const int MOD = 998244353; int n; int a[N]; int dp[N]; int C[N][N]; int main() { for(int i = 0; i < N; ++i){ C[i][0] = C[i][i] = 1; for(int j = 1; j < i; ++j) C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; } cin >> n; for(int i = 0; i ...
1000
E
We Need More Bosses
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $n$ locations connected by $m$ \textbf{two-way} passages. The passages are designed in such a way that it should be possible to get from any location to any other location. Of course, some passa...
It's quite obvious that we can place bosses only on the bridges of the given graph - if an edge is not a bridge, then removing it doesn't make the graph disconnected, so there still exists a path between any pair of vertices. And if we fix two vertices $s$ and $t$, and then find some simple path between them, then we w...
[ "dfs and similar", "graphs", "trees" ]
2,100
#include<bits/stdc++.h> using namespace std; const int N = 500043; vector<int> g[N]; vector<int> t[N]; int tin[N], tout[N], fup[N]; int p[N]; int T = 1; int rnk[N]; vector<pair<int, int> > bridges; int st; int d[N]; int n, m; int get(int x) { return (p[x] == x ? x : p[x] = get(p[x])); } void link(int x, int y) {...
1000
F
One Occurrence
You are given an array $a$ consisting of $n$ integers, and $q$ queries to it. $i$-th query is denoted by two integers $l_i$ and $r_i$. For each query, you have to find \textbf{any} integer that occurs \textbf{exactly once} in the subarray of $a$ from index $l_i$ to index $r_i$ (a subarray is a contiguous subsegment of ...
Suppose all queries have the same right border $r$. Then the answer for the query can be some integer $i$ such that the last occurence of $i$ on the prefix $[1, r]$ of the array is inside the segment, but the second to last occurence is outside the segment (or even does not exist). More formally, let $f(i)$ be the maxi...
[ "data structures", "divide and conquer" ]
2,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) #define x first #define y second const int N = 500 * 1000 + 13; const int P = 800; const int INF = 1e9; bool comp(const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b){ int num = a.x.x / P; if (nu...
1000
G
Two-Paths
You are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with $n$ vertices. The edge $\{u_j, v_j\}$ has weight $w_j$. Also each vertex $i$ has its own value $a_i$ assigned to it. Let's call a path starting in vertex $u$ and ending in vertex $v$, where each edge can appear no m...
Let's solve this task in several steps. Step 1. Calculate $dp_i$ for each vertex. Let $dp_i$ be maximal profit of some 2-path starting at $i$ and finishing at $i$. If vertex $i$ is a root of the tree, then $dp_i$ equivalent to $d'_i$, where $d'_i$ - maximal profit of 2-path $(i, i)$, when we can go only in subtree of $...
[ "data structures", "dp", "trees" ]
2,700
#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 all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& ...
1003
A
Polycarp's Pockets
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins i...
We have to find the maximum number of elements with the same value (it can be done by counting). This number will be the answer because if there are no more than $k$ elements with the same value in the array it is obvious that we cannot use less than $k$ pockets, but we also doesn't need to use more than $k$ pockets be...
[ "implementation" ]
800
#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; vector<int> cnt(101); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[x]; } cout << *max_element(cnt.begin(), cnt.end()) << ...
1003
B
Binary String Constructing
You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \le i < n$) such that $s_i \ne s_{i + 1}$. It is guaranteed that the answer always exists. For example, for t...
This problem has several general cases: $x$ is even and $a > b$, then the answer is 01 repeated $\frac{x}{2}$ times, then $b - \frac{x}{2}$ ones and $a - \frac{x}{2}$ zeroes; $x$ is even and $a \le b$, then the answer is 10 repeated $\frac{x}{2}$ times, then $a - \frac{x}{2}$ zeroes and $b - \frac{x}{2}$ ones; $x$ is o...
[ "constructive algorithms" ]
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 a, b, x; cin >> a >> b >> x; if (x % 2 == 0) { if (a > b) { for (int i = 0; i < x / 2; ++i) cout << "01"; cout << string(b - x / 2, '1'); ...
1003
C
Intense Heat
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually cal...
This task is very straight-forward implementation problem. So we can iterate over all segments of the given array, calculate their sum, and if the length of the current segment is not less than $k$, try to update the answer with the mean of this segment. Overall complexity is $O(n^2)$.
[ "brute force", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define all(a) a.begin(), a.end() #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, l, r) for(int i = int(l); i < int(r); i+...
1003
D
Coins and Queries
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. It is guaranteed that all the values are integer powers of $2$ (i.e. $a_i = 2^d$ for some \textbf{non-negative} integer number $d$). Polycarp wants to know answers on $q$ queries. The $j$-th query is described as integer number $b_j$. The answer to the que...
We can solve the problem by the following way: firstly, for each power of $2$ let's calculate the number of coins with the value equals this degree. Let's call it $cnt$. It is obvious that we can obtain the value $b_j$ greedily (because all less values of coins are divisors of all greater values of coins). Now let's it...
[ "greedy" ]
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, q; cin >> n >> q; vector<int> cnt(31); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[__builtin_ctz(x)]; } while (q--) { int x; c...
1003
E
Tree Constructing
You are given three integers $n$, $d$ and $k$. Your task is to construct an undirected tree on $n$ vertices with diameter $d$ and degree of each vertex at most $k$, or say that it is impossible. An undirected tree is a connected undirected graph with $n - 1$ edges. Diameter of a tree is the maximum length of a simpl...
Let's construct a tree by the following algorithm: if $d \ge n$, let's print "NO" and terminate the program. Otherwise let's keep the array $deg$ of the length $n$ which will represent degrees of vertices. The first step is to construct the diameter of the tree. Let first $d + 1$ vertices form it. Let's add $d$ edges t...
[ "constructive algorithms", "graphs" ]
2,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, d, k; cin >> n >> d >> k; if (d >= n) { cout << "NO" << endl; return 0; } vector<int> deg(n); vector<pair<int, int>> ans; set<pair<int, int>...
1003
F
Abbreviation
You are given a text consisting of $n$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $w_i$ is the $i$-th word of text. All words co...
Let $eq_{i, j}$ equals true if words $s_i$ and $s_j$ are equal, otherwise it will be equals false. We can iterate over all pairs of words and compare they just using standard string comparator (constraints are really small so we can do it naively). The next step is to calculate dynamic programming $dp_{i, j}$, which wi...
[ "dp", "hashing", "strings" ]
2,200
#include <bits/stdc++.h> using namespace std; const int N = 303; int n; bool eq[N][N]; int dp[N][N]; string s[N]; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n; int allsum = n - 1; for (int i = 0; i < n; ++i) { cin >> s[i]; allsum += s[i...
1004
A
Sonya and Hotels
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordin...
One hotel always can be built to the left of the first hotel. One more can be built to the right of the last hotel. Let's look at each pair of the adjacent hotels. If the distance between these two hotels is greater than $2\cdot d$, we can build one hotel at a distance of $d$ to the right from the left hotel and one mo...
[ "implementation" ]
900
null
1004
B
Sonya and Exhibition
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions shoul...
Note, that it is always optimal to use roses in even positions and lilies in odd positions. That is, the string $01010101010\ldots$ is always optimal.
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,300
null
1004
C
Sonya and Robots
Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers. Sonya has drawn $n$ numbers in a row, $a_i$ is located in the $i$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya wi...
Let's assume that our left robot is located in the $p$ position. The robot could be there only if the value that is written there did not occur earlier. The number of possible locations of the second robot is equal to the number of distinct numbers on the segment $[(p+1)\ldots n]$. Let $dp_i$ be the number of different...
[ "constructive algorithms", "implementation" ]
1,400
null
1004
D
Sonya and Matrix
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit. Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers ...
Suppose that a matrix has sizes $n\times m$, zero is located at $(x,y)$. Let $a$ be the distance to the cell $(1,1)$, and let $b$ the distance to the cell $(n,m)$. Obvious that the farthest distance from the zero cell will be to a corner cell. The maximum number in the list is equal to the maximum distance to a corner ...
[ "brute force", "constructive algorithms", "implementation" ]
2,300
null
1004
E
Sonya and Ice Cream
Sonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops. Sonya lives in a city with $n$ junctions and $n-1$ streets between them. All streets are two-way and connect two junctions. It is possible to travel from any j...
The editorial for the main solution with centroid decomposition will be published later. Another Solution (without really formal proof) It is possible to show, that if we have all weights equal to $1$, then optimal answer is always a middle part of diameter of right length. However, weights are arbitrary. Then we need ...
[ "binary search", "data structures", "dp", "greedy", "shortest paths", "trees" ]
2,400
null
1005
A
Tanya and Stairways
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $1$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $3$ steps, and the second contains $4$ ...
The answer contains such elements $a_i$ that $a_{i+1}=1$. Also add to the answer the last element $a_n$.
[ "implementation" ]
800
int n; cin >> n; vector<int> a; int p = -1; forn(i, n) { int x; cin >> x; if (x == 1 && p != -1) a.push_back(p); p = x; } a.push_back(p); cout << a.size() << endl; for (int i: a) cout << i << " ";
1005
B
Delete from the Left
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty. For example: - by applying a move to the string "where", the result is t...
Let's find the value $w$ - the length of the longest common suffix of $s$ and $t$. You can easily find it in one linear loop: just compare the last letters of $s$ and $t$. If they are equal then compare before the last letters of $s$ and $t$. And so on. The last $w$ letters of $s$ and $t$ are two equal strings which wi...
[ "brute force", "implementation", "strings" ]
900
string s, t; cin >> s >> t; int w = 0; while (true) { int i = s.length() - w - 1; int j = t.length() - w - 1; if (i >= 0 && j >= 0 && s[i] == t[j]) w++; else break; } cout << s.length() + t.length() - 2 * w << endl;
1005
C
Summarize to the Power of Two
A sequence $a_1, a_2, \dots, a_n$ is called good if, for each element $a_i$, there exists an element $a_j$ ($i \ne j$) such that $a_i+a_j$ is a power of two (that is, $2^d$ for some non-negative integer $d$). For example, the following sequences are good: - $[5, 3, 11]$ (for example, for $a_1=5$ we can choose $a_2=3$...
You should delete only such $a_i$ for which there is no such $a_j$ ($i \ne j$) that $a_i+a_j$ is a power of $2$. For each value let's find the number of its occurrences. You can use simple $map$ standard data-structure. Do $c[a[i]] := c[a[i]]+1$ for each element $a[i]$. Now you can easily check that $a_i$ doesn't have ...
[ "brute force", "greedy", "implementation" ]
1,300
int n; cin >> n; vector<int> a(n); map<int,int> c; forn(i, n) { cin >> a[i]; c[a[i]]++; } int ans = 0; forn(i, n) { bool ok = false; forn(j, 31) { int x = (1 << j) - a[i]; if (c.count(x) && (c[x] > 1 || (c[x] == 1 && x != a[i]))) ok = true; } if (!ok) ans++; }...
1005
D
Polycarp and Div 3
Polycarp likes numbers that are divisible by 3. He has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in tot...
There are multiple approaches to solve this problem. We will use dynamic programming approach. Let's calculate values of the array $z[0 \dots n]$, where $z[i]$ is the answer for prefix of the length $i$. Obviously, $z[0] := 0$, since for the empty string (the prefix of the length $0$) the answer is $0$. For $i>0$ you c...
[ "dp", "greedy", "number theory" ]
1,500
string s; cin >> s; int n = s.length(); int r = 0; vector<int> fin(3, -1); fin[0] = 0; vector<int> z(n + 1); for (int i = 1; i <= n; i++) { r = (r + s[i - 1] - '0') % 3; z[i] = z[i - 1]; if (fin[r] != -1) z[i] = max(z[i], z[fin[r]] + 1); fin[r] = i; } cout << z[n] << endl;
1005
E1
Median on Segments (Permutations Edition)
You are given a permutation $p_1, p_2, \dots, p_n$. A permutation of length $n$ is a sequence such that each integer between $1$ and $n$ occurs exactly once in the sequence. Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly t...
The segment $p[l \dots r]$ has median equals $m$ if and only if $m$ belongs to it and $less=greater$ or $less=greater-1$, where $less$ is number of elements in $p[l \dots r]$ that strictly less than $m$ and $greater$ is number of elements in $p[l \dots r]$ that strictly greater than $m$. Here we've used a fact that $p$...
[ "sortings" ]
1,800
int n, m; cin >> n >> m; vector<int> p(n); forn(i, n) cin >> p[i]; map<int,int> c; c[0] = 1; bool has = false; int sum = 0; long long ans = 0; for (int r = 0; r < n; r++) { if (p[r] < m) sum--; else if (p[r] > m) sum++; if (p[r] == m) has = true; if (has) ans += c[su...
1005
E2
Median on Segments (General Case Edition)
You are given an integer sequence $a_1, a_2, \dots, a_n$. Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$. The median of a sequence is the value of an element which is in the middle of the sequence after s...
Let's define a function greaterCount($m$) - number of subarrays with median greater or equal than $m$. In this case, the answer on the problem is greaterCount($m$) $-$ greaterCount($m + 1$). The subarray $a[l \dots r]$ has median greater or equal than $m$, if and only if $notLess>less$, where $notLess$ is the number eq...
[ "sortings" ]
2,400
long long greaterCount(int m) { vector<int> s(2 * n + 1); int sum = n; long long result = 0; s[sum] = 1; long long add = 0; forn(i, n) { if (a[i] < m) sum--, add -= s[sum]; else add += s[sum], sum++; result += add; s[sum]++; } retur...
1005
F
Berland and the Shortest Paths
There are $n$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $1$ to $n$. It is known that, from the capital (the city with the number $1$), you can rea...
Use BFS to precalculate an array $d$ - the array of the shortest path lengths from the Capital. The condition to minimize sum of distances in each tree is equal to the fact that each tree is a shortest path tree. Let's think about them as about oriented outgoing from the Capital trees. Moving along edges of such trees,...
[ "brute force", "dfs and similar", "graphs", "shortest paths" ]
2,100
int n, m, k; cin >> n >> m >> k; vector<vector<int>> g(n); vector<int> a(m), b(m); forn(i, m) { cin >> a[i] >> b[i]; a[i]--, b[i]--; g[a[i]].push_back(b[i]); g[b[i]].push_back(a[i]); } queue<int> q; q.push(0); vector<int> d(n, INT_MAX); d[0] = 0; while (!q.empty()) { int u = q.front(); q.pop()...
1006
A
Adjacent Replacements
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: - Replace each occur...
It is easy to see that for the odd elements there is no changes after applying the algorithm described in the problem statement, and for the even elements there is only one change: each of the even elements will be decreased by $1$. So we can iterate over all the elements of the array and print $a_i - (a_i \% 2)$, wher...
[ "implementation" ]
800
#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; for (int i = 0; i < n; ++i) { int x; cin >> x; cout << x - !(x & 1) << " "; } return 0; }