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
1238
E
Keyboard Purchase
You have a password which you often type — a string $s$ of length $n$. Every character of this string is one of the first $m$ lowercase Latin letters. Since you spend a lot of time typing it, you want to buy a new keyboard. A keyboard is a permutation of the first $m$ Latin letters. For example, if $m = 3$, then there are six possible keyboards: abc, acb, bac, bca, cab and cba. Since you type your password with one finger, you need to spend time moving your finger from one password character to the next. The time to move from character $s_i$ to character $s_{i+1}$ is equal to the distance between these characters on keyboard. The total time you have to spend typing the password with a keyboard is called the slowness of this keyboard. More formaly, the slowness of keyboard is equal to $\sum\limits_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |$, where $pos_x$ is position of letter $x$ in keyboard. For example, if $s$ is aacabc and the keyboard is bac, then the total time of typing this password is $|pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c|$ = $|2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3|$ = $0 + 1 + 1 + 1 + 2 = 5$. Before buying a new keyboard you want to know the minimum possible slowness that the keyboard can have.
Let's solve this problem by subset dynamic programming. Let's denote $cnt_{x, y}$ as the number of adjacent characters ($s_i$ and $s_{i+1}$) in $s$ such that $s_i = x, s_{i+1} = y$ or $s_i = y, s_{i+1} = x$. Let's $dp_{msk}$ be some intermediate result (further it will be explained what kind of intermediate result) if we already added letters corresponding to subset $msk$ to the keyboard (and we don't care about the order of these letters). Now let's consider how to recalculate values of this dynamic programming using some $dp_{msk}$. Let's iterate over a new letter $x$ on keyboard (and we know the position of this letter on the keyboard: it's equal to the number of elements in $msk$). After adding this new letter, we want to calculate what it added to the $dp_{msk \cup x}$. Let consider some letter $y \neq x$ and calculate how much time will be spent on moving $x \rightarrow y$ and $y \rightarrow x$. There are two cases. If letter $y$ is already on current keyboard, then we should add to answer $cnt_{x, y} (pos_x - pos_y)$, and $cnt_{x, y} (pos_y - pos_x)$ otherwise (where $pox_a$ is the position of character $a$ on the keyboard). But we don't know the position of the letter $y$. Let's fix it as follows. We will add the contribution of some letter when it will be added to the keyboard. So, when we added letter $x$, we should add the value $\sum\limits_{y \in msk} (cnt_{x, y} pos_x) - \sum\limits_{y \notin msk} (cnt_{x, y} pos_x)$. So, the total complexity is $O(a^2 2^a + n)$.
[ "bitmasks", "dp" ]
2,200
#include <bits/stdc++.h> using namespace std; void upd(int &a, int b){ a = min(a, b); } const int N = 20; const int M = (1 << N) + 55; const int INF = int(1e9) + 100; int a, n; string s; int cnt[N][N]; int d[M][N]; int dp[M]; int cntBit[M]; int minBit[M]; int main() { cin >> n >> a >> s; int B = (1 << a) - 1; for(int i = 1; i < s.size(); ++i){ ++cnt[s[i] - 'a'][s[i - 1] - 'a']; ++cnt[s[i - 1] - 'a'][s[i] - 'a']; } for(int i = 0; i < M; ++i) dp[i] = INF; dp[0] = 0; for(int msk = 1; msk < M; ++msk){ cntBit[msk] = 1 + cntBit[msk & (msk - 1)]; for(int i = 0; i < N; ++i) if((msk >> i) & 1){ minBit[msk] = i; break; } } for(int msk = 1; msk < M; ++msk) for(int i = 0; i < a; ++i){ int b = minBit[msk]; d[msk][i] = d[msk ^ (1 << b)][i] + cnt[i][b]; } for(int msk = 0; msk < (1 << a); ++msk){ for(int i = 0; i < a; ++i){ if((msk >> i) & 1) continue; //i -> x int pos = cntBit[msk]; int nmsk = msk | (1 << i); upd(dp[nmsk], dp[msk] + pos * (d[msk][i] - d[B ^ nmsk][i])); } } cout << dp[B] << endl; return 0; }
1238
F
The Maximum Subtree
Assume that you have $k$ one-dimensional segments $s_1, s_2, \dots s_k$ (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of $k$ vertexes, and there is an edge between the $i$-th and the $j$-th vertexes ($i \neq j$) if and only if the segments $s_i$ and $s_j$ intersect (there exists at least one point that belongs to both of them). For example, if $s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$, then the resulting graph is the following: A tree of size $m$ is good if it is possible to choose $m$ one-dimensional segments so that the graph built on these segments coincides with this tree. You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree. Note that you have to answer $q$ independent queries.
At first let's understand which trees are good. For this, let's consider some vertex $v$ (we denote its segment as $[l_v, r_v]$) which is not a leaf. Also let's consider some adjacent vertex $u$ (we denote its segment as $[l_u, r_u]$) which also is not leaf. It is claimed that segment $[l_v, r_v]$ can't be inside segment $[l_u, r_u]$ (it's means $l_u \le l_v \le r_v \le r_u$) and vice versa. It's true because if segment $[l_v, r_v]$ is inside the segment $[l_u, r_u]$ then some vertex $t$ adjacent with $v$ also will be adjacent with $u$. So any non-leaf vertex can be adjacent with at most 2 non-leaf vertexes. Therefore good tree is a path with a leafs adjacent to this path. So all the have to do it's find the such subtree of maximum size. We can do it by subtree dynamic programming. At first, let chose the root of the tree - some not leaf vertex. Let $dp_{v, 0}$ be the answer for the subtree with root in $v$ and dp_{v, 1} be the answer for the subtree with root in $v$ if we already took $v$ and its parent to the answer. It can be calculated as follows: $dp_{v, 0} = \max\limits_{to} dp_{to, 0}$; $dp_{v, 0} = \max(dp_{v, 0}, deg_v + 1 + firstMax + secondMax)$, there $firstMax$ is a first maximum of all $dp_{to, 1}$, and $secondMax$ is a second maximum, and $deg_v$ is a degree of vertex $v$; $dp_{v, 1} = deg_v - 1 + \max\limits_{to} dp_{to, 1}$.
[ "dfs and similar", "dp", "graphs", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int n; vector <int> g[N]; int d[N]; int dp[N][2]; void dfs(int v, int p){ vector <int> d1; dp[v][1] = d[v] - 1; for(auto to : g[v]){ if(to == p) continue; dfs(to, v); dp[v][0] = max(dp[v][0], dp[to][0]); if(g[to].size() > 1){ d1.push_back(dp[to][1]); dp[v][1] = max(dp[v][1], d[v] + dp[to][1] - 1); } } sort(d1.rbegin(), d1.rend()); int x = d[v] + 1; for(int i = 0; i < 2; ++i) if(i < d1.size()) x += d1[i]; dp[v][0] = max(dp[v][0], x); } int main() { int q; scanf("%d", &q); for(int qc = 0; qc < q; ++qc){ scanf("%d", &n); for(int i = 0; i < n; ++i){ g[i].clear(); d[i] = 0; dp[i][0] = dp[i][1] = 0; } for(int i = 0; i < n - 1; ++i){ int u, v; scanf("%d %d", &u, &v); --u, --v; g[u].push_back(v), g[v].push_back(u); } if(n <= 2){ printf("%d\n", n); continue; } for(int v = 0; v < n; ++v){ //d[v] = 1; //for(auto to : g[v]) // d[v] += g[to].size() == 1; d[v] = g[v].size(); } int r = -1; for(int v = 0; v < n; ++v) if(g[v].size() != 1) r = v; dfs(r, r); printf("%d\n", dp[r][0]); } return 0; }
1238
G
Adilbek and the Watering System
Adilbek has to water his garden. He is going to do it with the help of a complex watering system: he only has to deliver water to it, and the mechanisms will do all the remaining job. The watering system consumes one liter of water per minute (if there is no water, it is not working). It can hold no more than $c$ liters. Adilbek has already poured $c_0$ liters of water into the system. He is going to start watering the garden right now and water it for $m$ minutes, and the watering system should contain at least one liter of water at the beginning of the $i$-th minute (for every $i$ from $0$ to $m - 1$). Now Adilbek wonders what he will do if the watering system runs out of water. He called $n$ his friends and asked them if they are going to bring some water. The $i$-th friend answered that he can bring no more than $a_i$ liters of water; he will arrive at the beginning of the $t_i$-th minute and pour all the water he has into the system (if the system cannot hold such amount of water, the excess water is poured out); and then he will ask Adilbek to pay $b_i$ dollars for each liter of water he has brought. You may assume that if a friend arrives at the beginning of the $t_i$-th minute and the system runs out of water at the beginning of the same minute, the friend pours his water fast enough so that the system does not stop working. Of course, Adilbek does not want to pay his friends, but he has to water the garden. So he has to tell his friends how much water should they bring. Formally, Adilbek wants to choose $n$ integers $k_1$, $k_2$, ..., $k_n$ in such a way that: - if each friend $i$ brings exactly $k_i$ liters of water, then the watering system works during the whole time required to water the garden; - the sum $\sum\limits_{i = 1}^{n} k_i b_i$ is minimum possible. Help Adilbek to determine the minimum amount he has to pay his friends or determine that Adilbek not able to water the garden for $m$ minutes. You have to answer $q$ independent queries.
Despite the fact that statement sounds like some dp or flow, the actual solution is pretty greedy. Let's iterate over all minutes Adilbek has to water at and maintain the cheapest $C$ liters he can obtain to this minute. Let this be some structure which stores data in form (price for 1 liter, total volume Adilbek can buy for this price). Pairs will be sorted by the price of a liter. The most convenient structure for that might be a C++ map, for example. When moving to the next minute, pop the cheapest liter out of this structure and add it to the answer. If that minute some friend comes, then push his water to the structure: if the total updated volume in the structure is greater than $C$, then pop the most expensive left-overs out of it so that the structure holds no more than $C$ liters total. That prevents out solution to fill the watering system over its capacity. The main idea for why this greedy strategy works is that it's never optimal to take not the cheapest liter because a liter of that price or cheaper will still be available in the future minutes. Note that between each pairs of adjacent coming friends basically nothing happens. Thus you can find the time between them and pop that number of cheapest liters right away instead of iterating minute by minute. Overall complexity: $O(n \log n)$ per query.
[ "data structures", "greedy", "sortings" ]
2,700
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define forn(i, n) for (int i = 0; i < int(n); ++i) typedef long long li; typedef pair<int, int> pt; const int N = 500 * 1000 + 13; int n, m, c, c0; pair<int, pt> a[N]; li solve() { scanf("%d%d%d%d", &n, &m, &c, &c0); forn(i, n) scanf("%d%d%d", &a[i].x, &a[i].y.x, &a[i].y.y); a[n++] = mp(m, mp(0, 0)); sort(a, a + n); int sum = c0; map<int, int> q; q[0] = c0; li ans = 0; forn(i, n) { int x = a[i].x; int cnt = a[i].y.x; int cost = a[i].y.y; int dist = x - (i ? a[i - 1].x : 0); while (!q.empty() && dist > 0) { int can = min(q.begin()->y, dist); ans += q.begin()->x * 1ll * can; sum -= can; dist -= can; q.begin()->y -= can; if (q.begin()->y == 0) q.erase(q.begin()); } if (dist > 0) return -1; int add = min(c - sum, cnt); sum += add; while (add < cnt && !q.empty() && q.rbegin()->x > cost) { if (cnt - add >= q.rbegin()->y) { add += q.rbegin()->y; q.erase(--q.end()); } else { q.rbegin()->y -= cnt - add; add = cnt; } } q[cost] += add; } return ans; } int main() { int q; scanf("%d", &q); forn(i, q) printf("%lld\n", solve()); }
1239
A
Ivan the Fool and the Probability Theory
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of $n$ rows and $m$ columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has \textbf{at most} one adjacent cell of the same color. Two cells are considered adjacent if they share a side. Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo $10^9 + 7$.
If there is no adjecent cells with same color coloring is chess coloring. Otherwise there is exist two adjecent cells with same color. Let's decide for which cells we already know their color. It turns out that color rows or columns alternates. It means that this problem equal to the same problem about strip. Answer for the strip is $2F_n$. In this way the final answer is $2(F_n + F_m - 1)$.
[ "combinatorics", "dp", "math" ]
1,700
null
1239
B
The World Is Just a Programming Task (Hard Version)
This is a harder version of the problem. In this version, $n \le 300\,000$. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence. To digress from his problems, Vasya decided to select two positions of the string (\textbf{not necessarily distinct}) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him. We remind that bracket sequence $s$ is called correct if: - $s$ is empty; - $s$ is equal to "($t$)", where $t$ is correct bracket sequence; - $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. The cyclical shift of the string $s$ of length $n$ by $k$ ($0 \leq k < n$) is a string formed by a concatenation of the last $k$ symbols of the string $s$ with the first $n - k$ symbols of string $s$. For example, the cyclical shift of string "(())()" by $2$ equals "()(())". Cyclical shifts $i$ and $j$ are considered different, if $i \ne j$.
Note first that the number of opening brackets must be equal to the number of closing brackets, otherwise the answer is always $0$. The answer for a bracket sequence is the same as the answer for any of its cyclic shifts. Then find $i$- index of the minimum balance and perform a cyclic shift of the string by i to the left. The resulting line never has a balance below zero, which means it is a correct bracket sequence. Further we will work only with it Let us draw on the plane the prefix balances (the difference between the number of opening and closing brackets) of our correct bracket sequence in the form of a polyline. It will have a beginning at $(0, 0)$, an end - at $(2n, 0)$ and its points will be in the upper half-plane. It can easily be shown that the answer to the question of the number of cyclic shifts being correct bracket sequence is the number of times how much minimum balance is achieved in the array of prefix balances. For example, for string )(()))()((, the array of prefix balances is [-1, 0, 1, 0, -1, -2, -1, -2, -1, 0], and the number of cyclic shifts, $2$ - the number of minimums in it ($-2$). After swapping two different brackets (')' and '('), either on some sub-segment in an array of balances $2$ is added, or on some sub-segment $-2$ is added. In the first case (as you can see from the figure above), the minimum remains the same as it was - $0$, and its number does not increase due to the addition of $2$ to some sub-section of the array. So, there is no profit in swapping brackets in this case. In the second case, there are three options: the minimum becomes equal to $-2$, $-1$ or $0$. In the first case, the minimum reaches a value equal to $-2$ only at those points at which there was previously value equal to $0$, so this answer will less or equal than the one that would have turned out, if no operations were applied to the array at all. If the minimum becomes equal to $-1$, then on the segment in the balance array on which $2$ was deducted as a result of this operation there could not be balances equal to $0$, otherwise the new minimum would become equal to $-2$. So, if $0 = X_0 < X_1 < \dots < X_k = 2n$ - positions of minimums in the array of prefix balances, then the operation $-2$ was performed on the segment $[L, R]$ ($X_i < L \leq R < X_{i+1}$ for some $i$). After this operation, the number of local minimums will be equal to the number of elements of the array of balance on the segment $[L; R]$, equal to $1$. Since this number shall be maximized, the right border swall be maximised and the left border shall be minimised. So, for some fixed $i$ it is optimal to swap $X_i$-th and $X_{i+1}-1$-th brackets (see following figure) If the minimum remains equal to $0$, then using the reasoning similar to the reasoning above, it can be proven that for some $i$ if we consider points $X_i + 1 = Y_0 < Y_1 < \dots < Y_m = X_{i+1}-1$ - positions of $1$ in the array of balances on the segment $[X_i; X_{i+1}]$, it is optimal for some $j$ to swap $Y_j$ and $Y_{j+1}-1$ brackets (see following figure) Thus, we have the solution of $\mathcal{O}(n)$ complexity - we shall find all $X_i$, $Y_i$ and count on each of the segments of the form $[X_i; X_{i+1}]$ or $[Y_i; Y_{i+1}]$ the number of elements equal to $0$, $1$, $2$, then according to reasonings above, maximal answer can be found.
[ "implementation" ]
2,500
null
1239
C
Queue in the Train
There are $n$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \leq i \leq n$) will decide to go for boiled water at minute $t_i$. Tank with a boiled water is located to the left of the $1$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $p$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the $i$-th seat wants to go for a boiled water, he will first take a look on all seats from $1$ to $i - 1$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $i$ are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles.
The problem can be solved easily with an abstraction of "events". Let's define an "event" as a tuple of variables $(time, type, index)$, where $index$ is the index of the passenger $(1 \leq index \leq n)$, $time$ is the time when the event will happen, $type$ is either $0$ (the passenger exits the queue) or $1$ (the passenger wants to enter the queue). To simulate the activity described in the problem it's necessary to handle events in sorted order. At the start there are $n$ events $(t_i, 1, i)$, where $1 \leq i \leq n$. While there are any unprocessed events, we take the "smallest" event and process it. Event $(a, b, c)$ is "smaller" than event $(d, e, f)$ either if $(a < d)$ or $(a = d\ and\ b < e)$ or $(a = d\ and\ b = e\ and\ c < f)$. Let's define a few sets: $want$ (the set of passengers who want to enter the queue), $in\_queue$ (the set of passengers who are in the queue); and a few integer variables: $queue\_time$ (the time when the queue becomes empty, to help calculate the time when a new passenger will exit the queue if he enters now), $cur\_time$ (time of the last processed event). Suppose that we're processing an event. If the $type$ of the event is $1$, then we add $index$ to $want$, otherwise we remove $index$ from $in\_queue$. After processing an event we ought to check if there is a passenger who can enter the queue. Let $x$ be the smallest element of $want$, and if $in\_queue$ either is empty or $x$ is smaller than the smallest element of $in\_queue$, then $x$ immediately enters the queue, therefore creating a new event $(max(cur\_time, queue\_time) + p, 0, x)$. The complexity of the solution is $O(n log n)$, because we need to use sorted data structures (for example, std::set of std::priority_queue).
[ "data structures", "greedy", "implementation" ]
2,300
null
1239
D
Catowice City
In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are $n$ residents and $n$ cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from $1$ to $n$, where the $i$-th cat is living in the house of $i$-th resident. Each Catowice resident is in friendship with several cats, including the one living in his house. In order to conduct a contest, at least one jury member is needed and at least one cat contestant is needed. Of course, every jury member should know none of the contestants. For the contest to be successful, it's also needed that the number of jury members plus the number of contestants is equal to $n$. Please help Catowice residents to select the jury and the contestants for the upcoming competition, or determine that it's impossible to do.
You are given bipartite graph and a perfect matching in it. You have to find independent set of size $n$ which doesn't coincide with either of two parts. Suppose such independent set exists, let's call it $S$. Also, let's call left part of graph as $L$ and right part of graph as $R$. Then define $A = S \cap L$, $B = L \setminus A$, $A'$ is set of all nodes which are connected by edges from matching with $A$, $B'$ - similarly for $B$. It's easy to see that $S = A \cup B'$. Let's direct all edges in graph. Edges from matching will be directed from right to left, and all other edges will be directed from left to right. Now edges from matching will direct from $A'$ to $A$ and from $B'$ to $B$. Other edges could direct from $A$ to $A'$, from $B$ to $B'$ and from $B$ to $A'$. Observe that edges cannot direct from $A$ to $B'$, cause it wouldn't be an independent set otherwise. It's easy to see that $B'$ isn't reachable from $A$. So, let's find all strongly connected components (SCC) in this graph. If there's only one such component, answer doesn't exist due to the fact that any node of $B'$ isn't reachable from any node of $A$. If SCC is only one, any node is reachable from any other node therefore in this case either $A$ or $B'$ are empty. If there are at least two SCC, let's choose any source SCC and call it $Q$. Consider $B' = Q \cap R$ and define $A$ as set of all nodes in left part which are not connected by edges from matching with $B'$. Let's proof that if some $l \in L$ lies in $B'$, then $r$ - pair of $l$ in matching also lies in $B'$. That's obvious since there are no incoming edges in $B'$ and there's edge from $r$ to $l$. So, none of nodes from $A$ will lay in chosen SCC. Thus $B'$ won't be reachable from $A$ and $A \cup B'$ will be an independent set. The only exception is $n = 1$, in such case there are two SCC but answer doesn't exist (cause chosen $A$ will be empty).
[ "2-sat", "dfs and similar", "graph matchings", "graphs" ]
2,400
null
1239
E
Turtle
Kolya has a turtle and a field of size $2 \times n$. The field rows are numbered from $1$ to $2$ from top to bottom, while the columns are numbered from $1$ to $n$ from left to right. Suppose in each cell of the field there is a lettuce leaf. The energy value of lettuce leaf in row $i$ and column $j$ is equal to $a_{i,j}$. The turtle is initially in the top left cell and wants to reach the bottom right cell. The turtle can only move right and down and among all possible ways it will choose a way, maximizing the total energy value of lettuce leaves (in case there are several such paths, it will choose any of them). Kolya is afraid, that if turtle will eat too much lettuce, it can be bad for its health. So he wants to reorder lettuce leaves in the field, so that the energetic cost of leaves eaten by turtle will be minimized.
Consider that we already fixed the set in the top line and fixed. If we perform a swap in this situation, the answer will clearly won't become worse (some paths are not changing, and some are decreasing). So we can assume that the first line is sorted, and similarly the second line is sorted too (but descending). Now let's think which path the turtle will choose. Observe the difference between to paths: Then cost of path $i+1$ minus cost of path $i$ is equal to $x_{i+1} - y_{i}$. $x_i$ increases when $i$ increases, $y_i$ decreases, $x_{i+1} - y_{i}$ decreases, so the discrete derivative increases. Such function looks like: So clearly the turtle will choose either the first or the last path. So now we need to split our set into two of equal size, so that the maximum sum is smallest possible. This is a knapsack problem. The states are the prefix of elements considered, the number of elements taken, the weight. It works in $\mathcal{O}(n^3 maxa)$ EDIT: it turned out it was inobvious... The corner cells take two minimal elements and are not considered in knapsack since they are contained in all paths. It's easy to prove that it's optimal to put minimal elements in corners.
[ "dp", "implementation" ]
3,100
null
1239
F
Swiper, no swiping!
\begin{quote} I'm the Map, I'm the Map! I'm the MAP!!! \hfill Map \end{quote} In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose $t$ graph's variants, which Dora might like. However fox Swiper wants to spoil his plan. The Swiper knows, that Dora now is only able to count up to $3$, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every \textbf{remaining} vertex wouldn't change it's degree modulo $3$. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan. Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.
We will look only on set of vertex, that will stay after deleting. Let node-$x$ - node with degree $mod\ 3$ equal $x$. Let's consider some cases: Node-$0$ exists. It is the answer, except the case, when our graph consists of one node. Cycle on nodes-$2$ exists. So exists irreducible cycle on nodes-$2$. It is the answer, except the case, when our graph is cycle. Way between nodes-$1$ on nodes-$2$ exists. So exists irreducible way with same conditions. It is the answer, except the case, when our graph is way. Our graph contains one node-$1$ and nodes-$2$ form forest. Let's take two trees and delete all except two ways in this trees, such only endpoints are connected with node-$1$. Those ways and node-$1$ are the answer, except the case, when our graph is twho cycles with one common node. That's all cases. Let's show it: Nodes-$2$ form forest. Exists at least one leaf, that is connected with node-$1$. So in that case node-$1$ always exists. Degree of node-$1$ equals sum degree of nodes-$2$ minus doubled number of edges between nodes-$2$. Let $k$ - number of nodes-$2$. So degree of node-$1$ $mod\ 3$ equals $2k - 2(k - 1) = 2$. Contradiction. So forest consist of at least two trees.
[ "graphs", "implementation" ]
3,400
null
1240
F
Football
There are $n$ football teams in the world. The Main Football Organization (MFO) wants to host at most $m$ games. MFO wants the $i$-th game to be played between the teams $a_i$ and $b_i$ in one of the $k$ stadiums. Let $s_{ij}$ be the numbers of games the $i$-th team played in the $j$-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team $i$, the absolute difference between the maximum and minimum among $s_{i1}, s_{i2}, \ldots, s_{ik}$ should not exceed $2$. Each team has $w_i$ — the amount of money MFO will earn for \textbf{each} game of the $i$-th team. If the $i$-th team plays $l$ games, MFO will earn $w_i \cdot l$. MFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set. However, this problem is too complicated for MFO. Therefore, they are asking you to help them.
Let's assume that $m \leq n \cdot k$. We can randomly assign colors to edges. If there is a vertex that does not satisfy the condition, then we can choose color $a$ which appears the smallest number of times and color $b$ which appears the biggest number of times. We will "recolor" edges that have one of these two colors. Let's consider this graph only with edges with colors $a$ and $b$. Let's add a "fake" vertex $0$. This graph may have many components. If a component has at least one vertex with odd degree, we connect each such vertex with $0$. Otherwise, let's choose any vertex from that component and add two edges to $0$. Therefore, the graph will be connected and each vertex will have an even degree. Thus, we will be able to find an Euler cycle. Let's color the odd edges in the cycle in $a$, and even edges in $b$. As a result, the difference between these two colors for each vertex will be at most $1$. Let's do this operation while there is a vertex which does not satisfy the condition. If $m > n \cdot k$, let's split the edges into two groups with the equal sizes (that is, $\lfloor \frac{m}{2} \rfloor$ and $\lceil \frac{m}{2} \rceil$). If a group has not greater than $n \cdot k$ edges, then do the algorithm at the beginning of the tutorial. Otherwise, split it again. If you found the answers for two groups, you need to find the answer for the combined graph. Let $f_1$ be the most popular color in the first group, $f_2$ the second most popular color, ..., $f_k$ the least popular color in the first group. Similarly, let $g_1$ be the most popular color in the second graph, etc. So, in the combined graph, $f_1$ should be equal to $g_k$, $f_2$ should be equal to $g_{k-1}$. In other words, we take the most popular color in the first group and color the least popular color in the second group with that color. If there is a vertex that does not satisfy the condition, "recolor" the graph according to the algorithm explained in the third paragraph.
[ "graphs" ]
3,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector<pair<int, int> > v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set<pair<int, int> > s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair<int, int> get_s2(int i){ return {s[i].begin()->first - s[i].rbegin()->first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge > m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector<pair<int, int> > v2[MAX_N]; int deg2[MAX_N]; vector<int> vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set<int> used3; int i; vector<int> euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector<int> &e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i < (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j < 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector<int> &e){ s2.clear(); for (int i = 1; i <= n; i++){ s[i].clear(); for (int j = 1; j <= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i <= n; i++){ for (int j = 1; j <= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()->first > 2){ int ind = s2.begin()->second; int col1 = s[ind].begin()->second; int col2 = s[ind].rbegin()->second; vector<int> e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector<int> e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i < (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector<int> e){ if ((int) e.size() <= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector<int> e1, e2; int s = (int) e.size() / 2; for (int i = 0; i < (int) e.size(); i++){ if (i < s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector<pair<int, int> > v1(k), v2(k); for (int i = 1; i <= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i < k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i < k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen("/Users/antontsypko/tsypko/input.txt", "r", stdin); #endif cin >> n >> m >> k; for (int i = 1; i <= n; i++){ cin >> w[i]; } ll sum = 0; vector<int> e; for (int i = 1; i <= m; i++){ cin >> a[i] >> b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i <= m; i++){ assert(color[i]); cout << color[i] << endl; } }
1242
A
Tile Painting
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of $n$ consecutive tiles, numbered from $1$ to $n$. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two \textbf{different} tiles with numbers $i$ and $j$, such that $|j - i|$ is a divisor of $n$ greater than $1$, they have the same color. Formally, the colors of two tiles with numbers $i$ and $j$ should be the same if $|i-j| > 1$ and $n \bmod |i-j| = 0$ (where $x \bmod y$ is the remainder when dividing $x$ by $y$). Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?
If $n = p^k$ for some prime $p$, then the answer is $p$ colors. Simply color all tiles with indices $i \pmod p$ in color $i$. Since any divisor $d$ of $n$ greater than $1$ is divisible by $p$, then any two tiles $i$ and $i+d$ will have the same color. Also, if the first $p$ tiles are colored in $c$ different colors, then each next $p$ tiles have the same $c$ colors, hence the answer cannot be greater than $p$. If $n = pq$ for some $p, q > 1$ such that $\gcd(p, q) = 1$ then the answer is $1$. Examine any two distinct indices $i, j$. Let's prove that they must have the same color. By the Chinese Remainder Theorem, there exists such $1 \leq x \leq n$ that $x \equiv i \pmod p$ and $x \equiv j \pmod q$. Therefore, both tiles $i$ and $j$ must be colored in the same color as the tile $x$. Hence, all tiles must have the same color. To check which case it is, we use the following algorithm: First we check whether $n$ is prime. We use the standard $O(\sqrt n)$ algorithm. Otherwise, if $n = p^k$ for $k > 1$, then $p$ must be at most $\sqrt n \leq 10^6$. We can then find the smallest divisor $p$ of $n$ greater than $1$, which is at most $10^6$. Then we try to divide $n$ by the largest power of $p$. If $n = p^k$, then $n$ will become simply $1$; otherwise $n$ will remain greater than $1$, hence it is divisible by some prime other than $p$.
[ "constructive algorithms", "math", "number theory" ]
1,500
null
1242
B
0-1 MST
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph. It is an undirected weighted graph on $n$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $0$ or $1$; exactly $m$ edges have weight $1$, and all others have weight $0$. Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
First examine the given graph where there are only edges of weight $0$: suppose that the number of connected components in this subgraph is $k$. Then the minimum spanning tree of the given graph is equal to $k-1$. Therefore, we need to find the number of such (zero weight) components in the given graph. The following is a $O(m + n \log n)$ solution. Let's maintain the zero weight components in the disjoint set union, and let's also store the size of each such component. Then we iterate over all vertices $v$ from $1$ to $n$. Put the vertex $v$ in a new component of size $1$. Then we iterate over the weight $1$ edges $\{u, v\}$ such that $u < v$. For each of the zero weight components, we count the number of edges from this component to $v$. If the number of such edges is less than the size of the component of $u$, we should merge the component of $u$ with $v$ (because there is at least one $0$ weight edge between this component and $v$). Otherwise we should not merge the component with $v$. In the end, we get the number of zero weight components. What is the complexity of such algorithm? In total, $n$ new components are created in the course of the algorithm (a new one for each of the $n$ vertices). When we merge some old component with $v$, the number of components decreases by $1$. Thus the total number of such cases during the algorithm is at most $O(n)$, and for each we have one merge call for DSU. This part has $O(n \log n)$ complexity. When we don't merge an old component with $v$, there is at least one edge of weight $1$ from this component to $v$. Therefore, the total number of such cases is at most the number of edges, $m$. Thus the complexity of processing these cases is $O(m)$. Hence, the total complexity of the algorithm is $O(n \log n + m)$.
[ "dfs and similar", "dsu", "graphs", "sortings" ]
1,900
null
1242
C
Sum Balance
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers. There are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. \textbf{All of the integers are distinct.} Ujan is lazy, so he will do the following reordering of the numbers \textbf{exactly once}. He will pick a single integer from each of the boxes, $k$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box. Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
First, calculate the total average sum $s := (\sum_{i=1}^n a_i)/k$. If the answer is positive, the sum of integers in each box must be equal to $s$ after reordering. If $s$ is not integer, then the answer is immediately negative. Now, suppose that an integer $x := a_{i,p}$ is taken out of some box $i$. Then we know that it should be replaced by $y := s - \sum_{j = 1}^{n_i} a_{i,j} + a_{i,p}$. We then construct a graph where all of the given integers are vertices, and we draw a directed edge from $x$ to $y$. Note that we obtain a functional graph. Examine all of the cycles of this graph; since this a functional graph, no two cycles share the same vertex. Let $n := \sum_{i=1}^k n_i$, then the total number of cycles is at most $n \leq 15 \cdot 5000 = 75000$. Examine any valid reordering. It is easy to see that it is a collection of cycles from the obtained graph such that each box is visited by some cycle exactly once. Therefore, lets extract all of the cycles from our graph such that do not pass through the same box twice. A valid reordering then is some subset of these cycles that visit all of the $k$ boxes exactly once. We can also reformulate this problem in the following way: each of the extracted cycles $C$ visits some set of boxes $S$. Find all of such subsets $S$; the number of such subsets is at most $2^k$. Now, the problem is reduced to exactly covering the set $\{1,\ldots,k\}$ with some subset of such sets. This is a classical problem that can be solved in $O(3^n)$ using dynamic programming. For a subset $X$ of $\{1,\ldots,k\}$, define $dp[X]$ to be true if $X$ can be exactly covered, and false otherwise. Firstly, $dp[\varnothing] = true$. To find $dp[X]$ for $X \neq \varnothing$, iterate over all subsets $S$ of $X$, and check whether $S$ is visited by some cycle and $X \setminus S$ can be covered (e.g., $dp[X \setminus S]$ is true). Then the answer is $dp[\{1,\ldots,k\}]$. This algorithm can be implemented with complexity $O(3^k)$, you can read about it here:https://cp-algorithms.com/algebra/all-submasks.html. The reordering can be restored from this DP table. The total complexity of the algorithm: $O(k \cdot \sum_{i=1}^k n_i + 3^k)$.
[ "bitmasks", "dfs and similar", "dp", "graphs" ]
2,400
null
1242
D
Number Discovery
Ujan needs some rest from cleaning, so he started playing with infinite sequences. He has two integers $n$ and $k$. He creates an infinite sequence $s$ by repeating the following steps. - Find $k$ smallest distinct positive integers that are not in $s$. Let's call them $u_{1}, u_{2}, \ldots, u_{k}$ from the smallest to the largest. - Append $u_{1}, u_{2}, \ldots, u_{k}$ and $\sum_{i=1}^{k} u_{i}$ to $s$ in this order. - Go back to the first step. Ujan will stop procrastinating when he writes the number $n$ in the sequence $s$. Help him find the index of $n$ in $s$. In other words, find the integer $x$ such that $s_{x} = n$. It's possible to prove that all positive integers are included in $s$ only once.
Let's make some definitions: $x$ is non-self number if $x$ is appended into $s$ by summation form. For example, if $k = 2$, then $3, 9, 13, 18, \ldots$ are non-self numbers. $x$ is self number if $x$ is not non-self number. Let $I_{i} = [(k^2+1) \cdot i + 1, (k^2+1) \cdot i + 2, \ldots, (k^2+1) \cdot (i+1)]$. In other words, $I_{i}$ is $i$-th interval of positive integers with $k^2+1$ size. Now let me introduce some strong lemma - Every interval has exactly one non-self number. Furthermore, we can immediately determine the non-self number of $I_{k \cdot i}, I_{k \cdot i + 1}, I_{k \cdot i + 2}, \ldots, I_{k \cdot i + k - 1}$ using non-self number of $I_{i}$. How is this possible? First, you can prove there is only $1$ non-self number in $I_{0}$. Now let's try induction. Suppose $I_{i}$ has only $1$ non-self number and each $k$ numbers of $k^2$ self numbers form summation, then you can describe generated summations as follows: $\sum_{j=1}^{k} (i \cdot (k^2 + 1) + t \cdot k + j) + offset = (k \cdot i + t) \cdot (k^2 + 1) + \frac{k \cdot (k+1)}{2} - t + offset$ Where $t$ means index of subintervals in $I_{i}$ ($0 \le t \lt k$) and $offset$ means added offset into $t$-th subinterval ($0 \le offset \le k$) since $I_{i}$'s non-self number can be located at left or inside of $t$-th subinterval. Using this fact, you can solve this problem in $O(\frac{\log n}{\log k})$ per test case. Some testers solved this problem by detecting pattern of distribution of non-self numbers.
[ "math" ]
3,400
null
1242
E
Planar Perimeter
Ujan has finally cleaned up his house and now wants to decorate the interior. He decided to place a beautiful carpet that would really tie the guest room together. He is interested in carpets that are made up of polygonal patches such that each side of a patch is either a side of another (different) patch, or is an exterior side of the whole carpet. In other words, the carpet can be represented as a planar graph, where each patch corresponds to a face of the graph, each face is a simple polygon. The perimeter of the carpet is the number of the exterior sides. Ujan considers a carpet beautiful if it consists of $f$ patches, where the $i$-th patch has exactly $a_i$ sides, and the perimeter is the smallest possible. Find an example of such a carpet, so that Ujan can order it!
If there is just a single face, just output it. Suppose there are at least $2$ faces. Let's say that we "glue" a cycle to a planar graph along $k$ edges if we place this cycle so that the graph and the cycle share $k$ edges on their perimeters. First, sort the numbers in decreasing order (then we have $a_1 \geq a_2 \geq \ldots \geq a_n$). By gluing any $a_i$ to the $a_1$ cycle, we can decrease the number of edges by at most $a_i-2$. Also note that the answer is always at least $3$, because there cannot be multiple edges between two vertices. Thus, if $a_1-2 \geq \sum_{i=2}^n (a_i-2)$, then the answer is $a_1 - \sum_{i=2}^n (a_i-2)$ (we subtract $2$ from $a_1$ to keep the perimeter at least $3$: these are the $2$ edges that we don't glue anything to). Otherwise the answer is either $3$ or $4$ (depending on the parity of $\sum_{i=1}^n a_i$). The algorithm to construct the graph: let $C := a_1$. Iterate $i$ from $2$ to $n$. While $(C-2) + (a_i-2) < \sum_{j=i+1}^n (a_j-2)$, glue the $i$-th cycle with the graph along one edge ($C += (a_i-2)$). For the first $a_i$ such that this does not hold, glue it so that $\sum_{j=i+1}^n (a_j-2) \leq C-2 \leq \sum_{j=i+1}^n (a_j-2) + 1$. Afterwards just glue each remaining cycles $a_j$ along $a_j-1$ edges with the graph. There is one problem with this algorithm: it can happen that we add multiple edges between two vertices. This situation is as follows: suppose you are at some point of the algorithm with a planar graph that you're building. Suppose there is an edge between some vertices $u$ and $v$ on the current perimeter, and you now happen to glue a cycle $C$ along the edges between $u$ and $v$, and the last edge of the cycle $C$ you're gluing must connect $u$ and $v$. To solve this situation, take the vertex $u'$ adjacent to $u$ to the right on the perimeter, and the vertex $v'$ adjacent to $v$ also to the right on the perimeter. Now, $u'$ and $v'$ cannot be connected by an edge in the current graph, because then it would intersect the edge between $u$ and $v$. This would be a contradiction, because the graph is planar. Then you glue the cycle $C$ along the edges between $u'$ and $v'$. The complexity of the algorithm: $O(\sum_{i=1}^n a_i)$. You should be careful with the implementation: for example, not to make perimeter equal to $2$ at some point or use some edge in more than two faces.
[ "constructive algorithms", "graphs" ]
3,200
null
1243
A
Maximum Square
Ujan decided to make a new wooden roof for the house. He has $n$ rectangular planks numbered from $1$ to $n$. The $i$-th plank has size $a_i \times 1$ (that is, the width is $1$ and the height is $a_i$). Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical. For example, if Ujan had planks with lengths $4$, $3$, $1$, $4$ and $5$, he could choose planks with lengths $4$, $3$ and $5$. Then he can cut out a $3 \times 3$ square, which is the maximum possible. Note that this is not the only way he can obtain a $3 \times 3$ square. What is the maximum side length of the square Ujan can get?
There are different solutions: Solution 1: Bruteforce the length of the square $l$ from $1$ to $n$. If you can make a square of side length $l$, then there should be at least $l$ planks of length at least $l$. The complexity of such solution: $O(n^2)$. The parameter $l$ can be also checked using binary search: then the complexity becomes $O(n \log n)$. Solution 2: Suppose you want to take $i$ planks and cut the largest square from them. Of course, it is always better to take the longest $i$ planks. The side of the largest square that can be cut from them is bounded by the length of the smallest of these $i$ planks and the number of the planks, $i$. Therefore, the solution is: sort the numbers $a_i$ in descending order; then the solution is $\max(\min(i,a_i))$. The complexity: $O(n \log n)$. Since the numbers $a_i$ are at most $n$, we can use counting sort and the complexity becomes $O(n)$.
[ "implementation" ]
800
null
1243
B1
Character Swap (Easy Version)
{This problem is different from the hard version. In this version Ujan makes \textbf{exactly} one exchange. You can hack this problem only if you solve both problems.} After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two \textbf{distinct} strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $i$ and $j$ ($1 \le i,j \le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$. Can he succeed? Note that he has to perform this operation \textbf{exactly} once. He \textbf{has} to perform this operation.
First, suppose that we make the strings equal by picking some $i$, $j$. Then for all $p \neq i, j$, we must have $s_p = t_p$, since these letters don't change. Suppose that $i = j$. Since the strings are distinct, we then must have $s_i \neq t_i$. But then the strings are not equal also after the swap; hence, we always need to pick distinct $i$ and $j$. Now, if $i \neq j$ and the strings are equal after the swap, we must have that $s_i = s_j$, $t_i = t_j$ and $s_i, s_j \neq t_i, t_j$. Therefore, the solution is as follows: if the number of positions where $s$ and $t$ differ is not equal to $2$, the answer is "No". Otherwise we find the two positions $i$, $j$, where $s$ and $t$ differ, and check that the above conditions hold. Then the answer is "Yes". Complexity of the solution: $O(n)$.
[ "strings" ]
1,000
null
1243
B2
Character Swap (Hard Version)
This problem is different from the easy version. In this version Ujan makes at most $2n$ swaps. In addition, $k \le 1000, n \le 50$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two \textbf{distinct} strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $2n$ times: he takes two positions $i$ and $j$ ($1 \le i,j \le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$. Ujan's goal is to make the strings $s$ and $t$ equal. He does not need to minimize the number of performed operations: \textbf{any} sequence of operations of length $2n$ or shorter is suitable.
We claim that you can make the strings equal if and only if the total number of each character in both of the strings $s$ and $t$ is even. Proof that this is a necessary condition. If we can make the strings equal, then for each position, the characters of $s$ and $t$ will be the same. Therefore, each character must appear an even number of times in both strings together. Algorithm, if all characters appear even number of times. Iterate over the index $i$ from $1$ to $n$. If $s_i \neq t_i$, then one of the following cases holds: There is an index $j > i$ such that $s_i = s_j$. Then simply swap $s_j$ with $t_i$ and then the strings will have the same character at position $i$. There is an index $j > i$ such that $s_i = t_j$. Then first swap $t_j$ with $s_j$, and then swap $s_j$ with $t_i$. Again, the strings will have the same character at position $i$. This problem was introduced by [user:MikeMirzayanov] inspired by the easier version of the problem (with a single swap).
[ "strings" ]
1,600
null
1244
A
Pens and Pencils
Tomorrow is a difficult day for Polycarp: he has to attend $a$ lectures and $b$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $c$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $d$ practical classes, after which it is unusable. Polycarp's pencilcase can hold no more than $k$ writing implements, so if Polycarp wants to take $x$ pens and $y$ pencils, they will fit in the pencilcase if and only if $x + y \le k$. Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow! Note that you don't have to minimize the number of writing implements (though their total number must not exceed $k$).
There is a solution with brute force in $O(n^2)$ and a solution with formulas in $O(1)$. I'll describe the latter one. We should determine the minimum number of pens that we should take to be able to write all of the lectures. It is $\lceil \frac{a}{c} \rceil$, but how to compute it easily? We can use some internal ceiling functions. We can also do something like "compute the integer part of the quotient, and then add $1$ if the remainder is not zero". But the easiest option, in my opinion, is to use the following formula: $\lceil \frac{a}{c} \rceil = \lfloor \frac{a + c - 1}{c} \rfloor$. The minimum number of pencils can be calculated using the same method. All that's left is to check that $k$ is not less than the total number of writing implements we should take.
[ "math" ]
800
null
1244
B
Rooms and Staircases
Nikolay lives in a two-storied house. There are $n$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $1$ and $n$). If Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers $i$ and $i+1$ on each floor are neighbouring, for all $1 \leq i \leq n - 1$. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room $x$ on the first floor and the room $x$ on the second floor, then Nikolay can use it to move from one room to another. \begin{center} {\small The picture illustrates a house with $n = 4$. There is a staircase between the room $2$ on the first floor and the room $2$ on the second floor, and another staircase between the room $4$ on the first floor and the room $4$ on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string "0101" in the input.} \end{center} Nikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been). Calculate the maximum number of rooms Nikolay can visit during his tour, if: - he can start \textbf{in any room on any floor of his choice}, - and \textbf{he won't visit the same room twice}.
If there are no stairs, the best we can do is to visit all the rooms on the same floor, so the answer is $n$. Otherwise, the best course of action is to choose exactly one stair (let's denote its number by $s$) and do one of the following: either start from the leftmost room on the first floor, then use the stair and move to the leftmost room on the second floor, or do the same, but start and end in rightmost rooms instead of leftmost ones. Then for choosing the stair in room $s$, we get $max(2s, 2(n - s + 1))$ as the answer. Why is it optimal? Let's denote the leftmost stair as $l$, and the rightmost stair as $r$. There are four special segments of rooms such that if we enter them, we can't leave. These are: rooms $[1 \dots l - 1]$ on the first floor, rooms $[1 \dots l - 1]$ on the second floor, rooms $[r + 1 \dots n]$ on the first floor and rooms $[r + 1 \dots n]$ on the second floor. We can visit only two of them, if one contains the starting room and the other contains the ending room. So the answer cannot be greater than $2n - 2min(l - 1, n - r - 1)$ - and our algorithm will give exactly this value either by choosing stair $l$, or by choosing the stair $r$.
[ "brute force", "implementation" ]
1,000
null
1244
C
The Football Season
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets $w$ points, and the opposing team gets $0$ points. If the game results in a draw, both teams get $d$ points. The manager of the Berland capital team wants to summarize the results of the season, but, unfortunately, all information about the results of each match is lost. The manager only knows that the team has played $n$ games and got $p$ points for them. You have to determine three integers $x$, $y$ and $z$ — the number of wins, draws and loses of the team. If there are multiple answers, print any of them. If there is no suitable triple $(x, y, z)$, report about it.
The crucial observation is that $d$ wins give us the same amount of points as $w$ draws. Let's use them to solve a problem where we want to minimize the total amount of wins and draws giving $p$ points (if it is not greater than $n$, we can just lose all other matches). If $y \ge w$, then we can subtract $w$ from $y$ and add $d$ to $x$, the number of wins and draws will decrease, and the number of points will stay the same. So we can limit the number of draws to $w - 1$. And the solution is the following: iterate on the number of draws $y$ from $0$ to $w - 1$, and check if the current value of $y$ gives us the result we need ($p - yd$ should be non-negative and divisible by $w$, and $\frac{p - yd}{w} + y$ should be not greater than $n$).
[ "brute force", "math", "number theory" ]
2,000
null
1244
D
Paint the Tree
You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph. \begin{center} {\small Example of a tree.} \end{center} You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color. You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $(x, y, z)$ such that $x \neq y, y \neq z, x \neq z$, $x$ is connected by an edge with $y$, and $y$ is connected by an edge with $z$. The colours of $x$, $y$ and $z$ should be pairwise distinct. Let's call a painting which meets this condition good. You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.
The key observation is that if we fix the colors of two adjacent vertices $x$ and $y$, then the color of any vertex adjacent to $x$ or to $y$ can be only $6 - c_x - c_y$. So we can fix the colors of the endpoints of any edge (there are $6$ possibilities to do that), then do a traversal to color all other vertices, then do another traversal to check that we got a good painting. To avoid checking that the painting we got is good (which can be tricky to code), we can use the fact that, for each vertex, the colors of all its neighbours should be different from each other and from the color of the vertex we fixed. So, if some vertex has degree $3$ or greater, then there is no good painting; otherwise the painting we get is good, since the graph is a chain.
[ "brute force", "constructive algorithms", "dp", "graphs", "implementation", "trees" ]
1,800
null
1244
E
Minimizing Difference
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation \textbf{no more than} $k$ times.
Suppose that the maximum value in the resulting array should be $R$, and the minimum value should be $L$. Let's estimate the required number of operations to make an array with such properties. All elements that are less than $L$ should be increased to $L$, and all elements that are greater than $R$ should be decreased to $R$ - and we don't have to do any operation with remaining elements. Now we claim that either $L$ or $R$ should belong to the initial array. Why so? Suppose we constructed an answer such that $L \notin A$ and $R \notin A$. If the number of elements we increased to $L$ is not less than the number of elements we decreased to $R$, then we could construct the answer with minimum equal to $L - 1$ and maximum equal to $R - 1$, and it would not require more operations. And if the number of elements we increased to $L$ is less than the number of elements we decreased to $R$, then we construct the answer for $L + 1$ as minimum and $R + 1$ as maximum. So we can shift the range $[L, R]$ so that one of its endpoints belongs to the initial array. Now we can solve the problem as follows: iterate on the maximum in the resulting array and find the largest minimum we can obtain with binary search, and then do it vice versa: iterate on the minimum in the resulting array and find the largest maximum we can obtain with binary search. To check how many operations we need, for example, to make all values not less than $L$, we can find the number of elements that we have to change with another binary search (let the number of such elements be $m$), and find their sum with prefix sums (let their sum be $S$). Then the required number of operations is exactly $Lm - S$. The same approach can be used to find the number of operations to make all elements not greater than $R$. This is the way the problem was supposed to solve, but, unfortunately, we failed to find a much easier greedy solution.
[ "binary search", "constructive algorithms", "greedy", "sortings", "ternary search", "two pointers" ]
2,000
null
1244
F
Chips
There are $n$ chips arranged in a circle, numbered from $1$ to $n$. Initially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $i$ becomes white. Otherwise, the chip $i$ becomes black. Note that for each $i$ from $2$ to $(n - 1)$ two neighbouring chips have numbers $(i - 1)$ and $(i + 1)$. The neighbours for the chip $i = 1$ are $n$ and $2$. The neighbours of $i = n$ are $(n - 1)$ and $1$. The following picture describes one iteration with $n = 6$. The chips $1$, $3$ and $4$ are initially black, and the chips $2$, $5$ and $6$ are white. After the iteration $2$, $3$ and $4$ become black, and $1$, $5$ and $6$ become white. Your task is to determine the color of each chip after $k$ iterations.
The main observation for this problem is the following: a chip changes its color if and only if both of its neighbours have the opposite colors (so, a W chip changes its color only if both of its neighbours are B, and vice versa). Let's denote such chips as unstable, and also let's denote an unstable segment as a maximum by inclusion sequence of consecutive unstable chips. Let's analyze each unstable segment. If it covers the whole circle, then the whole circle changes during each iteration, so the answer depends on whether $k$ is odd or even. Otherwise the unstable segment we analyze is bounded by two stable chips. When the first chip in the unstable segment changes, its color becomes equal to the color of its neighbour that does not belong to the unstable segment. We can also say the same for the last chip. So, during each iteration all chips in the unstable segment change their colors, and after that, the segment shrinks (the first and the last chip become stable and won't change their colors anymore). All that's left is to find all unstable segments and analyze how they change.
[ "constructive algorithms", "implementation" ]
2,300
null
1244
G
Running in Pairs
Demonstrative competitions will be held in the run-up to the $20NN$ Berlatov Olympic Games. Today is the day for the running competition! Berlatov team consists of $2n$ runners which are placed on two running tracks; $n$ runners are placed on each track. The runners are numbered from $1$ to $n$ on each track. The runner with number $i$ runs through the entire track in $i$ seconds. The competition is held as follows: first runners on both tracks start running at the same time; when the slower of them arrives at the end of the track, second runners on both tracks start running, and everyone waits until the slower of them finishes running, and so on, until all $n$ pairs run through the track. The organizers want the run to be as long as possible, but if it lasts for more than $k$ seconds, the crowd will get bored. As the coach of the team, you may choose any order in which the runners are arranged on each track (but you can't change the number of runners on each track or swap runners between different tracks). You have to choose the order of runners on each track so that the duration of the competition is as long as possible, but does not exceed $k$ seconds. Formally, you want to find two permutations $p$ and $q$ (both consisting of $n$ elements) such that $sum = \sum\limits_{i=1}^{n} max(p_i, q_i)$ is maximum possible, but does not exceed $k$. If there is no such pair, report about it.
First of all, let's understand which values of $sum$ we can obtain at all. Obviously, the minimum possible value of $sum$ is $mn = \frac{n(n+1)}{2}$. The maximum possible value of $sum$ is $mx = (\lceil\frac{n}{2}\rceil + 1 + n) \cdot \lfloor\frac{n}{2}\rfloor + n \% 2 \cdot \lceil\frac{n}{2}\rceil$. We can obtain every possible value of $sum$ between $mn$ and $mx$ and we will show how to do it below. If $k < mn$ then the answer is -1 (and this is the only such case). Otherwise, the answer exists and we need to construct it somehow. Firstly, suppose that the first permutation is identic permutation ($1, 2, \dots, n$) and the only permutation we change is the second one. Initially, the second permutation is also identic. Now we have $sum = mn$ and we need to change it to $sum = k$ or to the maximum possible number not greater than $k$. To do that, let's learn how to increase $sum$ by one. Let's see what will happen if we swap $n$ and $n-1$. Then the value of $sum$ will increase by one. If we swap $n$ and $n-2$ then the value of $sum$ will increase by $2$, and so on. If we swap $n$ and $1$ then the value of $sum$ will increase by $n-1$. So, the following constructive algorithm comes to mind: let's carry the current segment of permutation $[l; r]$ we can change (it is always segment because after some swaps some leftmost and rightmost elements cannot increase our answer because they're will be already placed optimally) and the value $add$ we need to add to $sum$ to obtain the maximum possible sum not greater than $k$. Initially $l=1, r=n, add = k - mn$. Now let's understand the maximum value by which we can increase the value of $sum$. Now it is $r-l$. If this value is greater than $add$ then let's swap $p_r$ and $p_{r - add}$, and break the cycle ($p$ is the second permutation). Otherwise, let's swap $p_l$ and $p_r$, decrease $add$ by $r-l$ and set $l := l + 1, r := r - 1$ . If at some moment $l$ becomes greater than or equal to $r$ then break the cycle. Now we got the second permutation $p$ with the maximum possible value of $sum$ not greater than $k$, we can calculate the numeric answer (or print $min(mx, k)$), print identic permutation and the permutation $p$.
[ "constructive algorithms", "greedy", "math" ]
2,400
null
1245
A
Good ol' Numbers Coloring
Consider the set of all nonnegative integers: ${0, 1, 2, \dots}$. Given two integers $a$ and $b$ ($1 \le a, b \le 10^4$). We paint all the numbers in increasing number first we paint $0$, then we paint $1$, then $2$ and so on. Each number is painted white or black. We paint a number $i$ according to the following rules: - if $i = 0$, it is colored white; - if $i \ge a$ and $i - a$ is colored white, $i$ is also colored white; - if $i \ge b$ and $i - b$ is colored white, $i$ is also colored white; - if $i$ is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors. For example, if $a=3$, $b=5$, then the colors of the numbers (in the order from $0$) are: white ($0$), black ($1$), black ($2$), white ($3$), black ($4$), white ($5$), white ($6$), black ($7$), white ($8$), white ($9$), ... Note that: - It is possible that there are infinitely many nonnegative integers colored black. For example, if $a = 10$ and $b = 10$, then only $0, 10, 20, 30$ and any other nonnegative integers that end in $0$ when written in base 10 are white. The other integers are colored black. - It is also possible that there are only finitely many nonnegative integers colored black. For example, when $a = 1$ and $b = 10$, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored \textbf{black} is infinite. If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).
If $\gcd(a, b) \neq 1$, print "Infinite". This is correct because any integer that isn't divisible by $\gcd(a, b)$ will not be expressible in the form $ax + by$ since $ax + by$ is always divisible by $\gcd(a, b)$. Otherwise, print "Finite". To show that this is correct, we will prove that any integer greater than $ab$ is colored white. Let $x$ be an integer greater than $ab$. Consider the set $S = \{x, x - a, x - 2a, \ldots, x - (b - 1) a\}$. If, for any $y \in S$, $y$ is divisible by $b$, we are done. Otherwise, by the pigeonhole principle, there exists distinct $x - sa, x - ta \in S$ such that they have the same remainder when divided by $b$, thus $b$ divides $(x - sa) - (x - ta) = a (t - s)$. WLOG, let $s < t$. Thus, $0 < t - s$ and $b$ divides $t - s$, since $\gcd(a, b) = 1$. But $t - s \leq t < b$. However, it is not possible for $b$ to divide any integer $x$ such that $0 < x < b$, thus we arrive at a contradiction.
[ "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { while (b) { a %= b; swap(a, b); } return a; } int main() { int t; for (cin >> t; t--;) { int a, b; cin >> a >> b; if (gcd(a, b) == 1) cout << "Finite" << '\n'; else cout << "Infinite" << '\n'; } return 0; }
1245
B
Restricted RPS
Let $n$ be a positive integer. Let $a, b, c$ be nonnegative integers such that $a + b + c = n$. Alice and Bob are gonna play rock-paper-scissors $n$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $a$ times, paper $b$ times, and scissors $c$ times. Alice wins if she beats Bob in at least $\lceil \frac{n}{2} \rceil$ ($\frac{n}{2}$ rounded up to the nearest integer) hands, otherwise Alice loses. Note that in rock-paper-scissors: - rock beats scissors; - paper beats rock; - scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers $a, b, c$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win. If there are multiple answers, print any of them.
Let $A$, $B$, $C$ be the number of rocks, papers, and scissors in Bob's sequence, respectively. It is easy to see that Alice can win at most $w := \min(A, b) + \min(B, c) + \min(C, a)$ hands. So if $2w < n$, Alice can't win. Otherwise, Alice can always win. One way to construct a winning sequence of hands for Alice is as follows: Create a sequence of length $n$. For Bob's first $\min(A, b)$ rock hands, put a paper hand in the corresponding position in our sequence. For Bob's first $\min(B, c)$ paper hands, put a scissors hand in the corresponding position in our sequence. For Bob's first $\min(C, a)$ scissors hands, put a rock hand in the corresponding position in our sequence. Just fill in the other elements of the sequence by the remaining hands that Alice has. By construction, Alice uses exactly $a$ rock hands, $b$ paper hands, and $c$ scissors hands. Also, Alice beats Bob exactly $w$ times. Since $2w \ge n$, Alice wins.
[ "constructive algorithms", "dp", "greedy" ]
1,200
#include <vector> #include <string> #include <iostream> #include <cstdio> #include <algorithm> #include <stack> #include <queue> #include <deque> #include <set> #include <map> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int q; for (cin >> q; q--;) { int n; cin >> n; int a, b, c; cin >> a >> b >> c; string s; cin >> s; vector<int> count(26); for (char x : s) count[x - 'A']++; int wins = min(a, count['S' - 'A']) + min(b, count['R' - 'A']) + min(c, count['P' - 'A']); if (2 * wins < n) { cout << "NO" << '\n';continue; } cout << "YES" << '\n'; string t; for (int i = 0; i != n; ++i) { if (s[i] == 'S' && a) { t += 'R'; a--; } else if (s[i] == 'R' && b) { t += 'P'; b--; } else if (s[i] == 'P' && c) { t += 'S'; c--; } else t += '_'; } for (int i = 0; i != n; ++i) { if (t[i] != '_') continue; if (a) { t[i] = 'R'; a--; } else if (b) { t[i] = 'P'; b--; } else { t[i] = 'S'; c--; } } cout << t << '\n'; } return 0; }
1245
C
Constanze's Machine
Constanze is the smartest girl in her village but she has bad eyesight. One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto the paper. Thanks to this machine, she can finally write messages without using her glasses. However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe "uu" instead of "w", and if you pronounce 'm', it will inscribe "nn" instead of "m"! Since Constanze had bad eyesight, she was not able to realize what Akko did. The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper. The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense. But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got. But since this number can be quite large, tell me instead its remainder when divided by $10^9+7$. If there are no strings that Constanze's machine would've turned into the message I got, then print $0$.
If $s$ has any 'm' or 'w', the answer is 0. Otherwise, we can do dp. Define $dp_i$ to be the number of strings that Constanze's machine would've turned into the first $i$ characters of $s$. Then, $dp_0 = dp_1 = 1$. For $i > 1$, transition is $dp_i = dp_{i - 1} + dp_{i - 2}$ if both $s_i = s_{i - 1}$ and $s_i$ is either 'u' or 'n', and simply $dp_i = dp_{i - 1}$ otherwise. Answer is $dp_{|s|}$. Alternatively, notice that the maximum cardinality segment consisiting of $k$ letters 'u' or 'n' multiplies the answer by the $k$-th term of Fibonacci sequence. Thus, you can precalculate it and some sort of two iterators.
[ "dp" ]
1,400
// In the name of Allah. // We're nothing and you're everything. // Ya Ali! #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 + 14, mod = 1e9 + 7; int n, fib[maxn]; int main(){ ios::sync_with_stdio(0), cin.tie(0); fib[0] = fib[1] = 1; for(int i = 2; i < maxn; i++) fib[i] = (fib[i - 1] + fib[i - 2]) % mod; string s; cin >> s; n = s.size(); if(s.find('m') != -1 || s.find('w') != -1) return cout << "0\n", 0; int ans = 1; for(int i = 0, j = 0; i < n; i = j){ while(j < n && s[j] == s[i]) j++; if(s[i] == 'n' || s[i] == 'u') ans = (ll) ans * fib[j - i] % mod; } cout << ans << '\n'; }
1245
D
Shichikuji and Power Grid
Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are $n$ new cities located in Prefecture X. Cities are numbered from $1$ to $n$. City $i$ is located $x_i$ km North of the shrine and $y_i$ km East of the shrine. It is possible that $(x_i, y_i) = (x_j, y_j)$ even when $i \ne j$. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. - Building a power station in City $i$ will cost $c_i$ yen; - Making a connection between City $i$ and City $j$ will cost $k_i + k_j$ yen \textbf{per km of wire} used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City $i$ and City $j$ are connected by a wire, the wire will go through any shortest path from City $i$ to City $j$. Thus, the length of the wire if City $i$ and City $j$ are connected is $|x_i - x_j| + |y_i - y_j|$ km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.
Claim. Let $i$ be such that $c_i$ is minimum, then there is an optimal configuration with a power station in City $i$. Proof. Consider an optimal configuration. Let's say that City $u$ and City $v$ are in the same component if they are connected or City $v$ is connected to a City $w$ such that City $w$ is in the same component as City $u$. Consider the cities that are in the same component as City $i$. Exactly one of these cities have a power station, since having a power station in one of these cities is enough to provide electricity to all of them. Let City $j$ be the one with a power station. If $i = j$, then we are done. Otherwise, there are three cases: $c_i < c_j$, $c_i = c_j$, $c_i > c_j$. The first case leads to a contradiction since having a power station in City $i$ would be more optimal. The third case also leads to a contradiction since $c_i$ is minimum. For the remaining case, having a power station in City $i$ would be just as optimal. Let $i$ be such that $c_i$ is minimum. Build a power station in City $i$. For $j \neq i$, define $C_j := min(c_j, (k_i + k_j) \cdot D(i, j))$ where $D(i, j)$ is the manhattan distance between City $i$ and City $j$. Notice that the problem has been reduced to a similar problem, except that there is one less city, and $c$ values have been changed to the corresponding $C$ values. Thus, we can keep reducing until there are no cities left. Alternatively, you can think of it the following way. Let's call a connection between City $u$ and City $v$, an undirected edge $(u, v)$ with the weight $(k_u + k_v) \cdot D(u, v)$. Create a dummy City $0$ and connect each City $u$ to it with an edge $(0, u)$ with the weight $c_u$. The problem now is to find a minimal spanning tree of this graph. Prim's algorithm can do this in $O(n^2)$.
[ "dsu", "graphs", "greedy", "shortest paths", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) int main(){ int n; scanf("%d", &n); vector<int> x(n), y(n); forn(i, n) scanf("%d%d", &x[i], &y[i]); vector<int> c(n), k(n); forn(i, n) scanf("%d", &c[i]); forn(i, n) scanf("%d", &k[i]); ++n; vector<int> p(n, -1); vector<int> d(n, int(1e9)); vector<bool> used(n); forn(i, n - 1){ d[i] = c[i]; p[i] = n - 1; } used[n - 1] = true; long long ans = 0; vector<int> vv; vector<pair<int, int>> ee; forn(_, n - 1){ int v = -1; forn(i, n) if (!used[i] && (v == -1 || d[v] > d[i])) v = i; if (p[v] == n - 1) vv.push_back(v + 1); else ee.push_back(make_pair(v + 1, p[v] + 1)); ans += d[v]; used[v] = true; forn(i, n) if (!used[i]){ long long dist = (k[v] + k[i]) * 1ll * (abs(x[v] - x[i]) + abs(y[v] - y[i])); if (dist < d[i]){ d[i] = dist; p[i] = v; } } } printf("%lld\n", ans); printf("%d\n", int(vv.size())); for (auto it : vv) printf("%d ", it); puts(""); printf("%d\n", int(ee.size())); for (auto it : ee) printf("%d %d\n", it.first, it.second); }
1245
E
Hyakugoku and Ladders
Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snakes, so there are only ladders left now. The game is played on a $10 \times 10$ board as follows: - At the beginning of the game, the player is at the bottom left square. - The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends. - The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path. - During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is $r$. If the Goal is less than $r$ squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly $r$ squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player \textbf{chooses whether or not to climb up} that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn. - Some squares have a ladder in them. Ladders are only placed vertically — each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the square containing the top of the ladder also contains the bottom of another ladder, she is not allowed to use that second ladder. - The numbers on the faces of the dice are 1, 2, 3, 4, 5, and 6, with each number having the same probability of being shown. Please note that: - it is possible for ladders to overlap, but the player cannot switch to the other ladder while in the middle of climbing the first one; - it is possible for ladders to go straight to the top row, but not any higher; - it is possible for two ladders to lead to the same tile; - it is possible for a ladder to lead to a tile that also has a ladder, but the player will not be able to use that second ladder if she uses the first one; - the player can only climb up ladders, not climb down. Hyakugoku wants to finish the game as soon as possible. Thus, on each turn she chooses whether to climb the ladder or not optimally. Help her to determine the minimum expected number of turns the game will take.
To make implementation easier, flatten the board into an array $a$ such that the $i$-th tile on the path is $a_i$. Define a function $f$ as follows: $f(i) = i$ if $a_i$ has no ladder, otherwise $f(i) = j$ where $j$ is such that the ladder from $a_i$ leads to $a_j$. Then, do dp. Define $dp_i$ to be the minimum expected number of turns before the game ends when the player is at $a_i$. Then, $dp_{100} = 0$ since $a_{100}$ is the Goal. Next, use the formula $dp_i = 1 + \sum_{r = 1}^{6} \frac{1}{6} \cdot \min(dp_{g(i, r)}, dp_{f(g(i, r))})$ where $g(i, r) = i + r$ if $i + r \leq 100$ and $g(i, r) = i$ otherwise. Thus, for $95 \leq i \leq 99$, transition should be $dp_i = \frac{6}{100 - i} \cdot \left( 1 + \sum_{r = 1}^{100 - i} \frac{1}{6} \cdot \min(dp_{i + r}, dp_{f(i + r)}) \right)$. And for $i < 95$, transition is the same as the formula. Answer is $dp_1$. Alternatively, instead of doing dp, we can use numerical methods. Initialize $\textrm{expected}_{100} = 0$ and $\textrm{expected}_1 = \textrm{expected}_2 = \cdots = \textrm{expected}_{99} = 1$. Then, repeat the following several times: from $i=99$ to $i=1$, assign $1 + \sum_{r = 1}^{6} \frac{1}{6} \cdot \min(\textrm{expected}_{g(i, r)}, \textrm{expected}_{f(g(i, r))})$ to $\textrm{expected}_i$. After each iteration, $\textrm{expected}_1$ will get closer to the answer. For this problem, 1000 iterations is more than enough to get AC using this method.
[ "dp", "probabilities", "shortest paths" ]
2,300
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int grid[10][10]; for (int i = 0; i != 10; ++i) for (int j = 0; j != 10; ++j) cin >> grid[i][j]; int flat[10][10]; for (int i = 0; i != 10; ++i) for (int j = 0; j != 10; ++j) flat[i][j] = (9 - i) * 10 + ((i & 1) ? j : 9 - j); int d = 1; int x = 9; int y = 0; int arr[100]; for (int i = 0; i != 100; ++i) { arr[i] = flat[x - grid[x][y]][y]; if (y + d == -1 || y + d == 10) { d *= -1; x--; } else y += d; } double dp[100]; dp[99] = 0; for (int i = 98; i >= 0; --i) { dp[i] = 1; int c = 6; for (int r = 1; r <= 6; ++r) { if (i + r >= 100) continue; dp[i] += min(dp[i + r], dp[arr[i + r]]) / 6; c--; } dp[i] = 6 * dp[i] / (6 - c); } cout << setprecision(10) << fixed << dp[0] << '\n'; return 0; }
1245
F
Daniel and Spring Cleaning
While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $1 + 3$ using the calculator, he gets $2$ instead of $4$. But when he tries computing $1 + 4$, he gets the correct answer, $5$. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders! So, when he tries to compute the sum $a + b$ using the calculator, he instead gets the xorsum $a \oplus b$ (read the definition by the link: https://en.wikipedia.org/wiki/Exclusive_or). As he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers $l$ and $r$, how many pairs of integers $(a, b)$ satisfy the following conditions: $$a + b = a \oplus b$$ $$l \leq a \leq r$$ $$l \leq b \leq r$$ However, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked.
Claim. Let $x$, $y$ be nonnegative integers. If $x + y = x \oplus y$, then $x * y = 0$, where $x * y$ is the bitwise AND of $x$ and $y$. Proof. Recall that bitwise XOR is just addition in base two without carry. So if addition is to be equal to addition in base two without carry, then there must be no carry when added in base two, which is what we wanted. Define a function $f$ as follows: let $l$ and $r$ be nonnegative integers, then $f(l, r)$ should be the number of pairs of integers $(x, y)$ such that the following conditions are satisfied: $l \leq x < r$ $l \leq y < r$ $x + y = x \oplus y$ Notice that $f(0, r) = 2r - 1 + f(1, r)$. Claim. Let $l$ and $r$ be positive integers. Then, $f(2l, 2r) = 3 \cdot f(l, r)$. Proof. Let $x$, $y$ be positive integers. Suppose we want the following conditions to be satisfied: $2l \leq x < 2r$ $2l \leq y < 2r$ $x + y = x \oplus y$ What if $l$ and $r$ are not both even? Define a function $g$ as follows: let $x$ and $n$ be nonnegative integers, then $g(x, n)$ should be the number of integers $y$ such that the following conditions are satisfied: $0 \leq y < n$ $x + y = x \oplus y$ Now all that remains is to implement $g$ efficiently. Define a function $\textrm{LSB}$ as follows: let $n$ be a positive integer, then $\textrm{LSB}(n)$ should be the least significant 1-bit of $n$. Next, define a function $h$ as follows: let $x$ and $n$ be positive integers, then $h(x, n)$ should be the number of integers $y$ such that the following conditions are satisfied: $n - \textrm{LSB}(n) \leq y < n$ $x + y = x \oplus y$
[ "bitmasks", "brute force", "combinatorics", "dp" ]
2,300
#include<bits/stdc++.h> using namespace std; int f(int a, int b) { int ret = 0; int zeroes = 0; for (int i = 1; i <= b; i <<= 1) { if (b & i) { b ^= i; if (!(a & b)) ret += 1 << zeroes; } if (!(a & i)) zeroes++; } return ret; } long long rec(int a, int b) { if (a == b) return 0; if (a == 0) return 2 * b - 1 + rec(1, b); long long ret = 0; if (a & 1) { ret += 2 * (f(a, b) - f(a, a)); a++; } if (b & 1) { ret += 2 * (f(b - 1, b) - f(b - 1, a)); b--; } return ret + 3 * rec(a / 2, b / 2); } int main() { int t; for (cin >> t; t--;) { int a, b; cin >> a >> b; cout << rec(a, b + 1) << '\n'; } return 0; }
1246
F
Cursor Distance
There is a string $s$ of lowercase English letters. A cursor is positioned on one of the characters. The cursor can be moved with the following operation: choose a letter $c$ and a direction (left or right). The cursor is then moved to the closest occurence of $c$ in the chosen direction. If there is no letter $c$ in that direction, the cursor stays in place. For example, if $s = \mathtt{abaab}$ with the cursor on the second character ($\mathtt{a[b]aab}$), then: - moving to the closest letter $\mathtt{a}$ to the left places the cursor on the first character ($\mathtt{[a]baab}$); - moving to the closest letter $\mathtt{a}$ to the right places the cursor the third character ($\mathtt{ab[a]ab}$); - moving to the closest letter $\mathtt{b}$ to the right places the cursor on the fifth character ($\mathtt{abaa[b]}$); - any other operation leaves the cursor in place. Let $\mathrm{dist}(i, j)$ be the smallest number of operations needed to move the cursor from the $i$-th character to the $j$-th character. Compute $\displaystyle \sum_{i = 1}^n \sum_{j = 1}^n \mathrm{dist}(i, j)$.
Again, it's easier to solve the problem backwards. For a character $s_i$, from which characters $s_j$ can we reach $s_i$ in one step? Clearly, $s_j$ should lie in a subsegment of $s$ bounded by adjacent occurences of $s_i$ (inclusive), or by the borders of $s$. Let's denote this subsegment for $s_i$ by $[L_i, R_i)$ (we will use half-open intervals for convenience, as should you). Which characters can be reached from $s_i$ in $k$ reverse steps? We can see that these characters also form a subsegment, let's denote it $[L_i^{(k)}, R_i^{(k)})$. We have that $[L_i^{(0)}, R_i^{(0)}) = [i, i + 1)$, and $[L_i^{(k)}, R_i^{(k)}) = \displaystyle \cup_{j \in [L_i^{(k - 1)}, R_i^{(k - 1)})} [L_j, R_j)$. Note that having values of $[L_i^{(k)}, R_i^{(k)})$ can be used to directly compute the answer, for example, with a formula $\sum_{i = 1}^n \sum_{k = 0}^{n - 1} (n - (R_i^{(k)} - L_i^{(k)}))$. This formula is correct since the expression inside the brackets is the number of characters not reachable from $i$ in $k$ reverse steps, hence a position $j$ reachable in exactly $d$ steps will be accounted for $d$ times. Simplifying a bit, we arrive at the formula $n^3 - \sum_{i = 1}^n \sum_{k = 0}^{n - 1} (R_i^{(k)} - L_i^{(k)})$. Values of $[L_i^{(k)}, R_i^{(k)})$ can be computed in $O(n^2)$ individually by applying the above recurrence and using a sparse table, but that is still way too slow. It's tempting to try and use binary lifting, but as $k$ grows, evolution of $L_i^{(k)}$ and $R_i^{(k)}$ is mutually dependent, and we can't store an $n^2$-sized table. They do, however, become independent at some point, namely, when the range $[L_i^{(k)}, R_i^{(k)})$ contains all distinct letters present in $s$. Indeed, to compute $R_i^{(k + 1)}$ we simply need to take the largest $R_j$, where $j$ ranges over the last occurences of letters a, $\ldots$, z before $R_i^{(k)}$. Slightly more generally, we can treat the evolution of $L_i^{(k)}$ and $R_i^{(k)}$ independently in a range of $k$'s where the number of distinct characters in the segment doesn't change. And it can only change at most $\alpha = 26$ times... Time to put this together. For each $i$, we will store $k_i$ - the number of expansions we've applied to $[L_i^{(k)}, R_i^{(k)})$, as well as the range's endpoints themselves. We will iterate over the parameter $t$ - the number of distinct characters in ranges we're going to expand now. For each right endpoint $r$, let's find $f_r(r)$ as the largest $R_j$ over $t$ closest distinct letters to the left of $r$; define $f_l(l)$ similarly. Additionally, compute binary lifts $f^{2^y}_r(r)$, $f^{2^y}_l(l)$, as well as the sums of $r$ and $l$ visited by each binary lift. Now, for each $i$ we use binary lifting to find the largest number of iterations to apply to $[L_i^{(k)}, R_i^{(k)})$ so that the number of distinct characters in the range stays equal to $t$. Doing this, we can update $k_i$ and endpoints of $[L_i^{(k)}, R_i^{(k)})$ accordingly, as well as add a part of $\sum_{i = 1}^n \sum_{k = 0}^{n - 1} (R_i^{(k)} - L_i^{(k)})$ to the total. Thus, going into the next phase with $t + 1$, we will have all necessary values up-to-date. How fast does this work? For every $t = 1, \ldots, \alpha = 26$, we'll need $O(n \log n)$ work to construct binary lifts and update everything. The total complexity is thus $O(\alpha n \log n)$.
[]
3,500
null
1248
A
Integer Points
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $n$ distinct lines, given by equations $y = x + p_i$ for some distinct $p_1, p_2, \ldots, p_n$. Then JLS drew on the same paper sheet $m$ distinct lines given by equations $y = -x + q_i$ for some distinct $q_1, q_2, \ldots, q_m$. DLS and JLS are interested in counting how many line pairs have \textbf{integer} intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.
Consider two lines $y = x + p$ and $y = -x + q$: $\begin{cases} y = x + p \\ y = -x + q \end{cases} \Rightarrow \begin{cases} 2y = p + q \\ y = -x + q \end{cases} \Rightarrow \begin{cases} y = \frac{p + q}{2} \\ y = -x + q \end{cases} \Rightarrow \begin{cases} y = \frac{p + q}{2} \\ x = \frac{q - p}{2} \end{cases}$ It's clear that they will have integral intersection point iff $p$ and $q$ have the same parity. Let's find $p_0$ and $p_1$ - number of even and odd $p_i$ respectively. Moreover let's find $q_0$ and $q_1$ for $q_i$. Now answer is $p_0 \cdot q_0 + p_1 \cdot q_1$. Complexity: $O(n + m)$. Pay attention that answer does not fit in 32-bit data type.
[ "geometry", "math" ]
1,000
null
1248
B
Grow The Tree
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $(0, 0)$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $OX$ or $OY$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification. Alexey wants to make a polyline in such a way that its end is as far as possible from $(0, 0)$. Please help him to grow the tree this way. Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.
At first, let's do some maths. Consider having an expression $a^2 + b^2$ which we have to maximize, while $a + b = C$, where $C$ is some constant. Let's proof that the maximum is achieved when $a$ or $b$ is maximum possible. At first let $a$ or $b$ be about the same, while $a \geq b$. Let's see what happens when we add $1$ to $a$ and subtract $1$ from $b$. $(a + 1)^2 + (b - 1)^2 = a^2 + 2a + 1 + b^2 - 2b + 1 = a^2 + b^2 + 2(a - b + 1)$. Since $a \geq b$, this expression is greater than $a^2 + b^2$. It means that we should maximize $a$ (or $b$, doing the same steps) in order to achieve the maximum of $a^2 + b^2$. Notice that we should always grow the tree in one direction. For definiteness, let horizontal sticks go from left to right and vertical from down to top. Now, answer equals to square of the sum of lengths of horizontal sticks plus square of the sum of lengths of vertical sticks. As we proved earlier, to maximize this expression, we should maximize one of the numbers under the squares. Let's sort sticks by order and orient the half (and medium element if there's an odd amount of sticks) with the greater length vertically, and the other half horizontally. Work time: $O(n \log n)$
[ "greedy", "math", "sortings" ]
900
null
1248
D1
The World Is Just a Programming Task (Easy Version)
This is an easier version of the problem. In this version, $n \le 500$. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence. To digress from his problems, Vasya decided to select two positions of the string (\textbf{not necessarily distinct}) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him. We remind that bracket sequence $s$ is called correct if: - $s$ is empty; - $s$ is equal to "($t$)", where $t$ is correct bracket sequence; - $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. The cyclical shift of the string $s$ of length $n$ by $k$ ($0 \leq k < n$) is a string formed by a concatenation of the last $k$ symbols of the string $s$ with the first $n - k$ symbols of string $s$. For example, the cyclical shift of string "(())()" by $2$ equals "()(())". Cyclical shifts $i$ and $j$ are considered different, if $i \ne j$.
Note first that the number of opening brackets must be equal to the number of closing brackets, otherwise the answer is always $0$. Note that the answer to the question about the number of cyclic shifts, which are correct bracket sequences, equals the number of minimal prefix balances. For example, for string )(()))()((, the array of prefix balances is [-1, 0, 1, 0, -1, -2, -1, -2, -1, 0], and the number of cyclic shifts, $2$ - the number of minimums in it ($-2$). Now we have a solution of complexuty $\mathcal{O}(n^3)$: let's iterate over all pairs of symbols that can be swapped. Let's do this and find the number of cyclic shifts that are correct bracket sequences according to the algorithm described above.
[ "brute force", "dp", "greedy", "implementation" ]
2,000
null
1249
A
Yet Another Dividing into Teams
You are a coach of a group consisting of $n$ students. The $i$-th student has programming skill $a_i$. \textbf{All students have distinct programming skills}. You want to divide them into teams in such a way that: - No two students $i$ and $j$ such that $|a_i - a_j| = 1$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $1$); - the number of teams is the minimum possible. You have to answer $q$ independent queries.
The answer is always $1$ or $2$. Why it is so? Because if there is no such pair $i, j$ among all students that $|a_i - a_j| = 1$ then we can take all students into one team. Otherwise, we can divide them into two teams by their programming skill parity.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> a(n); for (int j = 0; j < n; ++j) { cin >> a[j]; } bool ok = true; for (int p1 = 0; p1 < n; ++p1) { for (int p2 = 0; p2 < p1; ++p2) { ok &= abs(a[p1] - a[p2]) != 1; } } cout << 2 - ok << endl; } return 0; }
1249
B1
Books Exchange (easy version)
\textbf{The only difference between easy and hard versions is constraints}. There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed. For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on. Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$. Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids: - after the $1$-st day it will belong to the $5$-th kid, - after the $2$-nd day it will belong to the $3$-rd kid, - after the $3$-rd day it will belong to the $2$-nd kid, - after the $4$-th day it will belong to the $1$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day. You have to answer $q$ independent queries.
In this problem you just need to implement what is written in the problem statement. For the kid $i$ the following pseudocode will calculate the answer (indices of the array $p$ and its values are $0$-indexed):
[ "dsu", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> p(n); for (int j = 0; j < n; ++j) { cin >> p[j]; --p[j]; } for (int j = 0; j < n; ++j) { int cnt = 0; int k = j; do { ++cnt; k = p[k]; } while (k != j); cout << cnt << " "; } cout << endl; } return 0; }
1249
B2
Books Exchange (hard version)
\textbf{The only difference between easy and hard versions is constraints}. There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed. For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on. Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$. Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids: - after the $1$-st day it will belong to the $5$-th kid, - after the $2$-nd day it will belong to the $3$-rd kid, - after the $3$-rd day it will belong to the $2$-nd kid, - after the $4$-th day it will belong to the $1$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day. You have to answer $q$ independent queries.
In this problem, we can notice that when we calculate the answer for the kid $i$, we also calculate the answer for kids $p_i$, $p_{p_i}$ and so on. So we can a little bit modify the pseudocode from the easy version to calculate answers faster: And of course, we don't need to run this while for all elements for which we already calculated the answer. Total time complexity is $O(n)$ because you'll process each element exactly once.
[ "dfs and similar", "dsu", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> p(n); for (int j = 0; j < n; ++j) { cin >> p[j]; --p[j]; } vector<int> used(n); vector<int> ans(n); for (int j = 0; j < n; ++j) { if (!used[j]) { vector<int> cur; while (!used[j]) { cur.push_back(j); used[j] = true; j = p[j]; } for (auto el : cur) ans[el] = cur.size(); } } for (int j = 0; j < n; ++j) cout << ans[j] << " "; cout << endl; } return 0; }
1249
C1
Good Numbers (easy version)
\textbf{The only difference between easy and hard versions is the maximum value of $n$}. You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$. The positive integer is called good if it can be represented as a sum of \textbf{distinct} powers of $3$ (i.e. no duplicates of powers of $3$ are allowed). For example: - $30$ is a good number: $30 = 3^3 + 3^1$, - $1$ is a good number: $1 = 3^0$, - $12$ is a good number: $12 = 3^2 + 3^1$, - but $2$ is \textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$), - $19$ is \textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid), - $20$ is also \textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid). Note, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of \textbf{distinct} powers of $3$. For the given positive integer $n$ find such smallest $m$ ($n \le m$) that $m$ is a good number. You have to answer $q$ independent queries.
As you can see from the example, the maximum answer doesn't exceed $2 \cdot 10^4$. So we can run some precalculation before all queries, which will find all good numbers less than $2 \cdot 10^4$. The number is good if it has no $2$ in the ternary numeral system. When you read the next query, you can increase $n$ until you find some precalculated good number. Time complexity is $O(nq + n \log n)$. You also can implement the solution which doesn't use any precalculations and just increase $n$ each time in each query and checks if the number is good inside this loop. Then time complexity will be $O(n q \log n)$.
[ "brute force", "greedy", "implementation" ]
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 q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; while (true) { bool ok = true; int cur = n; while (cur > 0) { if (ok && cur % 3 == 2) ok = false; cur /= 3; } if (ok) break; ++n; } cout << n << endl; } return 0; }
1249
C2
Good Numbers (hard version)
\textbf{The only difference between easy and hard versions is the maximum value of $n$}. You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$. The positive integer is called good if it can be represented as a sum of \textbf{distinct} powers of $3$ (i.e. no duplicates of powers of $3$ are allowed). For example: - $30$ is a good number: $30 = 3^3 + 3^1$, - $1$ is a good number: $1 = 3^0$, - $12$ is a good number: $12 = 3^2 + 3^1$, - but $2$ is \textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$), - $19$ is \textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid), - $20$ is also \textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid). Note, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of \textbf{distinct} powers of $3$. For the given positive integer $n$ find such smallest $m$ ($n \le m$) that $m$ is a good number. You have to answer $q$ independent queries.
Let's see the representation of $n$ in the ternary numeral system. If it has no twos, then the answer is $n$. Otherwise, let $pos_2$ be the maximum position of $2$ in the ternary representation. Then we obviously need to replace it with $0$ and add some power of three to the right from it. Let $pos_0$ be the leftmost position of $0$ to the right from $pos_2$. We can add $3^{pos_0}$ and replace all digits from the position $pos_0 - 1$ to the position $0$ with $0$. Then the resulting number will be good because we replaced all twos with zeros and the minimum because, in fact, we added only one power of three and this power is the minimum one we could add. Time complexity is $O(\log n)$ per query.
[ "binary search", "greedy", "math", "meet-in-the-middle" ]
1,500
#include <bits/stdc++.h> using namespace std; const long long INF64 = 1e18; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { long long n; cin >> n; vector<int> vals; int pos2 = -1; while (n > 0) { vals.push_back(n % 3); if (vals.back() == 2) pos2 = int(vals.size()) - 1; n /= 3; } vals.push_back(0); if (pos2 != -1) { int pos0 = find(vals.begin() + pos2, vals.end(), 0) - vals.begin(); vals[pos0] = 1; for (int i = pos0 - 1; i >= 0; --i) { vals[i] = 0; } } long long ans = 0; long long pw = 1; for (int i = 0; i < int(vals.size()); ++i) { ans += pw * vals[i]; pw *= 3; } if (vals.back() == 1) ans = pw / 3; cout << ans << endl; } return 0; }
1249
D1
Too Many Segments (easy version)
\textbf{The only difference between easy and hard versions is constraints}. You are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \le r_i$) and it covers all integer points $j$ such that $l_i \le j \le r_i$. The integer point is called \textbf{bad} if it is covered by \textbf{strictly more} than $k$ segments. Your task is to remove the minimum number of segments so that there are no \textbf{bad} points at all.
In this problem, the following greedy solution works: let's find the leftmost point covered by more than $k$ segments. We should fix it somehow. How to do it? Let's find some segment that was not removed already, it covers this point and its rightmost end is maximum possible, and remove this segment. You can implement it in any time you want, even in $O(n^3)$ naively.
[ "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 250; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<pair<int, int>> segs(n); vector<int> cnt(N); for (int i = 0; i < n; ++i) { cin >> segs[i].first >> segs[i].second; ++cnt[segs[i].first]; --cnt[segs[i].second + 1]; } for (int i = 0; i + 1 < N; ++i) { cnt[i + 1] += cnt[i]; } vector<int> ans(n); for (int i = 0; i < N; ++i) { while (cnt[i] > k) { int pos = -1; for (int p = 0; p < n; ++p) { if (!ans[p] && (segs[p].first <= i && i <= segs[p].second) && (pos == -1 || segs[p].second > segs[pos].second)) { pos = p; } } assert(pos != -1); for (int j = segs[pos].first; j <= segs[pos].second; ++j) { --cnt[j]; } ans[pos] = 1; } } cout << accumulate(ans.begin(), ans.end(), 0) << endl; for (int i = 0; i < n; ++i) { if (ans[i]) cout << i + 1 << " "; } cout << endl; return 0; }
1249
D2
Too Many Segments (hard version)
\textbf{The only difference between easy and hard versions is constraints}. You are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \le r_i$) and it covers all integer points $j$ such that $l_i \le j \le r_i$. The integer point is called \textbf{bad} if it is covered by \textbf{strictly more} than $k$ segments. Your task is to remove the minimum number of segments so that there are no \textbf{bad} points at all.
In this problem, we need to implement the same greedy solution as in the easy version, but faster. Firstly, let's calculate for each point the number of segments covering it. We can do it using standard trick with prefix sums: increase $cnt_{l_i}$, decrease $cnt_{r_i + 1}$ and build prefix sums on the array $cnt$. Let's maintain the set of segments that cover the current point, sorted by the right endpoint. We can do this with almost the same trick: append to the array $ev_{l_i}$ the index $i$ that says us that in the point $l_i$ the $i$-th segment is opened. And add to the $ev_{r_i + 1}$ the index $-i$ that says us that in the point $r_i + 1$ the $i$-th segment is closed. Note that you need to add $1$-indexed values $i$ because $+0$ and $-0$ are the same thing actually. We can change the array $cnt$ to carry the number of segments covering each point using some structure, but we don't need to do it. Let's maintain the variable $curSub$ that will say us the number of segments covering the current point that was already removed. Also, let's carry another one array $sub$ which will say us when we need to decrease the variable $curSub$. So, we calculated the array of arrays $ev$, the array $cnt$ and we can solve the problem now. For the point $i$, let's remove and add all segments we need, using the array $ev_i$ and add $sub_i$ to $curSub$. Now we know that the set of segments is valid, $curSub$ is also valid and we can fix the current point if needed. While $cnt_i - curSub > k$, let's repeat the following sequence of operations: take the segment with the maximum right border $rmax$ from the set, remove it, increase $curSub$ by one and decrease $sub_{rmax + 1}$ by one. Note that when we remove segments from the set at the beginning of the sequence of moves for the point $i$, we don't need to remove segments that we removed by fixing some previous points, and we need to pay attention to it. Time complexity: $O(n \log n)$.
[ "data structures", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 200200; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<pair<int, int>> segs(n); vector<int> cnt(N); vector<vector<int>> ev(N); for (int i = 0; i < n; ++i) { cin >> segs[i].first >> segs[i].second; ++cnt[segs[i].first]; --cnt[segs[i].second + 1]; ev[segs[i].first].push_back(i + 1); ev[segs[i].second + 1].push_back(-i - 1); } for (int i = 0; i + 1 < N; ++i) { cnt[i + 1] += cnt[i]; } vector<int> ans(n), sub(N); set<pair<int, int>> curSegs; int curSub = 0; for (int i = 0; i < N; ++i) { curSub += sub[i]; for (auto it : ev[i]) { if (it > 0) { curSegs.insert(make_pair(segs[it - 1].second, it - 1)); } else { auto iter = curSegs.find(make_pair(segs[-it - 1].second, -it - 1)); if (iter != curSegs.end()) curSegs.erase(iter); } } while (cnt[i] - curSub > k) { assert(!curSegs.empty()); int pos = curSegs.rbegin()->second; curSegs.erase(prev(curSegs.end())); ++curSub; --sub[segs[pos].second + 1]; ans[pos] = 1; } } cout << accumulate(ans.begin(), ans.end(), 0) << endl; for (int i = 0; i < n; ++i) { if (ans[i]) cout << i + 1 << " "; } cout << endl; return 0; }
1249
E
By Elevator or Stairs?
You are planning to buy an apartment in a $n$-floor building. The floors are numbered from $1$ to $n$ from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor. Let: - $a_i$ for all $i$ from $1$ to $n-1$ be the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the \textbf{stairs}; - $b_i$ for all $i$ from $1$ to $n-1$ be the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the \textbf{elevator}, also there is a value $c$ — time overhead for elevator usage (you need to wait for it, the elevator doors are too slow!). In one \textbf{move}, you can go from the floor you are staying at $x$ to any floor $y$ ($x \ne y$) in two different ways: - If you are using the stairs, just sum up the corresponding values of $a_i$. Formally, it will take $\sum\limits_{i=min(x, y)}^{max(x, y) - 1} a_i$ time units. - If you are using the elevator, just sum up $c$ and the corresponding values of $b_i$. Formally, it will take $c + \sum\limits_{i=min(x, y)}^{max(x, y) - 1} b_i$ time units. You can perform as many \textbf{moves} as you want (possibly zero). So your task is for each $i$ to determine the minimum total time it takes to reach the $i$-th floor from the $1$-st (bottom) floor.
This is easy dynamic programming problem. It is easy to understand that we don't need to go down at all (otherwise your solution will be Dijkstra's algorithm, not dynamic programming). Let $dp_{i, 0}$ be the minimum required time to reach the floor $i$ if we not in the elevator right now and $dp_{i, 1}$ be the minimum required time to reach the floor $i$ if we in the elevator right now. Initially, all values $dp$ are $+\infty$, except $dp_{1, 0} = 0$ and $dp_{1, 1} = c$. Transitions are pretty easy: $dp_{i + 1, 0} = min(dp_{i + 1, 0}, dp_{i, 0} + a_i)$ (we was not in the elevator and going to the next floor using stairs); $dp_{i + 1, 0} = min(dp_{i + 1, 0}, dp_{i, 1} + a_i)$ (we was in the elevator and going to the next floor using stairs); $dp_{i + 1, 1} = min(dp_{i + 1, 1}, dp_{i, 0} + b_i + c)$ (we was not in the elevator and going to the next floor using elevator); $dp_{i + 1, 1} = min(dp_{i + 1, 1}, dp_{i, 1} + b_i)$ (we was in the elevator and going to the next floor using elevator). The answer for the $i$-th floor is $min(dp_{i, 0}, dp_{i, 1})$. Time complexity: $O(n)$.
[ "dp", "shortest paths" ]
1,700
#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, c; cin >> n >> c; vector<int> a(n - 1), b(n - 1); for (int i = 0; i < n - 1; ++i) { cin >> a[i]; } for (int i = 0; i < n - 1; ++i) { cin >> b[i]; } vector<vector<int>> dp(n, vector<int>(2, INF)); dp[0][0] = 0, dp[0][1] = c; for (int i = 0; i < n - 1; ++i) { dp[i + 1][0] = min(dp[i + 1][0], dp[i][1] + a[i]); dp[i + 1][0] = min(dp[i + 1][0], dp[i][0] + a[i]); dp[i + 1][1] = min(dp[i + 1][1], dp[i][1] + b[i]); dp[i + 1][1] = min(dp[i + 1][1], dp[i][0] + b[i] + c); } for (int i = 0; i < n; ++i) { cout << min(dp[i][0], dp[i][1]) << " "; } cout << endl; return 0; }
1249
F
Maximum Weight Subset
You are given a tree, which consists of $n$ vertices. Recall that a tree is a connected undirected graph without cycles. \begin{center} {\small Example of a tree.} \end{center} Vertices are numbered from $1$ to $n$. All vertices have weights, the weight of the vertex $v$ is $a_v$. Recall that the distance between two vertices in the tree is the number of edges on a simple path between them. Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance $k$ or less between them in this subset.
Let's solve this problem using dynamic programming on a tree. Suppose the tree is rooted and the root of the tree is $1$. Also, let's increase $k$ to find the subset in which any pair of vertices had distance $k$ or greater instead of $k+1$ or greater. Let $dp_{v, dep}$ be the maximum total weight of the subset in the subtree of $v$ if the vertex with the minimum depth we took has depth at least $dep$. Then the answer is $dp_{1, 0}$. Firstly, let's calculate this dynamic programming for all children of $v$. Then we are ready to calculate all $dp_{v, dep}$ for all $dep$ from $0$ to $n$. Let the current depth be $dep$, then there are two cases: if $dep = 0$ then $dp_{v, dep} = a_v + \sum\limits_{to \in children(v)} dp_{to, max(0, k - dep - 1)}$. Otherwise, let's iterate over all children of $v$ and let $to$ be such child of $v$ that the vertex with the minimum depth we took is in the subtree of $to$. Then $dp_{v, dep} = max(dp_{v, dep}, dp_{to, dep - 1} + \sum\limits_{other \in children(v) \backslash \{to\}} dp_{other, max(dep - 1, k - dep - 1)}$. After we calculated all values of $dp_{v, dep}$ for the vertex $v$, we can notice that this is not what we wanted. The current value of $dp_{v, dep}$ means the maximum total weight of the subset in the subtree of $v$ if the vertex with the minimum depth we took has depth exactly $dep$. To fix this, let's push $dp_{v, dep}$ to $dp_{v, dep - 1}$ for all depths from $n$ to $1$. Time complexity: $O(n^3)$ but it can be easily optimized to $O(n^2)$ using some prefix and suffix maximums. You can ask, why this is $O(n^3)$ but not $O(n^4)$ because we iterating over all vertices, then over all possible depths, and then over children of the vertex, and again over children of the vertex. But in fact, this is $O(n^3)$ because if we change the order of multiplication, we can see that we are iterating over pairs (parent, child), then over children and possible depths, and the number of such pairs is $O(n)$, so the complexity is $O(n^3)$.
[ "dp", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) const int N = 200 + 13; const int INF = 1e9; int n, k; int a[N]; vector<int> g[N]; int dp[N][N]; int d[N]; int tmp[N]; void dfs(int v, int p = -1){ d[v] = 1; dp[v][0] = a[v]; for (auto u : g[v]) if (u != p){ dfs(u, v); int nw = max(d[v], d[u] + 1); forn(i, nw) tmp[i] = -INF; forn(i, d[v]) for (int j = max(0, k - i); j < d[u]; ++j) tmp[min(i, j + 1)] = max(tmp[min(i, j + 1)], dp[v][i] + dp[u][j]); forn(i, d[u]) tmp[i + 1] = max(tmp[i + 1], dp[u][i]); forn(i, d[v]) dp[v][i] = max(dp[v][i], tmp[i]); for (int i = d[v]; i < nw; ++i) dp[v][i] = tmp[i]; d[v] = nw; for (int i = d[v] - 1; i > 0; --i) dp[v][i - 1] = max(dp[v][i - 1], dp[v][i]); } } int main(){ scanf("%d%d", &n, &k); forn(i, n) scanf("%d", &a[i]); forn(i, n - 1){ int v, u; scanf("%d%d", &v, &u); --v, --u; g[v].push_back(u); g[u].push_back(v); } dfs(0); printf("%d\n", dp[0][0]); }
1251
A
Broken Keyboard
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $26$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $s$ appeared on the screen. When Polycarp presses a button with character $c$, one of the following events happened: - if the button was working correctly, a character $c$ appeared at the end of the string Polycarp was typing; - if the button was malfunctioning, \textbf{two} characters $c$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $\rightarrow$ abb $\rightarrow$ abba $\rightarrow$ abbac $\rightarrow$ abbaca $\rightarrow$ abbacabb $\rightarrow$ abbacabba. You are given a string $s$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning). You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.
If a key malfunctions, each sequence of presses of this key gives a string with even number of characters. So, if there is a substring consisting of odd number of equal characters $c$, such that it cannot be extended to the left or to the right without adding other characters, then it could not be produced by presses of button $c$ if $c$ was malfunctioning. The only thing that's left is to find all maximal by inclusion substrings consisting of the same character.
[ "brute force", "strings", "two pointers" ]
1,000
#include <bits/stdc++.h> using namespace std; bool ans[26]; void solve() { string s; cin >> s; memset(ans, 0, sizeof(ans)); for (int i = 0; i < s.size(); i++) { int j = i; while (j + 1 < s.size() && s[j + 1] == s[i]) j++; if ((j - i) % 2 == 0) ans[s[i] - 'a'] = true; i = j; } for (int i = 0; i < 26; i++) if (ans[i]) cout << char('a' + i); cout << endl; } int main() { int q; cin >> q; while (q--) solve(); }
1251
B
Binary Palindromes
A palindrome is a string $t$ which reads the same backward as forward (formally, $t[i] = t[|t| + 1 - i]$ for all $i \in [1, |t|]$). Here $|t|$ denotes the length of a string $t$. For example, the strings 010, 1001 and 0 are palindromes. You have $n$ binary strings $s_1, s_2, \dots, s_n$ (each $s_i$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions. Formally, in one move you: - choose four integer numbers $x, a, y, b$ such that $1 \le x, y \le n$ and $1 \le a \le |s_x|$ and $1 \le b \le |s_y|$ (where $x$ and $y$ are string indices and $a$ and $b$ are positions in strings $s_x$ and $s_y$ respectively), - swap (exchange) the characters $s_x[a]$ and $s_y[b]$. What is the maximum number of strings you can make palindromic simultaneously?
Let's make several observations. At first, note that the lengths of the strings doesn't change. At second, note that if the string has even length then being palindromic is the same as having even number of zeroes and even number of ones. But if the string has odd length, then it always is palindromic. So the question is how to fix "bad" strings with even length but with odd number of zeroes and ones. If we have at least one string with odd length, then you can trade between "bad" string and "odd" string either zero to one or one to zero, fixing the "bad" string. Otherwise you can fix two "bad" strings swapping appropriate characters. In result, we can either make all strings palindromic or all strings except one in case of absence of "odd" strings and having odd number of "bad" strings.
[ "greedy", "strings" ]
1,400
fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() var (odd, evenGood, evenBad) = listOf(0, 0, 0) for (i in 1..n) { val s = readLine()!! when { s.length % 2 == 1 -> odd++ s.count { it == '0' } % 2 == 0 -> evenGood++ else -> evenBad++ } } println(n - if (odd == 0 && evenBad % 2 == 1) 1 else 0) } }
1251
C
Minimize The Integer
You are given a huge integer $a$ consisting of $n$ digits ($n$ is between $1$ and $3 \cdot 10^5$, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $2$). For example, if $a = 032867235$ you can get the following integers in a single operation: - $302867235$ if you swap the first and the second digits; - $023867235$ if you swap the second and the third digits; - $032876235$ if you swap the fifth and the sixth digits; - $032862735$ if you swap the sixth and the seventh digits; - $032867325$ if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions $2$ and $4$ because the positions are not adjacent. Also, you can't swap digits on positions $3$ and $4$ because the digits have the same parity. You can perform any number (possibly, zero) of such operations. Find the minimum integer you can obtain. \textbf{Note that the resulting integer also may contain leading zeros.}
Let's consider two sequences of digits: $e_1, e_2, \dots , e_k$ and $o_1, o_2, \dots , o_m$, there $e_1$ is the first even digit in $a$, $e_2$ is the second even digit and so on and $o_1$ is the first odd digit in $a$, $o_2$ is the second odd digit and so on. Since you can't swap digits of same parity, the sequence $e$ of even digits of $a$ never changed. Sequence $o$ of odd digits of $a$ also never changed. So the first digit in the answer will be equal to $e_1$ or to $o_1$. And since we have to minimize the answer, we have to chose the $min(e_1, o_1)$ as the first digit in answer and them delete it from the corresponding sequence (in this way sequence $e$ turn into $e_2, e_3, \dots , e_k$ or sequence $o$ turn into $o_2, o_3, \dots , o_m$). Second, third and followings digits need to choose in the same way.
[ "greedy", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; int t; string a; int main() { cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> a; string s[2]; for(auto x : a) s[int(x - '0') & 1] += x; reverse(s[0].begin(), s[0].end()); reverse(s[1].begin(), s[1].end()); string res = ""; while(!(s[0].empty() && s[1].empty())){ if(s[0].empty()){ res += s[1].back(); s[1].pop_back(); continue; } if(s[1].empty()){ res += s[0].back(); s[0].pop_back(); continue; } if(s[0].back() < s[1].back()){ res += s[0].back(); s[0].pop_back(); } else{ res += s[1].back(); s[1].pop_back(); } } cout << res << endl; } return 0; }
1251
D
Salary Changing
You are the head of a large enterprise. $n$ people work at you, and $n$ is odd (i. e. $n$ is not divisible by $2$). You have to distribute salaries to your employees. Initially, you have $s$ dollars for it, and the $i$-th employee should get a salary from $l_i$ to $r_i$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible. To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: - the median of the sequence $[5, 1, 10, 17, 6]$ is $6$, - the median of the sequence $[1, 2, 1]$ is $1$. It is guaranteed that you have enough money to pay the minimum salary, i.e $l_1 + l_2 + \dots + l_n \le s$. \textbf{Note that you don't have to spend all your $s$ dollars on salaries.} You have to answer $t$ test cases.
Let $f(mid)$ be equal minimum amount of money to obtain the median salary at least $mid$. We'll solve this problem by binary search by $mid$. Suppose the have to calculate the minimum amount of money for obtaining median salary at least $mid$. Let's divide all salaries into three groups: $r_i < mid$; $mid \le l_i$; $l_i < mid \le r_i$. In order to the median salary be at least $mid$ there must be at least $\frac{n+1}{2}$ salaries greater than or equal to $mid$. Let's denote the number of such salaries as $cnt$. Note that salaries of the first group can't increment the value of $cnt$, so it's beneficial for us to pay the minimum salary for this group. Salaries if second group always increment the value of $cnt$, so it's also beneficial for us to pay the minimum salary. The salaries from the third group are more interesting. For each salary $[l_i, r_i]$ in this group we can pay $mid$ and increment $cnt$, or we can pay $l_i$ and don't increase $cnt$. The value of $cnt$ should be increased by $rem = max(0, \frac{n+1}{2} - cnt)$. So, if the size of the third group is less than $rem$ than we can't obtain the median salary $mid$. Otherwise, we can define how many salaries we can take with value $l_i$ and chose the minimal ones.
[ "binary search", "greedy", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; const int INF = int(1e9) + 100; int t; int n; long long s; pair<int, int> p[N]; bool ok(int mid){ long long sum = 0; int cnt = 0; vector <int> v; for(int i = 0; i < n; ++i){ if(p[i].second < mid) sum += p[i].first; else if(p[i].first >= mid){ sum += p[i].first; ++cnt; } else v.push_back(p[i].first); } assert(is_sorted(v.begin(), v.end())); int need = max(0, (n + 1) / 2 - cnt); if(need > v.size()) return false; for(int i = 0; i < v.size(); ++i){ if(i < v.size() - need) sum += v[i]; else sum += mid; } return sum <= s; } int main() { scanf("%d", &t); for(int tc = 0; tc < t; ++tc){ scanf("%d %lld", &n, &s); for(int i = 0; i < n; ++i) scanf("%d %d", &p[i].first, &p[i].second); sort(p, p + n); int lf = 1, rg = INF; ///WA -> 10^9 while(rg - lf > 1){ int mid = (lf + rg) / 2; if(ok(mid)) lf = mid; else rg = mid; } printf("%d\n", lf); } return 0; }
1251
E2
Voting (Hard Version)
\textbf{The only difference between easy and hard versions is constraints.} Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you. There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free. Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$. Calculate the minimum number of coins you have to spend so that everyone votes for you.
Denote the number of voters with $m_i = x$ as $c_x$. Also denote $pref_x = \sum\limits_{i=0}^{x-1} c_x$, i.e. $pref_x$ is equal to number of voters with $m_i < x$. Let's group all voters by value $m_i$. We'll consider all these group in decreasing value of $m_i$. Assume that now we consider group with $m_i = x$. Then there are two cases: if $pref_{x} + cnt \ge x$ then all these voters will vote for you for free. $cnt$ is equal to the number of votes bought in previous steps; if $pref_{x} + cnt < x$ then we have to buy $x - pref_{s} - cnt$ additional votes. Moreover the value $m_i$ of this "bought" voter must be greater than or equal to $x$. Since these voters indistinguishable we have to buy $x - pref_{s} - cnt$ cheapest voter (with a minimal value of $p_i$). So, all we have to do it maintain values $p_i$ not yet bought voters in some data structure (for example multiset in C++).
[ "binary search", "data structures", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int t, n; vector <int> v[N]; int main() { int t; scanf("%d", &t); for(int tc = 0; tc < t; ++tc){ scanf("%d", &n); for(int i = 0; i < n; ++i) v[i].clear(); for(int i = 0; i < n; ++i){ int x, s; scanf("%d %d", &x, &s); v[x].push_back(s); } multiset <int > q; long long res = 0; int pref = n; int cnt = 0; for(int i = n - 1; i >= 0; --i){ pref -= v[i].size(); int need = i - pref; for(auto x : v[i]) q.insert(x); while(cnt < need){ ++cnt; res += *q.begin(); q.erase(q.begin()); } } printf("%lld\n", res); } return 0; }
1251
F
Red-White Fence
Polycarp wants to build a fence near his house. He has $n$ white boards and $k$ red boards he can use to build it. Each board is characterised by its length, which is an integer. A good fence should consist of \textbf{exactly one} red board and several (possibly zero) white boards. The red board should be the longest one in the fence (every white board used in the fence should be strictly shorter), and the sequence of lengths of boards should be ascending before the red board and descending after it. Formally, if $m$ boards are used, and their lengths are $l_1$, $l_2$, ..., $l_m$ in the order they are placed in the fence, from left to right (let's call this array $[l_1, l_2, \dots, l_m]$ the array of lengths), the following conditions should hold: - there should be exactly one red board in the fence (let its index be $j$); - for every $i \in [1, j - 1]$ $l_i < l_{i + 1}$; - for every $i \in [j, m - 1]$ $l_i > l_{i + 1}$. When Polycarp will build his fence, he will place all boards from left to right on the same height of $0$, without any gaps, so these boards compose a polygon: \begin{center} {\small Example: a fence with $[3, 5, 4, 2, 1]$ as the array of lengths. The second board is red. The perimeter of the fence is $20$.} \end{center} Polycarp is interested in fences of some special perimeters. He has $q$ \textbf{even} integers he really likes (these integers are $Q_1$, $Q_2$, ..., $Q_q$), and for every such integer $Q_i$, he wants to calculate the number of different fences with perimeter $Q_i$ he can build (two fences are considered different if their \textbf{arrays of lengths} are different). Can you help him calculate these values?
Let's analyze how the perimeter of the fence can be calculated, if we know its array of lengths. Suppose there are $m$ boards in the fence. The perimeter of the fence can be composed of the three following values: the lower border of the fence (with length $m$); $m$ horizontal segments in the upper border of the fence (with total length $m$); $m + 1$ vertical segment of the border. The total length of all vertical segments before the red board (including its left border) is $l_1 + (l_2 - l_1) + \dots + (l_j - l_{j - 1}) = l_j$. The total length of all vertical segments after the red board (including its right border) is $l_j$ too. So, the perimeter of the fence is $2(m + l_j)$, where $m$ is the number of boards used in constructing the fence, and $l_j$ is the length of the red board. So, for example, if we want to create a fence that contains a red board with length $L$ and has perimeter $P$, it should contain exactly $\frac{P}{2} - L - 1$ white boards. Now let's solve the problem as follows: iterate on the length of the red board that will be used, and for each $Q_i$ calculate the number of ways to construct a fence with a red board of length $L$ and exactly $\frac{Q_i}{2} - L - 1$ white boards (which are shorter than $L$). Suppose all white boards shorter than $L$ have distinct lengths. Then for each board, there are three options: not place it at all, place it in the left part (to the left of the red board) or place it in the right part. So, if there are $n$ different white boards shorter than $L$, the number of ways to build a fence with $k$ white boards is ${n}\choose{k}$ $2^k$. Okay, now let's consider the opposite situation: there is no unique white board; that is, for each length, we have either $0$ boards or at least $2$ boards. Suppose the number of different lengths is $m$. For each length, we can choose whether we place a board of such length in the left side and in the right side. So, the number of ways to build a fence with $k$ white boards is ${2m}\choose{k}$. And now let's consider the general case. Divide all boards into two categories: "unique" and "non-unique". If we want to build a fence with exactly $k$ white boards, there are $\sum \limits_{i = 0}^{k}$ ${2m}\choose{k - i}$ ${n}\choose{i}$ $2^i$ ways to do it. Since we should calculate these values for many different values of $k$, we have to use FFT: we should form two polynomials $\sum\limits_{i = 0}^{n}$ ${n}\choose{i}$ $2^i x^i$ and $\sum\limits_{i = 0}^{2m}$ ${2m}\choose{i}$ $x^i$, and then multiply them. Since the modulo is special, it's better to use NTT.
[ "combinatorics", "fft" ]
2,500
#include<bits/stdc++.h> using namespace std; const int LOGN = 20; const int N = (1 << LOGN); const int MOD = 998244353; const int g = 3; #define forn(i, n) for(int i = 0; i < int(n); i++) inline int mul(int a, int b) { return (a * 1ll * b) % MOD; } inline int norm(int a) { while(a >= MOD) a -= MOD; while(a < 0) a += MOD; return a; } inline int binPow(int a, int k) { int ans = 1; while(k > 0) { if(k & 1) ans = mul(ans, a); a = mul(a, a); k >>= 1; } return ans; } inline int inv(int a) { return binPow(a, MOD - 2); } vector<int> w[LOGN]; vector<int> iw[LOGN]; vector<int> rv[LOGN]; void precalc() { int wb = binPow(g, (MOD - 1) / (1 << LOGN)); for(int st = 0; st < LOGN; st++) { w[st].assign(1 << st, 1); iw[st].assign(1 << st, 1); int bw = binPow(wb, 1 << (LOGN - st - 1)); int ibw = inv(bw); int cw = 1; int icw = 1; for(int k = 0; k < (1 << st); k++) { w[st][k] = cw; iw[st][k] = icw; cw = mul(cw, bw); icw = mul(icw, ibw); } rv[st].assign(1 << st, 0); if(st == 0) { rv[st][0] = 0; continue; } int h = (1 << (st - 1)); for(int k = 0; k < (1 << st); k++) rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h); } } inline void fft(int a[N], int n, int ln, bool inverse) { for(int i = 0; i < n; i++) { int ni = rv[ln][i]; if(i < ni) swap(a[i], a[ni]); } for(int st = 0; (1 << st) < n; st++) { int len = (1 << st); for(int k = 0; k < n; k += (len << 1)) { for(int pos = k; pos < k + len; pos++) { int l = a[pos]; int r = mul(a[pos + len], (inverse ? iw[st][pos - k] : w[st][pos - k])); a[pos] = norm(l + r); a[pos + len] = norm(l - r); } } } if(inverse) { int in = inv(n); for(int i = 0; i < n; i++) a[i] = mul(a[i], in); } } int aa[N], bb[N], cc[N]; inline void multiply(int a[N], int sza, int b[N], int szb, int c[N], int &szc) { int n = 1, ln = 0; while(n < (sza + szb)) n <<= 1, ln++; for(int i = 0; i < n; i++) aa[i] = (i < sza ? a[i] : 0); for(int i = 0; i < n; i++) bb[i] = (i < szb ? b[i] : 0); fft(aa, n, ln, false); fft(bb, n, ln, false); for(int i = 0; i < n; i++) cc[i] = mul(aa[i], bb[i]); fft(cc, n, ln, true); szc = n; for(int i = 0; i < n; i++) c[i] = cc[i]; } vector<int> T[N]; int a[N]; int b[N]; int n, k; int ans[N]; int Q[N]; int fact[N]; int rfact[N]; int auxa[N]; int auxb[N]; int auxc[N]; int C(int n, int k) { if(n < 0 || k < 0 || k > n) return 0; return mul(fact[n], mul(rfact[k], rfact[n - k])); } vector<int> newtonExp(int a, int b, int p) { vector<int> res(p + 1); for(int i = 0; i <= p; i++) res[i] = mul(C(p, i), mul(binPow(a, i), binPow(b, p - i))); return res; } int main() { precalc(); fact[0] = 1; for(int i = 1; i < N; i++) fact[i] = mul(fact[i - 1], i); for(int i = 0; i < N; i++) rfact[i] = inv(fact[i]); scanf("%d %d", &n, &k); for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int i = 0; i < k; i++) scanf("%d", &b[i]); int q; scanf("%d", &q); for(int i = 0; i < q; i++) scanf("%d", &Q[i]); map<int, int> cnt; for(int i = 0; i < n; i++) cnt[a[i]]++; for(int i = 0; i < k; i++) { int redL = b[i]; int cnt1 = 0; int cnt2 = 0; for(auto x : cnt) { if(x.first >= redL) break; if(x.second == 1) cnt1++; else cnt2++; } memset(auxa, 0, sizeof auxa); memset(auxb, 0, sizeof auxb); memset(auxc, 0, sizeof auxc); vector<int> p1 = newtonExp(2, 1, cnt1); vector<int> p2 = newtonExp(1, 1, cnt2 * 2); int sa = p1.size(); int sb = p2.size(); int sc; for(int j = 0; j < sa; j++) auxa[j] = p1[j]; for(int j = 0; j < sb; j++) auxb[j] = p2[j]; multiply(auxa, sa, auxb, sb, auxc, sc); for(int j = 0; j < q; j++) { int cntW = Q[j] / 2 - redL - 1; if(cntW >= 0 && cntW < sc) ans[j] = norm(ans[j] + auxc[cntW]); } } for(int i = 0; i < q; i++) printf("%d\n", ans[i]); }
1253
A
Single Push
You're given two arrays $a[1 \dots n]$ and $b[1 \dots n]$, both of the same length $n$. In order to perform a push operation, you have to choose three integers $l, r, k$ satisfying $1 \le l \le r \le n$ and $k > 0$. Then, you will add $k$ to elements $a_l, a_{l+1}, \ldots, a_r$. For example, if $a = [3, 7, 1, 4, 1, 2]$ and you choose $(l = 3, r = 5, k = 2)$, the array $a$ will become $[3, 7, \underline{3, 6, 3}, 2]$. You can do this operation \textbf{at most once}. Can you make array $a$ equal to array $b$? (We consider that $a = b$ if and only if, for every $1 \le i \le n$, $a_i = b_i$)
If we set $d_i = b_i - a_i$, we have to check that $d$ has the following form: $[0, 0, \ldots, 0, k, k, \ldots, k, 0, 0, \ldots, 0]$. Firstly check that there is no negative element in $d$. Solution 1 : add $0$ to the beginning and the end of the array $d$, then check that there is at most two indices $i$ such that $d_i \neq d_{i+1}$. Solution 2 : let $l$ be the smallest integer such that $d_l \neq 0$, and $r$ be the greatest integer such that $d_r \neq 0$. Check that for all $l \le i \le r$, $d_i = d_l$. Complexity : $O(n)$ for each test case.
[ "implementation" ]
1,000
"#include <iostream>\n#include <vector>\nusing namespace std;\n\nbool solve()\n{\n\tint nbElem;\n\tcin >> nbElem;\n\n\tint extSize = nbElem+2;\n\tvector<int> orig(extSize), target(extSize);\n\tvector<int> diff(extSize, 0);\n\n\tfor (int iElem = 1; iElem <= nbElem; ++iElem) {\n\t\tcin >> orig[iElem];\n\t}\n\n\tfor (int iElem = 1; iElem <= nbElem; ++iElem) {\n\t\tcin >> target[iElem];\n\t\tdiff[iElem] = target[iElem] - orig[iElem];\n\t}\n\n\tint cntModif = 0;\n\tfor (int iElem = 0; iElem < extSize-1; ++iElem) {\n\t\tif (diff[iElem] < 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif (diff[iElem] != diff[iElem+1]) {\n\t\t\t++cntModif;\n\t\t}\n\t}\n\n\treturn (cntModif <= 2);\n}\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint nbQueries;\n\tcin >> nbQueries;\n\n\tfor (int iQuery = 0; iQuery < nbQueries; ++iQuery) {\n\t\tif (solve()) {\n\t\t\tcout << \"YES\\n\";\n\t\t} else {\n\t\t\tcout << \"NO\\n\";\n\t\t}\n\t}\n\n\treturn 0;\n}"
1253
B
Silly Mistake
The Central Company has an office with a sophisticated security system. There are $10^6$ employees, numbered from $1$ to $10^6$. The security system logs entrances and departures. The entrance of the $i$-th employee is denoted by the integer $i$, while the departure of the $i$-th employee is denoted by the integer $-i$. The company has some strict rules about access to its office: - An employee can enter the office \textbf{at most} once per day. - He obviously can't leave the office if he didn't enter it earlier that day. - In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day. Any array of events satisfying these conditions is called a valid day. Some examples of valid or invalid days: - $[1, 7, -7, 3, -1, -3]$ is a valid day ($1$ enters, $7$ enters, $7$ leaves, $3$ enters, $1$ leaves, $3$ leaves). - $[2, -2, 3, -3]$ is also a valid day. - $[2, 5, -5, 5, -5, -2]$ is \underline{not} a valid day, because $5$ entered the office twice during the same day. - $[-4, 4]$ is \underline{not} a valid day, because $4$ left the office without being in it. - $[4]$ is \underline{not} a valid day, because $4$ entered the office and didn't leave it before the end of the day. There are $n$ events $a_1, a_2, \ldots, a_n$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events. You must partition (to cut) the array $a$ of events into \textbf{contiguous subarrays}, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day. For example, if $n=8$ and $a=[1, -1, 1, 2, -1, -2, 3, -3]$ then he can partition it into two contiguous subarrays which are valid days: $a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$. Help the administrator to partition the given array $a$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.
We can solve this problem with a straightforward greedy solution: simulate the events in the order in which they occured, and as soon as the office is empty, end the current day and begin a new one. We can prove that if there exists a valid solution, this greedy algorithm will find one (and furthermore, it will use maximum number of days, even if it wasn't required). To do the simulation efficiently, we should maintain the state of each employee in an array (never went to the office today / in the office / left the office) and the number of employees currently in the office. Each time we end a day, we have to reset all states of employees involved in the day (not all employees, otherwise the solution would be $O(n^2)$). Final complexity is $O(n + e)$ where $e$ is the number of employees, or $O(n)$ if you compress the array beforehand.
[ "greedy", "implementation" ]
1,400
"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int borne = (int)(1e6) + 5;\nconst int WAIT=0, ENTERED=1, LEFT=2;\nint state[borne];\n\nbool solve()\n{\n\tios::sync_with_stdio(false);\n\tint nbEvents;\n\tcin >> nbEvents;\n\tvector<int> res, cur;\n\tint ofs = 0;\n\n\tfor (int ind = 0; ind < nbEvents; ++ind) {\n\t\tint ev; cin >> ev;\n\t\tint guy = abs(ev);\n\t\tcur.push_back(guy);\n\t\tif (ev > 0) {\n\t\t\tif (state[guy] != WAIT) return false;\n\t\t\tstate[guy] = ENTERED; ++ofs;\n\t\t} else {\n\t\t\tif (state[guy] != ENTERED) return false;\n\t\t\tstate[guy] = LEFT; --ofs;\n\t\t}\n\t\tif (ofs == 0) {\n\t\t\tres.push_back(cur.size());\n\t\t\tfor (int x : cur) state[x] = WAIT;\n\t\t\tcur.clear();\n\t\t}\n\t}\n\n\tif (! cur.empty()) return false;\n\n\tint nbDays = res.size();\n\tcout << nbDays << \"\\n\";\n\tfor (int i = 0; i < nbDays; ++i) {\n\t\tcout << res[i];\n\t\tif (i+1 < nbDays) cout << \" \";\n\t\telse cout << \"\\n\";\n\t}\n\treturn true;\n}\n\nint main()\n{\n\tif (!solve()) cout << \"-1\\n\";\n\treturn 0;\n}"
1253
C
Sweets Eating
Tsumugi brought $n$ delicious sweets to the Light Music Club. They are numbered from $1$ to $n$, where the $i$-th sweet has a sugar concentration described by an integer $a_i$. Yui loves sweets, but she can eat at most $m$ sweets each day for health reasons. Days are $1$-indexed (numbered $1, 2, 3, \ldots$). Eating the sweet $i$ at the $d$-th day will cause a sugar penalty of $(d \cdot a_i)$, as sweets become more sugary with time. A sweet can be eaten at most once. The total sugar penalty will be the \textbf{sum} of the individual penalties of each sweet eaten. Suppose that Yui chooses exactly $k$ sweets, and eats them in any order she wants. What is the \textbf{minimum} total sugar penalty she can get? Since Yui is an undecided girl, she wants you to answer this question for every value of $k$ between $1$ and $n$.
Let's sort array $a$. Now we can easily that if Yui wants to eat $k$ sweets, she has to eat sweets $k, k-1, \ldots, 1$ in this order, because of rearrangement inequality (put lower coefficients (day) on higher values (sugar concentration)). A naive simulation of this strategy would have complexity $O(n^2)$, which is too slow. Let's look what happens when we replace $k$ by $k+m$. During the first day, Yui will eat sweets $k+m, k+(m-1), \ldots, k+1$. Then, we reproduce the strategy used for $x_k$, but one day late : all coefficients are increased by $1$. Formally, $x_{k+m} - x_k = new + inc$ where $new = (a_{k+m} + \ldots + a_{k+1})$ because of new sweets eaten and $inc = (a_k + \ldots + a_1)$ because the coefficient of these sweets are all increased by $1$ (we eat them one day later). We can derive the following formula : $x_k = (a_k + a_{k-1} + \ldots + a_1) + x_{k-m}$. If we maintain the current prefix sum, and all previous answers computed in an array, we can compute all answers in $O(n)$. Final complexity is $O(n \log n)$, because sorting is the slowest part of the solution.
[ "dp", "greedy", "math", "sortings" ]
1,500
"#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint nbSweets, maxPerDay;\n\tcin >> nbSweets >> maxPerDay;\n\n\tvector<int> val(nbSweets);\n\n\tfor (int iSweet = 0; iSweet < nbSweets; ++iSweet) {\n\t\tcin >> val[iSweet];\n\t}\n\n\tsort(val.begin(), val.end());\n\n\tvector<long long> ans(nbSweets);\n\n\tlong long curSum = 0;\n\n\tfor (int lastTaken = 0; lastTaken < nbSweets; ++lastTaken) {\n\t\tcurSum += val[lastTaken];\n\t\tans[lastTaken] = curSum;\n\n\t\tif (lastTaken >= maxPerDay) {\n\t\t\tans[lastTaken] += ans[lastTaken - maxPerDay];\n\t\t}\n\n\t\tcout << ans[lastTaken] << (lastTaken == nbSweets-1 ? '\\n' : ' ');\n\t}\n\n\treturn 0;\n}"
1253
D
Harmonious Graph
You're given an undirected graph with $n$ nodes and $m$ edges. Nodes are numbered from $1$ to $n$. The graph is considered harmonious if and only if the following property holds: - For every triple of integers $(l, m, r)$ such that $1 \le l < m < r \le n$, if there exists a \textbf{path} going from node $l$ to node $r$, then there exists a \textbf{path} going from node $l$ to node $m$. In other words, in a harmonious graph, if from a node $l$ we can reach a node $r$ through edges ($l < r$), then we should able to reach nodes $(l+1), (l+2), \ldots, (r-1)$ too. What is the minimum number of edges we need to add to make the graph harmonious?
For each connected component, let's find the weakest node $l$ and the biggest node $r$ in it (with one DFS per connected component). If we look for all components at their intervals $[l\ ;\ r]$, we can see that two components should be connected in the resulting graph if and only if their intervals intersect. This leads to a $O(n^2 + m)$ naive solution : create a second graph where nodes represent components, add an edge between all pairs of components with intersecting intervals, and choose any spanning forest. To optimize it, generate intervals in increasing order of $l$ (starting DFS in increasing order of nodes numbers). Look at them in this order, maintaining the biggest end $B$ seen. If $l \le B$, it is necessary to connect current interval to the interval ending at $B$ (hence increment answer). It is quite easy to prove that doing only these connections is also sufficient (i.e. resulting graph will be harmonious). Final complexity is $O(n + m)$.
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "sortings" ]
1,700
"#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nconst int borne = 201*1000;\nint nbNodes, nbEdges;\n\nvector<int> adj[borne];\nbool vu[borne];\nvector<pair<int, int>> ivComp;\n\nvoid dfs(int nod, int& weaker, int& bigger)\n{\n\tvu[nod] = true;\n\tweaker = min(weaker, nod);\n\tbigger = max(bigger, nod);\n\n\tfor (int neighbor : adj[nod]) if (! vu[neighbor]) {\n\t\tdfs(neighbor, weaker, bigger);\n\t}\n}\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tcin >> nbNodes >> nbEdges;\n\tfor (int iEdge = 0; iEdge < nbEdges; ++iEdge) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\t--u; --v;\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\n\tfor (int nod = 0; nod < nbNodes; ++nod) {\n\t\tif (! vu[nod]) {\n\t\t\tint weaker = nod, bigger = nod;\n\t\t\tdfs(nod, weaker, bigger);\n\t\t\tivComp.emplace_back(weaker, bigger);\n\t\t}\n\t}\n\n\t//sort(ivComp.begin(), ivComp.end()); // Useless, already sorted\n\n\tint curEnd = -1;\n\tint rep = 0;\n\n\tfor (auto comp : ivComp) {\n\t\tif (comp.first <= curEnd) {\n\t\t\t++rep;\n\t\t}\n\t\tcurEnd = max(curEnd, comp.second);\n\t}\n\n cout << rep << \"\\n\";\n\treturn 0;\n}"
1253
E
Antenna Coverage
The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $(Ox)$ axis. On this street, there are $n$ antennas, numbered from $1$ to $n$. The $i$-th antenna lies on the position $x_i$ and has an initial scope of $s_i$: it covers all integer positions inside the interval $[x_i - s_i; x_i + s_i]$. It is possible to increment the scope of any antenna by $1$, this operation costs $1$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want). To modernize the street, we need to make all \underline{integer} positions from $1$ to $m$ inclusive covered by \underline{at least} one antenna. Note that it is authorized to cover positions outside $[1; m]$, even if it's not required. What is the minimum amount of coins needed to achieve this modernization?
We can add an antenna $(x=0, s=0)$. It will not modifiy the answer, because it would be non-optimal to increase the scope of this antenna. Let $dp_x$ be the minimum cost to cover all positions from $x$ to $m$ inclusive, knowing that position $x$ is covered. We compute $dp$ in decreasing order of $x$. Base case is $dp_m := 0$. The default transition is $dp_x := (m - x)$. If position $x+1$ is initially covered, $dp_x := dp_{x+1}$ Otherwise, let's consider all antennas and their initial intervals $[l_i; r_i]$. If $x < l_i$, let $u = (l_i - x - 1)$, then a possible transition is $dp_x := u + dp_{min(m, r_i + u)}$. We take the minimum of all these transitions. Note that we always extend intervals as less as possible, but it's optimal because : If after using this interval $i$, we use another interval $j$ (at the right of $i$), the time spent to extend $i$ could have been used to extend $j$ instead, which will be more optimal. If $i$ was the last interval used, we don't care because the default transition will take care of this case. The final answer will be $dp_0$. There are $O(m)$ states and $O(n)$ transitions, hence final complexity is $O(nm)$ with very low constant. $O(n^2 \cdot m)$ can also get AC because of very low constant.
[ "data structures", "dp", "greedy", "sortings" ]
2,200
"#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nstruct Antenna\n{\n\tint iniLeft, iniRight;\n};\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint nbAntennas, totLen;\n\tcin >> nbAntennas >> totLen;\n\tvector<Antenna> ants(nbAntennas);\n\n\tfor (int iAnt = 0; iAnt < nbAntennas; ++iAnt) {\n\t\tint center, iniScope;\n\t\tcin >> center >> iniScope;\n\t\tants[iAnt].iniLeft = max(0, center - iniScope);\n\t\tants[iAnt].iniRight = min(totLen, center + iniScope);\n\t}\n\n\tvector<int> minCost(totLen+1);\n\tminCost[totLen] = 0;\n\n\tfor (int pos = totLen-1; pos >= 0; --pos) {\n\t\tminCost[pos] = (totLen - pos);\n\n\t\tfor (int iAnt = 0; iAnt < nbAntennas; ++iAnt) {\n\t\t\tint left = ants[iAnt].iniLeft, right = ants[iAnt].iniRight;\n\n\t\t\tif (left <= pos+1 && pos+1 <= right) {\n\t\t\t\tminCost[pos] = minCost[pos+1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif (pos < left) {\n\t\t\t\tint accessCost = (left - pos - 1);\n\t\t\t\tint nextPos = min(totLen, right + accessCost);\n\t\t\t\tminCost[pos] = min(minCost[pos], accessCost + minCost[nextPos]);\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << minCost[0] << \"\\n\";\n\n\treturn 0;\n}"
1253
F
Cheap Robot
You're given a simple, undirected, connected, weighted graph with $n$ nodes and $m$ edges. Nodes are numbered from $1$ to $n$. There are exactly $k$ centrals (recharge points), which are nodes $1, 2, \ldots, k$. We consider a robot moving into this graph, with a battery of capacity $c$, not fixed by the constructor yet. At any time, the battery contains an integer amount $x$ of energy between $0$ and $c$ inclusive. Traversing an edge of weight $w_i$ is possible only if $x \ge w_i$, and costs $w_i$ energy points ($x := x - w_i$). Moreover, when the robot reaches a central, its battery is entirely recharged ($x := c$). You're given $q$ \underline{independent} missions, the $i$-th mission requires to move the robot from \underline{central} $a_i$ to \underline{central} $b_i$. For each mission, you should tell the minimum capacity required to acheive it.
Key insight 1: Since we always end on a central, at any time our robot have to be able to reach the nearest central. Key insight 2: Since we always start from a central, from any node $u$, going to the nearest central, then going back to $u$ can't decrease the number of energy points in the battery. - Firstly, let's do a multi-source Dijkstra from all centrals. We denote $d_u$ the distance from node $u$ to the nearest central. Consider a fixed capacity $c$. Suppose that we're on node $u$ with $x$ energy points remaining in the battery. Note that $x \le c - d_u$. If $x < d_u$, we can't do anything, the robot is lost because it can't reach any central anymore. Otherwise, if $x \ge d_u$, we can go to the nearest central, then go back to $u$, hence we can always consider than $x = c - d_u$. This is a simple but very powerful observation that allows us to delete the battery level in states explored. Hence, we can now solve the problem in $O(m \log m + qm \log n)$, doing binary search on answer and simple DFS for each query. - We need to optimize this solution. Now, reaching a node $u$ will mean reaching it with $x \ge d_u$. During exploration of nodes, the necessary and sufficient condition for being able to reach node $v$ from $u$, through an edge of weight $w$, is that $(c - d_u) - w \ge d_v$, i.e. $d_u + d_v + w \le c$. Hence, if we replace the weight of each edge $(u, v, w)$ by $w' = d_u + d_v + w$, the problem is reduced to find a shortest path from $a_i$ to $b_i$, in terms of maximum weight over edges used (which will be the capacity required by this path). Solution 1 (offline): Sort edges by new weight. Add them progressively, maintaining connexity with DSU. As soon as two endpoints of a query become connected, we should put current capacity (i.e. new weight of the last edge added) as answer for this query. To effeciently detect this, we can put tokens on endpoints of each query, and each time we do union (of DSU), we make tokens go up to the parent. If we do union by rank, each token will move at most $O(\log n)$ times. Solution 2 (online): Let's construct a MST of the new graph with Kruskal. It is well-known that in this particular MST, for every pair of nodes $(u, v)$, the only path from $u$ to $v$ will be a shortest path (in terms of maximum weight over the path). Hence we just have to compute the weight of paths in a tree, which can be done with binary lifting. These two solutions both run in $O(m \log m + q \log n)$. Implementation of solution 1 is a bit shorter, but solution 2 can deal with online queries.
[ "binary search", "dsu", "graphs", "shortest paths", "trees" ]
2,500
"#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nusing llg = long long;\n\nconst int maxNod = (int)(1e5) + 5;\nconst int maxEdges = 3*(int)(1e5) + 5;\nconst int maxQueries = 3*(int)(1e5) + 5;\n\nconst int maxTokens = 2*maxQueries;\n\nconst llg BIG = (llg)(1e9) * (llg)(1e9);\n\nint nbNod, nbEdges, nbCentrals, nbQueries;\nllg rep[maxQueries];\n\n// DSU\n\nint dsuRepr[maxNod];\nint dsuSize[maxNod];\nvector<int> tokenIn[maxNod];\n\nint baseTok[maxTokens];\n\nvoid dsuInit()\n{\n\tfor (int nod = 0; nod < maxNod; ++nod) {\n\t\tdsuRepr[nod] = nod;\n\t\tdsuSize[nod] = 1;\n\t}\n}\n\nint dsuFind(int x)\n{\n\tif (x != dsuRepr[x]) {\n\t\tdsuRepr[x] = dsuFind(dsuRepr[x]);\n\t}\n\treturn dsuRepr[x];\n}\n\nvoid dsuMerge(int small, int big, llg curCap)\n{\n\tsmall = dsuFind(small);\n\tbig = dsuFind(big);\n\tif (small == big) return;\n\tif (dsuSize[small] > dsuSize[big]) swap(small, big);\n\n\tfor (int token : tokenIn[small]) {\n\t\tint oth = token^1;\n\t\tint query = token/2;\n\t\tif (dsuFind(baseTok[oth]) == big) {\n\t\t\trep[query] = curCap;\n\t\t}\n\t\ttokenIn[big].push_back(token);\n\t}\n\n\ttokenIn[small].clear();\n\ttokenIn[small].shrink_to_fit();\n\n\tdsuSize[big] += dsuSize[small];\n\tdsuRepr[small] = big;\n}\n\n// Dijkstra\n\nvector<pair<int, llg>> adj[maxNod];\nllg mdis[maxNod];\n\nvoid dijkstra()\n{\n\tpriority_queue<pair<llg, int>> pq;\n\tfor (int nod = 0; nod < nbNod; ++nod) {\n\t\tif (nod < nbCentrals) {\n\t\t\tpq.push({0, nod});\n\t\t} else {\n\t\t\tmdis[nod] = BIG;\n\t\t}\n\t}\n\n\twhile (! pq.empty()) {\n\t\tllg dist = -pq.top().first;\n\t\tint nod = pq.top().second;\n\t\tpq.pop();\n\t\tif (dist != mdis[nod]) continue;\n\n\t\tfor (auto rawNeigh : adj[nod]) {\n\t\t\tint neighbor = rawNeigh.first;\n\t\t\tllg newDis = dist + rawNeigh.second;\n\t\t\tif (newDis < mdis[neighbor]) {\n\t\t\t\tmdis[neighbor] = newDis;\n\t\t\t\tpq.push({-newDis, neighbor});\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Main\n\nstruct Edge\n{\n\tllg weight, n1, n2;\n};\n\nbool operator<(Edge a, Edge b)\n{\n\treturn a.weight < b.weight;\n}\n\nvector<Edge> tabEdges;\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tdsuInit();\n\n\tcin >> nbNod >> nbEdges >> nbCentrals >> nbQueries;\n\tfor (int iEdge = 0; iEdge < nbEdges; ++iEdge) {\n\t\tint n1, n2; llg weight;\n\t\tcin >> n1 >> n2 >> weight;\n\t\t--n1; --n2;\n\t\tadj[n1].emplace_back(n2, weight);\n\t\tadj[n2].emplace_back(n1, weight);\n\t\ttabEdges.push_back({weight, n1, n2});\n\t}\n\n\tfor (int query = 0; query < nbQueries; ++query) {\n\t\tint n1, n2;\n\t\tcin >> n1 >> n2;\n\t\t--n1; --n2;\n\t\tint tk1 = 2*query, tk2 = 2*query+1;\n\n\t\tbaseTok[tk1] = n1;\n\t\tbaseTok[tk2] = n2;\n\n\t\ttokenIn[n1].push_back(tk1);\n\t\ttokenIn[n2].push_back(tk2);\n\t}\n\n\tdijkstra();\n\n\tfor (auto &edge : tabEdges) {\n\t\tedge.weight += mdis[edge.n1] + mdis[edge.n2];\n\t}\n\n\tsort(tabEdges.begin(), tabEdges.end());\n\n\tfor (auto edge : tabEdges) {\n\t\tdsuMerge(edge.n1, edge.n2, edge.weight);\n\t}\n\n\tfor (int query = 0; query < nbQueries; ++query) {\n\t\tcout << rep[query] << \"\\n\";\n\t}\n}"
1254
A
Feeding Chicken
Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm. His farm is presented by a rectangle grid with $r$ rows and $c$ columns. Some of these cells contain rice, others are empty. $k$ chickens are living on his farm. \textbf{The number of chickens is not greater than the number of cells with rice on the farm.} Long wants to give his chicken playgrounds by assigning these farm cells to his chickens. He would like to satisfy the following requirements: - Each cell of the farm is assigned to \textbf{exactly one} chicken. - Each chicken is assigned \textbf{at least one} cell. - The set of cells assigned to every chicken forms a connected area. More precisely, if two cells $(x, y)$ and $(u, v)$ are assigned to the same chicken, this chicken is able to walk from $(x, y)$ to $(u, v)$ by passing only its cells and moving from each cell to another cell sharing a side. Long also wants to prevent his chickens from fighting for food. Hence he wants the difference between the maximum and the minimum number of cells with rice assigned to a chicken to be as small as possible. Please help him.
First, we will try to solve the problem when our rectangle is an array (or an $1 \cdot n$ rectangle). Let $r$ be the number of rice cells. It's not hard to see that the difference between the maximum and the minimum number of cells with rice assigned to a chicken is either $0$, when $r$ $mod$ $k = 0$, or $1$ otherwise. Turns out, there is an easy way to assign: for the first $r$ $mod$ $k$ chicken, we will assign to the current chicken a prefix of the current array that contains exactly $\lceil r/k \rceil$ rice cells, and delete that prefix. The same for the others $k - (r$ $mod$ $k)$ chicken, we will assign to the current chicken a prefix of the current array that contains exactly $\lfloor r/k \rfloor$ rice cells. Notice that there exists a path that goes through every cell exactly once and every two consecutive cells on the path share a side. One such path is $(1, 1), (1, 2), ... (1,c), (2,c), (2, c-1), ..., (2, 1), (3, 1), (3, 2), ...$ By thinking the path as an array, we can assign regions on the path according to the above paragraph. Such an assignment is also a valid assignment for the original rectangle.
[ "constructive algorithms", "greedy", "implementation" ]
1,700
#include<bits/stdc++.h> #define FOR(i, a, b) for (int i = (a), _b = (b); i <= _b; i++) #define FORD(i, b, a) for (int i = (b), _a = (a); i >= _a; i--) #define REP(i, n) for (int i = 0, _n = (n); i < _n; i++) #define FORE(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); i++) #define ALL(v) (v).begin(), (v).end() #define IS_INF(x) (std::isinf(x)) #define IS_NAN(x) (std::isnan(x)) #define fi first #define se second #define MASK(i) (1LL << (i)) #define BIT(x, i) (((x) >> (i)) & 1) #define div ___div #define next ___next #define prev ___prev #define left ___left #define right ___right #define __builtin_popcount __builtin_popcountll using namespace std; template<class X, class Y> bool minimize(X &x, const Y &y) { X eps = 1e-9; if (x > y + eps) { x = y; return true; } else return false; } template<class X, class Y> bool maximize(X &x, const Y &y) { X eps = 1e-9; if (x + eps < y) { x = y; return true; } else return false; } template<class T> T Abs(const T &x) { return (x < 0 ? -x : x); } /* Author: Van Hanh Pham */ /** END OF TEMPLATE - ACTUAL SOLUTION COMES HERE **/ const string SYMBOLS = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890"; #define MAX 111 char board[MAX][MAX], res[MAX][MAX]; int numRow, numCol, numChicken; void process(void) { memset(board, 0, sizeof board); memset(res, 0, sizeof res); scanf("%d%d%d", &numRow, &numCol, &numChicken); FOR(i, 1, numRow) scanf("%s", board[i] + 1); bool leftToRight = true; vector<pair<int, int>> cells; FOR(i, 1, numRow) { if (leftToRight) { FOR(j, 1, numCol) cells.push_back(make_pair(i, j)); } else { FORD(j, numCol, 1) cells.push_back(make_pair(i, j)); } leftToRight ^= 1; } int totRice = 0; FOR(i, 1, numRow) FOR(j, 1, numCol) if (board[i][j] == 'R') totRice++; int avg = totRice / numChicken; int diff = totRice % numChicken == 0 ? 0 : 1; REP(i, numChicken) { int cntRice = 0; while (true) { int x = cells.back().fi, y = cells.back().se; cells.pop_back(); res[x][y] = SYMBOLS[i]; if (board[x][y] == 'R') { totRice--; cntRice++; } if (cntRice < avg) continue; if (avg * (numChicken - i - 1) <= totRice && totRice <= (avg + diff) * (numChicken - i - 1)) break; } } while (!cells.empty()) { int x = cells.back().fi, y = cells.back().se; cells.pop_back(); res[x][y] = SYMBOLS[numChicken - 1]; } FOR(i, 1, numRow) { FOR(j, 1, numCol) printf("%c", res[i][j]); printf("\n"); } } int main(void) { int t; scanf("%d", &t); REP(love, t) process(); return 0; } /*** LOOK AT MY CODE. MY CODE IS AMAZING :D ***/
1254
B1
Send Boxes to Alice (Easy Version)
This is the easier version of the problem. In this version, $1 \le n \le 10^5$ and $0 \le a_i \le 1$. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces. Since Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, \textbf{at least one of $a_1, a_2, \ldots, a_n$ is positive}. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
Author: MofK. Prepared by UncleGrandpa The problem asked you to move chocolate pieces between adjacent boxes so that the number of chocolate pieces in all boxes is divisible by $k$ ($k>1$). Now, it's clear that we will divide the array into segments, such that the sum of each segment is divisible by $k$, and move all chocolate pieces in that segment to a common box. Here we take notice of 2 things: First, in each segment, let $A$ be the array of all position with 1, then the position that we move all the 1 to is the median of that array $A$ (easy to prove). First, in each segment, let $A$ be the array of all position with 1, then the position that we move all the 1 to is the median of that array $A$ (easy to prove). Second, the sum of each segment should be all equal to $k$. It's easy to see that if there exists some segment of sum $x*k$, then separating them into $x$ segments of sum $k$ will improve the result. Second, the sum of each segment should be all equal to $k$. It's easy to see that if there exists some segment of sum $x*k$, then separating them into $x$ segments of sum $k$ will improve the result. With that two observations, we can iterate from 1 to n, push each position with value 1 into a temp array, and whenever the size of array become k, we add to our result the sum of $|a_i-median|$ and clear the array. It is clear that $k$ must be a divisor of the total number of chocolate pieces. So we iterate through all possible $k$ and minimize our answer with the number of steps to make all numbers divisible by k. A number $\le 10^5$ has at most 128 divisors, and each calculation take $O(n)$ so the solution should pass easily.
[ "constructive algorithms", "greedy", "math", "number theory", "ternary search", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; const int maxn = 1000006; int n; int a[maxn]; vector <int> v; long long cost(int p) { long long ret = 0; for (int i = 0; i < v.size(); i += p) { int median = v[(i + i + p - 1) / 2]; for (int j = i; j < i + p; ++j) ret += abs(v[j] - median); } return ret; } int main(void) { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (a[i] == 1) v.push_back(i); } if (v.size() == 1) { cout << -1 << endl; return 0; } long long ans = 1e18; int tmp = v.size(), p = 2; while (p * p <= tmp) { if (tmp % p == 0) { ans = min(ans, cost(p)); while (tmp % p == 0) tmp /= p; } ++p; } if (tmp > 1) ans = min(ans, cost(tmp)); cout << ans << endl; return 0; }
1254
B2
Send Boxes to Alice (Hard Version)
This is the harder version of the problem. In this version, $1 \le n \le 10^6$ and $0 \leq a_i \leq 10^6$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces. Since Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, \textbf{at least one of $a_1, a_2, \ldots, a_n$ is positive}. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
Author: MofK. Prepared by MofK and UncleGrandpa The problem E2 is different from the problem E1 in some ways. Now all $A_i$ is at most $10^6$, and so is the number $n$. That makes our solution on E1 simply not usable in this problem. Let $S_i$ be the sum of $a_1 + a_2 + ... + a_i$. Now we see that: if we move a chocolate piece from box $i$ to box $i+1$, it is equivalent to decrease $S_i$ by 1. if we move a chocolate piece from box $i$ to box $i+1$, it is equivalent to decrease $S_i$ by 1. if we move a chocolate piece from box $i+1$ to box $i$, it is equivalent to increase $S_i$ by 1. if we move a chocolate piece from box $i+1$ to box $i$, it is equivalent to increase $S_i$ by 1. Wow, now each moving steps only affect one number. Next, we can see that if every $a_i$ is divisible by k, then so is every $S_i$. Thus, our problem is now transformed to: Given an array $S$. At each turn, you can choose one $S_i$ and increase (or decrease) it by one (except for $S_n$). Find the minimum number of steps to make all $S_i$ divisible by $k$. An intuitive approach is to try to increase (or decrease) each $S_i$ to the nearest multiple of $k$. If such a configuration can be achieved then it will obviously be the best answer. The only concern is that: is there any scenario when there exists some $i$ such that $S_i > S_{i+1}$, which is indeed a violation? Fortunately, the answer is no. We can enforce the solution to iterate each $S_i$ from $1$ to $n-1$ and always choose to decrease if there is a tie. This way, the sequence $S$ will remain non-decreasing throughout the process. So, the solution is as follows. Just iterate from $1$ to $n-1$ and for each $i$, add to our result $min(S_i\%k,k-S_i\%k)$. Again, like E1, it is clear that $k$ must be a divisor of the total number of chocolate pieces. But now the total number of chocolate pieces is at most $10^{12}$, which an iteration through all divisors will not be fast enough to fit in 1 second. (In fact, we did make just one single test case to block this solution. Nevertheless, on random testcases it runs super fast). But if you have solved the problem to this phase already, you can easily realize that we only need to consider prime $k$, because if $k$ is composite then picking any prime divisors of it will lead to either a better result or an equal result. That's it, there will be at most 12 distinct prime divisors. Each calculation takes $O(n)$. So the solution will also pass easily.
[ "constructive algorithms", "greedy", "math", "number theory", "ternary search", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; const int maxn = 1000006; int n; long long a[maxn]; long long s[maxn]; long long cost(long long mod) { long long ret = 0; for (int i = 1; i <= n; ++i) ret += min(s[i] % mod, mod - s[i] % mod); return ret; } int main(void) { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; s[i] = s[i-1] + a[i]; } if (s[n] == 1) { cout << -1 << endl; return 0; } long long ans = 1e18; long long tmp = s[n], p = 2; while (p * p <= tmp) { if (tmp % p == 0) { ans = min(ans, cost(p)); while (tmp % p == 0) tmp /= p; } ++p; } if (tmp > 1) ans = min(ans, cost(tmp)); cout << ans << endl; return 0; }
1254
C
Point Ordering
\textbf{This is an interactive problem.} Khanh has $n$ points on the Cartesian plane, denoted by $a_1, a_2, \ldots, a_n$. All points' coordinates are integers between $-10^9$ and $10^9$, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ such that the polygon $a_{p_1} a_{p_2} \ldots a_{p_n}$ is convex and vertices are listed in counter-clockwise order. Khanh gives you the number $n$, but hides the coordinates of his points. Your task is to guess the above permutation by asking multiple queries. In each query, you give Khanh $4$ integers $t$, $i$, $j$, $k$; where either $t = 1$ or $t = 2$; and $i$, $j$, $k$ are three \textbf{distinct} indices from $1$ to $n$, inclusive. In response, Khanh tells you: - if $t = 1$, the area of the triangle $a_ia_ja_k$ \textbf{multiplied by $2$}. - if $t = 2$, the sign of the cross product of two \textbf{vectors} $\overrightarrow{a_ia_j}$ and $\overrightarrow{a_ia_k}$. Recall that the cross product of vector $\overrightarrow{a} = (x_a, y_a)$ and vector $\overrightarrow{b} = (x_b, y_b)$ is the \textbf{integer} $x_a \cdot y_b - x_b \cdot y_a$. The sign of a number is $1$ it it is positive, and $-1$ otherwise. It can be proven that the cross product obtained in the above queries can not be $0$. You can ask at most $3 \cdot n$ queries. Please note that Khanh fixes the coordinates of his points and does not change it while answering your queries. You do not need to guess the coordinates. In your permutation $a_{p_1}a_{p_2}\ldots a_{p_n}$, $p_1$ should be equal to $1$ and the indices of vertices should be \textbf{listed in counter-clockwise order}.
Let's start by choosing vertices $1$ and $2$ as pivots. Recall that if the cross product of two vectors $\vec{A}$ and $\vec{B}$ is positive, point $B$ lies to the left of $\vec{A}$; if the product is negative, point $B$ lies to the right of $\vec{A}$; and if the product is zero, the 3 points $(0,0)$, $A$, $B$ are collinear. With $n-2$ queries of type 2, we can know which vertices lie to the left or to the right of edge $1-2$ and then solve the two sides separately. Consider the left side and there are $a$ vertices lie to the left, we can use $a$ queries of type 1 to calculate the distance from those vertices to edge $1-2$ (the distance from vertex $X$ to edge $1-2$ is twice the area of the triangle forms by $1$, $2$, $X$, divides by the length of edge $1-2$). Let Y be the farthest from $1-2$ (there can be at most 2 such vertices). We can use $a-1$ queries of type 2 to see if the others vertices lie between $1, Y$ or between $Y, 2$, then sort them counter-clockwise with the asked distances. So we will use $n-2$ queries to calculate the distances from vertices $3, 4, .. n$ to edge $1-2$ and at most $n - 3$ for the latter step. This solution uses at most $3n-7$ queries. Another solution is to find the vertex that is consecutive to $1$ in $n-2$ queries and do the same as the solution above.
[ "constructive algorithms", "geometry", "interactive", "math" ]
2,300
#include <bits/stdc++.h> using namespace std; int n; void check_if_zero(long long x){ if (x == 0) exit(0); } long long get_area(int a,int b,int c){ long long result; cout << 1 << ' ' << a << ' ' << b << ' ' << c << endl; cin >> result; check_if_zero(result); assert(result > 0); return result; } int get_sign(int o,int a,int b){ int result; cout << 2 << ' ' << o << ' ' << a << ' ' << b << endl; cin >> result; check_if_zero(result); assert(abs(result) == 1); return result; } vector <int> lef, rig; void divide(){ for(int i=3;i<=n;i++){ int sign = get_sign(1, 2, i); if (sign == 1) lef.push_back(i); else rig.push_back(i); } } long long area12[1005]; void _do(vector<int> &lst){ if (lst.size() <= 1) return; long long best = 0; for(auto v: lst){ area12[v] = get_area(1, 2, v); if (area12[v] > area12[best]) best = v; } vector <int> l, r; for(auto v: lst){ if (v == best) continue; if (get_sign(1, best, v) == 1) l.push_back(v); else r.push_back(v); } sort(l.begin(), l.end(), [&](int x,int y){ return area12[x] > area12[y]; }); sort(r.begin(), r.end(), [&](int x,int y){ return area12[x] < area12[y]; }); lst.clear(); for(auto v: r) lst.push_back(v); lst.push_back(best); for(auto v: l) lst.push_back(v); } void answer(){ cout << 0 << ' ' << 1 << ' '; for(auto v: rig) cout << v << ' '; cout << 2 << ' '; for(auto v: lef) cout << v << ' '; cout << endl; } int main(){ cin >> n; assert(n >= 3); divide(); // n-2 queries _do(lef); _do(rig); // 2*(n-2) - 1 or 2*(n-2) - 2 queries answer(); }
1254
D
Tree Queries
Hanh is a famous biologist. He loves growing trees and doing experiments on his own garden. One day, he got a tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. A tree with $n$ vertices is an undirected connected graph with $n-1$ edges. Initially, Hanh sets the value of every vertex to $0$. Now, Hanh performs $q$ operations, each is either of the following types: - Type $1$: Hanh selects a vertex $v$ and an integer $d$. Then he chooses some vertex $r$ \textbf{uniformly at random}, lists all vertices $u$ such that the path from $r$ to $u$ passes through $v$. Hanh then increases the value of all such vertices $u$ by $d$. - Type $2$: Hanh selects a vertex $v$ and calculates the expected value of $v$. Since Hanh is good at biology but not math, he needs your help on these operations.
Disclaimer: Our other authors and testers have found better solutions; our best complexity is $O(n \times log^{2}(n))$. However, since this solution is the theoretically worst complexity that we intended to accept, I decided to write about it. Feel free to share your better solution in the comment section :) Consider two distinct vertices $u$, $v$, the number of vertices $r$ such that the path from $r$ to $u$ passes through $v$ is $n - |Tree(v, u)|$, where $Tree(v, u)$ is the subtree we get by cutting the first edge on the path from $v$ to $u$, then keep the part with vertex $u$. If $u = v$ then this value will be $n$. By linearity of expectation, we can see that adding $d$ to $a[v]$ will add to the expected value of $a[u]$ an amount equal to $\frac{1}{n} \times d \times (n - |Tree(v, u)|)$. Note that this value is the same for all $u$ that lies on the same "subtree branch" of $v$. To update it efficiently, we can split the vertices into $2$ groups: those which has degree greater than $T$ (there are no more than $\frac{n}{T}$ of them), and those which does not. When we update a "light" vertex $v$, we iterate over the neighbors of $v$ and update the subtrees accordingly. When we get the value of a vertex $v$, we already have the sum of contributions from all "light" vertices to $v$, hence we can iterate over all "heavy" vertices and calculate the contribution from each of them to $v$. If we use range-update point-query data structures such as Fenwick Trees then the complexity will be $O(Q \times log(n) \times (\frac{n}{T} + T)) = O(Q \times \sqrt{n} \times log(n))$ if we choose $T = O(\sqrt{n})$.
[ "data structures", "probabilities", "trees" ]
2,700
#include <bits/stdc++.h> using namespace std; const int maxn = 150005; const int mod = 998244353; const int heavy = 300; int n, m, q; vector <int> adj[maxn]; int dad[maxn]; int sz[maxn]; vector <int> pos[maxn]; int tour[2*maxn]; vector <int> heavy_vector; int weight[2*maxn]; int pw(int x, int y) { int r = 1; while (y) { if (y & 1) r = 1LL * r * x % mod; x = 1LL * x * x % mod; y >>= 1; } return r; } void dfs(int u) { tour[++m] = u; pos[u].push_back(m); sz[u] = 1; for (auto v: adj[u]) { if (v == dad[u]) continue; dad[v] = u; dfs(v); sz[u] += sz[v]; tour[++m] = u; pos[u].push_back(m); } } int fwt[2*maxn]; void upd(int l, int r, int d) { for (int p = l; p <= m; p += p & -p) fwt[p] = (fwt[p] + d) % mod; ++r; for (int p = r; p <= m; p += p & -p) fwt[p] = (fwt[p] + mod - d) % mod; } int get(int p) { int ret = 0; for (; p; p -= p & -p) ret = (ret + fwt[p]) % mod; return ret; } int main(void) { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> n >> q; int inv_n = pw(n, mod - 2); for (int i = 1; i < n; ++i) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } dfs(1); for (int i = 1; i <= n; ++i) if (adj[i].size() >= heavy) heavy_vector.push_back(i); while (q--) { int type, v; cin >> type >> v; if (type == 1) { int d; cin >> d; weight[v] = (weight[v] + d) % mod; if (adj[v].size() < heavy) { for (auto u: adj[v]) if (u != dad[v]) upd(pos[u][0], pos[u].back(), 1LL * d * (n - sz[u]) % mod * inv_n % mod); if (v == 1) continue; upd(1, pos[v][0] - 1, 1LL * d * sz[v] % mod * inv_n % mod); upd(pos[v].back() + 1, m, 1LL * d * sz[v] % mod * inv_n % mod); } } else { int ans = (weight[v] + get(pos[v][0])) % mod; for (auto u: heavy_vector) { if (u == v) continue; auto it = lower_bound(pos[u].begin(), pos[u].end(), pos[v][0]); if (it == pos[u].begin() || it == pos[u].end()) ans = (ans + 1LL * weight[u] * sz[u] % mod * inv_n) % mod; else { int p = tour[*(--it) + 1]; ans = (ans + 1LL * weight[u] * (n - sz[p]) % mod * inv_n) % mod; } } cout << ans << '\n'; } } return 0; }
1254
E
Send Tree to Charlie
Christmas was knocking on the door, and our protagonist, Bob, was preparing a spectacular present for his long-time second best friend Charlie. As chocolate boxes are lame, he decided to decorate a tree instead. Bob's tree can be represented as an undirected connected graph with $n$ nodes (numbered $1$ to $n$) and $n-1$ edges. Initially, Bob placed a decoration with label $i$ on node $i$, for each $1 \le i \le n$. However, as such a simple arrangement is lame, he decided to shuffle the decorations a bit. Formally, Bob did the following steps: - First, he listed the $n-1$ edges in some order. - Then, he considered the edges one by one in that order. For each edge $(u, v)$, he swapped the decorations of node $u$ with the one of node $v$. After finishing, Bob seemed satisfied with the arrangement, so he went to sleep. The next morning, Bob wakes up only to find out that his beautiful arrangement has been ruined! Last night, Bob's younger brother Bobo dropped some of the decorations on the floor while he was playing with the tree. Fortunately, no decorations were lost, so Bob can repair the tree in no time. However, he completely forgets how the tree looked like yesterday. Therefore, given the labels of the decorations still on the tree, Bob wants to know the number of possible configurations of the tree. As the result can be quite large, Bob will be happy if you can output the result modulo $1000000007$ ($10^9+7$). Note that, it is possible that there exists no possible configurations.
Let's solve an easier version of this problem first: when all $a_i$ is equal to $0$. Let $P[1..n-1]$ be some order of edges. If $n=2$ then the answer is clearly $1$. Otherwise, consider any leaf $u$ and its neighbor $v$. The label of $u$ in the end will depend solely on the relative position of the edge $(u, v)$ compared to other edges incident to $v$ in $P$. We can also prove that if that relative position is fixed then the final configuration will be the same. Therefore, if we add $u$ to the tree, the answer will be multiplied by $deg(v)$. It follows that the answer in this case will be $\displaystyle\prod_{u=1}^{n} deg(u)!$. We can also see that each configuration can be obtained by ordering the edges incident to $u$ for each vertex $u$. Now, let's consider some constraint of the form $a[u] = v$. If $u = v$ then clearly there's no such configuration. Otherwise, it will create some conditions of the orderings in each vertex. Formally, let $B(u)$ be the ordering of edges incident to $u$, and $u, t_1, \ldots, t_k, v$ be the path from $u$ to $v$, we have the following conditions: $(u, t_1)$ is the first edge in $B(u)$. $(t_i, t_{i-1})$ must be followed immediately by $(t_i, t_{i+1})$ in $B(t_i)$, for all $1 \le i \le k$. $(v, t_k)$ is the last edge in $B(v)$. Another thing to note is that in the final configuration, the sum of distance between $u$ and the vertex that contains label $u$ will be exactly $2n-2$ because each swap increases the sum by exactly $2$. Therefore, we can quit immediately upon finding out that the sum is larger than $2n-2$, and by that we ensure the total number of conditions will be $O(n)$. Now, we can solve each vertex independently. For each vertex, there will be no possible configurations iff at least one of the following holds: Some edge follows or is followed by more than one edge. The conditions create some cycles. The conditions create a path from the first edge to the last edge, but there exists some edge not in it. Otherwise, the conditions create some chains. We then multiply the answer by $k!$, where $k$ is the number of such chains, excluding those that contain the first edge or the last edge. Time complexity: $O(n)$.
[ "combinatorics", "dfs and similar", "dsu", "trees" ]
3,300
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int maxn = 500005; int n; vector <int> adj[maxn]; int a[maxn]; int dad[maxn]; int h[maxn]; vector <pair <int, int> > conditions[maxn]; int nxt[maxn], prv[maxn], seen[maxn]; void no(int ncase) { cerr << ncase << endl; cout << 0 << endl; exit(0); } void dfs(int u) { for (auto v: adj[u]) if (v != dad[u]) { dad[v] = u; h[v] = h[u] + 1; dfs(v); } } int cnt; ///total distance, must not be more than 2n-2 void go(int u, int v) { if (u == v) no(0); vector <int> from_u, to_v; ///naive LCA works here as long as we exit upon finding a conflict from_u.push_back(n + 1); ///first edge (fake) to_v.push_back(n + 2); ///last edge (fake) while (h[u] > h[v]) { from_u.push_back(u); u = dad[u]; } while (h[v] > h[u]) { to_v.push_back(v); v = dad[v]; } while (u != v) { from_u.push_back(u); u = dad[u]; to_v.push_back(v); v = dad[v]; } from_u.push_back(u); from_u.insert(from_u.end(), to_v.rbegin(), to_v.rend()); for (int i = 1; i + 1 < from_u.size(); ++i) conditions[from_u[i]].push_back({from_u[i-1], from_u[i+1]}); cnt += from_u.size() - 3; if (cnt > 2 * n - 2) no(0); ///important break } int main(void) { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> n; for (int i = 1; i < n; ++i) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } for (int i = 1; i <= n; ++i) { adj[i].push_back(n + 1); ///first edge (fake) adj[i].push_back(n + 2); ///last edge (fake) } for (int i = 1; i <= n; ++i) cin >> a[i]; if (n == 1) { cout << 1 << endl; exit(0); } dfs(1); for (int i = 1; i <= n; ++i) if (a[i] != 0) go(i, a[i]); ///answer 0 if: ///1. there are 2 or more incoming/outgoing ///conditions to/from an edge, or ///2. there is a cycle, or ///3. first (n+1) is connected to last (n+2), ///but does not contain all other edges. int ans = 1; for (int i = 1; i <= n; ++i) { ///check case 1 for (auto edge: conditions[i]) { int u = edge.first, v = edge.second; if (nxt[u] && nxt[u] != v) no(1); if (prv[v] && prv[v] != u) no(1); nxt[u] = v; prv[v] = u; } ///check case 2 for (auto u: adj[i]) if (!seen[u]) { seen[u] = 1; int cur = nxt[u]; while (cur) { if (cur == u) no(2); if (seen[cur]) break; seen[cur] = 1; cur = nxt[cur]; } } ///check case 3 if (nxt[n+1]) { int cur = n + 1, all = 1; while (cur) { if (cur == n + 2) break; ++all; cur = nxt[cur]; } if (cur == n + 2 && all < adj[i].size()) no(3); } ///all good - for now int free = 0; for (auto u: adj[i]) if (u <= n && !prv[u]) ///fake edges doesn't count ++free; if (prv[n+2]) --free; ///connected to last edge => not free for (int j = 1; j <= free; ++j) ans = 1ll * ans * j % mod; ///reset for (auto u: adj[i]) nxt[u] = prv[u] = seen[u] = 0; } ///no conflicts cout << ans << endl; return 0; }
1255
A
Changing Volume
Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume. There are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can either increase or decrease the current volume by $1$, $2$, or $5$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $0$. As Bob is so angry, he wants to change the volume to $b$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $a$ and $b$, finds the minimum number of presses to change the TV volume from $a$ to $b$.
Notice that if at some moment we increase the volume and at some moment we decrease the volume, we can remove those two actions and replace them with at most two new actions that are both increasing or decreasing (for instance, $+5$ $-1$ can be replaced with $+2$ $+2$; $+2$ and $-2$ can be replaced with nothing and $+2$ and $-1$ can be replaced with $+1$). We can see that replacing like this will not make the volume goes below zero at any moment. So, we will increase the volume all the time, or decrease all the time. Assume that we only increase the volume. It can be proved that for any set consists of only $1$s and $2$s and the sum of its elements is greater than or equal to $5$, it has a subset which its elements sums to $5$. This means that if we use $+1$ and $+2$ to increase the volume by at least $5$, we can replace some of those actions with a $+5$. Hence, it is optimal to increase the volume by $5$ until the gap between $a$ and $b$ is less than $5$, then the remaining job is trivial.
[ "math" ]
800
null
1255
B
Fridge Lockers
Hanh lives in a shared apartment. There are $n$ people (including Hanh) living there, each has a private fridge. $n$ fridges are secured by several steel chains. Each steel chain connects two \textbf{different} fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $n$ people can open it. \begin{center} {\small For exampe, in the picture there are $n=4$ people and $5$ chains. The first person knows passcodes of two chains: $1-4$ and $1-2$. The fridge $1$ can be open by its owner (the person $1$), also two people $2$ and $4$ (acting together) can open it.} \end{center} The weights of these fridges are $a_1, a_2, \ldots, a_n$. To make a steel chain connecting fridges $u$ and $v$, you have to pay $a_u + a_v$ dollars. Note that the landlord allows you to create \textbf{multiple chains connecting the same pair of fridges}. Hanh's apartment landlord asks you to create exactly $m$ steel chains so that all fridges are private. A fridge is private if and only if, among $n$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $i$ is not private if there exists the person $j$ ($i \ne j$) that the person $j$ can open the fridge $i$. For example, in the picture all the fridges are private. On the other hand, if there are $n=2$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person). Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $m$ chains, and if yes, output any solution that minimizes the total cost.
Author: I_love_tigersugar ft. MikeMirzayanov. Prepared by UncleGrandpa We modelize the problem as graph, where each fridge is a vertex and each chain is an edge between two vertexes. The problem is now equivalent to: Given a graph with $n$ vertexes, each vertex has a value $a_i \ge 0$. We have to add $m$ edges to the graph such that each vertex is connected to at least two different vertexes and the total cost of edges added is minimum. The cost of an edge is the sum of value of its two end-points. Now, each edge added will increase the sum of degree of all vertexes by 2. So adding m edges will make the sum of degree equal to $2 \times m$. Since each vertexes must be connected to at least $2$ other vertexes, the minimum sum of degree is $2 \times n$. Case 1: $2\times m < 2\times n \Leftrightarrow m<n$ In this case, it is obvious that the answer is $-1$. Case 2: $2\times m = 2\times n \Leftrightarrow m=n$ In this case, it is easy to see that the degree of each vertex will be exactly 2. As a result, no matter what edges we add, the result is still $2\times (a_1+a_2+...+a_n)$. But please take note that if $n=2$, then the answer will be $-1$ since for each vertex we have at most $1$ different vertex to connect to. Case 3(Of the original, pre-modified version of the problem): $2\times m > 2\times n \Leftrightarrow m>n$ Please read this excellent answer by Um_nik. All credit goes to him for the excellent proof.
[ "graphs", "implementation" ]
1,100
null
1255
C
League of Leesins
Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of $n$ ($n \ge 5$) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from $1$-st to $n$-th. After the final, he compared the prediction with the actual result and found out that the $i$-th team according to his prediction ended up at the $p_i$-th position ($1 \le p_i \le n$, all $p_i$ are unique). In other words, $p$ is a permutation of $1, 2, \dots, n$. As Bob's favorite League player is the famous "3ga", he decided to write down every $3$ consecutive elements of the permutation $p$. Formally, Bob created an array $q$ of $n-2$ triples, where $q_i = (p_i, p_{i+1}, p_{i+2})$ for each $1 \le i \le n-2$. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation $p$ even if Bob rearranges the elements of $q$ and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if $n = 5$ and $p = [1, 4, 2, 3, 5]$, then the original array $q$ will be $[(1, 4, 2), (4, 2, 3), (2, 3, 5)]$. Bob can then rearrange the numbers within each triple and the positions of the triples to get $[(4, 3, 2), (2, 3, 5), (4, 1, 2)]$. Note that $[(1, 4, 2), (4, 2, 2), (3, 3, 5)]$ is not a valid rearrangement of $q$, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her \textbf{any permutation} $p$ that is consistent with the array $q$ she was given.
There will be exactly $2$ numbers that appear only once in the input and they are the first and the last element of the permutation. Let $p_1$ be any of them and start with the only triple that contains $p_1$. If $x, y$ are the other members of the mentioned triple, there exists a unique triple that contains $x, y$ but not $p_1$. We can easily find that triple by searching through every triple that contains $x$ (and there are at most $3$ such triples). By repeating doing this, we can get a list $r$ that $r_i = perm(p_i, p_{i+1}, p_{i+2})$. From $r$, we can construct a permutation that satisfies the problem. Assume we know $p_1$ and $p_2$, then we can find the rest of the permutation easily. To determine which number is $p_2$, we can use the fact $p_2$ is the only number that only appears in $r_1$ and $r_2$.
[ "constructive algorithms", "implementation" ]
1,600
null
1256
A
Payment Without Change
You have $a$ coins of value $n$ and $b$ coins of value $1$. You always pay in exact change, so you want to know if there exist such $x$ and $y$ that if you take $x$ ($0 \le x \le a$) coins of value $n$ and $y$ ($0 \le y \le b$) coins of value $1$, then the total value of taken coins will be $S$. You have to answer $q$ independent test cases.
Firstly, we obviously need to take at least $S \% n$ coins of value $1$. If we cannot do it, the answer it NO. Otherwise we always can obtain the required sum $S$ if $a \cdot n + b \ge S$.
[ "math" ]
1,000
#include <iostream> using namespace std; int main() { int q; cin >> q; for (int qr = 0; qr < q; ++qr) { int a, b, n, s; cin >> a >> b >> n >> s; if (s % n <= b && 1ll * a * n + b >= s) { cout << "YES\n"; } else { cout << "NO\n"; } } }
1256
B
Minimize the Permutation
You are given a permutation of length $n$. Recall that the permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n=3$ but there is $4$ in the array). You can perform at most $n-1$ operations with the given permutation (it is possible that you don't perform any operations at all). The $i$-th operation allows you to swap elements of the given permutation on positions $i$ and $i+1$. \textbf{Each operation can be performed at most once}. The operations can be performed in arbitrary order. Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order. You can see the definition of the lexicographical order in the notes section. You have to answer $q$ independent test cases. For example, let's consider the permutation $[5, 4, 1, 3, 2]$. The minimum possible permutation we can obtain is $[1, 5, 2, 4, 3]$ and we can do it in the following way: - perform the second operation (swap the second and the third elements) and obtain the permutation $[5, 1, 4, 3, 2]$; - perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $[5, 1, 4, 2, 3]$; - perform the third operation (swap the third and the fourth elements) and obtain the permutation $[5, 1, 2, 4, 3]$. - perform the first operation (swap the first and the second elements) and obtain the permutation $[1, 5, 2, 4, 3]$; Another example is $[1, 2, 4, 3]$. The minimum possible permutation we can obtain is $[1, 2, 3, 4]$ by performing the third operation (swap the third and the fourth elements).
The following greedy solution works: let's take the minimum element and move it to the leftmost position we can. With this algorithm, all forbidden operations are form the prefix of operations: ($1, 2$), $(2, 3)$, ..., and so on. So we can carry the position of the leftmost operation we can perform $pos$. Initially, it is $1$. We repeat the algorithm until $pos \ge n$. Let's find the position of the minimum element among elements $a_{pos}, a_{pos + 1}, \dots, a_{n}$. Let this position be $nxt$. If $nxt = pos$ then let's increase $pos$ and continue the algorithm. Otherwise, we need to move the element from the position $nxt$ to the position $pos$ and then set $pos := nxt$. Time complexity: $O(n^2)$.
[ "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 q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> a(n); for (int j = 0; j < n; ++j) { cin >> a[j]; --a[j]; } int pos = 0; while (pos < n) { int nxt = min_element(a.begin() + pos, a.end()) - a.begin(); int el = a[nxt]; a.erase(a.begin() + nxt); a.insert(a.begin() + pos, el); if (pos == nxt) pos = nxt + 1; else pos = nxt; } for (auto it : a) cout << it + 1 << " "; cout << endl; } return 0; }
1256
C
Platforms Jumping
There is a river of width $n$. The left bank of the river is cell $0$ and the right bank is cell $n + 1$ (more formally, the river can be represented as a sequence of $n + 2$ cells numbered from $0$ to $n + 1$). There are also $m$ wooden platforms on a river, the $i$-th platform has length $c_i$ (so the $i$-th platform takes $c_i$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $n$. You are standing at $0$ and want to reach $n+1$ somehow. If you are standing at the position $x$, you can jump to any position in the range $[x + 1; x + d]$. \textbf{However} you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $d=1$, you can jump only to the next position (if it belongs to the wooden platform). \textbf{You can assume that cells $0$ and $n+1$ belong to wooden platforms}. You want to know if it is possible to reach $n+1$ from $0$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms. \textbf{Note that you should move platforms until you start jumping} (in other words, you first move the platforms and then start jumping). For example, if $n=7$, $m=3$, $d=2$ and $c = [1, 2, 1]$, then one of the ways to reach $8$ from $0$ is follow: \begin{center} {\small The first example: $n=7$.} \end{center}
This problem has a very easy idea but requires terrible implementation. Firstly, let's place all platforms as rightmost as we can. Thus, we will have the array, in which the first $n - \sum\limits_{i=1}^{m} c_i$ elements are zeros and other elements are $1$, $2$, ..., $m$. Now, let's start the algorithm. Firstly, we need to jump to the position $d$ or less. If we could jump to the position $d$ then we don't need to jump to some position to the left from $d$. But if we cannot do it, let's take the leftmost platform to the right from the position $d$ and move it in such a way that its left border will be at the position $d$. Now we can jump to the position $d$ and then jump by $1$ right to reach the position $d + c_1 - 1$. Let's repeat the same algorithm and continue jumping. If after some move we can jump to the position at least $n+1$ then we are done. Time complexity: $O(n^2)$ but I'm sure it can be implemented in $O(n \log n)$ or $O(n)$.
[ "greedy" ]
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, m, d; cin >> n >> m >> d; vector<int> c(m); for (int i = 0; i < m; ++i) { cin >> c[i]; } vector<int> ans(n + 2); for (int i = m - 1, pos = n; i >= 0; --i) { for (int len = 0; len < c[i]; ++len) { ans[pos - len] = i + 1; } pos -= c[i]; } int now = 0; while (true) { while (now + 1 < n + 1 && ans[now + 1] > 0) ++now; if (now + d >= n + 1) break; if (ans[now + d] == 0) { int lpos = -1; for (int i = now + d; i < n + 2; ++i) { if (ans[i] != 0) { lpos = i; break; } } if (lpos == -1) { cout << "NO" << endl; return 0; } int rpos = -1; for (int i = lpos; i < n + 2; ++i) { if (ans[i] == ans[lpos]) rpos = i; } while (ans[now + d] == 0) { swap(ans[lpos - 1], ans[rpos]); --lpos, --rpos; } } now += d; } cout << "YES" << endl; for (int i = 1; i <= n; ++i) { cout << ans[i] << " "; } cout << endl; return 0; }
1256
D
Binary String Minimizing
You are given a binary string of length $n$ (i. e. a string consisting of $n$ characters '0' and '1'). In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform \textbf{no more} than $k$ moves? It is possible that you do not perform any moves at all. Note that you can swap the same pair of adjacent characters with indices $i$ and $i+1$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move. You have to answer $q$ independent test cases.
This problem has a very standard solution: let's take the leftmost zero, place it as left as possible, and solve the problem without this zero and all operations we spent. But we should do it fast. Let's go from left to right and carry the number of ones on the prefix $cnt$. If we meet $1$, let's just increase $cnt$ and continue the algorithm. It is obvious that if we meet $0$ we need to make exactly $cnt$ swaps to place it before all ones. If we can do it, let's just add $0$ to the answer, decrease $k$ by $cnt$ and continue. Otherwise, this zero will be between some of these $cnt$ ones and we can place it naively. In this case, the suffix of the string will not change. If after all operations we didn't meet the case above, let's add all ones to the suffix of the resulting string. Time complexity: $O(n)$.
[ "greedy" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; while (q--) { int n; long long k; string s; cin >> n >> k >> s; string res; int cnt = 0; bool printed = false; for (int i = 0; i < n; ++i) { if (s[i] == '0') { if (cnt <= k) { res += '0'; k -= cnt; } else { res += string(cnt - k, '1'); res += '0'; res += string(k, '1'); res += s.substr(i + 1); cout << res << endl; printed = true; break; } } else { ++cnt; } } if (!printed) { res += string(cnt, '1'); cout << res << endl; } } return 0; }
1256
E
Yet Another Division Into Teams
There are $n$ students at your university. The programming skill of the $i$-th student is $a_i$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $2 \cdot 10^5$ students ready for the finals! Each team should consist of \textbf{at least three students}. Each student should belong to \textbf{exactly one team}. The diversity of a team is the difference between the \textbf{maximum} programming skill of some student that belongs to this team and the \textbf{minimum} programming skill of some student that belongs to this team (in other words, if the team consists of $k$ students with programming skills $a[i_1], a[i_2], \dots, a[i_k]$, then the diversity of this team is $\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$). The total diversity is the sum of diversities of all teams formed. Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students.
Let's sort all students by their programming skills but save the initial indices to restore the answer. Now we can understand that we don't need to compose the team of size greater than $5$ because in this case we can split it into more teams with fewer participants and obtain the same or even less answer. Now we can do the standard dynamic programming $dp_{i}$ - the minimum total diversity of the division if we divided the first $i$ students (in sorted order). Initially, $dp_{0} = 0$, all other values of $dp$ are $+\infty$. Because of the fact above, we can do only three transitions ($0$-indexed): $dp_{i + 3} = min(dp_{i + 3}, dp_{i} + a_{i + 2} - a_{i})$; $dp_{i + 4} = min(dp_{i + 4}, dp_{i} + a_{i + 3} - a_{i})$; $dp_{i + 5} = min(dp_{i + 5}, dp_{i} + a_{i + 4} - a_{i})$. The answer is $dp_{n}$ and we can restore it by standard carrying parent values (as a parent of the state we can use, for example, the number of participants in the team).
[ "dp", "greedy", "sortings" ]
2,000
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pt; #define x first #define y second #define mp make_pair const int N = 200043; const int INF = int(1e9) + 43; int n; int dp[N]; int p[N]; pt a[N]; int t[N]; int main() { scanf("%d", &n); for(int i = 0; i < n; i++) { a[i].y = i; scanf("%d", &a[i].x); } sort(a, a + n); for(int i = 1; i <= n; i++) { dp[i] = INF; p[i] = -1; } for(int i = 0; i < n; i++) for(int j = 3; j <= 5 && i + j <= n; j++) { int diff = a[i + j - 1].x - a[i].x; if(dp[i + j] > dp[i] + diff) { p[i + j] = i; dp[i + j] = dp[i] + diff; } } int cur = n; int cnt = 0; while(cur != 0) { for(int i = cur - 1; i >= p[cur]; i--) t[a[i].y] = cnt; cnt++; cur = p[cur]; } printf("%d %d\n", dp[n], cnt); for(int i = 0; i < n; i++) { if(i) printf(" "); printf("%d", t[i] + 1); } puts(""); return 0; }
1256
F
Equalizing Two Strings
You are given two strings $s$ and $t$ both of length $n$ and both consisting of lowercase Latin letters. In one move, you can choose any length $len$ from $1$ to $n$ and perform the following operation: - Choose any contiguous substring of the string $s$ of length $len$ and reverse it; - \textbf{at the same time} choose any contiguous substring of the string $t$ of length $len$ and reverse it as well. Note that during one move you reverse \textbf{exactly one} substring of the string $s$ and \textbf{exactly one} substring of the string $t$. Also note that borders of substrings you reverse in $s$ and in $t$ \textbf{can be different}, the only restriction is that you reverse the substrings of equal length. For example, if $len=3$ and $n=5$, you can reverse $s[1 \dots 3]$ and $t[3 \dots 5]$, $s[2 \dots 4]$ and $t[2 \dots 4]$, but not $s[1 \dots 3]$ and $t[1 \dots 2]$. Your task is to say if it is possible to make strings $s$ and $t$ equal after some (possibly, empty) sequence of moves. You have to answer $q$ independent test cases.
The necessary condition to make strings equal is that the number of occurrences of each character should be the same in both strings. Let's show that if some character appears more than once, we always can make strings equal. How? Let's sort the first string by swapping adjacent characters (and it does not matter what do we do in the second string). Then let's sort the second string also by swapping adjacent characters but choose the pair of adjacent equal characters in the first string (it always exists because the first string is already sorted). Otherwise, all characters in both strings are distinct and they lengths are at most $26$. Then the answer is YES if the parity of the number of inversions (the number inversions in the array $a$ is the number of such pairs of indices $i, j$ that $i < j$ but $a_i > a_j$) are the same. It can be proven in the following way: every swap of two adjacent elements changes the parity of the number of inversions. Time complexity: $O(max(n, AL^2))$.
[ "constructive algorithms", "sortings", "strings" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; string s, t; cin >> n >> s >> t; vector<int> cnts(26), cntt(26); for (int j = 0; j < n; ++j) { ++cnts[s[j] - 'a']; ++cntt[t[j] - 'a']; } bool ok = true; bool good = false; for (int j = 0; j < 26; ++j) { ok &= cnts[j] == cntt[j]; good |= cnts[j] > 1; } if (!ok) { cout << "NO" << endl; continue; } if (good) { cout << "YES" << endl; continue; } int invs = 0, invt = 0; for (int l = 0; l < n; ++l) { for (int r = 0; r < l; ++r) { invs += s[l] > s[r]; invt += t[l] > t[r]; } } ok &= (invs & 1) == (invt & 1); if (ok) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1257
A
Two Rival Students
You are the gym teacher in the school. There are $n$ students in the row. And there are two rivalling students among them. The first one is in position $a$, the second in position $b$. Positions are numbered from $1$ to $n$ from left to right. Since they are rivals, you want to maximize the distance between them. If students are in positions $p$ and $s$ respectively, then distance between them is $|p - s|$. You can do the following operation at most $x$ times: choose two \textbf{adjacent (neighbouring)} students and swap them. Calculate the maximum distance between two rivalling students after at most $x$ swaps.
To solve the problem you need to understand two facts: The answer can't be greater than $n - 1$; If current distance between rivaling student if less then $n-1$ we always can increment this distance by one swap; In means that answer is equal to $\min (n - 1, |a - b| + x)$.
[ "greedy", "math" ]
800
import kotlin.math.abs fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val (n, x, a, b) = readLine()!!.split(' ').map { it.toInt() } println(minOf(n - 1, abs(a - b) + x)) } }
1257
B
Magic Stick
Recently Petya walked in the forest and found a magic stick. Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a \textbf{positive} integer: - If the chosen number $a$ is even, then the spell will turn it into $\frac{3a}{2}$; - If the chosen number $a$ is greater than one, then the spell will turn it into $a-1$. Note that if the number is even and greater than one, then Petya can choose which spell to apply. Petya now has only one number $x$. He wants to know if his favorite number $y$ can be obtained from $x$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $x$ as it is.
$1$ cannot be transformed into any other number. $2$ can be transformed into $3$ or $1$, and $3$ can be transformed only into $2$. It means that if $x = 1$, then only $y = 1$ is reachable; and if $x = 2$ or $x = 3$, then $y$ should be less than $4$. Otherwise, we can make $x$ as large as we want, so if $x > 3$, any $y$ is reachable.
[ "math" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve() { int x, y; cin >> x >> y; if (x > 3) puts("YES"); else if (x == 1) puts(y == 1 ? "YES" : "NO"); else puts(y <= 3 ? "YES" : "NO"); } int main() { int tc; cin >> tc; while (tc--) solve(); }
1257
C
Dominated Subarray
Let's call an array $t$ dominated by value $v$ in the next situation. At first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any other number $v'$. For example, arrays $[1, 2, 3, 4, 5, 2]$, $[11, 11]$ and $[3, 2, 3, 2, 3]$ are dominated (by $2$, $11$ and $3$ respectevitely) but arrays $[3]$, $[1, 2]$ and $[3, 3, 2, 2, 1]$ are not. Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not. You are given array $a_1, a_2, \dots, a_n$. Calculate its shortest dominated subarray or say that there are no such subarrays. The subarray of $a$ is a contiguous part of the array $a$, i. e. the array $a_i, a_{i + 1}, \dots, a_j$ for some $1 \le i \le j \le n$.
At first, let's prove that the shortest dominated subarray has pattern like $v, c_1, c_2, \dots, c_k, v$ with $k \ge 0$ and dominated by value $v$. Otherwise, we can decrease its length by erasing an element from one of its ends which isn't equal to $v$ and it'd still be dominated. Now we should go over all pairs of the same numbers and check its subarrays... Or not? Let's look closely at the pattern: if $v$ and all $c_i$ are pairwise distinct then the pattern is dominated subarray itself. Otherwise, we can find in our pattern other shorter pattern and either the found pattern is dominated or it has the pattern inside it and so on. What does it mean? It means that the answer is just the shortest pattern we can find. And all we need to find is the shortest subarray with the same first and last elements or just distance between two consecutive occurrences of each number. We can do it by iterating over current position $i$ and keeping track of the last occurrence of each number in some array $lst[v]$. Then the current distance is $i - lst[a[i]] + 1$. The total complexity is $O(n)$.
[ "greedy", "implementation", "sortings", "strings", "two pointers" ]
1,200
#include<bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) 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]; return true; } inline void solve() { int ans = n + 5; vector<int> lst(n + 1, -1); for(int i = 0; i < n; i++) { if(lst[a[i]] != -1) ans = min(ans, i - lst[a[i]] + 1); lst[a[i]] = i; } if(ans > n) ans = -1; cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int tc; cin >> tc; while(tc--) { assert(read()); solve(); } return 0; }
1257
D
Yet Another Monster Killing Problem
You play a computer game. In this game, you lead a party of $m$ heroes, and you have to clear a dungeon with $n$ monsters. Each monster is characterized by its power $a_i$. Each hero is characterized by his power $p_i$ and endurance $s_i$. The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day. When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $k$ monsters, the hero fights with the monster $k + 1$). When the hero fights the monster, there are two possible outcomes: - if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends; - otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $i$-th hero cannot defeat more than $s_i$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends. Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.
At first, lets precalc array $bst$; $bst_i$ is equal to maximum hero power whose endurance is greater than or equal to $i$. Now let's notice that every day it's profitable for as to kill as many monster as possible. Remains to understand how to calculate it. Suppose that we already killed $cnt$ monsters. If $a_{cnt+1} > bst_1$ then answer is -1, because we can't kill the $cnt+1$-th monster. Otherwise we can kill at least $x = 1$ monsters. All we have to do it increase the value $x$ until conditions $\max\limits_{cnt < i \le cnt + x} a_i \le bst_x$ holds. After calculating the value $x$ we just move to the next day with $cnt + x$ killed monsters.
[ "binary search", "data structures", "dp", "greedy", "sortings", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; int t; int n; int a[N]; int m; int p[N], s[N]; int bst[N]; int main() { scanf("%d", &t); for(int tc = 0; tc < t; ++tc){ scanf("%d", &n); for(int i = 0; i <= n; ++i) bst[i] = 0; for(int i = 0; i < n; ++i) scanf("%d", a + i); scanf("%d", &m); for(int i = 0; i < m; ++i){ scanf("%d %d", p + i, s + i); bst[s[i]] = max(bst[s[i]], p[i]); } for(int i = n - 1; i >= 0; --i) bst[i] = max(bst[i], bst[i + 1]); int pos = 0; int res = 0; bool ok = true; while(pos < n){ ++res; int npos = pos; int mx = 0; while(true){ mx = max(mx, a[npos]); if(mx > bst[npos - pos + 1]) break; ++npos; } if(pos == npos){ ok = false; break; } pos = npos; } if(!ok) res = -1; printf("%d\n", res); } return 0; }
1257
E
The Contest
A team of three programmers is going to play a contest. The contest consists of $n$ problems, numbered from $1$ to $n$. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems $a_{1, 1}, a_{1, 2}, \dots, a_{1, k_1}$. The second one has received problems $a_{2, 1}, a_{2, 2}, \dots, a_{2, k_2}$. The third one has received all remaining problems ($a_{3, 1}, a_{3, 2}, \dots, a_{3, k_3}$). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? \textbf{It is possible that after redistribution some participant (or even two of them) will not have any problems}.
Suppose we want to divide $r$ first problems of the contest between the first contestant and the second contestant (the first contestant will get $l$ first problems, and the second contestant will get $r - l$ problems in the middle), and then give all the remaining problems to the third contestant. We are going to iterate on $r$ from $0$ to $n$ and, for each possible $r$, find the best value of $l$. Okay. Now suppose we fixed $l$ and $r$, and now we want to calculate the number of problems that should be redistributed. Let's denote $cnt_{l, i}$ as the number of problems among $l$ first ones given to the $i$-th contestant, $cnt_{r, i}$ as the number of problems among $r$ last ones given to the $i$-th contestant, and $cnt_{m, i}$ as the number of problems in the middle given to the $i$-th contestant. Obviously, the answer for fixed $l$ and $r$ is $cnt_{l, 2} + cnt_{l, 3} + cnt_{m, 1} + cnt_{m, 3} + cnt_{r, 1} + cnt_{r, 2}$, but we don't like this expression because we don't know how to minimize it for fixed $r$. We know that, for fixed $r$, the values of $cnt_{l, i} + cnt_{m, i}$ and $cnt_{r, i}$ are constant. Using that, we may arrive at the fact that minimizing $cnt_{l, 2} + cnt_{l, 3} + cnt_{m, 1} + cnt_{m, 3} + cnt_{r, 1} + cnt_{r, 2}$ is the same as minimizing $cnt_{l, 2} - cnt_{l, 1}$ for fixed $r$ - and now we have a way to quickly find best possible $l$ for fixed $r$.
[ "data structures", "dp", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { int k1, k2, k3; scanf("%d %d %d", &k1, &k2, &k3); int n = k1 + k2 + k3; vector<int> a(n); for(int i = 0; i < k1; i++) { int x; scanf("%d", &x); a[x - 1] = 0; } for(int i = 0; i < k2; i++) { int x; scanf("%d", &x); a[x - 1] = 1; } for(int i = 0; i < k3; i++) { int x; scanf("%d", &x); a[x - 1] = 2; } int ans = 0; int bestp = 0; for(int i = 0; i < n; i++) if(a[i] != 2) ans++; vector<int> cntl(3); vector<int> cntr(3); for(int i = 0; i < n; i++) cntr[a[i]]++; for(int i = 0; i < n; i++) { cntl[a[i]]++; cntr[a[i]]--; bestp = max(bestp, cntl[0] - cntl[1]); int curans = cntr[0] + cntr[1] + cntl[2] + cntl[0] - bestp; ans = min(ans, curans); } cout << ans << endl; }
1257
F
Make Them Similar
Let's call two numbers similar if their binary representations contain the same number of digits equal to $1$. For example: - $2$ and $4$ are similar (binary representations are $10$ and $100$); - $1337$ and $4213$ are similar (binary representations are $10100111001$ and $1000001110101$); - $3$ and $2$ are not similar (binary representations are $11$ and $10$); - $42$ and $13$ are similar (binary representations are $101010$ and $1101$). You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$. You may choose a non-negative integer $x$, and then get another array of $n$ integers $b_1$, $b_2$, ..., $b_n$, where $b_i = a_i \oplus x$ ($\oplus$ denotes bitwise XOR). Is it possible to obtain an array $b$ where all numbers are similar to each other?
Iterating over all possible values of $x$ and checking them may be too slow (though heavily optimized brute force is difficult to eliminate in this problem), so we need to speed this approach up. The resulting number consists of $30$ bits. Let's use the classical meet-in-the-middle trick: try all $2^{15}$ combinations of $15$ lowest bits, try all $2^{15}$ combinations of $15$ highest bits, and somehow "merge" the results. When we fix a combination of $15$ lowest bits, we fix $15$ lowest bits in every $b_i$. Suppose that there are $cnt_{0, i}$ ones among $15$ lowest bits of $b_i$. Analogically, when we fix a combination of $15$ highest bits, we fix $15$ highest bits in every $b_i$. Suppose that there are $cnt_{1, i}$ ones among $15$ highest bits of $b_i$. We want to find a combination of lowest and highest bits such that $cnt_{0, i} + cnt_{1, i}$ is the same for each $i$. Let's represent each combination of $15$ lowest bits with an $(n-1)$-dimensional vector with coordinates $(cnt_{0, 1} - cnt_{0, 2}, cnt_{0, 1} - cnt_{0, 3}, \dots, cnt_{0, 1} - cnt_{0, n})$. Let's also represent each combination of $15$ highest bits with an $(n-1)$-dimensional vector with coordinates $(cnt_{1, 1} - cnt_{1, 2}, cnt_{1, 1} - cnt_{1, 3}, \dots, cnt_{1, 1} - cnt_{1, n})$. We want to find a combination of lowest bits and a combination of highest bits such that their vectors are opposite. We can do so, for example, by precalculating all vectors for all combinations of $15$ lowest bits, storing them in a map or a trie, iterating on a combination of $15$ highest bits and searching for the opposite vector in the map/trie.
[ "bitmasks", "brute force", "hashing", "meet-in-the-middle" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long li; const int N = 143; const int K = 15; const int V = 5000000; int n; li a[N]; int lst[V]; map<int, int> nxt[V]; int t = 1; li a1[N]; li a2[N]; int get_nxt(int v, int x) { if(!nxt[v].count(x)) nxt[v][x] = t++; return nxt[v][x]; } void add(vector<int> diff, int x) { int v = 0; for(auto i : diff) v = get_nxt(v, i); lst[v] = x; } int try_find(vector<int> diff) { int v = 0; for(auto i : diff) { if(!nxt[v].count(i)) return -1; v = nxt[v][i]; } return lst[v]; } vector<int> get_diff(li arr[N], int x) { vector<int> cnt(n); for(int i = 0; i < n; i++) cnt[i] = __builtin_popcountll(arr[i] ^ x); vector<int> diff(n - 1); for(int i = 0; i + 1 < n; i++) diff[i] = cnt[i + 1] - cnt[0]; return diff; } int main() { cin >> n; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) { a1[i] = (a[i] >> K); a2[i] = a[i] ^ (a1[i] << K); } for(int i = 0; i < (1 << K); i++) { vector<int> d = get_diff(a1, i); add(d, i); } for(int i = 0; i < (1 << K); i++) { vector<int> d = get_diff(a2, i); for(int j = 0; j + 1 < n; j++) d[j] *= -1; int x = try_find(d); if(x != -1) { li res = (li(x) << K) ^ i; cout << res << endl; return 0; } } cout << -1 << endl; return 0; return 0; }
1257
G
Divisor Set
You are given an integer $x$ represented as a product of $n$ its prime divisors $p_1 \cdot p_2, \cdot \ldots \cdot p_n$. Let $S$ be the set of all positive integer divisors of $x$ (including $1$ and $x$ itself). We call a set of integers $D$ good if (and only if) there is no pair $a \in D$, $b \in D$ such that $a \ne b$ and $a$ divides $b$. Find a good subset of $S$ with maximum possible size. Since the answer can be large, print the size of the subset modulo $998244353$.
The problem consists of two parts: what do we want to calculate and how to calculate it? What do we want to calculate? There are several ways to figure it out. At first, you could have met this problem before and all you need is to remember a solution. At second, you can come up with the solution in a purely theoretical way - Hasse diagram can help with it greatly. Let's define $deg(x)$ as the number of primes in prime factorization of $x$. For example, $deg(2 \cdot 3 \cdot 2) = 3$ and $deg(1) = 0$. If you look at Hasse diagram of $p_1 \cdot \ldots \cdot p_n$ you can see that all divisors with $deg(d) = i$ lies on level $i$. If $x$ is divisible by $y$ then $deg(x) > deg(y)$ so all divisors on the same level don't divide each other. Moreover, the diagram somehow symmetrical about its middle level and sizes of levels are increasing while moving to the middle. It gives us an idea that the answer is the size of the middle level, i.e. the number of divisors with $deg(d) = \frac{n}{2}$. The final way is just to brute force the answers for small $x$-s and find the sequence in OEIS with name A096825, where the needed formulas are described. The second step is to calculate the number of divisors with $deg(d) = \frac{n}{2}$. Suppose we have $m$ distinct primes $p_j$ and the number of occurences of $p_j$ is equal to $cnt_j$. Then we need to calculate pretty standard knapsack problem where you need to calculate number of ways to choose subset of size $\frac{n}{2}$ where you can take each $p_j$ up to $cnt_j$ times. Or, formally, number of vectors $(x_1, x_2, \dots x_m)$ with $\sum\limits_{j = 0}^{j = m}{x_j} = \frac{n}{2}$ and $0 \le x_j \le cnt_j$. Calculating the answer using $dp[pos][sum]$ will lead to time limit, so we need to make the following transformation. Let's build for each $p_j$ a polynomial $f_j(x) = 1 + x + x^2 + \dots + x^{cnt_j}$. Now the answer is just a coefficient before $x^{\frac{n}{2}}$ in product $f_1(x) \cdot f_2(x) \cdot \ldots \cdot f_m(x)$. Note, that the product has degree $n$, so we can multiply polynomials efficiently with integer FFT in the special order to acquire $O(n \log^2(n))$ time complexity. There several ways to choose the order of multiplications. At first, you can, at each step, choose two polynomials with the lowest degree and multiply them. At second, you can use the divide-and-conquer technique by dividing the current segment in two with pretty same total degrees. At third, you can also use D-n-C but divide the segment at halves and, it seems still to be $O(n \log^2(n))$ in total. What about the proof of the solution? Thanks to tyrion__ for the link at the article: https://pure.tue.nl/ws/files/4373475/597494.pdf. The result complexity is $O(n \log^2(n))$ time and $O(n)$ space (if carefully written). Note, that the hidden constant in integer FFT is pretty high and highly depends on the implementation, so it's possible for poor implementations not to pass the time limit.
[ "divide and conquer", "fft", "greedy", "math", "number theory" ]
2,600
#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()) const int LOGN = 18; const int MOD = 998244353; int g = 3; int mul(int a, int b) { return int(a * 1ll * b % MOD); } int norm(int a) { while(a >= MOD) a -= MOD; while(a < 0) a += MOD; return a; } int binPow (int a, int k) { int ans = 1; for (; k > 0; k >>= 1) { if (k & 1) ans = mul(ans, a); a = mul(a, a); } return ans; } int inv(int a) { return binPow(a, MOD - 2); } vector<int> w[LOGN], rv; bool precalced = false; void precalc() { if(precalced) return; precalced = true; int wb = binPow(g, (MOD - 1) / (1 << LOGN)); fore(st, 0, LOGN) { w[st].assign(1 << st, 1); int bw = binPow(wb, 1 << (LOGN - st - 1)); int cw = 1; fore(k, 0, (1 << st)) { w[st][k] = cw; cw = mul(cw, bw); } } rv.assign(1 << LOGN, 0); fore(i, 1, sz(rv)) rv[i] = (rv[i >> 1] >> 1) | ((i & 1) << (LOGN - 1)); } const int MX = (1 << LOGN) + 3; inline void fft(int a[MX], int n, bool inverse) { precalc(); int ln = __builtin_ctz(n); assert((1 << ln) < MX); assert((1 << ln) == n); fore(i, 0, n) { int ni = rv[i] >> (LOGN - ln); if(i < ni) swap(a[i], a[ni]); } for(int st = 0; (1 << st) < n; st++) { int len = (1 << st); for(int k = 0; k < n; k += (len << 1)) { fore(pos, k, k + len) { int l = a[pos]; int r = mul(a[pos + len], w[st][pos - k]); a[pos] = norm(l + r); a[pos + len] = norm(l - r); } } } if(inverse) { int in = inv(n); fore(i, 0, n) a[i] = mul(a[i], in); reverse(a + 1, a + n); } } int aa[MX], bb[MX], cc[MX]; vector<int> multiply(const vector<int> &a, const vector<int> &b) { int ln = 1; while(ln < (sz(a) + sz(b))) ln <<= 1; fore(i, 0, ln) aa[i] = (i < sz(a) ? a[i] : 0); fore(i, 0, ln) bb[i] = (i < sz(b) ? b[i] : 0); fft(aa, ln, false); fft(bb, ln, false); fore(i, 0, ln) cc[i] = mul(aa[i], bb[i]); fft(cc, ln, true); vector<int> ans(cc, cc + ln); while(ans.back() == 0) ans.pop_back(); return ans; } int n; vector<int> ps; inline bool read() { if(!(cin >> n)) return false; ps.resize(n); fore(i, 0, n) cin >> ps[i]; return true; } struct cmp { bool operator ()(const vector<int> &a, const vector<int> &b) { return sz(a) < sz(b); } }; inline void solve() { map<int, int> cnt; fore (i, 0, n) cnt[ps[i]]++; multiset< vector<int>, cmp > polys; for (auto p : cnt) polys.emplace(p.second + 1, 1); while (sz(polys) > 1) { auto it2 = polys.begin(); auto it1 = it2++; polys.insert(multiply(*it1, *it2)); polys.erase(it1); polys.erase(it2); } auto poly = *polys.begin(); // cerr << '['; // fore(i, 0, sz(poly)) { // if(i) cerr << ", "; // cerr << poly[i]; // } // cerr << ']' << endl; cout << poly[n / 2] << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1260
A
Heating
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house. Your house has $n$ rooms. In the $i$-th room you can install at most $c_i$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $k$ sections is equal to $k^2$ burles. Since rooms can have different sizes, you calculated that you need at least $sum_i$ sections in total in the $i$-th room. For each room calculate the minimum cost to install at most $c_i$ radiators with total number of sections not less than $sum_i$.
Let's denote the number of sections in the $i$-th radiator as $x_i$. Let's prove that in the optimal answer $\max(x_i) - \min(x_i) < 2$. Proof by contradiction: suppose we have $x$ and $y \ge x + 2$ in the answer, let's move $1$ from $y$ to $x$ and check: $(x + 1)^2 + (y - 1)^2 = x^2 + 2x + 1 + y^2 - 2y + 1 = (x^2 + y^2) + 2(x - y + 1) < x^2 + y^2$ Finally, there is the only way to take $x_1 + x_2 + \dots + x_c = sum$ with $\max(x_i) - \min(x_i) \le 1$. And it's to take $(sum \mod c)$ elements with value $\left\lfloor \frac{sum}{c} \right\rfloor + 1$ and $c - (sum \mod c)$ elements with $\left\lfloor \frac{sum}{c} \right\rfloor$.
[ "math" ]
1,000
#include<bits/stdc++.h> using namespace std; int c, sum; inline bool read() { if(!(cin >> c >> sum)) return false; return true; } inline void solve() { int d = sum / c; int rem = sum % c; cout << rem * (d + 1) * (d + 1) + (c - rem) * d * d << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif int n; cin >> n; while(n--) { read(); solve(); } return 0; }
1260
B
Obtain Two Zeroes
You are given two integers $a$ and $b$. You may perform any number of operations on them (possibly zero). During each operation you should choose any positive integer $x$ and set $a := a - x$, $b := b - 2x$ or $a := a - 2x$, $b := b - x$. Note that you may choose different values of $x$ in different operations. Is it possible to make $a$ and $b$ equal to $0$ simultaneously? Your program should answer $t$ independent test cases.
Let's assume $a \le b$. Then the answer is YES if two following conditions holds: $(a+b) \equiv 0 \mod 3$, because after each operation the value $(a+b) \mod 3$ does not change; $a \cdot 2 \ge b$.
[ "binary search", "math" ]
1,300
for t in range(int(input())): a, b = map(int, input().split()) if a > b: a, b = b, a print ('YES' if ( ((a + b) % 3) == 0 and a * 2 >= b) else 'NO')
1260
C
Infinite Fence
You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor. You must paint a fence which consists of $10^{100}$ planks in two colors in the following way (suppose planks are numbered from left to right from $0$): - if the index of the plank is divisible by $r$ (such planks have indices $0$, $r$, $2r$ and so on) then you must paint it red; - if the index of the plank is divisible by $b$ (such planks have indices $0$, $b$, $2b$ and so on) then you must paint it blue; - if the index is divisible both by $r$ and $b$ \textbf{you can choose the color} to paint the plank; - otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all \textbf{painted} planks of the fence in ascending order: if there are $k$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed. The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.
At first, suppose that $r \le b$ (if not - swap them). Let's look at the case, where $gcd(r, b) = 1$. We can be sure that there will be a situation where the $pos$-th plank is painted in blue and $pos + 1$ plank is painted in red. It's true because it's equivalent to the solution of equation $r \cdot x - b \cdot y = 1$. And all we need to check that interval $(pos, pos + b)$ contains less than $k$ red planks. Or, in formulas, $(k - 1) \cdot r + 1 \ge b$. The situation with $gcd(r, b) > 1$ is almost the same if we look only at positions, which are divisible by $gcd(r, b)$ - in other words we can just divide $r$ on $gcd$ and $b$ on $gcd$ and check the same condition.
[ "greedy", "math", "number theory" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long li; li a, b, k; inline bool read() { if(!(cin >> a >> b >> k)) return false; return true; } inline void solve() { li g = __gcd(a, b); a /= g; b /= g; if(a > b) swap(a, b); if((k - 1) * a + 1 < b) cout << "REBEL"; else cout << "OBEY"; cout << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif int tc; cin >> tc; while(tc--) { read(); solve(); } return 0; }
1260
D
A Game with Traps
You are playing a computer game, where you lead a party of $m$ soldiers. Each soldier is characterised by his agility $a_i$. The level you are trying to get through can be represented as a straight line segment from point $0$ (where you and your squad is initially located) to point $n + 1$ (where the boss is located). The level is filled with $k$ traps. Each trap is represented by three numbers $l_i$, $r_i$ and $d_i$. $l_i$ is the location of the trap, and $d_i$ is the danger level of the trap: whenever a soldier with agility lower than $d_i$ steps on a trap (that is, moves to the point $l_i$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $r_i$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers. You have $t$ seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring \textbf{all of the chosen soldiers} to the boss. To do so, you may perform the following actions: - if your location is $x$, you may move to $x + 1$ or $x - 1$. This action consumes one second; - if your location is $x$ and the location of your squad is $x$, you may move to $x + 1$ or to $x - 1$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with $d_i$ greater than agility of some soldier from the squad). This action consumes one second; - if your location is $x$ and there is a trap $i$ with $r_i = x$, you may disarm this trap. This action is done instantly (it consumes no time). Note that after each action both your coordinate and the coordinate of your squad should be integers. You have to choose the maximum number of soldiers such that they all can be brought from the point $0$ to the point $n + 1$ (where the boss waits) in no more than $t$ seconds.
When we fix a set of soldiers, we can determine a set of traps that may affect our squad: these are the traps with danger level greater than the lowest agility value. So we can use binary search on minimum possible agility of a soldier that we can choose. How should we actually bring our soldiers to the boss? Each trap that can affect our squad can be actually treated as a segment $[l_i, r_i]$ such that our squad cannot move to $l_i$ until we move to $r_i$ and disarm this trap. We should walk through such segments for three times: the first time we walk forwards without our squad to disarm the trap, the second time we walk backwards to return to our squad, and the third time we walk forwards with our squad. So the total time we have to spend can be calculated as $n + 1 + 2T$, where $T$ is the number of unit segments belonging to at least one trap-segment - and it can be calculated with event processing algorithms or with segment union. Time complexity is $O(n \log n)$ or $O(n \log^2 n)$, but it is possible to write a solution in $O(n \alpha(n))$ without binary search.
[ "binary search", "dp", "greedy", "sortings" ]
1,900
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<cstdio> #include<vector> #include<algorithm> #include<map> using namespace std; typedef pair<int, int> pt; #define x first #define y second int m, n, k, t; vector<int> l, r, d, a; bool can(int x) { int mn = int(1e9); for (int i = 0; i < x; i++) mn = min(mn, a[i]); vector<pt> segm; for (int i = 0; i < k; i++) if (d[i] > mn) segm.push_back(make_pair(l[i], r[i])); int req_time = 0; sort(segm.begin(), segm.end()); int lastr = 0; for (auto s : segm) { if (s.x <= lastr) { req_time += max(0, s.y - lastr); lastr = max(s.y, lastr); } else { req_time += s.y - s.x + 1; lastr = s.y; } } req_time = 2 * req_time + n + 1; return req_time <= t; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif scanf("%d %d %d %d", &m, &n, &k, &t); a.resize(m); for (int i = 0; i < m; i++) scanf("%d", &a[i]); sort(a.begin(), a.end()); reverse(a.begin(), a.end()); l.resize(k); r.resize(k); d.resize(k); for (int i = 0; i < k; i++) scanf("%d %d %d", &l[i], &r[i], &d[i]); int lf = 0; int rg = m + 1; while (rg - lf > 1) { int mid = (lf + rg) / 2; if (can(mid)) lf = mid; else rg = mid; } printf("%d\n", lf); return 0; }
1260
E
Tournament
You are organizing a boxing tournament, where $n$ boxers will participate ($n$ is a power of $2$), and your friend is one of them. All boxers have different strength from $1$ to $n$, and boxer $i$ wins in the match against boxer $j$ if and only if $i$ is stronger than $j$. The tournament will be organized as follows: $n$ boxers will be divided into pairs; the loser in each pair leaves the tournament, and $\frac{n}{2}$ winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength $i$ can be bribed if you pay him $a_i$ dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?
If our friend is the strongest boxer, he wins without any bribing. Otherwise, we have to bribe the strongest boxer - and he can defeat some $\frac{n}{2} - 1$ other boxers (directly or indirectly). Suppose we chose the boxers he will defeat, then there is another strongest boxer. If our friend is the strongest now, we don't need to bribe anyone; otherwise we will bribe the strongest remaining boxer again, and he can defeat $\frac{n}{4} - 1$ other boxers, and so on. The only thing that's unclear is which boxers should be defeated by the ones we bribe. We may use dynamic programming to bribe them: $dp_{i, j}$ is the minimum cost to bribe $i$ boxers so that all boxers among $j$ strongest ones are either bribed or defeated by some bribed boxer. For each value of $i$ we know the maximum amount of boxers that are defeated by $i$ bribed boxers, so the transitions in this dynamic programming are the following: if we can't defeat the next boxer "for free" (our bribed boxers have already defeated as many opponents as they could), we have to bribe him; otherwise, we either bribe him or consider him defeated by some other boxer. Overall complexity is $O(n \log n)$.
[ "brute force", "dp", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; const int LOGN = 20; const int N = (1 << LOGN) + 99; const long long INF = 1e18; int n; int a[N]; long long dp[LOGN+2][N]; int sum[100]; long long calc(int cnt, int pos){ long long &res = dp[cnt][pos]; if(res != -1) return res; if(a[pos] == -1) return res = 0; int rem = sum[cnt] - pos; res = INF; if(cnt < LOGN) res = calc(cnt + 1, pos + 1) + a[pos]; if(rem > 0) res = min(res, calc(cnt, pos + 1)); return res; } int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); for(int i = 1, x = n / 2; i < 100; ++i, x /= 2) sum[i] = sum[i - 1] + x; reverse(a, a + n); memset(dp, -1, sizeof dp); printf("%lld", calc(0, 0)); return 0; }
1260
F
Colored Tree
You're given a tree with $n$ vertices. The color of the $i$-th vertex is $h_{i}$. The value of the tree is defined as $\sum\limits_{h_{i} = h_{j}, 1 \le i < j \le n}{dis(i,j)}$, where $dis(i,j)$ is the number of edges on the shortest path between $i$ and $j$. The color of each vertex is lost, you only remember that $h_{i}$ can be any integer from $[l_{i}, r_{i}]$(inclusive). You want to calculate the sum of values of all trees meeting these conditions modulo $10^9 + 7$ (the set of edges is fixed, but each color is unknown, so there are $\prod\limits_{i = 1}^{n} (r_{i} - l_{i} + 1)$ different trees).
Let's set the root as $1$. Define $lca(u,v)$ as the lowest common ancestor of vertices $u$ and $v$, $dep(u)$ as the depth of vertex $u$ $(dep(u) = dis(1,u))$. Obviously $dis(u,v) = dep(u) + dep(v) - 2 \times dep(lca(u,v))$. The answer we want to calculate is $\sum_{G}{\sum_{h_{i} = h_{j},i < j}{dis(i,j)}}$ where $G$ represent all possible colorings of the tree. We can enumerate the color $c$. For a fixed color $c$, we need to calculate $\sum_{l_{i} \leq c \leq r_{i} , l_{j} \leq c \leq r_{j}}{[dis(i,j) \times \prod_{k \neq i,j}{(r_{k} - l_{k} + 1)}]}$ Let $P = \prod_{1 \leq i \leq n}{(r_{i} - l_{i} + 1)} , g_{i} = r_{i} - l_{i} + 1$. Also denote $V(i)$ as a predicate which is true iff $l_{i} \leq c \leq r_{i}$. $\begin{align} & \sum_{l_{i} \leq c \leq r_{i} , l_{j} \leq c \leq r_{j}}{[dis(i,j) \times \prod_{k \neq i,j}{(r_{k} - l_{k} + 1)}]} \\ = & \sum_{V(i) \land V(j)}{dep(i) \times \frac{P}{g_{i} \times g_{j}}} + \sum_{V(i) \land V(j)}{dep(j) \times \frac{P}{g_{i} \times g_{j}}} - 2 \times \sum_{V(i) \land V(j)}{dep(lca(i,j)) \times \frac{P}{g_{i} \times g_{j}}} \\ = & P \times (\sum_{V(i)}{\frac{dep(i)}{g_{i}}}) \times (\sum_{V(i)}{\frac{1}{g_{i}}}) - P \times \sum_{V(i)}{\frac{dep(i)}{g_{i}^2}} - 2P \times \sum_{V(i) \land V(j)}{dep(lca(i,j)) \times \frac{1}{g_{i} \times g_{j}}} \end{align}$ Now our problem is how to maintain this formula while enumerating the color $c$. $P \times (\sum_{V(i)}{\frac{dep(i)}{g_{i}}}) \times (\sum_{V(i)}{\frac{1}{g_{i}}})$ can be easily maintained. For $\sum_{V(i) \land V(j)}{dep(lca(i,j)) \times \frac{1}{g_{i} \times g_{j}}}$, we can add $\frac{1}{g_{i}}$ to all vertices in path $i$ to $1$ (for each existing vertex $i$), and when new vertex is added, just calculate the sum of vertices on path from $i$ to $1$, minus the contribution of vertex $1$ (because there are $dep(u) + 1$ vertices in the path $u$ to $1$), and multiply it $\frac{1}{g_{i}}$. Similar operation can be used to handle the situation when some vertex disappears. All of this can be done with HLD. Overall it's $O(c_{max} + nlog^2(n))$.
[ "data structures", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; int n ; const int maxn = 1e5 + 5; const int mod = 1e9 + 7 ; vector<int> E[maxn]; vector<int> in[maxn] , out[maxn]; int cm = 0; int l[maxn] , dfn = 0 , dep[maxn]; int g[maxn]; int siz[maxn] , top[maxn] , h[maxn] , f[maxn]; ///-----segment tree struct seg { int l , r; int sum , add ; }Node[maxn * 4]; void build(int u,int l,int r) { Node[u].l = l , Node[u].r = r; Node[u].sum = Node[u].add = 0; if(l == r) return ; build(u<<1 , l , (l + r >> 1)); build(u<<1|1 , (l + r >>1) + 1 , r); return ; } void pd(int u) { Node[u].sum = (1LL*Node[u].add*(Node[u].r - Node[u].l + 1) + Node[u].sum) % mod ; if(Node[u].l == Node[u].r) { Node[u].add = 0 ;return ; } (Node[u<<1].add += Node[u].add ) %= mod; (Node[u<<1|1].add += Node[u].add ) %= mod; Node[u].add = 0 ; return ; } void modify(int u,int l,int r,int v) { if(Node[u].l == l && Node[u].r == r) { (Node[u].add += v ) %= mod; pd(u) ; return ; return ; } pd(u) ; if(Node[u<<1].r >= r) {modify(u<<1 , l , r , v) ; pd(u<<1|1);} else if(Node[u<<1|1].l <= l) {modify(u<<1|1 , l , r , v) ; pd(u<<1) ;} else { modify(u<<1 , l , Node[u<<1].r , v) ; modify(u<<1|1 , Node[u<<1|1].l , r , v); } Node[u].sum = (Node[u<<1].sum + Node[u<<1|1].sum) % mod; return ; } int query(int u,int l,int r) { pd(u) ; if(Node[u].l == l && Node[u].r == r) return Node[u].sum ; if(Node[u<<1].r >= r) return query(u<<1 , l , r) ; else if(Node[u<<1|1].l <= l) return query(u<<1|1 , l , r); else return (query(u<<1 , l , Node[u<<1].r) + query(u<<1|1 , Node[u<<1|1].l , r)) % mod; } ///---segment tree end void dfs(int fa,int u,int d) { f[u] = fa; dep[u] = d;siz[u] = 1;h[u] = -1; for(int i = 0;i < E[u].size();i++) { if(E[u][i] != fa) { dfs(u , E[u][i] , d + 1) ;siz[u] += siz[E[u][i]]; if(h[u] == -1 || siz[E[u][i]] > siz[E[u][h[u]]]) h[u] = i; } } return ; } void dfs2(int fa,int u) { l[u] = ++dfn; if(h[u] != -1) { top[E[u][h[u]]] = top[u] ; dfs2(u , E[u][h[u]]); } for(int i = 0;i < E[u].size();i++) { if(E[u][i] != fa && i != h[u]) { top[E[u][i]] = E[u][i] ; dfs2(u , E[u][i]) ; } } return ; } int fpow(int a,int b) { int ans = 1; while(b) { if(b & 1) ans = (1LL * ans * a) % mod; a = (1LL * a * a) % mod ;b >>= 1; } return ans; } void add(int u,int v) { while(u) { modify(1 , l[top[u]] , l[u] , v) ; u = f[top[u]] ; } return ; } int cal(int u) { int ans = mod - query(1 , 1 , 1); while(u) { ans = (ans + query(1 , l[top[u]] , l[u])) % mod; u = f[top[u]] ; } return ans; } int main() { scanf("%d",&n) ; int P = 1; for(int i = 1;i <= n;i++) { int l , r;scanf("%d%d",&l,&r) ; in[l].push_back(i) ; out[r + 1].push_back(i) ; cm = max(cm , r); g[i] = fpow(r - l + 1 , mod - 2) ; P = 1LL * P * (r - l + 1) % mod; } for(int i = 1;i < n;i++) { int u , v;scanf("%d%d",&u,&v) ; E[u].push_back(v) ; E[v].push_back(u) ; } dfs(0 , 1 , 0) ; top[1] = 1; dfs2(0 , 1) ; build(1 , 1 , n) ; int ans = 0 , cur = 0; int d1 = 0 , d2 = 0 , u , d3 = 0; for(int i = 1;i <= cm;i++) { for(int j = 0;j < out[i].size();j++) { u = out[i][j] ; d1 = (d1 - 1LL * dep[u] * g[u] % mod + mod) % mod; d2 = (d2 - g[u] + mod) % mod ; d3 = (d3 - 1LL*dep[u]*g[u] % mod * g[u] % mod + mod) % mod; add(u , mod - g[u]) ; cur = (cur - 1LL * g[u] * cal(u) % mod + mod) % mod; } for(int j = 0;j < in[i].size();j++) { u = in[i][j] ; d1 = (d1 + 1LL * dep[u] * g[u]) % mod; d2 = (d2 + g[u]) % mod; d3 = (d3 + 1LL*dep[u]*g[u]%mod*g[u]) % mod; cur = (cur + 1LL * g[u] * cal(u)) % mod; add(u , g[u]) ; } ans = (ans + 1LL * d1 * d2%mod - 2LL*cur - d3) % mod; ans = (ans + mod) % mod; } ans = 1LL * ans * P % mod; printf("%d\n",ans); return 0; }
1261
F
Xor-Set
You are given two sets of integers: $A$ and $B$. You need to output the sum of elements in the set $C = \{x | x = a \oplus b, a \in A, b \in B\}$ modulo $998244353$, where $\oplus$ denotes the bitwise XOR operation. Each number should be counted only once. For example, if $A = \{2, 3\}$ and $B = \{2, 3\}$ you should count integer $1$ only once, despite the fact that you can get it as $3 \oplus 2$ and as $2 \oplus 3$. So the answer for this case is equal to $1 + 0 = 1$. Let's call a segment $[l; r]$ a set of integers $\{l, l+1, \dots, r\}$. The set $A$ is given as a union of $n_A$ segments, the set $B$ is given as a union of $n_B$ segments.
Consider a segment tree over the interval $[0,2^{60}-1]$, a node representing a segment of length $2^n$ would represent all numbers with the first $60-n$ bits same, with all possible last n bits. In other words, the binary representation of any number in the segment would be $a_1a_2a_3\ldots a_{59-n}a_{60-n}x_1x_2x_3\ldots x_n$, where all $a_i$ and $x_i$ is either 0 or 1. $a_1$ to $a_{60-n}$ would be fixed and all $x_i$s can be arbitrarily chosen. We can observe that if we have two segments $A$ and $B$ in the tree, all possible numbers that equals the xor sum of a number in $A$ and a number in $B$ also forms a segment in the tree, with the length of $\max(|A|,|B|)$, and the unchanging bits is equal to the xor sum of the two segment's unchanging bits. Using this observation we would get an $O( (n^2 \log^2 10^{18}) \log (n^2 \log^2 10^{18}))$ or $O( n^2 \log^2 10^{18})$ algorithm, depending on the sorting method. First, we get all segments that compose the intervals in $A$ and $B$, we can get $O( n^2 \log^2 10^{18})$ resulting segments. Then we are left with evaluating the sum in the combination of segments. We can sort these segments to get the answer. This algorithm will get an MLE in practice since the number of resulting segments could easily exceed $10^8$. To improve this algorithm, we can make another observation that when segments of different sizes are combined as described above, the smaller segment is equivalent to the ancestor of the same size as the bigger segment. Let's call all the segments in the decomposition of the input the "real" segments, and all segments with a "real" segment in the subtree as "auxiliary" segments. Then we could iterate over 60 possible values of the size of the segment, and for each value, we could iterate over the "real" segments of set $A$ and "auxiliary" segments of set $B$ and add the results to the set. We can prove that the number of both "real" and "auxiliary" segments of any size is not greater than $4n$. Thus, the solution runs at $O( (n^2 \log 10^{18}) \log (n^2 \log 10^{18}))$ or $O( n^2 \log 10^{18})$ algorithm, depending on the sorting method.
[ "bitmasks", "divide and conquer", "math" ]
3,100
null
1263
A
Sweet Problem
You have three piles of candies: red, green and blue candies: - the first pile contains only red candies and there are $r$ candies in it, - the second pile contains only green candies and there are $g$ candies in it, - the third pile contains only blue candies and there are $b$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day. Find the maximal number of days Tanya can eat candies? Each day she needs to eat \textbf{exactly} two candies.
Sort the values of $r$, $g$, $b$ such that $r \geq g \geq b$. Now consider two cases. If $r \geq g + b$, then Tanya can take $g$ candies from piles $r$ and $g$, and then - $b$ candies from piles $r$ and $b$. After that there may be a bunch of candies left in the pile $r$ that Tanya won't be able to eat, so the answer is $g + b$. Otherwise, we need to achieve the equality of the piles $r$, $g$, $b$. First, we make equal $r$ and $g$ by eating $r - g$ from the piles $r$ and $b$ (this can always be done since $r < g + b$). Then we make equal the piles $g$, $b$ by eating $g - b$ from the piles $r$ and $g$. After that, $r = g = b$, and we can get three different cases. $r = g = b = 0$ - nothing needs to be done, Tanya has already eaten all the sweets; $r = g = b = 1$ - you can take candy from any of two piles so in the end there will always be one candy left; $r = g = b \geq 2$ - we reduce all the piles by $2$, taking, for example, a candy from piles $r$ and $g$, $g$ and $b$, $r$ and $b$. With such actions, Tanya eventually reaches the two previous cases, since the sizes of the piles are reduced by 2. Since with this strategy we always have 0 or 1 candy at the end, Tanya will be able to eat candies for $\lfloor \frac{r + g + b}{2} \rfloor$ days.
[ "math" ]
1,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int a[3]; cin >> a[0] >> a[1] >> a[2]; sort(a, a + 3); if (a[2] <= a[0] + a[1]) cout << (a[0] + a[1] + a[2]) / 2 << endl; else cout << a[0] + a[1] << endl; } }
1263
B
PIN Codes
A PIN code is a string that consists of exactly $4$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0. Polycarp has $n$ ($2 \le n \le 10$) bank cards, the PIN code of the $i$-th card is $p_i$. Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $n$ codes would become different. Formally, in one step, Polycarp picks $i$-th card ($1 \le i \le n$), then in its PIN code $p_i$ selects one position (from $1$ to $4$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different. Polycarp quickly solved this problem. Can you solve it?
Group all the numbers into groups of equals PIN-Codes. Note that the size of each such group does not exceed $10$. Therefore, in each PIN-Code we need to change no more than $1$ digits. If the group consists of $1$ element, then we do nothing, otherwise, we take all the PIN-codes except one from this group and change exactly one digit in them so that the new PIN-code becomes unique.
[ "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<char> calced(n); vector<string> a(n); set<string> have; int res = 0; for (string &pin : a) { cin >> pin; have.insert(pin); } for (int i = 0; i < n; i++) { if (calced[i]) { continue; } vector<int> sameIds; for (int j = i + 1; j < n; j++) { if (a[i] == a[j]) { sameIds.push_back(j); calced[j] = 1; res++; for (int k = 0; k < 4 && a[i] == a[j]; k++) { for (char c = '0'; c <= '9'; c++) { string t = a[j]; t[k] = c; if (!have.count(t)) { have.insert(t); a[j] = t; break; } } } } } } cout << res << "\n"; for (string& s : a) { cout << s << "\n"; } } int main() { int test; cin >> test; while (test--) { solve(); } }
1263
C
Everyone is a Winner!
On the well-known testing system MathForces, a draw of $n$ rating units is arranged. The rating will be distributed according to the following algorithm: if $k$ participants take part in this event, then the $n$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain — it is not given to any of the participants. For example, if $n = 5$ and $k = 3$, then each participant will recieve an $1$ rating unit, and also $2$ rating units will remain unused. If $n = 5$, and $k = 6$, then none of the participants will increase their rating. Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help. For example, if $n=5$, then the answer is equal to the sequence $0, 1, 2, 5$. Each of the sequence values (and only them) can be obtained as $\lfloor n/k \rfloor$ for some positive integer $k$ (where $\lfloor x \rfloor$ is the value of $x$ rounded down): $0 = \lfloor 5/7 \rfloor$, $1 = \lfloor 5/5 \rfloor$, $2 = \lfloor 5/2 \rfloor$, $5 = \lfloor 5/1 \rfloor$. Write a program that, for a given $n$, finds a sequence of all possible rating increments.
There are two approaches to solving this problem. Mathematical Solution Note that the answer will always contain the numbers $0 \le x < \lfloor \sqrt{n} \rfloor$. You can verify this by solving the equation $\lfloor \frac{n}{k} \rfloor = x$, equivalent to the inequality $x \le \frac{n}{k} < x + 1$, for integer values of $k$. The solution to this double inequality is the interval $k \in \left (\frac{n}{x + 1};\; \frac{n}{x} \right]$, whose length is $\frac{n}{x^2 + x}$. For $x < \lfloor \sqrt{n} \rfloor$ $\frac{n}{x^2 + x} > 1$, and on an interval of length greater than 1 there is always a whole solution $k = \lfloor \frac{n}{x} \rfloor$, so all integers $0 \le x < \lfloor \sqrt {n} \rfloor$ belong to the answer. Note that we no longer need to iterate over the values of $k > \lfloor \sqrt{n} \rfloor$, because these numbers always correspond to the values $0 \le x < \lfloor \sqrt {n} \rfloor$. Thus, it is possible, as in a naive solution, to iterate over all the values of $k$ upto $\lfloor \sqrt{n} \rfloor$ and add $x = \lfloor \frac{n}{k} \rfloor$ to the answer. It remains only to carefully handle the case $k = \lfloor \sqrt{n} \rfloor$. Total complexity of the solution: $\mathcal{O} (\sqrt{n} \log n)$ or $\mathcal{O} (\sqrt{n})$ Algorithmic Solution In the problem, it could be assumed that there are not so many numbers in the answer (after all, they still need to be printed, which takes the majority of the program execution time). Obviously, $n$ always belongs to the answer. Note that as $k$ increases, the value of $x = \lfloor \frac{n}{k} \rfloor$ decreases. Thus, using a binary search, you can find the smallest value of $k'$ such that $\frac{n}{k'} < x$. Value $x' = \frac{n}{k'}$ will be the previous one for $x$ in the answer. Total complexity of the solution: $\mathcal{O} (\sqrt{n} \log n)$
[ "binary search", "math", "meet-in-the-middle", "number theory" ]
1,400
// #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <bits/stdc++.h> #define ALL(s) (s).begin(), (s).end() #define rALL(s) (s).rbegin(), (s).rend() #define sz(s) (int)(s).size() #define mkp make_pair #define pb push_back #define sqr(s) ((s) * (s)) using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef unsigned int ui; #ifdef EUGENE mt19937 rng(1337); #else mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); #endif void solve() { int n; cin >> n; vector<int> ans; int s = (int)sqrtl(n); for (int i = 0; i <= s; i++) ans.pb(i); for (int i = 1; i <= s; i++) ans.pb(n / i); sort(ALL(ans)); ans.resize(unique(ALL(ans)) - ans.begin()); cout << sz(ans) << endl; for (int &x : ans) cout << x << " "; cout << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); #ifdef EUGENE freopen("input.txt", "r", stdin); // freopen("output.txt", "r", stdout); #endif int t; cin >> t; while (t--) solve(); }
1263
D
Secret Passwords
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $n$ passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $a$ and $b$ as follows: - two passwords $a$ and $b$ are equivalent if there is a letter, that exists in both $a$ and $b$; - two passwords $a$ and $b$ are equivalent if there is a password $c$ from the list, which is equivalent to both $a$ and $b$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: - admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; - admin's password is "d", then you can access to system by using only "d". \textbf{Only one} password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to \textbf{guaranteed} access to the system. Keep in mind that the hacker does not know which password is set in the system.
This problem can be solved in many ways (DSU, bipartite graph, std::set and so on). A solution using a bipartite graph will be described here. Consider a bipartite graph with $26$ vertices corresponding to each letter of the Latin alphabet in the first set and $n$ vertices corresponding to each password in the second set. Connect each password and the letters that are part of this password with an edge. From the definition of equivalence of passwords, it is easy to understand that the answer to the problem is the number of connected components in this bipartite graph. Total complexity: $\mathcal{O}(n)$.
[ "dfs and similar", "dsu", "graphs" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = (int)2e5 + 100; vector<int> g[N]; char used[N]; void addEdge(int v, int u) { g[v].push_back(u); g[u].push_back(v); } void dfs(int v) { used[v] = 1; for (int to : g[v]) { if (!used[to]) { dfs(to); } } } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { string s; cin >> s; for (char c : s) { addEdge(i, n + c - 'a'); } } int res = 0; for (int i = n; i < n + 26; i++) { if (!g[i].empty() && !used[i]) { dfs(i); res++; } } cout << res; return 0; }
1263
E
Editor
The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text. Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left. Initially, the cursor is in the first (leftmost) character. Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position. Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence. Formally, correct text (CT) must satisfy the following rules: - any line without brackets is CT (the line can contain whitespaces); - If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT; - two consecutively written CT is also CT. Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me). The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command. The correspondence of commands and characters is as follows: - L — move the cursor one character to the left (remains in place if it already points to the first character); - R — move the cursor one character to the right; - any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now. For a complete understanding, take a look at the first example and its illustrations in the note below. You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to: - check if the current text in the editor is a correct text; - if it is, print the least number of colors that required, to color all brackets. If two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is $2$, and for the bracket sequence (()(()())())(()) — is $3$. Write a program that prints the minimal number of colors after processing each command.
To respond to requests, you need two stacks. The first stack will contain all the brackets at the positions left than the cursor position, and the second one all the remaining ones. Also, for each closing bracket in the first stack, we will maintain the maximum depth of the correct bracket sequence (CBS) ending with this bracket. Similarly, in the second stack, we will maintain the maximum depth of CBS that starting in this bracket. Since the brackets are added to the stack at the end and one at a time, you can easily recalculate this value. Even in the left stack, you need to maintain the number of opening brackets that do not have a pair of closing brackets, and in the right stack the number of closing brackets that do not have a pair of opening brackets. If the previous two values are equal, then the current line is CBS. Otherwise, there is either one non-closed bracket or one bracket that does not have an opening one. The answer to the problem, after each query, will be a maximum of three values - the maximum depth in the left stack, the maximum depth in the right stack and the number of non-closed brackets (the number of non-opened brackets in the right stack does not need to be taken into account, since if the line is CBS, then it is the number of open brackets in the left). Total complexity is $\mathcal{O}(n)$.
[ "data structures", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; struct MyStack { int cnt = 0; int allOpens = 0; stack<int> s; stack<int> minValue; stack<int> maxValue; void push(int x) { s.push(x); cnt += x; if (x == 1) { allOpens += 1; } minValue.push((minValue.size() ? min(minValue.top(), cnt) : cnt)); maxValue.push((maxValue.size() ? max(maxValue.top(), cnt) : cnt)); } void pop() { if (s.size() == 0) { return; } cnt -= s.top(); if (s.top() == 1) { allOpens -= 1; } s.pop(); minValue.pop(); maxValue.pop(); } int top() { return s.top(); } bool isCorrect() { return (minValue.size() == 0 || minValue.top() >= 0); } int depth() { return (maxValue.size() ? maxValue.top() : 0); } }; int main() { int n; cin >> n; string s; cin >> s; MyStack left, right; vector<int> ans(n); for (int i = 0; i < n; i++) { right.push(0); } left.push(0); int pos = 0; for (int i = 0; i < n; i++) { if (s[i] == 'L') { if (pos != 0) { pos--; right.push(-left.top()); left.pop(); } } else if (s[i] == 'R') { pos++; left.push(-right.top()); right.pop(); } else if (s[i] == '(') { left.pop(); left.push(1); } else if (s[i] == ')') { left.pop(); left.push(-1); } else { left.pop(); left.push(0); } if (left.isCorrect() && right.isCorrect() && left.cnt == right.cnt) { cout << max({left.depth(), right.depth(), left.cnt}) << " "; } else { cout << "-1 "; } } }
1263
F
Economic Difficulties
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea! Each grid (main and reserve) has a head node (its number is $1$). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly $n$ nodes, which do not spread electricity further. In other words, every grid is a rooted directed tree on $n$ leaves with a root in the node, which number is $1$. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid. Also, the palace has $n$ electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device. \begin{center} {\small In this example the main grid contains $6$ nodes (the top tree) and the reserve grid contains $4$ nodes (the lower tree). There are $3$ devices with numbers colored in blue.} \end{center} It is guaranteed that the whole grid (two grids and $n$ devices) can be shown in this way (like in the picture above): - main grid is a top tree, whose wires are directed 'from the top to the down', - reserve grid is a lower tree, whose wires are directed 'from the down to the top', - devices — horizontal row between two grids, which are numbered from $1$ to $n$ from the left to the right, - wires between nodes do not intersect. Formally, for each tree exists a depth-first search from the node with number $1$, that visits leaves in order of connection to devices $1, 2, \dots, n$ (firstly, the node, that is connected to the device $1$, then the node, that is connected to the device $2$, etc.). Businessman wants to sell (remove) \textbf{maximal} amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.
We assume that the leaves of the trees are numbered in the same way as the devices to which these leaves are connected. Let's calculate $cost_{l, r}$ ($l \le r$) for each tree (let's call them $upperCost_{l, r}$ and $lowerCost_{l, r}$) - the maximum number of edges that can be removed so that on the segment $[l, r]$ exists a path from each leaf to the root of the opposite tree. Let's calculate $cost_{l, r}$ for some fixed $l$. Let's call 'bamboo' the connected set of ancestors of the node $v$ such that each node has at most $1$ child, and the node $v$ itself is in this set. Obviously, $cost_{l, l}$ is the maximum length of $l$'s 'bamboo'. Suppose we have already calculated $cost_{l, r - 1}$. Let's calculate $cost_{l, r -1 }$. Obviously, we can remove all edges counted in $cost_{l, r - 1}$. We can also remove the resulting 'bamboo' of the leaf $r$ (because we do not need to have paths from the leaves $[l, r]$ to the root in the tree, for which we are calculating $cost$). Let's prove that we cannot remove more edges. For each tree exists a depth-first search from the node $1$, that visits leaves in order of connection to devices, so for each node $v$ the set of leaf indices in its subtree is a segment. If there is $r$ in the segment for the node $v$, then the $r$-th leaf is in the subtree of the node $v$. Let's have a look at the nodes whose subtree does not contain leaf $r$. If in their subtree there are nodes not from the segment $[l, r]$, then we cannot remove edge to the parent of this node, because we don't want to lose the path to the root for the nodes out of the segment $[l, r]$ (we are calculating the answer only for the segment $[l, r]$). So in the $v$'s subtree leaves are only from the segment $[l, r]$. Leaves from the segment $[l, r - 1]$ were calculated in $cost_{l, r - 1}$. Then the segment for the $v$'s nodes is $[i, r], l \le i$. So we can remove the edge from each such node to its parent. And the set of these nodes is a 'bamboo' from the leaf $r$ because we have already removed all 'bamboos' on $[l, r - 1]$ segment. So to calculate $cost_{l, r}$ it is enough to know $cost_{l, r - 1}$ and the maximum length of $r$'s 'bamboo'. This can be calculated in $\mathcal{O}(n(a + b))$ time complexity. Let's calculate $dp_i$ - the answer for the $i$-th prefix. Let's take a look at the answer: some suffix of leaves has a path to the root in only one tree, and the rest of prefix has a maximum answer (if not, then we take the maximum answer for the prefix, which will improve the answer). Then we get the formula $dp_i = \max\limits_{0 \le j < i}(dp_{j} + \max(upperCost_{j, i-1}, lowerCost_{j, i-1}))$ (and $dp_0 = 0$), which can be calculated in the $\mathcal{O}(n^2)$ time complexity. Then the answer is $dp_n$. Challenge: Can you solve this problem with linear time complexity (for example, $\mathcal{O}(n + a + b)$)?
[ "data structures", "dfs and similar", "dp", "flows", "graphs", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; #define sz(x) int((x).size()) #define all(x) begin(x), end(x) #ifdef LOCAL #define eprint(x) cerr << #x << " = " << (x) << endl #define eprintf(args...) fprintf(stderr, args), fflush(stderr) #else #define eprint(x) #define eprintf(...) #endif vector<vector<int>> precalc(int n, vector<int> p, vector<int> id) { vector<vector<int>> res(n, vector<int>(n)); for (int l = 0; l < n; l++) { vector<int> deg(sz(p)); for (int i = 1; i < sz(p); i++) deg[p[i]]++; int val = 0; for (int r = l; r < n; r++) { int v = id[r]; while (v != 0 && deg[v] == 0) { deg[p[v]]--; v = p[v]; val++; } res[l][r] = val; } } return res; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<vector<int>> p(2); vector<vector<int>> id(2); for (int i = 0; i < 2; i++) { int vn; cin >> vn; p[i].resize(vn); for (int v = 1; v < vn; v++) { cin >> p[i][v]; p[i][v]--; } id[i].resize(n); for (int j = 0; j < n; j++) { cin >> id[i][j]; id[i][j]--; } } vector<vector<vector<int>>> cost(2); for (int i = 0; i < 2; i++) cost[i] = precalc(n, p[i], id[i]); vector<int> dp(n + 1); for (int i = 0; i < n; i++) { for (int j = i + 1; j <= n; j++) { dp[j] = max(dp[j], dp[i] + max( cost[0][i][j - 1], cost[1][i][j - 1] )); } } cout << dp[n] << endl; }
1264
A
Beautiful Regional Contest
So the Beautiful Regional Contest (BeRC) has come to an end! $n$ students took part in the contest. The final standings are already known: the participant in the $i$-th place solved $p_i$ problems. Since the participants are primarily sorted by the number of solved problems, then $p_1 \ge p_2 \ge \dots \ge p_n$. Help the jury distribute the gold, silver and bronze medals. Let their numbers be $g$, $s$ and $b$, respectively. Here is a list of requirements from the rules, which all must be satisfied: - for each of the three types of medals, at least one medal must be awarded (that is, $g>0$, $s>0$ and $b>0$); - the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $g<s$ and $g<b$, but there are no requirements between $s$ and $b$); - each gold medalist must solve strictly more problems than any awarded with a silver medal; - each silver medalist must solve strictly more problems than any awarded a bronze medal; - each bronze medalist must solve strictly more problems than any participant not awarded a medal; - the total number of medalists $g+s+b$ should not exceed half of all participants (for example, if $n=21$, then you can award a maximum of $10$ participants, and if $n=26$, then you can award a maximum of $13$ participants). The jury wants to reward with medals the total \textbf{maximal} number participants (i.e. to maximize $g+s+b$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.
To solve this problem, we have to make the following observations: All participants who solved the same number of problems must be either not awarded at all or all are awarded a same type of medal. All $g+s+b$ awarded participants are the first $g+s+b$ participants. Suppose we have an optimal solution with $g$ gold medals, $s$ silver medals and $b$ bronze medals where $g+s+b$ is maximized. We can make the followings changes that resulted in another valid (and still optimal) solution: Only keep gold medalist who solved most problem. For others, we change their medal types from gold to silver. After this change, $g+s+b$ is unchanged and other rules are still satisfied. Similarly, only keep a minimized number of silver medalist who solved most problems among all silver medalist and the number of kept silver must strictly larger than the number gold medals. For others, we change their medal types from silver to bronze. After this changed, $g+s+b$ is unchanged and other rules are still satisfied. Time complexity: $\mathcal{O}(n)$
[ "greedy", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; map<int,int> c; forn(i, n) { int pi; cin >> pi; c[-pi]++; } vector<int> pp; for (auto p: c) pp.push_back(p.second); bool ok = false; int g = pp[0]; int i = 1; int s = 0; while (s <= g && i < pp.size()) s += pp[i++]; if (g < s) { int b = 0; while (b <= g && i < pp.size()) b += pp[i++]; while (i < pp.size() && g + s + b + pp[i] <= n / 2) b += pp[i++]; if (g < b && g + s + b <= n / 2) { ok = true; cout << g << " " << s << " " << b << endl; } } if (!ok) cout << 0 << " " << 0 << " " << 0 << endl; } }
1264
B
Beautiful Sequence
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to $1$. More formally, a sequence $s_1, s_2, \ldots, s_{n}$ is beautiful if $|s_i - s_{i+1}| = 1$ for all $1 \leq i \leq n - 1$. Trans has $a$ numbers $0$, $b$ numbers $1$, $c$ numbers $2$ and $d$ numbers $3$. He wants to construct a beautiful sequence using all of these $a + b + c + d$ numbers. However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?
Firstly, let's arrange even numbers. It is optimal to arrange those numbers as $0, 0, 0,\ldots,0,2, 2, \ldots 2$. Because we can place number $1$ anywhere while number $3$ only between two numbers $2$ or at the end beside a number $2$. So we need to maximize the number of positions where we can place number $3$. The above gives us an optimal way. The next step is to place the remaining numbers $1, 3$. Inserting them in internal positions first then at the ends later. Base on the above argument, we can do as following way that eliminates corner case issues: Starting from a number (try all possible value $0, 1, 2, 3$). At any moment, if $x$ is the last element and there is at least number $x - 1$ remains, we append $x - 1$ otherwise we append $x + 1$ or stop if there is no $x + 1$ left. If we manage to use all numbers then we have a beautiful sequence and answer is 'YES'.
[ "brute force", "constructive algorithms", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { map<int, int> hs; cin >> hs[0] >> hs[1] >> hs[2] >> hs[3]; int total = hs[0] + hs[1] + hs[2] + hs[3]; for (int st = 0; st < 4; st++) if (hs[st]) { vector<int> res; auto ths = hs; ths[st]--; res.push_back(st); int last = st; for (int i = 0; i < total - 1; i++) { if (ths[last - 1]) { ths[last - 1]--; res.push_back(last - 1); last--; } else if (ths[last + 1]) { ths[last + 1]--; res.push_back(last + 1); last++; } else { break; } } if ((int) res.size() == total) { cout << "YES\n"; for (int i = 0; i < (int) res.size(); i++) { cout << res[i] << " \n"[i == (int) res.size() - 1]; } return 0; } } cout << "NO\n"; return 0; }
1264
C
Beautiful Mirrors with queries
Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$. \textbf{Some mirrors are called checkpoints}. Initially, only the $1$st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities: - The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day; - In the other case, Creatnx will feel upset. The next day, Creatnx will start asking \textbf{from the checkpoint with a maximal number that is less or equal to $i$}. \textbf{There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints}. You are given $q$ queries, each query is represented by an integer $u$: If the $u$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $u$-th mirror is no longer a checkpoint. After each query, you need to calculate the expected number of days until Creatnx becomes happy. Each of this numbers should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
Assuming that currently there are $k$ checkpoints $1 = x_1 < x_2 < \ldots < x_k \leq n$, the journey becoming happy of Creatnx can be divided to $k$ stages where in $i$-th stage Creatnx "moving" from mirror $x_i$ to mirror at position $x_{i+1} - 1$. Denote the $i$-th stage as $(x_i, x_{i+1}-1)$. These $k$ stages are independent so the sum of expected number of days Creatnx spending in each stage will be the answer to this problem. When a new checkpoint $b$ appear between 2 old checkpoints $a$ and $c$, stage $(a, c - 1)$ will be removed from the set of stages and 2 new stages will be added, they are $(a, b - 1)$ and $(b, c - 1)$. Similarly, when a checkpoint $b$ between 2 checkpoints $a$ and $c$ is no longer a checkpoint, 2 stages $(a, b - 1)$ and $(b, c - 1)$ will be removed from the set of stages and new stage $(a, c-1)$ will be added. These removed/added stages can be fastly retrieved by storing all checkpoints in an ordered data structure such as set in C++. For removed/added stages, we subtract/add its expected number of days from/to the current answer. We see that when a query occurs, the number of stages removed/added is small (just 3 in total). Therefore, if we can calculate the expected number of days for an arbitrary stage fast enough, we can answer any query in a reasonable time. From the solution of problem Beautiful Mirror, we know that the expected number of days Creatnx spending in stage $(u, v)$ is: $\frac{1 + p_u + p_u \cdot p_{u+1} + \ldots + p_u \cdot p_{u+1} \cdot \ldots \cdot p_{v-1}}{p_u \cdot p_{u+1} \cdot \ldots \cdot p_v} = \frac{A}{B}$ The denominator $B$ can be computed by using a prefix product array - a common useful trick. We prepare an array $s$ where $s_i = p_1 \cdot p_2 \cdot \ldots \cdot p_i$. After that, $B$ can be obtained by using 1 division: $B = \frac{s_v}{s_{u-1}}$. For numerator $A$, we also use the same trick. An array $t$ will be prepare where $t_i = p_1 + p_1 \cdot p_2 + \ldots + p_1 \cdot p_2 \ldots \cdot p_i$. We have $t_{v-1} = t_{u-2} + p_1\cdot p_2 \cdot\ldots\cdot p_{u-1} \cdot A$ so $A = \frac{t_{v-1} - t_{u-2}}{p_1\cdot p_2 \cdot\ldots\cdot p_{u-1}} = \frac{t_{v-1} - t_{u-2}}{s_{u-1}}$.
[ "data structures", "probabilities" ]
2,400
#include <bits/stdc++.h> using namespace std; const int MOD = 119 << 23 | 1; struct node_t { int prd; int val; node_t() { prd = val = 0; } }; node_t operator + (node_t a, node_t b) { if (!a.prd) return b; if (!b.prd) return a; node_t c; c.prd = (long long) a.prd * b.prd % MOD; c.val = (long long) a.val * b.prd % MOD; c.val = (c.val + b.val) % MOD; return c; } int inv(int a) { int r = 1, t = a, k = MOD - 2; while (k) { if (k & 1) r = (long long) r * t % MOD; t = (long long) t * t % MOD; k >>= 1; } return r; } int main() { int n, q; cin >> n >> q; vector<int> p(n); for (int i = 0; i < n; i++) cin >> p[i], p[i] = (long long) p[i] * inv(100) % MOD; vector<node_t> st(n << 2); auto upd = [&] (int p, node_t val) { for (st[p += n] = val; 1 < p; ) p >>= 1, st[p] = st[p << 1] + st[p << 1 | 1]; }; auto query = [&] (int l, int r) { node_t lres, rres; for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1) { if (l & 1) { lres = lres + st[l++]; } if (r & 1) { rres = st[--r] + rres; } } return (lres + rres).val; }; for (int i = 0; i < n; i++) { node_t c; c.val = c.prd = inv(p[i]); upd(i, c); } set<int> ss; ss.insert(0); int res = query(0, n - 1); for (int i = 0; i < q; i++) { string op; int u; cin >> u; u--; auto it = ss.lower_bound(u); if (it == ss.end() || *it != u) { it = ss.insert(u).first; int lo = *(--it); it++; int hi = n; if (++it != ss.end()) { hi = *it; } res -= query(lo, hi - 1); res += MOD; res %= MOD; res += query(lo, u - 1); res %= MOD; res += query(u, hi - 1); res %= MOD; } else { int lo = *(--it); it++; int hi = n; if (++it != ss.end()) { hi = *it; } res += query(lo, hi - 1); res %= MOD; res -= query(lo, u - 1); res += MOD; res %= MOD; res -= query(u, hi - 1); res += MOD; res %= MOD; ss.erase(u); } cout << res << "\n"; } return 0; }
1264
C
Beautiful Mirrors with queries
Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$. \textbf{Some mirrors are called checkpoints}. Initially, only the $1$st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities: - The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day; - In the other case, Creatnx will feel upset. The next day, Creatnx will start asking \textbf{from the checkpoint with a maximal number that is less or equal to $i$}. \textbf{There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints}. You are given $q$ queries, each query is represented by an integer $u$: If the $u$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $u$-th mirror is no longer a checkpoint. After each query, you need to calculate the expected number of days until Creatnx becomes happy. Each of this numbers should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
We calculate the depth of a sequence as follow: Let two pointers at each end of the sequence. If character at the left pointer is ')', we move the left pointer one position to the right. If character at the right pointer is '(', we move the right pointer one position to the left. If the character at the left pointer is '(' and the right pointer is ')' we increase our result and move the left pointer to the right and the right one to the left each with one position. We repeat while the left one is at the left of the right one. $dp[l][r] += dp[l + 1][r]$ if $a_l \ne$ '('. $dp[l][r] += dp[l][r - 1]$ if $a_r \ne$ ')'. $dp[l][r] -= dp[l + 1][r - 1]$ if $a_l \ne$ '(' and $a_r \ne$ ')'. $dp[l][r] += dp[l + 1][r - 1] + 2^k$ if $a_l \ne$ ')' and $a_r \ne$ '(', where $k$ is the number of '?' character in $s_{l + 1}s_{l + 2}\ldots s_{r - 1}$.
[ "data structures", "probabilities" ]
2,400
#include <bits/stdc++.h> using namespace std; const int MOD = 119 << 23 | 1; int fpow(int a, int k) { int r = 1, t = a; while (k) { if (k & 1) r = (long long) r * t % MOD; t = (long long) t * t % MOD; k >>= 1; } return r; } int main() { string s; cin >> s; int n = s.size(); vector<vector<int>> dp(n, vector<int>(n)); vector<int> f(n + 1); for (int i = 0; i < n; i++) { f[i + 1] = f[i]; f[i + 1] += s[i] == '?'; } for (int len = 2; len <= n; len++) { for (int i = 0; i < n - len + 1; i++) { int j = i + len - 1; if (s[i] != '(') { dp[i][j] += dp[i + 1][j]; dp[i][j] %= MOD; } if (s[j] != ')') { dp[i][j] += dp[i][j - 1]; dp[i][j] %= MOD; } if (s[i] != '(' && s[j] != ')') { dp[i][j] -= dp[i + 1][j - 1]; dp[i][j] += MOD; dp[i][j] %= MOD; } if (s[i] != ')' && s[j] != '(') { dp[i][j] += dp[i + 1][j - 1]; dp[i][j] %= MOD; dp[i][j] += fpow(2, f[j] - f[i + 1]); dp[i][j] %= MOD; } } } cout << dp[0][n - 1] << "\n"; return 0; }
1264
D2
Beautiful Bracket Sequence (hard version)
This is the hard version of this problem. The only difference is the limit of $n$ - the length of the input string. In this version, $1 \leq n \leq 10^6$. Let's define a correct bracket sequence and its depth as follow: - An empty string is a correct bracket sequence with depth $0$. - If "s" is a correct bracket sequence with depth $d$ then "(s)" is a correct bracket sequence with depth $d + 1$. - If "s" and "t" are both correct bracket sequences then their concatenation "st" is a correct bracket sequence with depth equal to the maximum depth of $s$ and $t$. For a (not necessarily correct) bracket sequence $s$, we define its depth as the maximum depth of any \textbf{correct} bracket sequence induced by removing some characters from $s$ (possibly zero). For example: the bracket sequence $s = $"())(())" has depth $2$, because by removing the third character we obtain a correct bracket sequence "()(())" with depth $2$. Given a string $a$ consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in $a$ by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo $998244353$. \textbf{Hacks} in this problem can be done only if easy and hard versions of this problem was solved.
By the way calculate the depth in easy version we can construct a maximal depth correct bracket $S$. At $i$-th position containing '(' or '?' we will count how many times it appears in $S$. Let $x$ be the number of '(' before the $i$-th position, $y$ be the number of ')' after the $i$-th position, $c$ be the number of '?' before the $i$-th position and $d$ be the number of '?' after the $i$-th position. The $i$-th position appears in $S$ iff the number of '(' before the $i$-th position must less than the number of ')' after the $i$-th position. So we can derive a mathematics formula: $\sum_{a + i < b + j}{C(c, i)\cdot C(d, j)} = \sum_{a + i < b + j}{C(c, i)\cdot C(d, d - j)} = \sum_{i + j < b + d - a}{C(c, i)\cdot C(d, j)}$. Expanding both hand sides of indentity $(x + 1)^{c + d} = (x + 1)^c\cdot (x + 1)^d$, the above sum is simplified as: $\sum_{0\le i < b + d - a}{C(c + d, i)}$. Notice that $c + d$ doesn't change much, it only is one of two possible values. So we can prepare and obtain $O(N)$ complexity.
[ "combinatorics", "probabilities" ]
2,900
#include <bits/stdc++.h> using namespace std; const int MOD = 119 << 23 | 1; int inv(int a) { int r = 1, t = a, k = MOD - 2; while (k) { if (k & 1) r = (long long) r * t % MOD; t = (long long) t * t % MOD; k >>= 1; } return r; } int main() { string s; cin >> s; int k = s.size() + 1; int a = 0, b = 0, c = 0, d = 0; for (char e : s) { if (e == ')') { b++; } if (e == '?') { d++; } } map<int, vector<int>> dps; auto calc = [&] (int a, int b, int c, int d) { int x = b + d - a; if (x < 0) return 0; int k = c + d; if (k < x) x = k; if (dps.count(k)) return dps[k][x]; auto& dp = dps[k]; dp.resize(k + 1); int t = 0, w = 1; for (int i = 0; i <= k; i++) { t += w; t %= MOD; dp[i] = t; w = (long long) w * (c + d - i) % MOD; w = (long long) w * inv(i + 1) % MOD; } return dp[x]; }; int res = 0; for (int i = 0; i < (int) s.size(); i++) { char e = s[i]; if (e == '(') { a++; } if (e == ')') { b--; } if (e == '?') { c++; d--; } if (e == '(') { res += calc(a, b, c, d); res %= MOD; } else if (e == '?') { a++, c--; res += calc(a, b, c, d); res %= MOD; a--, c++; } } cout << res << "\n"; return 0; }
1264
E
Beautiful League
A football league has recently begun in Beautiful land. There are $n$ teams participating in the league. Let's enumerate them with integers from $1$ to $n$. There will be played exactly $\frac{n(n-1)}{2}$ matches: each team will play against all other teams exactly once. In each match, there is always a winner and loser and there is no draw. After all matches are played, the organizers will count the number of beautiful triples. Let's call a triple of three teams $(A, B, C)$ beautiful if a team $A$ win against a team $B$, a team $B$ win against a team $C$ and a team $C$ win against a team $A$. We look only to a triples of different teams and the order of teams in the triple is important. The beauty of the league is the number of beautiful triples. At the moment, $m$ matches were played and their results are known. What is the maximum beauty of the league that can be, after playing all remaining matches? Also find a possible results for all remaining $\frac{n(n-1)}{2} - m$ matches, so that the league has this maximum beauty.
Firstly, Let's calculate the number of non-beautiful triples given all result of matches. It is obvious that for each non-beautiful triple $(A, B, C)$ there exactly is one team that wins over the others. So if a team $A$ wins $k$ other teams $B_1, B_2,\ldots, B_k$ then team A corresponds to $\frac{k\cdot (k - 1)}{2}$ non-beautiful triple $(A, B_i, B_j)$. If we define $(p_1, p_2,\ldots, p_n)$ as the number of wins of $n$ teams. Then the number of non-beautiful triples will be $\frac{p_1\cdot (p_1 - 1) + p_2\cdot (p_2 - 1) +\ldots+ p_n\cdot (p_n - 1)}{2}$. Notice that $p_1 + p_2 +\ldots+ p_n = \frac{n\cdot (n - 1)}{2}$. So we only need to minimize the square sum: $p_1^2 + p_2^2 +\ldots+ p_n^2$. The remain can be solved easily by Mincost-Maxflow: Creating source $S$, sink $T$, each 'match node' for each match haven't played yet, each 'team node' for each team. Add an edge between source $S$ and each 'match node' with capacity $1$ cost $0$. Add an edge between each 'match node' and each of two 'team nodes' with capacity $1$ cost $0$. Assuming, after $m$ matches played, $i$-th team wins $q_i$ matches. We add $n - q_i - 1$ edges between the $i$-th 'team node' and sink $T$ with capacity $1$ and costs $2\cdot q_i + 1, 2\cdot q_i + 3,\ldots, 2\cdot n - 1$. The min cost after run Mincost-Maxflow plus $q_1^2 + q_2^2 +\ldots+ q_n^2$ will give us the minimal square sum. Base on Mincost-Maxflow idea, we can solve in more sophisticated way. At any moment, we will try to pick a team with minimal number of wins. Then we try to give it one more win by setting result of a match (that haven't used so far) and possibly changing results of a path of matches to keep the number of win of others. If not pick next one and so on. Complexity: $O(N^4)$.
[ "constructive algorithms", "flows", "graph matchings" ]
2,700
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> d(n); vector<vector<int>> g(n, vector<int>(n)); vector<vector<int>> f(n, vector<int>(n, 1)); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; u--, v--; d[u]++; g[u][v] = 1, g[v][u] = 2; f[u][v] = f[v][u] = 0; } priority_queue<pair<int, int>> heap; for (int i = 0; i < n; i++) { if (d[i] < n - 1) { heap.push({-d[i], i}); } } while (!heap.empty()) { int u = heap.top().second; heap.pop(); queue<int> que; vector<int> vis(n), from(n); que.push(u), vis[u] = 1; int id = -1; while (!que.empty()) { int v = que.front(); que.pop(); int found = 0; for (int w = 0; w < n; w++) if (w != v && !g[v][w]) { found = 1; break; } if (found) { id = v; break; } for (int w = 0; w < n; w++) if (!vis[w] && g[v][w] == 2 && f[v][w] == 1) { que.push(w), vis[w] = 1; from[w] = v; } } if (id == -1) { continue; } for (int v = 0; v < n; v++) if (v != id && !g[id][v]) { g[id][v] = 1, g[v][id] = 2; break; } while (id != u) { int nid = from[id]; swap(g[id][nid], g[nid][id]); id = nid; } d[u]++; if (d[u] < n - 1) { heap.push({-d[u], u}); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { cout << 0; } else { cout << 2 - g[i][j]; } } cout << "\n"; } return 0; }
1264
F
Beautiful Fibonacci Problem
The well-known Fibonacci sequence $F_0, F_1, F_2,\ldots $ is defined as follows: - $F_0 = 0, F_1 = 1$. - For each $i \geq 2$: $F_i = F_{i - 1} + F_{i - 2}$. Given an increasing arithmetic sequence of positive integers with $n$ elements: $(a, a + d, a + 2\cdot d,\ldots, a + (n - 1)\cdot d)$. You need to find another increasing arithmetic sequence of positive integers with $n$ elements $(b, b + e, b + 2\cdot e,\ldots, b + (n - 1)\cdot e)$ such that: - $0 < b, e < 2^{64}$, - for all $0\leq i < n$, the decimal representation of $a + i \cdot d$ appears as substring in the last $18$ digits of the decimal representation of $F_{b + i \cdot e}$ (if this number has less than $18$ digits, then we consider all its digits).
Intuitively, we want to a formula for $F_{m + n}$. This is one we need: $F_{m + n} = F_m\cdot F_{n + 1} + F_{m - 1}\cdot F_n$. Denote $n = 12\cdot 10^k$, one can verify that $F_{i\cdot n} \equiv 0$ modulo $10^k$ (directly calculate or use 'Pisano Period'). So we have following properties: $F_{2\cdot n + 1} = F_{n + 1}^2 + F_n^2$ $\Rightarrow F_{2\cdot n + 1} = F_{n + 1}^2$ modulo $10^{2\cdot k}$. $F_{3\cdot n + 1} = F_{2\cdot n + 1}\cdot F_{n + 1} + F_{2\cdot n}\cdot F_n$ $\Rightarrow F_{3\cdot n + 1} = F_{n + 1}^3$ modulo $10^{2\cdot k}$. So on, $F_{u\cdot n + 1} = F_{n + 1}^u$ modulo $10^{2\cdot k}$. Notice that $F_{n + 1} = 8\cdot 10^k\cdot t + 1$, where $gcd(t, 10) = 1$. So $F_{u\cdot n + 1} = (8\cdot 10^k\cdot t + 1)^u = 8\cdot u\cdot t\cdot 10^k + 1$ modulo $10^{2\cdot k}$. Let $u = 125.a.t^{-1}$ modulo $10^k$, $v = 125.d.t^{-1}$ modulo $10^k$. Then we choose $b = u\cdot n + 1, e = v\cdot n$.
[ "constructive algorithms", "number theory" ]
3,500
n,a,d=map(int,input().split()) print(368131125*a%10**9*12*10**9+1,368131125*d%10**9*12*10**9)
1265
A
Beautiful String
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string $s$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him! More formally, after replacing all characters '?', the condition $s_i \neq s_{i+1}$ should be satisfied for all $1 \leq i \leq |s| - 1$, where $|s|$ is the length of the string $s$.
If string $s$ initially contains 2 equal consecutive letters ("aa", "bb" or "cc") then the answer is obviously -1. Otherwise, it is always possible to replacing all characters '?' to make $s$ beautiful. We will replacing one '?' at a time and in any order (from left to right for example). For each '?', since it is adjacent to at most 2 other characters and we have 3 options ('a', 'b' and 'c') for this '?', there always exists at least one option which differ from 2 characters that are adjacent with this '?'. Simply find one and replace '?' by it. Time comlexity: $\mathcal{O}(n)$ where $n$ is length of $s$.
[ "constructive algorithms", "greedy" ]
1,000
T = int(input()) for tc in range(T): s = [c for c in input()] n = len(s) i = 0 while (i < n): if (s[i] == '?'): prv = 'd' if i == 0 else s[i - 1] nxt = 'e' if i + 1 >= n else s[i + 1] for x in ['a', 'b', 'c']: if (x != prv) and (x != nxt): s[i] = x break else: i += 1 ok = True for i in range(n - 1): if (s[i] == s[i + 1]): print("-1") ok = False break if (ok == True): print("".join(s))
1265
B
Beautiful Numbers
You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$. For example, let $p = [4, 5, 1, 3, 2, 6]$. In this case, the numbers $1, 3, 5, 6$ are beautiful and $2, 4$ are not. It is because: - if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; - if $l = 3$ and $r = 5$ we will have a permutation $[1, 3, 2]$ for $m = 3$; - if $l = 1$ and $r = 5$ we will have a permutation $[4, 5, 1, 3, 2]$ for $m = 5$; - if $l = 1$ and $r = 6$ we will have a permutation $[4, 5, 1, 3, 2, 6]$ for $m = 6$; - it is impossible to take some $l$ and $r$, such that $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$ for $m = 2$ and for $m = 4$. You are given a permutation $p=[p_1, p_2, \ldots, p_n]$. For all $m$ ($1 \le m \le n$) determine if it is a beautiful number or not.
A number $m$ is beautiful if and only if all numbers in range $[1, m]$ occupies $m$ consecutive positions in the given sequence $p$. This is equivalent to $pos_{max} - pos_{min} + 1 = m$ where $pos_{max}, pos_{min}$ are the largest, smallest position of $1, 2, \dots, m$ in sequence $p$ respectively. We will consider $m$ in increasing order, that its $m = 1, 2, \ldots, n$. For each $m$ we will find a way to update $pos_{max}, pos_{min}$ so we can tell either $m$ is a beautiful number or not in constant time. Denote $pos_i$ is the position of number $i$ in the sequence $p$. When $m=1$, we have $pos_{max} = pos_{min} = pos_1$. When $m>1$, the value of $pos_{max}, pos_{min}$ can be updated by the following formula: $new\_pos_{max} = max(old\_pos_{max}, pos_m)$ $new\_pos_{min} = min(old\_pos_{min}, pos_m)$ Total time comlexity: $\mathcal{O}(n)$
[ "data structures", "implementation", "math", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; const int M = 2e5 + 239; int n, p[M], x; void solve() { cin >> n; for (int i = 0; i < n; i++) { cin >> x; p[x - 1] = i; } int l = n; int r = 0; string ans = ""; for (int i = 0; i < n; i++) { l = min(l, p[i]); r = max(r, p[i]); if (r - l == i) ans += '1'; else ans += '0'; } cout << ans << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) solve(); return 0; }