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
1130
C
Connect
Alice lives on a flat planet that can be modeled as a square grid of size $n \times n$, with rows and columns enumerated from $1$ to $n$. We represent the cell at the intersection of row $r$ and column $c$ with ordered pair $(r, c)$. Each cell in the grid is either land or water. \begin{center} {\small An example plan...
Let $S$ be the set of cells accessible from $(r_1, c_1)$. Similarly, let $T$ be the set of cells accessible from $(r_2, c_2)$. We can find $S$ and $T$ using a search algorithm such as a DFS or a BFS. If $S = T$, then a tunnel is not needed, so the answer is $0$. Otherwise, we need to create a tunnel with an endpoint in...
[ "brute force", "dfs and similar", "dsu" ]
1,400
null
1131
A
Sea Battle
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of $w_1$ and a height of $h_1$, while the second rectangle has a width of $w_2$ and a height of $h_2$, where $w_1 \ge w_2$. In this game, exactly one ...
Let's classify marked squares to two groups. First group will consist of cells that are neighboring by corner to ship. There are exactly $5$ such corners. Second group will consist of cells that are neighboring by side to ship. Number of such squares is equal to length of perimeter of a ship. Thus answer is equal to $2...
[ "math" ]
800
null
1131
B
Draw!
You still have partial information about the score during the historic football match. You are given a set of pairs $(a_i, b_i)$, indicating that at some point during the match the score was "$a_i$: $b_i$". It is known that if the current score is «$x$:$y$», then after the goal it will change to "$x+1$:$y$" or "$x$:$y+...
Since some scores are already fixed, we only have "liberty" in between of them. One can easily see, that basically we need to solve the problem between each neighboring pair and then sum all the answers (it may turn out, that for a fixed score, it will be accounted twice, in the "left" pair and in the "right", but it's...
[ "greedy", "implementation" ]
1,400
null
1131
C
Birthday
Cowboy Vlad has a birthday today! There are $n$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing...
The solution is greedy one. Suppose we have reordered $a_i$, so that $a_i \le a_{i + 1}$. Then I claim that the answer can be built as follows: First write all elements with even indices and then all elements with odd indices in reversed order. For example, if $n = 5$: we get $a_1, a_3, a_5 \mid a_4, a_2$ and if $n = 6...
[ "binary search", "greedy", "sortings" ]
1,200
null
1131
D
Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the d...
This task has different possible solutions. One of them is as follows - make a DSU for all $n+m$ dishes (Disjoint Set Union data structure, https://en.wikipedia.org/wiki/Disjoint-set_data_structure), and unite all dishes that should be evaluated with the same number according to the table (unite dishes $i$ and $n+j$ if...
[ "dfs and similar", "dp", "dsu", "graphs", "greedy" ]
2,000
null
1131
E
String Multiplication
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings $s$ of length $m...
Let's notice, that the string multiplication is associative, that is $(a \cdot b) \cdot c = a \cdot (b \cdot c)$. So instead of left "$(a \cdot b) \cdot c$" given in statement, let's use "$a \cdot (b \cdot c)$" That is, we have $s_n$, then go to $s_{n-1} \cdot s_n$, then $s_{n - 2} \cdot (s_{n-1} \cdot s_n)$ and so on....
[ "dp", "greedy", "strings" ]
2,300
null
1131
F
Asya And Kittens
Asya loves animals very much. Recently, she purchased $n$ kittens, enumerated them from $1$ and $n$ and then put them into the cage. The cage consists of one row of $n$ cells, enumerated with integers from $1$ to $n$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there...
In this problem we are given a disjoint set union process with $n - 1$ steps, merging $n$ initial 1-element sets into one $n$-element set. We have to put elements into a linear array of cells, so that the cells to be joined at each step of the process were immediate neighbours (i.e. not separated by other cells). This ...
[ "constructive algorithms", "dsu" ]
1,700
null
1131
G
Most Dangerous Shark
Semyon participates in the most prestigious competition of the world ocean for the title of the most dangerous shark. During this competition sharks compete in different subjects: speed swimming, masking, map navigation and many others. Now Semyon is taking part in «destruction» contest. During it, $m$ dominoes are pl...
This problem can be solved using dynamic programming technique. Let $dp_i$ be minimum cost to fall first $i$ dominoes. If $i$-th domino was dropped to the right $dp_i = min(dp_j + c_i)$ over such $j$ that dropped $i$-th domino will fall all dominoes from $j + 1$ to $i$. Otherwise, some other domino was dropped to the r...
[ "data structures", "dp", "two pointers" ]
2,700
null
1132
A
Regular Bracket Sequence
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; ")...
For bracket sequence to be regular, it should have equal number of opening and closing brackets. So, if $cnt_1 \ne cnt_4$, then it's impossible to construct any regular bracket sequence. $cnt_2$ is completely irrelevant to us, since inserting or removing a () substring doesn't change the status of the string we get. Al...
[ "greedy", "implementation" ]
1,100
cnt = [] for i in range(4): cnt.append(int(input())) if(cnt[0] == cnt[3] and (cnt[2] == 0 or cnt[0] > 0)): print(1) else: print(0)
1132
B
Discounts
You came to a local shop and want to buy some chocolate bars. There are $n$ bars in the shop, $i$-th of them costs $a_i$ coins (and you want to buy all of them). You have $m$ different coupons that allow you to buy chocolate bars. $i$-th coupon allows you to buy $q_i$ chocolate bars while you have to pay only for the ...
When using $i$-th coupon, the bar we get for free should have at least $x_i - 1$ bars not cheaper than it. So, if we consider $a$ sorted in non-decreasing order, then we cannot get discount greater than $a_{n - x_i + 1}$. On the other hand, we can always get such a discount if we pick $x_i$ most expensive bars to buy u...
[ "greedy", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; const int N = 300009; int n; int a[N]; long long res[N]; int main() { long long sum = 0; scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d", a + i); sum += a[i]; } sort(a, a + n); memset(res, -1, sizeof res); int m; scanf("%d", &m); for(int i = 0; ...
1132
C
Painting the Fence
You have a long fence which consists of $n$ sections. Unfortunately, it is not painted, so you decided to hire $q$ painters to paint it. $i$-th painter will paint all sections $x$ such that $l_i \le x \le r_i$. Unfortunately, you are on a tight budget, so you may hire only $q - 2$ painters. Obviously, only painters yo...
Let $c_i$ be the number of painters that are painting the $i$-th section. Let's fix the first painter (denote his index as $x$) we won't take and decrease the numbers of array $c$ in the range which he paints. Then we may new array $d$, such that $d_i$ is equal to $1$ if and only if $c_i = 1$, and $0$ otherwise. This a...
[ "brute force" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = 5043; int p1[N]; int p2[N]; int p3[N]; int n, q; int l[N], r[N]; int solve(int idx) { memset(p1, 0, sizeof p1); for(int i = 0; i < q; i++) { if(i == idx) continue; p1[l[i]]++; p1[r[i]]--; } memset(p2, 0, sizeof p2); int c = 0; for(int i = 0; i...
1132
D
Stressful Training
Berland SU holds yet another training contest for its students today. $n$ students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers! Let students be numbered from $1$ to $n$. Laptop of the $i$-th student has charge $a_i$ at the beginning of the contest and it uses $...
The easiest part of the solution is to notice that if the charger of power $x$ works then the charger of power $x + 1$ also works. Thus, binary search is applicable to the problem. $k$ is really small and only one laptop can be charged during some minute. It implies that check function can work in something polynomial ...
[ "binary search", "greedy" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; const long long INF64 = 1e18; int n, k; long long a[N]; int b[N]; long long cur[N]; vector<int> qr[N]; bool check(long long x){ forn(i, k) qr[i].clear(); forn(i, n) cur[i] = a[i]; fo...
1132
E
Knapsack
You have a set of items, each having some integer weight not greater than $8$. You denote that a subset of items is good if total weight of items in the subset does not exceed $W$. You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original...
Let's consider the optimal answer. Suppose we take $c_i$ items of weight $i$. Let $L$ be the least common multiple of all weights (that is $840$). Then we may represent $c_i$ as $c_i = \frac{L}{i} p_i + q_i$, where $0 \le q < \frac{L}{i}$. Let's do the following trick: we will take $q_i$ items of weight $i$, and all th...
[ "dfs and similar", "dp", "greedy" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 9; const int L = 840; typedef long long li; li dp[N][L * N]; li W; li cnt[N]; int main() { cin >> W; for(int i = 0; i < 8; i++) cin >> cnt[i]; for(int i = 0; i < N; i++) for(int j = 0; j < L * N; j++) dp[i][j] = -1; dp[0][0] = 0; for(int i = 0; i <...
1132
F
Clear the String
You are given a string $s$ of length $n$ consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd ...
We will solve the problem by dynamic programming. Let $dp_{l, r}$ be the answer for substring $s_{l, l + 1, \dots, r}$. Then we have two cases: The first letter of the substring is deleted separately from the rest, then $dp_{l, r} = 1 + dp_{l + 1, r}$; The first letter of the substring is deleted alongside with some ot...
[ "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 505; int n; string s; int dp[N][N]; int calc(int l, int r){ int &res = dp[l][r]; if(res != -1) return res; if(l > r) return res = 0; if(l == r) return res = 1; res = 1 + calc(l + 1, r); for(int i = l + 1; i <= r; ++ i) if(s[l] == s[i]) r...
1132
G
Greedy Subsequences
For some array $c$, let's denote a greedy subsequence as a sequence of indices $p_1$, $p_2$, ..., $p_l$ such that $1 \le p_1 < p_2 < \dots < p_l \le |c|$, and for each $i \in [1, l - 1]$, $p_{i + 1}$ is the minimum number such that $p_{i + 1} > p_i$ and $c[p_{i + 1}] > c[p_i]$. You are given an array $a_1, a_2, \dots,...
Let's calculate for each position $i$ position $nxt_i$ - "the closest greater from the right" element to $i$ and add directed edge from $i$ to $nxt_i$. Then we will get oriented forest (or tree if we'd add fictive vertex) where all edges are directed to some root. So, we can look at current subsegment we need to calcul...
[ "data structures", "dp", "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 sz(a) int((a).size()) #define x first #define y second int n, k; vector<int> a; inline bool read() { if(!(cin >> n >> k)) return false; a.assign(n, 0); fore(i, 0, n) cin >> a[i]; return true; } i...
1133
A
Middle of the Contest
Polycarp is going to participate in the contest. It starts at $h_1:m_1$ and ends at $h_2:m_2$. It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is gu...
Firstly, let's parse both strings to four integers ($h_1, m_1, h_2, m_2$). Just read them and then use some standard functions to transform them into integers (or we can do it manually). The second part is to obtain $t_1 = h_1 \cdot 60 + m_1$ and $t_2 = h_2 \cdot 60 + m_2$. Then let t3=t1+t22. It is the answer. We have...
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int h1, m1; scanf("%d:%d", &h1, &m1); int h2, m2; scanf("%d:%d", &h2, &m2); int t1 = h1 * 60 + m1; int t2 = h2 * 60 + m2; int t3 = (t1 + t2) / 2; printf("...
1133
B
Preparation for International Women's Day
International Women's Day is coming soon! Polycarp is preparing for the holiday. There are $n$ candy boxes in the shop for sale. The $i$-th box contains $d_i$ candies. Polycarp wants to prepare the maximum number of gifts for $k$ girls. Each gift will consist of \textbf{exactly two} boxes. The girls should be able to...
Let $cnt_i$ be the number of boxes with $i$ candies modulo $k$. Firstly, the number of pairs of boxes we can obtain using two boxes with remainder $0$ modulo $k$ is $\lfloor\frac{cnt_0}{2}\rfloor$. Secondly, if $k$ is even then we also can obtain pairs of boxes using two boxes with remainder $\frac{k}{2}$ modulo $k$ an...
[ "math", "number theory" ]
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; vector<int> cnt(k); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[x % k]; } int ans = cnt[0] / 2; if (k % 2 == 0) ans...
1133
C
Balanced Team
You are a coach at your local university. There are $n$ students under your supervision, the programming skill of the $i$-th student is $a_i$. You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with th...
Let's sort all values in non-decreasing order. Then we can use two pointers to calculate for each student i the maximum number of students j such that aj-ai \le 5 (j>i). This is pretty standard approach. We also can use binary search to do it (or we can store for each programming skill the number of students with this ...
[ "sortings", "two pointers" ]
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; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.begin(), a.end()); int ans = 0; int j = 0; for (int i = 0; i < n...
1133
D
Zero Quantity Maximization
You are given two arrays $a$ and $b$, each contains $n$ integers. You want to create a new array $c$ as follows: choose some real (i.e. not necessarily integer) number $d$, and then for every $i \in [1, n]$ let $c_i := d \cdot a_i + b_i$. Your goal is to maximize the number of zeroes in array $c$. What is the largest...
For each index i \in [1,n] let's try to find which d we should use in order to make i-th element of c equal to zero. If ai=0, then ci=bi no matter which d we choose. So we should just ignore this index and add 1 to the answer if bi=0. Otherwise, we should choose d=-biai. Let's calculate the required fraction for each i...
[ "hashing", "math", "number theory" ]
1,500
#include<bits/stdc++.h> using namespace std; #define x first #define y second const int N = 200043; void norm(pair<int, int>& p) { if(p.x < 0) { p.x *= -1; p.y *= -1; } else if (p.x == 0 && p.y < 0) { p.y *= -1; } int d = __gcd(abs(p.x), abs(p.y)); p.x /= d; p.y /= d; } map<pair<int, int>, int> m; ...
1133
E
K Balanced Teams
You are a coach at your local university. There are $n$ students under your supervision, the programming skill of the $i$-th student is $a_i$. You have to form $k$ teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your univers...
Firstly, let's sort all students in order of non-decreasing their programming skill. Then let's calculate the following dynamic programming: dpi,j is the maximum number of students in at most j non-empty teams if we consider first i students. How to do transitions from dpi,j? The first transition is pretty intuitive: j...
[ "dp", "sortings", "two pointers" ]
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, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.begin(), a.end()); vector<int> cnt(n); for (int i = 0; i ...
1133
F1
Spanning Tree with Maximum Degree
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find \textbf{any} spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall t...
We can take any vertex with the maximum degree and all its neighbours. To implement it, just run bfs from any vertex with the maximum degree. See the authors solution for better understanding.
[ "graphs" ]
1,600
#include <bits/stdc++.h> using namespace std; int n, m; vector<vector<int>> g; vector<int> deg, used; vector<pair<int, int>> ans; mt19937 rnd(time(NULL)); void bfs(int s) { used = vector<int>(n); used[s] = 1; queue<int> q; q.push(s); while (!q.empty()) { int v = q.front(); q.pop(); for (auto to : g[v])...
1133
F2
Spanning Tree with One Fixed Degree
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find \textbf{any} spanning tree of this graph such that the \textbf{degree of the first vertex (vertex with label $1$ on i...
Firstly, let's remove the vertex 1 from the graph. Then let's calculate the number of connected components. Let it be cnt. The answer is NO if and only if cnt>D or D is greater than the number of edges incident to the first vertex. Otherwise let's construct the answer. Firstly, let's add into the new graph spanning tre...
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; int n, m, D; vector<vector<int>> g; int cnt; vector<int> p, color; vector<pair<int, int>> ans; mt19937 rnd(time(NULL)); void bfs(int s, int bad) { queue<int> q; q.push(s); color[s] = cnt; while (!q.empty()) { int v = q.front(); q.pop(); if (p[v] != -1) { i...
1136
A
Nastya Is Reading a Book
After lessons Nastya decided to read a book. The book contains $n$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page. Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $k$ as th...
It is easy to understand that the first unread chapter is the last chapter, whom $l_i \leq k$. In order to find it we can iterate through list of chapters in increasing order.
[ "implementation" ]
800
"#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\nconst int N = 101;\nint n;\npair <int, int> a[N];\nsigned main() {\n #ifdef HOME\n freopen(\"input.txt\", \"r\", stdin);\n #else\n ios_base::sync_with_stdio(0); cin.tie(0);\n #endif\n cin >> n;\n for (int i = 0; i < n; ...
1136
B
Nastya Is Playing Computer Games
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible. There are $n$ manholes in the room which are situated on one line, but, unfortunately, all the manholes are c...
Note that in any case we will open $n$ hatches. Also, initial position of stones is : $1,1,1,1,1,1 ... 1$ ($1$ - the number of stones on the i-th hatch ).After any permutation of stones we will have permutation of numbers : $2,0,1,1,1,1,1...$ So, to open hatch with $2$ stones, we need at least $2$ movements. So, at all...
[ "constructive algorithms", "math" ]
1,000
"#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\nsigned main() {\n #ifdef HOME\n freopen(\"input.txt\", \"r\", stdin);\n #else\n ios_base::sync_with_stdio(0); cin.tie(0); cout.precision(20);\n #endif\n int n, p;\n cin >> n >> p;\n cout << (2 * n + 1) + (n - 1) + min...
1136
C
Nastya Is Transposing Matrices
Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task. Two matrices $A$ and $B$ are given, each of them has size $n \times m$. Nastya can perform the following operation to matrix $A$ unlimited number of times: - take any square square submatri...
Let's note that after applying the operation multiset of numbers on each diagonal (which goes up and right) stays the same. Also we can get any permutation of numbers on any diagonal because we can swap neighboring elements on diagonal. So, we just need to check if the multisets of numbers on corresponding diagonals ar...
[ "constructive algorithms", "sortings" ]
1,500
"#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n#define int long long\nconst int MAXN = 500;\nint a[MAXN][MAXN];\nint b[MAXN][MAXN];\nvector<int> aa[MAXN * 2];\nvector<int> bb[MAXN * 2];\nsigned main() {\n\tios_base::sync_with_stdio(false);\n\n\tint n, m;\n\tcin >> n >> m;\n\tfor (i...
1136
D
Nastya Is Buying Lunch
At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going...
Solution 1: Let's solve the proiblem, iterating from the end, adding pupils one by one. I. e for every suffix we are solving original problem without pupils, which don't belong to this suffix. What happens when we add pupil $i$ to the suffix? By the time when we add pupil $i$ we have answer for the previous suffix. In ...
[ "greedy" ]
1,800
"#include <bits/stdc++.h>\n//#pragma comment(linker, \u201d/STACK:36777216\u201c)\n \nusing namespace std;\n \ntypedef long long ll;\n#define mp make_pair\n#define pb push_back\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define db long double\n\nint n, m;\nvector<int> a, ...
1136
E
Nastya Hasn't Written a Legend
In this task, Nastya asked us to write a formal statement. An array $a$ of length $n$ and an array $k$ of length $n-1$ are given. Two types of queries should be processed: - increase $a_i$ by $x$. Then if $a_{i+1} < a_i + k_i$, $a_{i+1}$ becomes exactly $a_i + k_i$; again, if $a_{i+2} < a_{i+1} + k_{i+1}$, $a_{i+2}$ ...
Let $t_{i} = k_{1} + k_{2} + ... + k_{i - 1}$, $b_{i} = a_{i} - t_{i}$. We can rewrite the condition $a_{i+1} >= a_{i} + k_{i}$, using array $b$: $a_{i+1} >= a_{i} + k_{i}$ $a_{i+1} - k_{i} >= a_{i}$ $a_{i+1} - k_{i} - k_{i-1} - ... - k_{1} >= a_{i} - k_{i-1} - ... - k_{1}$ $a_{i+1} - t_{i+1} >= a_{i} - t_{i}$ $b_{i+1}...
[ "binary search", "data structures" ]
2,200
"/*\n\nCode for problem E by cookiedoth\nGenerated 23 Feb 2019 at 02.32 P\n\n\n\u2585\u2588\u2588\u2588\u2588\u2588\u2588\u2588 ]\u2584\u2584\u2584\u2584\u2584\u2584\u2584 \n\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2585\u2584\u2583 \nIl\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2...
1137
A
Skyscrapers
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $n$ streets along the Eastern direction and $m$ streets across the Southern direction. Naturally, this city has $nm$ intersections. At any intersection of $i$-th Eastern street and $j$-th Southern street there is ...
Let's examine the $i$-th row and $j$-th column, suppose the element on their intersection is $x$ Let's denote the number of different elements less than $x$ in the row as $L_{row}$, and in the column as $L_{col}$. Similarly, let's say that the number of different elements greater than $x$ in row is $G_{row}$ and in col...
[ "implementation", "sortings" ]
1,600
null
1137
B
Camp Schedule
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $s$, which can be represented as a binary string, in which the $i$-th ...
If we can't make any occurrences of string $t$ in string $s$ just output any permutation of $s$. Otherwise, we can show that there is an optimal answer $x$, such that it starts with a string $t$. Suppose the opposite, then remove all characters of the string $s$ before the first occurrence of the string $t$ and insert ...
[ "greedy", "hashing", "strings" ]
1,600
null
1137
C
Museums Tour
In the country $N$, there are $n$ cities connected by $m$ one-way roads. Although this country seems unremarkable, there are two interesting facts about it. At first, a week lasts $d$ days here. At second, there is exactly one museum in each city of the country $N$. Travel agency "Open museums" is developing a new pro...
Let's build a graph where the vertices are ($u$, $t$) where u is the node for original graph and $t$ is a day modulo $d$ (days are indexed from $0$ to $d - 1$). Then connect ($u$, $t$) to ($v$, $(t + 1)\,mod\,d$) for all edges $(u, v)$ from original graph and find the strongly connected components of this graph. For ea...
[ "dp", "graphs", "implementation" ]
2,500
null
1137
D
Cooperative Game
This is an interactive problem. Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake". Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is ...
The count of friends you have in the problem was actually a misleading. Here is how to solve this problem with only three of them. Let's name them $fast$, $slow$, $lazy$, and then consider the following process: $fast$ and $slow$ moves forward, then $fast$ only, then $fast$ and $slow$ again and so on until at some mome...
[ "constructive algorithms", "interactive", "number theory" ]
2,400
null
1137
E
Train Car Selection
Vasya likes to travel by train, but doesn't like when the car he travels in is located in the tail of the train. Vasya gets on the train at the station. The train consists of $n$ cars indexed from $1$ to $n$ counting from the locomotive (head of the train). Three types of events occur while the train is moving: - Som...
There are many approaches to this problem, many of them having $\mathcal{O}(q \log q)$ time, but we will describe a purely linear solution. First, notice that for every group of cars added together, we need only to care about the first car in this group - the remaining ones will never be the answer. Second, notice that...
[ "data structures", "greedy" ]
2,700
null
1137
F
Matches Are Not a Child's Play
Lena is playing with matches. The natural question arising in the head of any child playing with matches is whether it's possible to set a tree on fire with a matches, or not. Let's say, that the tree is a connected graph without cycles and the vertices are labeled with integers $1, 2, \ldots, n$. Also every vertex $v...
First, let's notice, that operation "compare" is redundant and can be implemented as two "when" operations (we didn't removed it from onsite olympiad's version as a possible hint). Suppose we know the order of the burning vertices. How it will change after "up" operation? Actually, quite simply: let's notice, that the ...
[ "data structures", "trees" ]
3,400
null
1138
A
Sushi for Two
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $n$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $i$-th fr...
It is more or less obvious that the answer is the maximum among the minimums of the length of two consecutive segments of equal elements. As for implementation, just go from left to right and keep the last element, the length of the current segment and the length of the next segment. When the current element is not the...
[ "binary search", "greedy", "implementation" ]
900
null
1138
B
Circus
Polycarp is a head of a circus troupe. There are $n$ — an even number — artists in the troupe. It is known whether the $i$-th artist can perform as a clown (if yes, then $c_i = 1$, otherwise $c_i = 0$), and whether they can perform as an acrobat (if yes, then $a_i = 1$, otherwise $a_i = 0$). Split the artists into two...
Note, that there are only four types of artists: <<0; 0>>, <<0; 1>>, <<1; 0>>, <<1; 1>>. So the whole problem can be described with four integers - the number of artists of each type. Let's say, that there are $n_a$ <<0; 0>> artists, $n_b$ <<0; 1>> artists, $n_c$ <<1; 0>> artists, $n_d$ <<1, 1>> artists. In the same ma...
[ "brute force", "greedy", "math", "strings" ]
1,800
null
1139
A
Even Substrings
You are given a string $s=s_1s_2\dots s_n$ of length $n$, which only contains digits $1$, $2$, ..., $9$. A substring $s[l \dots r]$ of $s$ is a string $s_l s_{l + 1} s_{l + 2} \ldots s_r$. A substring $s[l \dots r]$ of $s$ is called even if the number represented by it is even. Find the number of even substrings of $...
Any substring ending in $2, 4, 6, 8$ forms an even substring. Thus, iterate over all positions $i$ of the string $s$, and if the digit represented by character at $i_{th}$ index is even, then add $i+1$ to the answer, since all the substrings starting at $0, 1, ..., i$ and ending at $i$ are even substrings. Overall Comp...
[ "implementation", "strings" ]
800
import java.util.*; public class SolutionA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); char[] s = sc.next().toCharArray(); int ans = 0; for(int i = 0; i < n; ++i) { if((s[i] - '0') % 2 == 0) ans += (i + 1); } System.out.print(ans); ...
1139
B
Chocolates
You went to the store, selling $n$ types of chocolates. There are $a_i$ chocolates of type $i$ in stock. You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $x_i$ chocolates of type $i$ (clearly, $0 \le x_i \le a_i$), then for a...
It is optimal to proceed greedily from the back of the array. If we have taken $x$ candies of the $i+1$ type, then we can only take $\min(x - 1, A_i)$ candies for type $i$. If this value is less than zero, we take $0$ from here. Overall Complexity: $O(n)$
[ "greedy", "implementation" ]
1,000
import java.util.*; import static java.lang.Math.*; public class SolutionB { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long a[] = new long[n]; for(int i = 0; i < n; ++i) a[i] = sc.nextLong(); long ans = 0; long curV = 1000000001; for(int ...
1139
C
Edgy Trees
You are given a tree (a connected undirected graph without cycles) of $n$ vertices. Each of the $n - 1$ edges of the tree is colored in either black or red. You are also given an integer $k$. Consider sequences of $k$ vertices. Let's call a sequence $[a_1, a_2, \ldots, a_k]$ good if it satisfies the following criterio...
Let's find the number of bad sequences - Sequences of length $k$ that do not pass through any black edges. Then answer is all possible sequences minus the number of bad sequences. Thus, we can remove black edges from the tree. Now the tree would be split into connected components. For every connected component, if we s...
[ "dfs and similar", "dsu", "graphs", "math", "trees" ]
1,500
import java.util.*; import static java.lang.Math.*; public class SolutionC { static void dfs(int i) { vis[i] = 1; cnt++; for(int j : adj[i]) { if(vis[j] == 0) dfs(j); } } static long fast_pow(long a, long b) { if(b == 0) return 1L; long val = fast_pow(a, b / 2); if(b % 2 == 0) re...
1139
D
Steps to One
Vivek initially has an empty array $a$ and some integer constant $m$. He performs the following algorithm: - Select a random integer $x$ uniformly in range from $1$ to $m$ and append it to the end of $a$. - Compute the greatest common divisor of integers in $a$. - In case it equals to $1$, break - Otherwise, return t...
Let $dp[x]$ be the expected number of additional steps to get a gcd of 1 if the gcd of the current array is $x$. Suppose the current gcd of the array $a$ is $x$, after the next iteration of the algorithm, we would append some randomly chosen $j$ with a probability $\frac{1}{m}$, and move to state $gcd(x,j)$ and since t...
[ "dp", "math", "number theory", "probabilities" ]
2,300
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; const int MOD = 1e9 + 7; int pow(int a, int b, int m) { int ans=1; while(b) { if(b&1) ans=(ans*a)%m; b/=2; a=(a*a)%m; } return an...
1139
E
Maximize Mex
There are $n$ students and $m$ clubs in a college. The clubs are numbered from $1$ to $m$. Each student has a potential $p_i$ and is a member of the club with index $c_i$. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next $d$ days. There is a c...
Let's reverse the queries so that instead of removal of edges we need to work with the addition of edges. Now consider a bipartite graph with values $0 \ldots m$ on the left side and clubs $1 \ldots m$ on the right side. For an ind $i$, which has not been removed, we add an edge from $p_i$ on the left to $c_i$ on the r...
[ "flows", "graph matchings", "graphs" ]
2,400
import java.util.*; import static java.lang.Math.*; public class SolutionE { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int deg[] = new int[m]; int p[] = new int[n]; for(int i = 0; i ...
1139
F
Dish Shopping
There are $m$ people living in a city. There are $n$ dishes sold in the city. Each dish $i$ has a price $p_i$, a standard $s_i$ and a beauty $b_i$. Each person $j$ has an income of $inc_j$ and a preferred beauty $pref_j$. A person would never buy a dish whose standard is less than the person's income. Also, a person c...
Let's consider a matrix where $i$-th row represents price $i$ and $j$-th column represents beauty $j$, such that the value of $c[i][j]$ represents the number of dishes that can be bought by a person having income $i$ and preferred beauty $j$. Then, adding a dish with price $p$, standard $s$ and beauty $b$ is similar to...
[ "data structures", "divide and conquer" ]
2,500
import java.util.*; import static java.lang.Math.*; public class SolutionF { static int queryBit(int[] bit, int ind) { int ans = 0; while(ind > 0) { ans += bit[ind]; ind -= Integer.lowestOneBit(ind); } return ans; } static void updateBit(int[] bit, i...
1140
A
Detective Book
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $i$-th page contains some mystery that will be explained on page $a_i$ ($a_i \ge i$). Ivan wants to read the whole book. Each day, he reads the first page ...
Solution is just some implementation: simulate algorithm given in the legend, maintaining maximum over all $a_i$ on prefix and breaking when the maximum becomes smaller than index of the next page.
[ "implementation" ]
1,000
#include<bits/stdc++.h> using namespace std; int n; vector<int> a; inline bool read() { if(!(cin >> n)) return false; a.resize(n); for(int i = 0; i < n; i++) { cin >> a[i]; a[i]--; } return true; } inline void solve() { int cnt = 0, pos = 0; while(pos < n) { cnt++; int mx = pos; while(pos < n && p...
1140
B
Good String
You have a string $s$ of length $n$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was t...
A string is good when either its first character is > or the last is <. Strings of type < $\dots$ > are not good, as their first and last characters will never change and they will eventually come to the form < >. So, the answer is the minimum number of characters from the beginning of the string, which must be removed...
[ "implementation", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; int t, n; string s; int main(){ cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> n >> s; int res = n - 1; for(int i = 0; i < n; ++i) if(s[i] == '>' || s[n - 1 - i] == '<') res = min(res, i); cout << res << endl; } return 0; }
1140
C
Playlist
You have a playlist consisting of $n$ songs. The $i$-th song is characterized by two numbers $t_i$ and $b_i$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of list...
If we fix a song with minimum beauty in the answer, then we need to take the remaining $k - 1$ songs (or less) among those having beauty greater than or equal to the beauty of the fixed song - and the longer they are, the better. So, we will iterate on the songs in the order of decreasing their beauty, and for the curr...
[ "brute force", "data structures", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 300009; int n, k; pair<int, int> a[N]; int main() { cin >> n >> k; for(int i = 0; i < n; ++i) cin >> a[i].second >> a[i].first; sort(a, a + n); long long res = 0; long long sum = 0; set<pair<int, int> > s; for(int i = n - 1; i >= 0; --i){ s.i...
1140
D
Minimum Triangulation
You are given a regular polygon with $n$ vertices labeled from $1$ to $n$ in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and th...
You can use straightforward way and calculate answer with "l-r-dp" with $O(n^3)$. But there is a easier claim: it's optimal to split $n$-gon with diagonals coming from $1$, so answer is $\sum\limits_{i = 2}^{n - 1}{i \cdot (i + 1)}$. Proof: let's look at the triange which contains edge $1-n$. Let's name it $1-n-x$. If ...
[ "dp", "greedy", "math" ]
1,200
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long long ans = 0; for(int id = 2; id < n; id++) ans += 1ll * id * (id + 1); cout << ans << endl; }
1140
E
Palindrome-less Arrays
Let's denote that some array $b$ is bad if it contains a subarray $b_l, b_{l+1}, \dots, b_{r}$ of odd length more than $1$ ($l < r$ and $r - l + 1$ is odd) such that $\forall i \in \{0, 1, \dots, r - l\}$ $b_{l + i} = b_{r - i}$. If an array is not bad, it is \textbf{good}. Now you are given an array $a_1, a_2, \dots...
At first, "array contains a palindromic subarray of length $\ge 3$" is equivalent to "array contains a palindromic subarray of length $=3$". So we need to calculate number of arrays without palindromes of length $3$. It's equivalent to finding arrays where $a[i] \neq a[i + 2]$ for all appropriate $i$. Note, that $i$ an...
[ "combinatorics", "divide and conquer", "dp" ]
2,200
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int MOD = 998244353; int norm(int a) { while(a >= MOD) a -= MOD; while(a < 0) a += MO...
1140
F
Extending Set of Points
For a given set of two-dimensional points $S$, let's denote its extension $E(S)$ as the result of the following algorithm: Create another set of two-dimensional points $R$, which is initially equal to $S$. Then, while there exist four numbers $x_1$, $y_1$, $x_2$ and $y_2$ such that $(x_1, y_1) \in R$, $(x_1, y_2) \in ...
Let's try to analyze how the size of $E(S)$ can be calculated. Let's connect points having same $x$-coordinates to each other, and do the same for points having same $y$-coordinates. Then we can solve the problem for each component separatedly: after the algorithm is run, the component will contain the points $(X, Y)$ ...
[ "data structures", "divide and conquer", "dsu" ]
2,600
#include <bits/stdc++.h> using namespace std; typedef long long li; #define x first #define y second const int N = 300043; const int K = 300000; int p[2 * N]; int s1[2 * N]; int s2[2 * N]; li ans = 0; int* where[80 * N]; int val[80 * N]; int cur = 0; void change(int& x, int y) { where[cur] = &x; val[cur] = x; ...
1140
G
Double Tree
You are given a special undirected graph. It consists of $2n$ vertices numbered from $1$ to $2n$. The following properties hold for the graph: - there are exactly $3n-2$ edges in the graph: $n$ edges connect vertices having odd numbers with vertices having even numbers, $n - 1$ edges connect vertices having odd number...
Suppose we want to minimize the number of traversed edges of the second type (edges that connect odd vertices to each other or even vertices to each other), and minimizing the length of the path has lower priority. Then we exactly know the number of edges of the second type we will use to get from one vertex to another...
[ "data structures", "divide and conquer", "shortest paths", "trees" ]
2,700
#include <bits/stdc++.h> using namespace std; typedef long long li; #define x first #define y second const int N = 600043; li d1[N]; li d2[N][2]; li dist_temp[N][2]; vector<pair<int, int> > g[N]; vector<int> qs[N]; int qq[N][2]; li ans[N]; int n; int used[N]; int cnt[N]; int last[N]; int cc = 1; void preprocess()...
1141
A
Game 23
Polycarp plays "Game 23". Initially he has a number $n$ and his goal is to transform it to $m$. In one move, he can multiply $n$ by $2$ or multiply $n$ by $3$. He can perform any number of moves. Print the number of moves needed to transform $n$ to $m$. Print -1 if it is impossible to do so. It is easy to prove that ...
If $m$ is not divisible by $n$ then just print -1 and stop the program. Otherwise, calculate $d=m/n$, denoting the required number of times to multiply $n$. It is easy to see that $d$ should be a product of zero or more $2$'s and of zero or more $3$'s, i.e. $d=2^x3^y$ for integers $x,y \ge 0$. To find $x$ just use a lo...
[ "implementation", "math" ]
1,000
int n, m; cin >> n >> m; int result = -1; if (m % n == 0) { result = 0; int d = m / n; while (d % 2 == 0) d /= 2, result++; while (d % 3 == 0) d /= 3, result++; if (d != 1) result = -1; } cout << result << endl;
1141
B
Maximal Continuous Rest
Each day in Berland consists of $n$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $a_1, a_2, \dots, a_n$ (each $a_i$ is either $0$ or $1$), where $a_i=0$ if Polycarp works during the $i$-th hour of the day and $a_i=1$ if Polycarp rests during the $i$-th hour o...
At first consider we process the only day. In this case just iterate over hours and maintain $len$ - the length of the current rest block (i.e. if the element equals $1$ then increase $len$, if the element equals $0$ then reset $len$ to $0$). The maximum intermediate value of $len$ is the answer. In case of multiple da...
[ "implementation" ]
900
int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; int result = 0; int len = 0; for (int i = 0; i < 2 * n; i++) { if (a[i % n] == 1) { len++; result = max(result, len); } else { len = 0; } } cout << result << endl;
1141
C
Polycarp Restores Permutation
An array of integers $p_1, p_2, \dots, p_n$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3, 1, 2]$, $[1]$, $[1, 2, 3, 4, 5]$ and $[4, 3, 1, 2]$. The following arrays are not permutations: $[2]$, $[1, 1]$, $[2, 3, 4]$. Polycarp in...
Let's $p[1]=x$. Thus, $p[2]=p[1]+(p[2]-p[1])$=$x+q[1]$, $p[3]=p[1]+(p[2]-p[1])+(p[3]-p[2])$=$x+q[1]+q[2]$, ..., $p[n]=p[1]+(p[2]-p[1])+(p[3]-p[2])+\dots+(p[n]-p[n-1])$=$x+q[1]+q[2]+\dots+q[n-1]$. It means that the sequence of $n$ partial sums $p'=[0, q[1], q[1]+q[2], \dots, q[1]+q[2]+\dots+q[n-1]]$ is the required perm...
[ "math" ]
1,500
int n; cin >> n; vector<int> q(n - 1); long long sum = 0; long long min_val = 0; for (int i = 0; i + 1 < n; i++) { cin >> q[i]; sum += q[i]; if (sum < min_val) min_val = sum; } vector<long long> p(n); p[0] = 1 - min_val; forn(i, n - 1) p[i + 1] = p[i] + q[i]; bool ok = true; for (int i = 0; i < ...
1141
D
Colored Boots
There are $n$ left boots and $n$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $l$ and $r$, both of length $n$. The character $l_i$ stands for the color of the $i$-th left boot and the character $r_i$ stands for the color of the...
Use greedy approach in this problem. At first, match such pairs that colors are exactly the same (and they are specific, not indefinite). After it match each indefinite colored left boot (if any) with any specific colored right boot. Possibly, some indefinite colored left boots stay unmatched. Similarly, match each ind...
[ "greedy", "implementation" ]
1,500
#define forn(i, n) for (int i = 0; i < int(n); i++) const int A = 26; ... int n; cin >> n; string l; cin >> l; vector<vector<int>> left(A); vector<int> wl; forn(i, n) if (l[i] != '?') left[l[i] - 'a'].push_back(i); else wl.push_back(i); string r; cin >> r; vector<vector<int>> right(A); vector<in...
1141
E
Superhero Battle
A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $n$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again. Each round has the same scenario. It is described by a sequence of $n$ numbers: $d_1, d_2, \dots, d_n$ ($-10^6 \le d_i ...
In general the answer looks like: some number of complete (full) round cycles plus some prefix the the round. Check corner case that there are no complete (full) rounds at all (just check the first round in naive way). If no solution found, the answer has at least one complete (full) cycle and some prefix. If total sum...
[ "math" ]
1,700
long long H; int n; cin >> H >> n; vector<long long> a(n); long long sum = 0; long long gap = 0; long long h = H; for (int i = 0; i < n; i++) { cin >> a[i]; sum -= a[i]; h += a[i]; if (h <= 0) { cout << i + 1 << endl; return 0; } gap = max(gap, sum); } if (sum <= 0) { cout <<...
1141
F2
Same Sum Blocks (Hard)
This problem is given in two editions, which differ exclusively in the constraints on the number $n$. You are given an array of integers $a[1], a[2], \dots, a[n].$ A block is a sequence of contiguous (consecutive) elements $a[l], a[l+1], \dots, a[r]$ ($1 \le l \le r \le n$). Thus, a block is defined by a pair of indic...
Let's $x$ the same sum of blocks in the answer. Obviously, $x$ can be represented as a sum of some adjacent elements of $a$, i.e. $x=a[l]+a[l+1]+\dots+a[r]$ for some $l$ and $r$. Iterate over all possible blocks in $O(n^2)$ and for each sum store all the blocks. You can use 'map<int, vector<pair<int,int>>>' to store bl...
[ "data structures", "greedy" ]
1,900
int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; map<int, vector<pair<int,int>>> segs; for (int r = 0; r < n; r++) { int sum = 0; for (int l = r; l >= 0; l--) { sum += a[l]; segs[sum].push_back({l, r}); } } int result = 0; vector<p...
1141
G
Privatization of Roads in Treeland
Treeland consists of $n$ cities and $n-1$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree. There are some private road companies in Treeland. The government decided to sell roads ...
Formally, the problem is to paint tree edges in minimal number of colors in such a way, the the number of improper vertices doesn't exceed $k$. A vertex is improper if it has at least two incident edges of the same color. It is easy to show that $D$ colors is always enough to paint a tree in such a way that all the ver...
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
1,900
int n, k, r; vector<vector<pair<int,int>>> g; int D; vector<int> col; void dfs(int u, int p, int f) { int color = 0; for (auto e: g[u]) if (p != e.first) { if (color == f) { color = (color + 1) % D; f = -1; } col[e.second] = color; ...
1142
A
The Beatles
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through $n \cdot k$ cities. The cities are numerated from $1$ to $n \cdot k$, the distance between the neighboring cities is exactly $1$ km. Sergey does not like beetles, he loves burgers. Fortunately for him, there are $n$ fast f...
Let's assume that we know the length of the jump, and it is equal to $l$. Then, in order to be back at the starting point, Sergey will need to make exactly $n \cdot k / gcd(n \cdot k, l)$ moves, where $gcd$ is the greatest common divider. Let $l = kx + c$, where $c$ and $x$ are non-negative integers. So, if we know $a$...
[ "brute force", "math" ]
1,700
null
1142
B
Lynyrd Skynyrd
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $p$ of length $n$, and Skynyrd bought an array $a$ of length $m$, consisting of integers from $1$ to $n$. Lynyrd and Skynyrd became bored, so they asked you $q$ queries, each of which has the following form: "does the subsegment of $a$ from t...
For each $a_i$ if the number $a_i$ has position $j$ in $p$, let's find the greatest $l$, such that $l$ is less then $i$ and $a_l = p_{j - 1}$ (let's define $p_0 = p_n$) We will call this position $b_i$. This can be done in $O(n)$ time, just for each $p_j$ we will keep the last it's position in $a$ while iterating over ...
[ "data structures", "dfs and similar", "dp", "math", "trees" ]
2,000
null
1142
C
U2
Recently Vasya learned that, given two points with different $x$ coordinates, you can draw through them exactly one parabola with equation of type $y = x^2 + bx + c$, where $b$ and $c$ are reals. Let's call such a parabola an $U$-shaped one. Vasya drew several distinct points with integer coordinates on a plane and th...
Let's rewrite parabola equation $y = x^2 + bx + c$ as $y - x^2 = bx + c$. This means, that if you change each point $(x_i, y_i)$ to $(x_i, y_i - x_i^2)$, then the parabolas will turn into straight lines, and the task will be reduced to constructing a top part of convex hull on the obtained points and calculate the numb...
[ "geometry" ]
2,400
null
1142
D
Foreigner
Traveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner. You define inadequate numbers as follows: - all integers from $1$ to $9$ are inadequate; - for an integer $x \ge 10$ to be inadequate, it is required that the integer $\lfloor x / 10 \rfloor$...
Let's take any inadequate number $x$ of length $n$. Let's keep 3 parameters for it: $a_x$ which is the number of all inadequate numbers less of equal then $x$, $b_x$ which is the number of inadequate numbers less then $x$ which have length $n$ and $c_x$ which is the number of inadequate numbers grater then $x$ which ha...
[ "dp" ]
2,800
null
1142
E
Pink Floyd
This is an interactive task. Scientists are about to invent a new optimization for the Floyd-Warshall algorithm, which will allow it to work in linear time. There is only one part of the optimization still unfinished. It is well known that the Floyd-Warshall algorithm takes a graph with $n$ nodes and exactly one edge...
First let's assume that graph has only the green edges and we still don't know their directions. Then we can do the following. We will keep some node which we will call the "top node" and the list of the nodes, that can be reached from the top node. Let's take some node $A$ which is not reachable and ask about the dire...
[ "graphs", "interactive" ]
3,200
null
1143
A
The Doors
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house. There are ex...
Let's walk through the array and find for each exit the door, that was opened last. Then the answer is minimum of the numbers of these doors.
[ "implementation" ]
800
null
1143
B
Nirvana
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper. Help Kurt find the maximum possible product of digits among all integers from $1$ to $n$.
Let number $x$ be an answer, and $\overline{y_0 y_1 \ldots y_l}$ - number from input, so $x$ = $\overline{y_0 y_1 \ldots y_k (y_{k + 1} - 1) 9 9 \ldots 9}$ for some $k$ (otherwise, you can increase one of the digits by $1$, so that $x$ will still be no more than $y$). So, let's go through $k$ from $0$ to the length of ...
[ "brute force", "math", "number theory" ]
1,200
null
1143
C
Queen
You are given a rooted tree with vertices numerated from $1$ to $n$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex $i$ are all vertices on the path from the root to the vertex $i$, except the vertex $i$ itself. The parent of the vertex $i$ is the nea...
From the condition about the fact that each vertex equally respects all its ancestors, we can understand that each vertex is either always a candidate for deletion or it can never be deleted. That is because when we delete some vertex all new vertices which become sons of it's parent are also disrespecting it. Now we c...
[ "dfs and similar", "trees" ]
1,400
null
1144
A
Diverse Strings
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are \textbf{not} diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and ...
The string is diverse if it is a permutation of some substring of the Latin alphabet ("abcd ... xyz"). In other words, the string is diverse if all letters in it are distinct (we can check it using some structure like std::set or array of used elements) and if the number of letters between the letter with the maximum a...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int n; cin >> n; forn(i, n) { string s; cin >> s; if (set<char>(s.begin(), s.end()).size() == s.length() && *max_element(s.begin(), s.end()) == char(*min_...
1144
B
Parity Alternated Deletions
Polycarp has an array $a$ consisting of $n$ integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $n-1$ elements). For each of the next moves he chooses any element with the only restrictio...
Let's calculate the sum of the whole array $sum$ and then divide all its elements into two arrays $odd$ and $even$ by their parity ($odd$ for odd, $even$ for even). Sort both of them in non-increasing order. Then what can we see? We always can delete first $k = min(|odd|, |even|)$ elements from both arrays (where $|x|$...
[ "greedy", "implementation", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; int sum = 0; vector<int> even, odd; for (int i = 0; i < n; ++i) { int x; cin >> x; sum += x; if (x & 1) odd.push_back(x); else eve...
1144
C
Two Shuffled Sequences
Two integer sequences existed initially — one of them was \textbf{strictly} increasing, and the other one — \textbf{strictly} decreasing. Strictly increasing sequence is a sequence of integers $[x_1 < x_2 < \dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \dots > y_l]$. Note that...
Let's count the number of occurrences of each element in the array $cnt$. Because the maximum possible element is $2 \cdot 10^5$, it can be done without any data structures. Then let's check if $cnt_i$ is greater than $2$ for some $i$ from $0$ to $2 \cdot 10^5$, and if it is, then the answer is "NO", because this eleme...
[ "constructive algorithms", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> cnt(200 * 1000 + 1); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[x]; if (cnt[x] > 2) { cout << "NO" << endl; ...
1144
D
Equalize Them All
You are given an array $a$ consisting of $n$ integers. You can perform the following operations arbitrary number of times (possibly, zero): - Choose a pair of indices $(i, j)$ such that $|i-j|=1$ (indices $i$ and $j$ are adjacent) and set $a_i := a_i + |a_i - a_j|$; - Choose a pair of indices $(i, j)$ such that $|i-j|...
Let's find the most frequent element in the array (using the array of frequencies $cnt$, of course). Let this element be $x$. If we will see the operations more carefully, we can see that the part of these operations means "set element $p$ to element $q$". if $p < q$ then this operation is $1 p q$, otherwise it is $2 p...
[ "constructive algorithms", "greedy" ]
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 n; cin >> n; vector<int> a(n), cnt(200 * 1000 + 1); for (int i = 0; i < n; ++i) { cin >> a[i]; ++cnt[a[i]]; } int val = max_element(cnt.begin(),...
1144
E
Median String
You are given two strings $s$ and $t$, both consisting of exactly $k$ lowercase Latin letters, $s$ is lexicographically less than $t$. Let's consider list of all strings consisting of exactly $k$ lowercase Latin letters, lexicographically not less than $s$ and not greater than $t$ (including $s$ and $t$) in lexicograp...
This problem supposed to be easy long arithmetic problem. Let's represent our strings as huge numbers with base $26$. Let $s$ be $l$ and $t$ be $r$. So if we will see more precisely in the problem statement, then we can see that the answer is $\frac{l + r}{2}$. The operation $l + r$ with long numbers can be done in $O(...
[ "bitmasks", "math", "number theory", "strings" ]
1,900
#include <bits/stdc++.h> using namespace std; vector<int> get(const string &s) { vector<int> res(s.size() + 1); for (int i = 0; i < int(s.size()); ++i) { res[i + 1] = s[i] - 'a'; } return res; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int k...
1144
F
Graph Without Long Directed Paths
You are given a connected undirected graph consisting of $n$ vertices and $m$ edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the ...
What if the given graph will contain a cycle of odd length? It will mean that some two consecutive edges of this cycle will be oriented in the same way and will form a path of length two. What if there is no cycles of odd length in this graph? Then it is bipartite. Let's color it and see what we got. We got some vertic...
[ "dfs and similar", "graphs" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 11; int n, m; vector<int> g[N]; vector<pair<int, int>> e; bool bipartite; vector<int> color; void dfs(int v, int c) { color[v] = c; for (auto to : g[v]) { if (color[to] == -1) { dfs(to, c ^ 1); } else { if (color[to] == color[v]) ...
1144
G
Two Merged Sequences
Two integer sequences existed initially, one of them was \textbf{strictly} increasing, and another one — \textbf{strictly} decreasing. Strictly increasing sequence is a sequence of integers $[x_1 < x_2 < \dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \dots > y_l]$. Note that th...
I know about greedy solutions and other approaches, but I'll describe my solution. This is dynamic programming. I'll consider all positions $0$-indexed. Let $dp_{i, 0}$ be the maximum possible minimal element in the decreasing sequence, if the last element ($i-1$-th) was in the increasing sequence, and $dp_{i, 1}$ be t...
[ "dp", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<vector<int>> dp(n, vector<int>({-INF, INF})...
1146
A
Love "A"
Alice has a string $s$. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not. Alice can erase some characters from her string $s$. She would like to kno...
In this problem, it is only ever optimal to erase characters that are not "a". Let $x$ be the number of "a" characters in the string $s$, and let $n$ be the total number of characters in $s$. In order for the $a$s to be a strict majority, we can have at most $x-1$ characters that are not "a", so the maximum string leng...
[ "implementation", "strings" ]
800
#include <iostream> #include <algorithm> using namespace std; int main() { string t; cin >> t; cout << min(2*(int)count(t.begin(),t.end(),'a')-1,(int)t.size()); }
1146
B
Hate "A"
Bob has a string $s$ consisting of lowercase English letters. He defines $s'$ to be the string after removing all "a" characters from $s$ (keeping all other characters in the same order). He then generates a new string $t$ by concatenating $s$ and $s'$. In other words, $t=s+s'$ (look at notes for an example). You are ...
There are a few different ways to approach this. In one way, we can approach it by looking at the frequency of all characters. We want to find a split point so that all "a"s lie on the left side of the split, and all other characters are split evenly between the left and right side. This split can be uniquely determine...
[ "implementation", "strings" ]
1,100
#include <iostream> using namespace std; int main() { string t; cin >> t; int cnt=0,pos=-1; for (int i=0;i<t.size();i++) { if (t[i]=='a') cnt++; if (2*(i+1)-cnt==t.size()) { pos=i; break; } } if (pos==-1) { cout << "...
1146
C
Tree Diameter
There is a weighted tree with $n$ nodes and $n-1$ edges. The nodes are conveniently labeled from $1$ to $n$. The weights are positive integers at most $100$. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is th...
The standard algorithm for finding the diameter of a tree is to find the farthest distance from node $1$, then find the farthest distance from that node. We can do the same technique in this problem. We use one question to get the farthest distance from node $1$ in the graph. Then, we use binary search to figure out wh...
[ "bitmasks", "graphs", "interactive" ]
1,700
/** * code generated by JHelper * More info: https://github.com/AlexeyDmitriev/JHelper * @author Azat Ismagilov */ #include <fstream> #include <iostream> #include <algorithm> #include <vector> #include <numeric> //#define int long long #define fs first #define sc second #define pb push_back #define ppb pop_ba...
1146
D
Frog Jumping
A frog is initially at position $0$ on the number line. The frog has two positive integers $a$ and $b$. From a position $k$, it can either jump to position $k+a$ or $k-b$. Let $f(x)$ be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval $[0, x]$. The frog doesn't ne...
Split this into $a$ problems. For each $i$ modulo $a$, we want to find the leftmost node that the frog can reach modulo $i$, and what is the smallest $x$ needed to get this. We can do this greedily, starting at $0$, jump to the right until we can jump left $b$, and repeat this until we find a repeated value modulo $a$....
[ "dfs and similar", "math", "number theory" ]
2,100
#include <iostream> #include <algorithm> #include <set> using namespace std; int dist[200005]; long long sum[200005]; long long f(long long x) { return x*(x+1)/2; } int main() { int m,a,b; scanf("%d%d%d",&m,&a,&b); int g=__gcd(a,b),n=min(m,a+b-1); for (int i=0;i<=n;i++) dist[i]=n+1; set<pair...
1146
E
Hot is Cold
You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$. You will perform $q$ operations. In the $i$-th operation, you have a symbol $s_i$ which is either "<" or ">" and a number $x_i$. You make a new array $b$ such that $b_j = -a_j$ if $a_j s_i x_i$ and $b_j = a_j$ otherwise (i.e. if $s_i$ is '>', then all $a...
You can keep track of an array $w_i$ from $i = 0 \ldots 10^5$ which is number from $0$ to $3$. This means 'keep sign', 'flip sign', 'positive', or 'negative', respectively. You can use this to determine the final value. For example, if $a_i = j$, then we look at $w_{|j|}$, and that will help us see what the final answe...
[ "bitmasks", "data structures", "divide and conquer", "implementation" ]
2,400
#include <iostream> #include <vector> using namespace std; #define sh 100000 vector<int> v[200005]; int arr[100005],tree[2][400005],ans[200005],cur=-sh; pair<char,int> qu[100005]; void update(int node,int st,int en,int idx,pair<char,int> val) { if (st==en) { tree[0][node]=0; if ((val.first=='>' ...
1146
F
Leaf Partition
You are given a rooted tree with $n$ nodes, labeled from $1$ to $n$. The tree is rooted at node $1$. The parent of the $i$-th node is $p_i$. A leaf is node with no children. For a given set of leaves $L$, let $f(L)$ denote the smallest connected subgraph that contains all leaves $L$. You would like to partition the le...
We can solve this with tree dp. Here, we extend the partition to include nodes in the $f$ values of the leaf set. The dp state counts the number of partitions of leaves in the subtree rooted at node $i$ subject to some conditions. We keep $3$ values for each node. $dp[i][0]$ will count the number of ways to partition t...
[ "dp", "trees" ]
2,500
/** * code generated by JHelper * More info: https://github.com/AlexeyDmitriev/JHelper * @author Azat Ismagilov */ #include <fstream> #include <iostream> #include <algorithm> #include <vector> #include <numeric> #define int long long #define fs first #define sc second #define pb push_back #define ppb pop_back...
1146
G
Zoning Restrictions
You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$. In each spot, if a house has height $a$, you can gain $a^2...
There are two different solutions. The first is min cut. Let's build the graph as follows: There is a source and sink. The source side represents things that are "true", and sink side represents things that are "false" There are $O(n*h)$ nodes $(i,j)$ for ($1 \leq i \leq n, 0 \leq j \leq h$) where $i$ is a spot and $j$...
[ "dp", "flows", "graphs" ]
2,700
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; im...
1146
H
Satanic Panic
You are given a set of $n$ points in a 2D plane. No three points are collinear. A pentagram is a set of $5$ points $A,B,C,D,E$ that can be arranged as follows. Note the length of the line segments don't matter, only that those particular intersections exist. Count the number of ways to choose $5$ points from the give...
Originally, I only had an $O(n^4)$ solution, but [user:y0105w49] recognized an easy solution with bitsets and helped me find an $O(n^3)$ solution instead. We do this by counting out bad configurations. There are initially $\binom{n}{5}$ tuples of $5$ points, and we want to subtract out bad configurations. There are two...
[ "dp", "geometry" ]
2,900
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <complex> using namespace std; #define FR(i, a, b) for(int i = (a); i < (b); ++i) #define FOR(i, n) FR(i, 0, n) #define MP make_pair #define A first #define B second typedef long long ll; typedef complex<ll> pnt; const int MAXN ...
1147
A
Hide and Seek
Alice and Bob are playing a game on a line with $n$ cells. There are $n$ cells labeled from $1$ through $n$. For each $i$ from $1$ to $n-1$, cells $i$ and $i+1$ are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $x_1, x_2...
Another way to phrase this problem is to count the number of ordered pairs $(p,q)$ that satisfy the following $|p-q| \leq 1$ There exists a number $i$ such that p doesn't appear in $x[0\ldots i]$ and $q$ doesn't appear in $x[i+1\ldots n]$. There are only $O(n)$ pairs that satisfy the first condition, so we can loop ove...
[ "graphs" ]
1,500
/** * code generated by JHelper * More info: https://github.com/AlexeyDmitriev/JHelper * @author Azat Ismagilov */ #include <fstream> #include <iostream> #include <algorithm> #include <vector> #include <numeric> #define int long long #define fs first #define sc second #define pb push_back #define ppb pop_back...
1147
B
Chladni Figure
Inaka has a disc, the circumference of which is $n$ units. The circumference is equally divided by $n$ points numbered clockwise from $1$ to $n$, such that points $i$ and $i + 1$ ($1 \leq i < n$) are adjacent, and so are points $n$ and $1$. There are $m$ straight segments on the disc, the endpoints of which are all am...
Let's brute force the value of $k$ and check if it's possible to rotate the image by $k$ to get the same image. We can do this by iterating through all segments $(a,b)$, and checking that $(a+k,b+k)$ is a segment (the endpoints taken modulo $n$ if needed). This gives an $O(nm)$ solution, however, you can notice that we...
[ "brute force", "strings" ]
1,900
#include <iostream> #include <algorithm> #include <vector> using namespace std; int n,m; vector<pair<int,int> > s; bool test(int k) { if (k==n) return 0; vector<pair<int,int> > cur; for (auto p:s) { p.first=(p.first+k)%n; p.second=(p.second+k)%n; if (p.first>p.second) ...
1147
C
Thanos Nim
Alice and Bob are playing a game with $n$ piles of stones. It is guaranteed that $n$ is an even number. The $i$-th pile has $a_i$ stones. Alice and Bob will play a game alternating turns with Alice going first. On a player's turn, they must choose \textbf{exactly} $\frac{n}{2}$ nonempty piles and independently remove...
The main claim is that if a player is forced to reduce the minimum number of stones over all piles, then they lose. Intuitively, every time a player reduces the minimum, the other player has a move that doesn't reduce the minimum, and if a player isn't forced to reduce the minimum, they have a move that will force the ...
[ "games" ]
2,000
#include <iostream> using namespace std; int main() { int n,mn=1e9,cnt; scanf("%d",&n); for (int i=0;i<n;i++) { int a; scanf("%d",&a); if (a<mn) { mn=a; cnt=0; } if (a==mn) cnt++; } if (cnt>n/2) printf("Bob"); ...
1147
D
Palindrome XOR
You are given a string $s$ consisting of characters "1", "0", and "?". The first character of $s$ is guaranteed to be "1". Let $m$ be the number of characters in $s$. Count the number of ways we can choose a pair of integers $a, b$ that satisfies the following: - $1 \leq a < b < 2^m$ - When written without leading ze...
Since the leading character of $s$ is a "1", then that means $a < 2^{m-1}$ and $2^{m-1} \leq b < 2^m$. Let's fix the length of $a$ as $k$. I'll describe a more general solution, so there might be simpler solutions that work for this specific problem. Let's make a graph with $n+k+2$ nodes. The first $n$ nodes represent ...
[ "dfs and similar", "graphs" ]
2,400
#include <bits/stdc++.h> #define gcd(a, b) ((!a || !b) ? (a || b) : __gcd(a, b)) using namespace std; typedef long long ll; mt19937 rnd(1); const int N = 2e3 + 7; vector <pair <int, int> > g[N]; int val[N]; void add_edge(int a, int b, int c) { g[a].push_back({b, c}); g[b].push_back({a, c}); } vector <...
1147
E
Rainbow Coins
Carl has $n$ coins of various colors, and he would like to sort them into piles. The coins are labeled $1,2,\ldots,n$, and each coin is exactly one of red, green, or blue. He would like to sort the coins into three different piles so one pile contains all red coins, one pile contains all green coins, and one pile conta...
Let's define a new question that takes a list of coins $t_1, t_2, \ldots, t_k$, and returns the answers about all adjacent pairs of coins in this list (e.g. the answers to $(t_1, t_2), (t_2, t_3), (t_3, t_4), \ldots$. We can do this in two questions, one question is $(t_1, t_2), (t_3, t_4), \ldots,$ and the other is $(...
[ "interactive" ]
3,000
#include <bits/stdc++.h> #define gcd(a, b) ((!a || !b) ? (a || b) : __gcd(a, b)) using namespace std; typedef long long ll; mt19937 rnd(1); struct ev { int a, b, eq; }; int col[123456]; vector <ev> ask(vector <pair <int, int> > e) { if (e.empty()) return {}; cout << "Q " << e.size() << ' '; string s...
1147
F
Zigzag Game
You are given a complete bipartite graph with $2n$ nodes, with $n$ nodes on each side of the bipartition. Nodes $1$ through $n$ are on one side of the bipartition, and nodes $n+1$ to $2n$ are on the other side. You are also given an $n \times n$ matrix $a$ describing the edge weights. $a_{ij}$ denotes the weight of the...
I first got the idea for this problem from this problem: https://www.codechef.com/problems/HAMILG. There might be an easier version of the problem on a bipartite graph out there somewhere also. Anyways, the solution for the problem is conceptually simple. Find a matching of the graph, and then you can play according to...
[ "games", "interactive" ]
3,500
#include <bits/stdc++.h> #define gcd(a, b) ((!a || !b) ? (a || b) : __gcd(a, b)) using namespace std; typedef long long ll; mt19937 rnd(1); bool wPrefersM1OverM(const vector <vector <int> > &prefer, int w, int m, int m1) { int n = (int) prefer.size() / 2; // Check if w prefers m over her current engagment m1 ...
1148
A
Another One Bites The Dust
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string. You have $a$ strings "a", $b$ strings "b" and $c$ strings "ab". You want to choose some subset of these...
The answer is $2 * c + min(a, b) + min(max(a, b), min(a, b) + 1)$. First, you can place all "ab" strings together. Then if there are more "a" strings than "b" strings, you can start adding in the end "a" and "b" strings one by one in an alternating order. If there are more "b" strings than "a" strings, you can do the s...
[ "greedy" ]
800
null
1148
B
Born This Way
Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C. There are $n$ flights from A to B, they depart at time moments $a_1$, $a_2$, $a_3$, ..., $a_n$ and arrive at B $t_a$ moments later. There are $m$ fligh...
If $k \geq n$, we can cancel all flights between A and B, and Arkady won't be able to get to C, so answer will be equal to $-1$. Otherwise, $k < n$. If the subset of canceled flights is chosen, the Arkady's strategy is clear: use the earliest available flight from A to B, arrive to B at some time moment $t$ and choose ...
[ "binary search", "brute force", "two pointers" ]
1,600
null
1148
C
Crazy Diamond
You are given a permutation $p$ of integers from $1$ to $n$, where $n$ is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: - take two indices $i$ and $j$ such that $2 \cdot |i - j| \geq n$ and swap $p_i$ and $p_j$. There is \textbf{no need...
The problem can be solved in $4n$ swaps in total in the worst case (might be there is a more optimal solution, but it wasn't required). Let's go from left to right through the array. Suppose our current position is $i$ and position of the number $i$ is $j$. If $i \ne j$, we want to swap them. If $|i - j| \cdot 2 \geq n...
[ "constructive algorithms", "sortings" ]
1,700
null
1148
D
Dirty Deeds Done Dirt Cheap
You are given $n$ pairs of integers $(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)$. All of the integers in the pairs are distinct and are in the range from $1$ to $2 \cdot n$ inclusive. Let's call a sequence of integers $x_1, x_2, \ldots, x_{2k}$ good if either - $x_1 < x_2 > x_3 < \ldots < x_{2k-2} > x_{2k-1} < x_{2k}...
First notice, that there are two types of pairs: one with $a_i < b_i$ and another one with $a_i > b_i$. Note, that we can't form an answer with pairs of different types. Now let's notice that we can take all pairs of fixed type. Suppose the type is $a_i < b_i$. Then sort pairs by their $a_i$ in the decreasing order and...
[ "greedy", "sortings" ]
1,800
null
1148
E
Earth Wind and Fire
There are $n$ stones arranged on an axis. Initially the $i$-th stone is located at the coordinate $s_i$. There may be more than one stone in a single place. You can perform zero or more operations of the following type: - take two stones with indices $i$ and $j$ so that $s_i \leq s_j$, choose an integer $d$ ($0 \leq ...
Consider original and target position of stones in sorted order. Note, that we can always construct an answer preserving the original stones order (suppose we have an answer which doesn't preserve the order. It will happen when there are two stones at the same spot, just move the other one). So now we simplified our pr...
[ "constructive algorithms", "greedy", "math", "sortings", "two pointers" ]
2,300
null
1148
F
Foo Fighters
You are given $n$ objects. Each object has two integer properties: $val_i$ — its price — and $mask_i$. It is guaranteed that the sum of all prices is initially non-zero. You want to select a positive integer $s$. All objects will be modified after that. The $i$-th object will be modified using the following procedure:...
Let's solve this problem using the induction method. Let's solve this problem for all objects with masks less than $2^{K}$. Base of the induction: $K = 1$, than we just can multiply price by $-1$, like adding a single bit into the answer, if the price has the same sign as the initial sum. Move: we solved the problem fo...
[ "bitmasks", "constructive algorithms" ]
2,700
null
1148
G
Gold Experience
Consider an undirected graph $G$ with $n$ vertices. There is a value $a_i$ in each vertex. Two vertices $i$ and $j$ are connected with an edge if and only if $gcd(a_i, a_j) > 1$, where $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. Consider a set of vertices. Let's call a vertex in thi...
Firstly, let's discuss how to find the answer in $O(N^2)$ time. Let's assume $k$ is even. Pick any set on $k$ vertices. If it is a clique, just print it as an answer, if it is not, there must be two vertices in this set that don't share an edge. Just remove these two vertices and replace them with 2 arbitrary ones from...
[ "constructive algorithms", "graphs", "math", "number theory", "probabilities" ]
3,300
null
1148
H
Holy Diver
You are given an array which is initially empty. You need to perform $n$ operations of the given format: - "$a$ $l$ $r$ $k$": append $a$ to the end of the array. After that count the number of integer pairs $x, y$ such that $l \leq x \leq y \leq r$ and $\operatorname{mex}(a_{x}, a_{x+1}, \ldots, a_{y}) = k$. The elem...
First, let's try to solve it if we know the whole array initially. Let's move from the last element to the first. When we are in the element $i$ let's store all segments of right borders ($[r', r"]$) in the set, so that segment $[i, r]$ have the same mex value for all $r' \le r \le r"$. You can see that mex values in t...
[ "data structures" ]
3,500
null
1149
A
Prefix Sum Primes
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains $n$ tiles. Each of them has a single number written on it — either $1$ or $2$. However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence...
There are at least a couple of correct solutions I had in mind. Let me present the one I find the most straightforward, which doesn't even require implementing any sieve. If all the numbers on the tiles are equal, we have no choice but to output the only possible permutation. In the remaining cases, we'll show that the...
[ "constructive algorithms", "greedy", "math", "number theory" ]
1,200
N = int(input()) num_ones = input().count('1') num_twos = N - num_ones if not num_ones or not num_twos: solution = [1] * num_ones + [2] * num_twos else: solution = [2, 1] + [2] * (num_twos - 1) + [1] * (num_ones - 1) print(*solution)
1149
B
Three Religions
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The \underline{...
For our convenience, construct a two-dimensional helper array $N$ where $N(i, c)$ is the location of the first occurrence of character $c$ in the Word of Universe on position $i$ or later (or $\infty$ if no such character exists). This array can be created in a straightforward in $O(26 \cdot n)$ time, by iterating the ...
[ "dp", "implementation", "strings" ]
2,200
#include <bits/stdc++.h> using namespace std; const int AlphaSize = 26; const int MaxN = 1e5 + 100; const int MaxM = 256; int next_occur[MaxN][AlphaSize]; int dp[MaxM][MaxM][MaxM]; string pattern; string words[3]; int N, Q; void CreateLinks() { for (int i = 0; i < AlphaSize; ++i) { next_occur[N][i] = next...
1149
C
Tree Generator™
Owl Pacino has always been into trees — unweighted rooted trees in particular. He loves determining the diameter of every tree he sees — that is, the maximum length of any simple path in the tree. Owl Pacino's owl friends decided to present him the Tree Generator™ — a powerful machine creating rooted trees from their ...
Take any rooted tree and its description. For any vertices $u$, $v$, let $h(v)$ be its depth in the tree, and $d(u, v) = h(u) + h(v) - 2h(\mathrm{lca}(u, v))$ be the distance between $u$ and $v$. Consider the traversal of the tree represented by the description. Let's say we're processing the parentheses one by one eac...
[ "data structures", "implementation", "trees" ]
2,700
#include <algorithm> #include <cassert> #include <iostream> #include <string> #include <vector> using namespace std; struct Tree { // Node maximizing the value of depth(l) - 2*depth(v) + depth(r) for l<=v<=r struct Node { int delta; // num '(' - num ')' int min_depth; // minimum value of [num ...
1149
D
Abandoning Roads
Codefortia is a small island country located somewhere in the West Pacific. It consists of $n$ settlements connected by $m$ bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to $a$ or $b$ seconds. It's guaranteed that one can go bet...
Let's partition the edges of the graph into two classes: light (weight $a$) and heavy (weight $b$). Let's now fix a single settlement $p$ as the location of the parliament house, and consider how the path between settlements $1$ and $p$ could look like. Lemma 1. If there is a path between two settlements $u$, $v$ consi...
[ "brute force", "dp", "graphs", "greedy" ]
3,000
#include <bits/stdc++.h> using namespace std; const int MaxN = 80; const int kCompoSizeBound = 4; int N, M, A, B; vector<int> adj_cheap[MaxN]; vector<int> adj_expensive[MaxN]; vector<vector<int>> large_cheap_compos; unsigned large_compo_mask[MaxN]; bool is_same_compo[MaxN][MaxN]; bool visited[MaxN]; vector<int>...
1149
E
Election Promises
In Byteland, there are two political parties fighting for seats in the Parliament in the upcoming elections: Wrong Answer Party and Time Limit Exceeded Party. As they want to convince as many citizens as possible to cast their votes on them, they keep promising lower and lower taxes. There are $n$ cities in Byteland, ...
Let's get straight to the main lemma: Lemma. For any vertex $v$, let's define the level of $v$ as $M(v) = \mathrm{mex}\,\{M(u)\,\mid\,v\to u\,\text{is an edge}\}$ where $\mathrm{mex}$ is the minimum-excluded function. Moreover, for any $t \in \mathbb{N}$, let $X(t)$ be the xor-sum of the taxes in all cities $v$ fulfill...
[ "games", "graphs" ]
3,200
#include <bits/stdc++.h> using namespace std; const int MaxN = 2e5 + 100; int stack_sizes[MaxN]; vector<int> adj[MaxN]; int N, M; int vertex_group_idx[MaxN]; bool visited[MaxN]; int group_xor[MaxN]; vector<int> vertex_groups[MaxN]; void DfsMakeLayers(int vert) { visited[vert] = true; vector<int> seen_laye...
1150
A
Stock Arbitraging
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market! In the morning, there are $n$ opportunities to buy shares. The $i$-th of them allows to buy as many shares as you want, each at the pri...
The main observation is that we always want to buy shares as cheaply as possible, and sell them as expensively as possible. Therefore, we should pick the lowest price at which we can buy shares $s_{\min} = \min(s_1, s_2, \dots, s_n)$, and the highest price at which we can sell the shares $b_{\max} = \max(b_1, b_2, \dot...
[ "greedy", "implementation" ]
800
R = int(input().split()[-1]) best_buy = min(map(int, input().split())) best_sell = max(map(int, input().split())) num_buy = R // best_buy print(max(R, R + (best_sell - best_buy) * num_buy))
1150
B
Tiling Challenge
One day Alice was cleaning up her basement when she noticed something very curious: an \textbf{infinite} set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: By the pieces lay a large square wooden board. The board is divided into $n^2$ cells arranged into ...
Notice that there is only one orientation of the wooden piece (and this is the orientation depicted in the statement). Moreover, we can notice the following fact: Take any (untiled) topmost cell of the board. If there is any correct tiling of the board, this cell must be covered by the topmost tile of the piece. The fa...
[ "greedy", "implementation" ]
900
vectors = [(0, 0), (1, -1), (1, 0), (1, 1), (2, 0)] N = int(input()) board = [list(input()) for row_id in range(N)] for row in range(N - 2): for col in range(1, N - 1): can_place = all(board[row + dr][col + dc] == '.' for (dr, dc) in vectors) if can_place: for (dr, dc) in vectors: ...
1151
A
Maxim and Biology
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG". Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string $s$ consisting of uppercase letters and length of...
Check every substring of string $s$ of length $4$ and find the minimum number of operations to transform it into "ACTG" and update the answer. Complexity is $\mathcal{O}(n)$.
[ "brute force", "strings" ]
1,000
null