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
1102
C
Doors Breaking and Repairing
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are $n$ doors, the $i$-th door initially has durability equal to $a_i$. During your move you can try to break one of the doors. If you choose door $i$ and its current durability is $b_i$ then you reduce its durability to $max(0, b_i - x)$ (the value $x$ is given). During Slavik's move he tries to repair one of the doors. If he chooses door $i$ and its current durability is $b_i$ then he increases its durability to $b_i + y$ (the value $y$ is given). \textbf{Slavik cannot repair doors with current durability equal to $0$}. The game lasts $10^{100}$ turns. If some player cannot make his move then he has to skip it. Your goal is to maximize the number of doors with durability equal to $0$ at the end of the game. You can assume that Slavik \textbf{wants to minimize} the number of such doors. What is the number of such doors in the end if you both play optimally?
Let's consider two cases: If $x > y$ then the answer is $n$ because we can make opposite moves to the Slavik's moves and it always will reduce durability of some door (so at some point we will reach the state when all doors will have durability $0$). Otherwise $x \le y$ and we have to realize the optimal strategy for us. If we have some door with durability $z \le x$ then let's break it immediately (why shouldn't we do this?). If we don't do it then Slavik will repair this door during his move. So what Slavik will do now? He will repair some door. Which door he has to repair? Of course the one with durability $z \le x$ because otherwise we will break it during our next move. So we can realize that doors with durability $z > x$ are not interesting for us because Slavik will make opposite moves to our moves. And what is the answer if the number of doors with durability $z \le x$ equals to $cnt$? It is $\lceil\frac{cnt}{2}\rceil$.
[ "games" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, x, y; cin >> n >> x >> y; int cnt = 0; for (int i = 0; i < n; ++i) { int cur; cin >> cur; if (cur <= x) { ++cnt; } } if (x > y) { cout << n << endl; } else { cout << (cnt + 1) / 2 << endl; } return 0; }
1102
D
Balanced Ternary String
You are given a string $s$ consisting of exactly $n$ characters, and each character is either '0', '1' or '2'. Such strings are called \textbf{ternary strings}. Your task is to \textbf{replace minimum number of characters} in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2'). Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest. Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'. It is \textbf{guaranteed} that the answer exists.
Let's count how many characters '0', '1' and '2' we have in the string $s$ and store it in the array $cnt$. Also let's count our "goal" array $cur$. Firstly, the array $cur$ is $[\frac{n}{3}, \frac{n}{3}, \frac{n}{3}]$. The main idea of this problem is a pretty standard lexicographically greedy approach. We go from left to right and try to place the minimum possible character at the current position in such a way that placing this character is not breaking conditions of our problem. How can we apply this approach to this problem? Firstly, let's define a function $need(cnt, cur) = \frac{|cnt_0 - cur_0| + |cnt_1 - cur_1| + |cnt_2 - cur_2|}{2}$. What does the value of this function mean? It means the number of replacements we need to reach $cur$ from $cnt$. Let $initNeed = need(cur, cnt)$ at the beginning of the program. This value means the minimum number of replacements to obtain some balanced ternary string. Let's maintain the variable $curRep$ which initially is $0$ and means the number of replacements we already made. So, we iterate over all positions $i$ from $1$ to $n$. Firstly, let's decrease $cnt_{s_i}$. So the array $cnt$ maintains the current amount of characters on suffix of the string. Now let's iterate over characters $j$ from $0$ to $2$ and try to place every character. If the current character is needed ($cur_j > 0$), then let's decrease $cur_j$ and if the number of replacements will still be minimum possible after such replacement ($curRep + need(cnt, cur) + (s_i \ne j) = initNeed$) then let's place this character, set $curRep := curRep + (s_i \ne j)$ and go to the next position. This will form lexicographically minimum possible answer with minimum number of replacements. There is another (simpler) solution from PikMike, you can call him to explain it, I just will add his code to the editorial.
[ "greedy", "strings" ]
1,500
n = int(input()) s = [ord(x) - ord('0') for x in input()] cnt = [s.count(x) for x in [0, 1, 2]] def forw(x): for i in range(n): if (cnt[x] < n // 3 and s[i] > x and cnt[s[i]] > n // 3): cnt[x] += 1 cnt[s[i]] -= 1 s[i] = x def back(x): for i in range(n - 1, -1, -1): if (cnt[x] < n // 3 and s[i] < x and cnt[s[i]] > n // 3): cnt[x] += 1 cnt[s[i]] -= 1 s[i] = x forw(0) forw(1) back(2) back(1) print(''.join([str(x) for x in s]))
1102
E
Monotonic Renumeration
You are given an array $a$ consisting of $n$ integers. Let's denote monotonic renumeration of array $a$ as an array $b$ consisting of $n$ integers such that all of the following conditions are met: - $b_1 = 0$; - for every pair of indices $i$ and $j$ such that $1 \le i, j \le n$, if $a_i = a_j$, then $b_i = b_j$ (note that if $a_i \ne a_j$, it is still possible that $b_i = b_j$); - for every index $i \in [1, n - 1]$ either $b_i = b_{i + 1}$ or $b_i + 1 = b_{i + 1}$. For example, if $a = [1, 2, 1, 2, 3]$, then two possible monotonic renumerations of $a$ are $b = [0, 0, 0, 0, 0]$ and $b = [0, 0, 0, 0, 1]$. Your task is to calculate the number of different monotonic renumerations of $a$. The answer may be large, so print it modulo $998244353$.
We are interested in such subsegments of the array $a$ that for every value belonging to this segment all occurences of this value in the array are inside this segment. Let's call such segments closed segments. For example, if $a = [1, 2, 1, 2, 3]$, then $[1, 2, 1, 2]$, $[3]$ and $[1, 2, 1, 2, 3]$ are closed segments. We can see that the result is some partition of the given array into several closed segments - if for some value $x$ all occurences of $x$ in $b_i$ do not form a segment in $a_i$, then there exists some pair $b_i, b_{i + 1}$ such that $b_i > b_{i + 1}$ (which contradicts the statement); and if the formed segment is not a closed segment, then for some indices $i$ and $j$ such that $a_i = a_j$ it is not true that $b_i = b_j$ (which also contradicts the statement). Okay, let's try to partition the array into closed segments greedily: take the first prefix of the array that is a closed segment, erase it, take the next prefix, and so on. Let $m$ be the number of closed segments we got with this procedure. The key fact is that any valid partition can be produced from this partition by merging some adjacent segments. To prove it, suppose we partitioned the array in some other way. The intersection of two closed segments, if it exists, is also a closed segment; so there exists at least one segment in the partition we picked greedily that can be broken into two - but that contradicts the algorithm we used to construct this partition. So we may merge some of $m$ segments to get a valid partition. There are exactly $2^{m - 1}$ ways to do so, because for every pair of adjacent segments we may choose whether we will merge it.
[ "combinatorics", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int main() { int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); map<int, int> lst; vector<int> last_pos(n); for(int i = n - 1; i >= 0; i--) { if(!lst.count(a[i])) lst[a[i]] = i; last_pos[i] = lst[a[i]]; } int ans = 1; int cur_max = -1; for(int i = 0; i < n - 1; i++) { cur_max = max(cur_max, last_pos[i]); if(cur_max == i) ans = (2 * ans) % MOD; } printf("%d\n", ans); return 0; }
1102
F
Elongated Matrix
You are given a matrix $a$, consisting of $n$ rows and $m$ columns. Each cell contains an integer in it. You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be $s_1, s_2, \dots, s_{nm}$. The traversal is $k$-acceptable if for all $i$ ($1 \le i \le nm - 1$) $|s_i - s_{i + 1}| \ge k$. Find the maximum integer $k$ such that there exists some order of rows of matrix $a$ that it produces a $k$-acceptable traversal.
Really low constraints, choosing some permutation... Surely, this will be some dp on subsets! At first, let's get rid of $m$. For each two rows calculate the minimum difference between the elements of the same columns - let's call this $mn1_{i, j}$ for some rows $i$, $j$. This will be used to put row $j$ right after row $i$. Let's also calculate $mn2_{i, j}$ - the minimum difference between the elements of the column $k$ of row $i$ and column $k + 1$ of row $j$. This will be used to put row $i$ as the last row and row $j$ as the first one. Now let's think of choosing the permutation as choosing the traversal of the following graph. Vertices are rows and the weights of edges between the vertices are stored in $mn1$. However, you can't straight up do minimum weight Hamiltonian cycle search as the edge between the first vertex and the last one should be of weight from $mn2$ and not $mn1$. Let's fix some starting vertex and find minimum weight Hamiltonian paths from it to all vertices. Finally, update the answer with $min(mn2_{u, v}, path_{v, u})$. That will lead to $2^n \cdot n^3$ approach (minimum weight Hamiltonian path is a well-known problem solved by $dp[mask of used vertices][last visited vertex]$). That's completely fine and it's the most intended solution. However, there exist another solution that would have worked better if the edge weight were a bit smaller. Let's do binary search, each time checking if the answer is greater or equal to $mid$. The check is simple enough. Now the graph is binary (edge exists if its weight is greater or equal to $mid$), thus you should check for existence of Hamiltonian path, not for the minimum weight one. That can be done in $O(2^n \cdot n^2)$, leading to $O(2^n \cdot n^2 \log MAXN)$ solution. The key idea of that dp is storing the vertices where the path of the current mask could have ended as a mask itself. Then it becomes $dp[mask]$ with $n$ transitions. Overall complexity: $O(2^n \cdot n^3)$ or $O(2^n \cdot n^2 \log MAXN)$.
[ "binary search", "bitmasks", "brute force", "dp", "graphs" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 18; const int M = 100 * 1000 + 13; const int INF = 1e9; int used[1 << N]; char dp[1 << N]; int g[1 << N]; int n, m; int a[N][M]; int mn1[N][N], mn2[N][N]; bool calc(int mask){ if (dp[mask] != -1) return dp[mask]; used[mask] = 0; dp[mask] = 0; forn(i, n){ if (!((mask >> i) & 1)) continue; if (!calc(mask ^ (1 << i))) continue; if (!(used[mask ^ (1 << i)] & g[i])) continue; used[mask] |= (1 << i); dp[mask] = 1; } return dp[mask]; } bool check(int k){ forn(i, n){ g[i] = 0; forn(j, n) g[i] |= (1 << j) * (mn1[j][i] >= k); } forn(i, n){ memset(dp, -1, sizeof(dp)); forn(j, n){ dp[1 << j] = (j == i); used[1 << j] = (1 << j); } calc((1 << n) - 1); forn(j, n) if (mn2[j][i] >= k && ((used[(1 << n) - 1] >> j) & 1)) return true; } return false; } int main() { scanf("%d%d", &n, &m); forn(i, n) forn(j, m) scanf("%d", &a[i][j]); forn(i, n) forn(j, n){ int val = INF; forn(k, m) val = min(val, abs(a[i][k] - a[j][k])); mn1[i][j] = val; val = INF; forn(k, m - 1) val = min(val, abs(a[i][k] - a[j][k + 1])); mn2[i][j] = val; } int l = 0, r = INF; while (l < r - 1){ int m = (l + r) / 2; if (check(m)) l = m; else r = m; } printf("%d\n", check(r) ? r : l); }
1103
A
Grid game
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.
One possible solution is to place vertical tiles into lower-left corner and place horizontal tiles into upper-right corner.If some tile comes, but there is already a tile of the same type, than we will place the new tile into upper-left corner. So both tiles will be cleared and only them.
[ "constructive algorithms", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(0); string s; cin>>s; bool occv=false, occh=false; for(auto& x:s){ if(x=='0'){ if(occv) cout<<"3 4\n"; else cout<<"1 4\n"; occv=!occv; } else { if (occh) cout<<"4 3\n"; else cout<<"4 1\n"; occh=!occh; } } return 0; }
1103
B
Game with modulo
\textbf{This is an interactive problem.} Vasya and Petya are going to play the following game: Petya has some positive integer number $a$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $(x, y)$. Petya will answer him: - "x", if $(x \bmod a) \geq (y \bmod a)$. - "y", if $(x \bmod a) < (y \bmod a)$. We define $(x \bmod a)$ as a remainder of division $x$ by $a$. Vasya should guess the number $a$ using \textbf{no more, than 60 questions}. \textbf{It's guaranteed that} Petya has a number, that satisfies the inequality $1 \leq a \leq 10^9$. Help Vasya playing this game and write a program, that will guess the number $a$.
Let's ask this pairs of numbers: $(0, 1), (1, 2), (2, 4), (4, 8), \ldots, (2^{29}, 2^{30})$. Let's find the first pair in this list with the answer "x". This pair exists and it will happen for the first pair $(l_0, r_0)$, that satisfy the inequality $l_0 < a \leq r_0$. We can simply find this pair using $\leq 30$ or $\leq 31$ questions. Now we have a pair of numbers $(l_0, r_0)$, such that $l_0 < a \leq r_0$. Let's note, that $r_0 < 2 \cdot a$, because it was the first such pair in the list. Now if we ask pair $(l_0, x)$ for some $l_0 < x \leq r_0$ we will get the answer "y", if $x < a$ and the answer "x" otherwise. So let's do the binary search in the segment $[l_0+1, r_0]$, asking the question $(l_0, x)$ and moving the borders of binary search according to this. Here we will use $\leq 29$ questions. So we have a solution asked $\leq 59$ questions.
[ "binary search", "constructive algorithms", "interactive" ]
2,000
null
1103
C
Johnny Solving
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with $n$ vertices without loops and multiedges, such that a degree of any vertex is at least $3$, and also he gave a number $1 \leq k \leq n$. Because Johnny is not too smart, he promised to find a simple path with length at least $\frac{n}{k}$ in the graph. In reply, Solving promised to find $k$ simple by vertices cycles with representatives, such that: - Length of each cycle is at least $3$. - Length of each cycle is not divisible by $3$. - In each cycle must be a representative - vertex, which belongs only to this cycle among all \textbf{printed} cycles. You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least $\frac{n}{k}$ ($n$ is not necessarily divided by $k$), or solution for Solving: $k$ cycles that satisfy all the conditions above. If there is no any solution - print $-1$.
Let's build a dfs spanning tree from the vertex $1$ and find the depth of the tree. If the depth is at least $\frac{n}{k}$ then we can just print the path from the root to the deepest vertex. Otherwise, there will be at least $k$ leaves in the tree. Let's prove it. Consider a tree with $c$ leaves, after that consider a path from a particular leaf to the root, let's denote length of $i$-th path (in vertices) by $x_i$. We can say that $x_1 + \ldots + x_c \geq n$, because every particular vertex in the tree will be covered by one of pathways. So, using Dirichlet's principle we can say that $max(x_1, \ldots, x_c) \geq \frac{n}{c}$. Hence, depth of the tree is at least $\frac{n}{c}$. Now, consider a leaf in our spanning tree, let's denote it like $v$. This leaf has at least 2 back edges (edges which connected with one of ancestors), let's denote ancestors like $x$ and $y$. Obviosly, we have three cycles here: path from $x$ to $v$ with corresponding back edge, the same cycle from $y$ to $v$, and path between $x$ and $y$ with two back edges connected with $v$. Lengths of these cycles are $d(v, x) + 1$, $d(v, y) + 1$ and $d(x, y) + 2$, where $d(a, b)$ - distance between vertices a and b. It's clear that one of these numbers is not divisible by three. Last problem is to choose representative - we should choose leaves. Size of output is not exceed $10^6$ because the depth of our tree at most $\frac{n}{k}$ and each cycle has length $O(\frac{n}{k})$.
[ "constructive algorithms", "dfs and similar", "graphs", "math" ]
2,700
null
1103
D
Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are $n$ judges now in the layer and you are trying to pass the entrance exam. You have a number $k$ — your skill in Cardbluff. Each judge has a number $a_i$ — an indicator of uncertainty about your entrance to the professional layer and a number $e_i$ — an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only \textbf{one} game with each judge. As a result of a particular game, you can divide the uncertainty of $i$-th judge by any natural divisor of $a_i$ which is at most $k$. If GCD of all indicators is equal to $1$, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with $x$ judges with total experience $y$ you will spend $x \cdot y$ seconds. Print minimal time to enter to the professional layer or $-1$ if it's impossible.
We supposed this as the author solution: Let's find $gcd$ and factorize it. $gcd = p_1^{\alpha_1} \cdot \ldots \cdot p_m^{\alpha_m}$, where $p_i$ $i$-th prime number in factorization ($p_i < p_{i+1}$) and $\alpha_i > 0$ - number of occurrences of this prime. It's clear, that $m \leq 11$ in our constraints, because $a_i \leq 10^{12}$. Obviously, that in optimal answer is always best to divide set of our primes in subsets and distribute these subsets between array numbers and divide each number $a_i$ by product of all primes (with $a_i$ powers) in corresponding subset. Also clear, that we are interested in only vector of powers of primes of $gcd$, other primes in a factorization of $a_i$ we can ignore, but we need to be cautious about costs, so, we can left the cheapest $m$ numbers with the same prime-vector. After this compression we will left at most $M = 12000$ numbers. We can get this estimation by this point: maximum numbers after compression we can reach if all primes are small as possible and $\alpha_i = 1$ for all $i$. Hence, we have at most $11$ possibilities and can easily brute all of them. Also, after compression, let's calculate vector $best(mask)$ - best $m$ numbers by cost to cover set of primes corresponding to $mask$. We can do it easily in $O(M \cdot 2^m \cdot m)$. Now let's fix a partition of our set of primes into subsets. Well known, that the number of partitions is equal to $B_m$, where $B_i$ - $i$-th Bell number. Now, we want to update the current answer. We need to do it by value $x \cdot y$, where $x$ is number of subsets in the partition (we already know it) and $y$ is minimum cost to distribute our subsets between array numbers. Let's consider all indices $i$ for subset $mask$ which we can match with this $mask$ by constraint "divisor is at most k". We will get the bipartite graph with weighted right part (part with indices) and our purpose is to find perfect matching with minimal cost of used vertices in the right part. We can solve this problem with Kuhn algorithm greedily - we can sort right part in not ascending order and do all iterations in this order. It's correct, because we can consider transversal matroid with elements in right part and apply greed Rado-Edmonds theorem. Now we need just to figure out, that we can build this graph using precalced $best(mask)$, because we are interested only in at most $m$ best indices for the particular vertex in the left part. So, we will have graph with $O(x^2)$ edges and $O(x)$ size of the left part. Kuhn algorithm will be work in $O(x^3)$ (even we do the algorithm in right part with size $O(x^2)$) if we clear $used$ array carefully - only after increasing of the current matching. Summing up $x^3$ over all partitions of $11$ elements we will get $\sim 10^8$ operations. P. S. Solutions that were passed by participants during the contest used same ideas about the compression. But instead of minimal matching we will use dynamic programming approach. Let's denote $dp(mask, i)$ - minimal cost to correctly cover set of primes corresponding to $mask$ using exactly $i$ divisions. To calculate it let's precalc $best'(i)$ (inversion of $best(mask)$) - $m$ masks for which $i$-th number of the array is one of $m$ best. Using this helped data we can calculate our $dp(mask, i)$. For this, we can iterate over all numbers and try to update all states where we can use our $best'(i)$ masks. It will be work in $O(m^2 \cdot 3^m)$ and all algorithm will be work in $O(M \cdot 2^m \cdot m + m^2 \cdot 3^m)$
[ "bitmasks", "dp" ]
3,100
null
1103
E
Radix sum
Let's define \textbf{radix sum} of number $a$ consisting of digits $a_1, \ldots ,a_k$ and number $b$ consisting of digits $b_1, \ldots ,b_k$(we add leading zeroes to the shorter number to match longer length) as number $s(a,b)$ consisting of digits $(a_1+b_1)\mod 10, \ldots ,(a_k+b_k)\mod 10$. The \textbf{radix sum} of several integers is defined as follows: $s(t_1, \ldots ,t_n)=s(t_1,s(t_2, \ldots ,t_n))$ You are given an array $x_1, \ldots ,x_n$. The task is to compute for each integer $i (0 \le i < n)$ number of ways to consequently choose one of the integers from the array $n$ times, so that the \textbf{radix sum} of these integers is equal to $i$. Calculate these values modulo $2^{58}$.
After reading the problem statement, it is pretty clear that you should apply something like Hadamard transform, but inner transform should have size ten instead of two. There is no $10$-th root of one modulo $2^{58}$ (except $5$-th and $2$-th roots), so it is not possible to solve the problem just calculating all values modulo $2^{58}$. The main idea is that you should calculate all values in a polynomial ring modulo $x^{10}-1$ (in this ring identity $x^{10}=1$ holds, so $x$ is the one's $10$-th root). Now the problem is there is no modular inverse of $10^5$, so we apply the trick. Let's just use unsigned long long, and in the end we will divide the answer by $5^5$ (it is invertible, because it is relatively prime to 2), and then we simply divide the answer by $2^5$ with integer division, it can be easily shown that the result will be correct. It is worth noting that after inverse transform you should eliminate monomes larger than $x^4$ by applying the identity $x^4-x^3+x^2-x^1+x^0=0$ (modulo $x^{10}-1$). After that only the coefficient with $x^0$ remains, and this will be the answer.
[ "fft", "math", "number theory" ]
3,400
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; const int two = 2; const int M = 1e5; const int L = 7; const int X = 2e5 + 1e3; const int fr = 4; const int ten = 10; const ull cs = 6723469279985657373; const ull RT = (1LL << 58LL) - 1; ull f[X][fr], bf[L]; int cur; inline int sum(int i, int j) { for (int x = 0; x < fr; x++) f[cur][x] = f[i][x] + f[j][x]; return (cur++); } inline int mult(int i, int j) { for (int x = 0; x < L; x++) bf[x] = 0; for (int x = 0; x < fr; x++) for (int y = 0; y < fr; y++) bf[x + y] += f[i][x] * f[j][y]; bf[1] -= bf[6]; bf[0] -= bf[5]; bf[3] += bf[4]; bf[2] -= bf[4]; bf[1] += bf[4]; bf[0] -= bf[4]; for (int x = 0; x < fr; x++) f[cur][x] = bf[x]; return (cur++); } inline void sum_to(int who, int i, int j) { for (int x = 0; x < fr; x++) f[who][x] = f[i][x] + f[j][x]; } inline void mult_to(int who, int i, int j) { for (int x = 0; x < L; x++) bf[x] = 0; for (int x = 0; x < fr; x++) for (int y = 0; y < fr; y++) bf[x + y] += f[i][x] * f[j][y]; bf[1] -= bf[6]; bf[0] -= bf[5]; bf[3] += bf[4]; bf[2] -= bf[4]; bf[1] += bf[4]; bf[0] -= bf[4]; for (int x = 0; x < fr; x++) f[who][x] = bf[x]; } inline int init(int x) { f[cur][0] = x; return (cur++); } inline int cpy(int x) { for (int i = 0; i < fr; i++) f[cur][i] = f[x][i]; return (cur++); } inline void cpy_to(int x, int y) { for (int i = 0; i < fr; i++) f[x][i] = f[y][i]; } inline void clr(int x) { for (int i = 0; i < fr; i++) f[x][i] = 0; } int n, kol[M], a[M], b[ten]; int st[two][ten], buf; inline int power(int i, int st) { vector<int> rt; while (st) { rt.push_back(st & 1); st >>= 1; } reverse(rt.begin(), rt.end()); int ans = init(1); for (int x = 0; x < (int)rt.size(); x++) { mult_to(ans, ans, ans); if (rt[x]) mult_to(ans, ans, i); } return ans; } inline void conv(int c) { int up = M; while (up >= 10) { up /= 10; for (int x = 0; x < M; x += (10 * up)) for (int i = x; i < up + x; i++) { for (int u = 0; u < 10; u++) cpy_to(b[u], a[i + up * u]); for (int u = 0; u < 10; u++) { int nd = (i + up * u); clr(a[nd]); for (int pw = 0; pw < 10; pw++) { clr(buf); mult_to(buf, st[c][(pw * u) % 10], b[pw]); sum_to(a[nd], a[nd], buf); } } } } } int main() { #ifdef ONPC freopen("test.in", "r", stdin); freopen("test.out", "w", stdout); #endif ios::sync_with_stdio(0); cin.tie(); cout.tie(0); cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; kol[x]++; } for (int i = 0; i < M; i++) a[i] = init(kol[i]); for (int i = 0; i < ten; i++) b[i] = init(0); int w = init(0); f[w][1] = 1; int wm = init(0); f[wm][0] = 1, f[wm][1] = -1, f[wm][2] = 1, f[wm][3] = -1; st[0][0] = init(1); st[1][0] = init(1); for (int t = 1; t < 10; t++) { st[0][t] = mult(st[0][t - 1], w); st[1][t] = mult(st[1][t - 1], wm); } buf = init(0); conv(0); for (int i = 0; i < M; i++) a[i] = power(a[i], n); conv(1); for (int i = 0; i < n; i++) { ull ans = f[a[i]][0] * cs; cout << ((ans >> 5LL) & RT) << "\n"; } return 0; }
1104
A
Splitting into digits
Vasya has his favourite number $n$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $d_1, d_2, \ldots, d_k$, such that $1 \leq d_i \leq 9$ for all $i$ and $d_1 + d_2 + \ldots + d_k = n$. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $d_1, d_2, \ldots, d_k$. Help him!
It was a joke :). Let's split number $n$ to $n$ digits, equal to $1$. Their sum is $n$ and the number of different digits is $1$. So, it can be found as the answer.
[ "constructive algorithms", "implementation", "math" ]
800
null
1104
B
Game with string
Two people are playing a game with a string $s$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses. Your task is to determine which player will win if both play optimally.
It can be shown that the answer does not depend on the order of deletions. Let's remove letters from left to right, storing a stack of letters, remaining in the left. When we process a letter, it will be deleted together with the last letter in the stack if they are equal or will be pushed to the stack. Let's calculate parity of the number of deletions during this process and determine the answer.
[ "data structures", "implementation", "math" ]
1,200
null
1105
A
Salem and Sticks
Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \ldots, a_n$. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $a$ to $b$ is $|a - b|$, where $|x|$ means the absolute value of $x$. A stick length $a_i$ is called almost good for some integer $t$ if $|a_i - t| \le 1$. Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $t$ and the total cost of changing is minimum possible. The value of $t$ is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of $t$ and the minimum cost. If there are multiple optimal choices for $t$, print any of them.
Firstly, we must find the value of $t$ and it can easily proven that $t$ is less than or equal to $100$, so we can iterate over all possible value of $t$ from $1$ to $100$ and calculate the cost of making all the sticks almost good for that $t$. That works in $100 \cdot n$.
[ "brute force", "implementation" ]
1,100
null
1105
B
Zuhair and Strings
Given a string $s$ of length $n$ and integer $k$ ($1 \le k \le n$). The string $s$ has a level $x$, if $x$ is largest non-negative integer, such that it's possible to find in $s$: - $x$ \textbf{non-intersecting} (non-overlapping) substrings of length $k$, - all characters of these $x$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $i$ and $j$ ($1 \le i \le j \le n$), denoted as $s[i \dots j]$ = "$s_{i}s_{i+1} \dots s_{j}$". For example, if $k = 2$, then: - the string "aabb" has level $1$ (you can select substring "aa"), - the strings "zzzz" and "zzbzz" has level $2$ (you can select two non-intersecting substrings "zz" in each of them), - the strings "abed" and "aca" have level $0$ (you can't find at least one substring of the length $k=2$ containing the only distinct character). Zuhair gave you the integer $k$ and the string $s$ of length $n$. You need to find $x$, the level of the string $s$.
Since all the substrings of length $k$ must be of the same latter, we can iterate over all letters from 'a' to 'z' and for each letter count the number of disjoint substrings of length $k$ and take the maximum one.
[ "brute force", "implementation", "strings" ]
1,100
null
1105
C
Ayoub and Lost Array
Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties: - All the integers in the array were between $l$ and $r$ (inclusive). - The sum of all the elements was divisible by $3$. Unfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l$ and $r$, so he asked you to find the number of ways to restore the array. Since the answer could be very large, print it modulo $10^9 + 7$ (i.e. the remainder when dividing by $10^9 + 7$). In case there are no satisfying arrays (Ayoub has a wrong memory), print $0$.
Since we need the sum of the array to be divisible by $3$, we don't care about the numbers themselves: We care about how many numbers $x$ such that $x \pmod{3} = 0$ or $1$ or $2$ and we count them by simple formulas. For example, let's count the number of $x$ with remainder $1$ modulo $3$, hence $x = 3k + 1$ for some integer $k$. Then we have $l \le 3k + 1 \le r$, $l - 1 \le 3k \le r - 1$ and then $ceil(\frac{l - 1}{3}) \le k \le floor(\frac{r - 1}{3})$. It is easy to count number of such $k$ then. After counting all numbers we can solve the problem using dynamic programming. Let's say that dp[i][j] represents that the sum of the first $i$ numbers modulo $3$ is equal to $j$. There are $O(n)$ states and transitions and the answer will be at dp[n][0].
[ "combinatorics", "dp", "math" ]
1,500
null
1105
D
Kilani and the Game
Kilani is playing a game with his friends. This game can be represented as a grid of size $n \times m$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell). The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $i$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $s_i$ (where $s_i$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
This problem can be solved in many ways, one of them uses a bfs. Let's process the first round. Iterate over players and use a multi-source bfs for each player from his starting castles to find cells reachable in at most s[i] moves. A multi-source bfs works just like regular one, except you push more vertices in the queue in the beginning. While moving, we can't enter a blocked cell or an already controlled cell. And in the each following turn do the same, but start from the cells we stopped on the previous turn, instead of starting castles. Keep doing this until no player can move anymore. Complexity: $O(p \cdot nm)$
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
1,900
null
1105
E
Helping Hiasat
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle. Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types: - $1$ — Hiasat can change his handle. - $2$ $s$ — friend $s$ visits Hiasat's profile. The friend $s$ will be happy, if each time he visits Hiasat's profile his handle would be $s$. Hiasat asks you to help him, find the maximum possible number of happy friends he can get.
Let's change this problem to a graph problem first. Let's say, that each action of the first type is a "border". Consider all friends visiting our profile after this "border" but before the next one. Clearly, we can satisfy at most one of them. Let's change the friends into graph nodes and add edges between every two friends that are between the same borders. Then it's enough to solve "the maximum independent set of the graph", clearly any possible answer must be an independent set and by any independent set we can always build a way to change our handle. The maximum independent set can be solved in $O(2^m)$ (where $m$ is the number of friends). But since $m$ is up to $40$, it is too slow. However, we can apply the meet in the middle approach and then it becomes $O(2^{(m/2)})$ or $O(2^{(m/2)} m)$. The simplest way is to do the following (notice, that the independent set is same as clique if all edges are inverted, so we will solve a max clique problem). Let's write a bruteforce solve(mask) which returns size of the largest clique, which forms a subset of mask. The answer will be just to run solve of full mask. How to write solve? Let's find a first bit of mask, let it be vertex $v$. There are two cases: The vertex $v$ is not in an answer. Kick it and run a recursive call. The vertex $v$ is in answer. Hence all other vertices of answers are neighbors of $v$. Run the recursive call from mask & g[v], where g[v] denotes the mask of neighbors. Clearly, it works in $O(2^m)$. However, if we add memorization (don't calculate for same mask twice) it is magically becomes $O(2^{m/2})$. Why? Consider the recursion, there are at most $m/2$ recursion calls before we arrive into the state, where there are no set bits of the first half. This part will take at most $2^{m/2}$ then. And clearly there are at most $2^{m/2}$ states with no set bits in the first half.
[ "bitmasks", "brute force", "dp", "meet-in-the-middle" ]
2,200
null
1106
A
Lunar New Year and Cross Counting
Lunar New Year is approaching, and you bought a matrix with lots of "crosses". This matrix $M$ of size $n \times n$ contains only 'X' and '.' (without quotes). The element in the $i$-th row and the $j$-th column $(i, j)$ is defined as $M(i, j)$, where $1 \leq i, j \leq n$. We define a cross appearing in the $i$-th row and the $j$-th column ($1 < i, j < n$) if and only if $M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $ 'X'. The following figure illustrates a cross appearing at position $(2, 2)$ in a $3 \times 3$ matrix. \begin{center} \begin{verbatim} X.X .X. X.X \end{verbatim} \end{center} Your task is to find out the number of crosses in the given matrix $M$. Two crosses are different if and only if they appear in different rows or columns.
The solution is simple: Just check if crosses can appear in every positions. Two nesting for-loops will be enough to solve this problem. Time complexity: $\mathcal{O}(n^2)$
[ "implementation" ]
800
#include <bits/stdc++.h> #define N 510 using namespace std; char a[N][N]; int n; int main(){ scanf("%d", &n); for (int i = 1; i <= n; i++){ scanf("%s", a[i] + 1); } int ans = 0; for (int i = 2; i < n; i++){ for (int j = 2; j < n; j++){ if (a[i][j] == 'X' && a[i - 1][j - 1] == 'X' && a[i - 1][j + 1] == 'X' && a[i + 1][j - 1] == 'X' && a[i + 1][j + 1] == 'X'){ ans ++; } } } printf("%d\n", ans); return 0; }
1106
B
Lunar New Year and Food Ordering
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's". The restaurant "Alice's" serves $n$ kinds of food. The cost for the $i$-th kind is always $c_i$. Initially, the restaurant has enough ingredients for serving exactly $a_i$ dishes of the $i$-th kind. In the New Year's Eve, $m$ customers will visit Alice's one after another and the $j$-th customer will order $d_j$ dishes of the $t_j$-th kind of food. The $(i + 1)$-st customer will only come after the $i$-th customer is completely served. Suppose there are $r_i$ dishes of the $i$-th kind remaining (initially $r_i = a_i$). When a customer orders $1$ dish of the $i$-th kind, the following principles will be processed. - If $r_i > 0$, the customer will be served exactly $1$ dish of the $i$-th kind. The cost for the dish is $c_i$. Meanwhile, $r_i$ will be reduced by $1$. - Otherwise, the customer will be served $1$ dish of the \textbf{cheapest} available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $1$. - If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $0$. If the customer doesn't leave after the $d_j$ dishes are served, the cost for the customer will be the sum of the cost for these $d_j$ dishes. Please determine the total cost for each of the $m$ customers.
The implementation of the problem is easy: Just do what Bob tells you to do. The only difficulty, if it is, is to handle the cheapest dish. This can be done by a pointer or a priority queue. The details can be found in the code. Time complexity: $\mathcal{O}(m + n \log n)$
[ "data structures", "implementation" ]
1,500
#include <bits/stdc++.h> #define N 300010 #define PII pair<int, int> using namespace std; typedef long long LL; int n, m, a[N], c[N], t, d; LL ans = 0; priority_queue<PII, vector<PII>, greater<PII> > Q; int main(){ scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++){ scanf("%d", &a[i]); } for (int i = 1; i <= n; i++){ scanf("%d", &c[i]); Q.push(make_pair(c[i], i)); } for (int i = 1; i <= m; i++){ scanf("%d%d", &t, &d); if (d <= a[t]){ a[t] -= d; printf("%lld\n", 1LL * d * c[t]); } else { bool flag = false; LL ans = 1LL * a[t] * c[t]; d -= a[t]; a[t] = 0; while (!Q.empty()){ while (!Q.empty() && a[Q.top().second] == 0) Q.pop(); if (Q.empty()) break; PII now = Q.top(); if (d <= a[now.second]){ a[now.second] -= d; ans += 1LL * d * now.first; flag = true; printf("%lld\n", ans); break; } else { ans += 1LL * a[now.second] * now.first; d -= a[now.second]; a[now.second] = 0; Q.pop(); } } if (!flag){ puts("0"); } } } }
1106
C
Lunar New Year and Number Division
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem. There are $n$ positive integers $a_1, a_2, \ldots, a_n$ on Bob's homework paper, where $n$ is always an \textbf{even} number. Bob is asked to divide those numbers into groups, where each group must contain at least $2$ numbers. Suppose the numbers are divided into $m$ groups, and the sum of the numbers in the $j$-th group is $s_j$. Bob's aim is to minimize the sum of the square of $s_j$, that is $$\sum_{j = 1}^{m} s_j^2.$$ Bob is puzzled by this hard problem. Could you please help him solve it?
This problem is easy as it looks like, and it is proved to be simple. As $n$ is even, the optimal grouping policy is to group the smallest with the largest, the second smallest with the second largest, etc. First, it is easy to prove that it is optimal to group these numbers $2$ by $2$, so the proof is given as an exercise to you. The proof of the second part is about the Rearrangement Inequality. Let's consider two of the permutations of the sequence $\{a_i\}$. Suppose they are $\{b_i\}, \{c_i\}$ where $b_i = c_j$ if and only if $b_j = c_i$. Then the sum $\frac{1}{2} \sum_{i = 1}^{n} (b_i + c_i)^2$ $\frac{1}{2} \sum_{i = 1}^{n} (b_i^2 + c_i^2)$ Time complexity: $\mathcal{O}(n \log n)$
[ "greedy", "implementation", "math", "sortings" ]
900
#include <bits/stdc++.h> #define N 300010 using namespace std; typedef long long LL; int n, a[N]; LL ans = 0; int main(){ scanf("%d", &n); for (int i = 1; i <= n; i++){ scanf("%d", &a[i]); } sort(a + 1, a + n + 1); for (int i = 1; i <= n / 2; i++){ ans += 1LL * (a[i] + a[n - i + 1]) * (a[i] + a[n - i + 1]); } printf("%lld\n", ans); return 0; }
1106
D
Lunar New Year and a Wander
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with $n$ nodes and $m$ bidirectional edges. Initially Bob is at the node $1$ and he records $1$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $a_1, a_2, \ldots, a_n$ is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds: - $x$ is a prefix of $y$, but $x \ne y$ (this is impossible in this problem as all considered sequences have the same length); - in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.
In fact, you don't really need to consider the path Bob wanders. A priority queue is enough for this problem. When Bob visits a node, add its adjacent nodes into the priority queue. Every time he visits a new node, it will be one with the smallest index in the priority queue. Time complexity: $\mathcal{O}(m \log n)$
[ "data structures", "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,500
#include <bits/stdc++.h> #define N 300010 using namespace std; typedef long long LL; priority_queue<int, vector<int>, greater<int> > Q; vector<int> e[N]; vector<int> seq; bool vis[N]; int n, m; int main(){ scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++){ int u, v; scanf("%d%d", &u, &v); e[u].push_back(v); e[v].push_back(u); } vis[1] = true; Q.push(1); while (!Q.empty()){ int now = Q.top(); Q.pop(); seq.push_back(now); for (auto p : e[now]){ if (!vis[p]){ Q.push(p); vis[p] = true; } } } for (auto p : seq){ printf("%d ", p); } puts(""); return 0; }
1106
E
Lunar New Year and Red Envelopes
Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself. Let's describe this problem in a mathematical way. Consider a timeline from time $1$ to $n$. The $i$-th red envelope will be available from time $s_i$ to $t_i$, inclusive, and contain $w_i$ coins. If Bob chooses to collect the coins in the $i$-th red envelope, he can do it only in an \textbf{integer} point of time between $s_i$ and $t_i$, inclusive, and he can't collect any more envelopes until time $d_i$ (inclusive) after that. Here $s_i \leq t_i \leq d_i$ holds. Bob is a greedy man, he collects coins greedily — whenever he can collect coins at some integer time $x$, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter $d$ is the \textbf{largest}. If there are still multiple choices, Bob will choose one from them randomly. However, Alice — his daughter — doesn't want her father to get too many coins. She could disturb Bob at no more than $m$ integer time moments. If Alice decides to disturb Bob at time $x$, he could not do anything at time $x$ and resumes his usual strategy at the time $x + 1$ (inclusive), which may lead to missing some red envelopes. Calculate the minimum number of coins Bob would get if Alice disturbs him optimally.
Yes, this is where Alice shows up and ... probably the problem is not related to Game Theory. Let's divide the problem into two parts: The first is to obtain the maximum coins Bob can get from time points $1$ to $n$, and the second is to decide when to disturb Bob. For the first part, we apply event sorting to those time segments. After that, we use a set with a sweep line to deal with it. Whenever we meet a start or a terminate of one red envelope, we add this into the set or remove that from the set. Note that you need to use multiset, since there can be multiple red envelopes with same $d$ and $w$. For the second part, we apply dynamic programming since $m$ is relatively small. Let $f[i][j]$ denote that the minimum coins Bob gets when we only consider the timeline from $1$ to $i$ and Alice disturbs Bob for $j$ times. The transition is trivial and you can take a look at it in the code. Time complexity: $\mathcal{O}((n + k) \log k + nm)$
[ "data structures", "dp" ]
2,100
#include <bits/stdc++.h> #define N 100010 using namespace std; typedef long long LL; struct Event{ int d, w, t; bool operator < (const Event &e) const { return w > e.w || (w == e.w && d > e.d); } }; vector<Event> e[N]; Event a[N]; map<Event, int> cur; int n, m, k; LL f[2][N], ans = 0x3f3f3f3f3f3f3f3fLL; void insert(Event x){ if (cur.count(x)){ cur[x] ++; } else { cur[x] = 1; } } void erase(Event x){ cur[x] --; if (cur[x] == 0){ cur.erase(x); } } int main(){ scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= k; i++){ int s, t, d, w; scanf("%d%d%d%d", &s, &t, &d, &w); e[s].push_back((Event){d, w, 1}); e[t + 1].push_back((Event){d, w, -1}); } for (int i = 1; i <= n; i++){ for (auto p : e[i]){ if (p.t == 1){ insert(p); } else { erase(p); } } if (cur.size()){ a[i] = (*cur.begin()).first; } else { a[i] = (Event){i, 0, 0}; } } memset(f, 0x3f, sizeof(f)); f[0][1] = 0; for (int j = 0; j <= m; j++){ memset(f[(j ^ 1) & 1], 0x3f, sizeof(f[(j ^ 1) & 1])); for (int i = 1; i <= n; i++){ f[(j ^ 1) & 1][i + 1] = min(f[(j ^ 1) & 1][i + 1], f[j & 1][i]); f[j & 1][a[i].d + 1] = min(f[j & 1][a[i].d + 1], f[j & 1][i] + a[i].w); } ans = min(ans, f[j & 1][n + 1]); } printf("%lld\n", ans); return 0; }
1106
F
Lunar New Year and a Recursive Sequence
Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it. Let $f_1, f_2, \ldots, f_i, \ldots$ be an infinite sequence of positive integers. Bob knows that for $i > k$, $f_i$ can be obtained by the following recursive equation: $$f_i = \left(f_{i - 1} ^ {b_1} \cdot f_{i - 2} ^ {b_2} \cdot \cdots \cdot f_{i - k} ^ {b_k}\right) \bmod p,$$ which in short is $$f_i = \left(\prod_{j = 1}^{k} f_{i - j}^{b_j}\right) \bmod p,$$ where $p = 998\,244\,353$ (a widely-used prime), $b_1, b_2, \ldots, b_k$ are known integer constants, and $x \bmod y$ denotes the remainder of $x$ divided by $y$. Bob lost the values of $f_1, f_2, \ldots, f_k$, which is extremely troublesome – these are the basis of the sequence! Luckily, Bob remembers the first $k - 1$ elements of the sequence: $f_1 = f_2 = \ldots = f_{k - 1} = 1$ and the $n$-th element: $f_n = m$. Please find any possible value of $f_k$. If no solution exists, just tell Bob that it is impossible to recover his favorite sequence, regardless of Bob's sadness.
This problem seems weird first looking at it, but we can rewrite it into a linear recursive equation. The most important thing you should know is that $g = 3$ is a primitive root of $p = 998\,244\,353$. Briefly speaking, the primitive $g$ is called a primitive root of $p$ if and only if the following two constraints are satisfied: $g^{p - 1} \bmod p = 1$ (shown by Fermat's little theorem) $\forall 1 \leq k < p - 1$, $g^k \bmod p \ne 1$ The two constraints shown above imply that $\forall 1 \leq x < y < p$, $g^x \bmod p \ne g^y \bmod p$. The proof is simple: If $g^x \bmod p = g^y \bmod p$, we have $g^{y - x} \bmod p = 1$. However, it violates the second constraint since $1 \leq y - x < p - 1$. Thus the function $q(x)$ defined by $g^{q(x)} \bmod p = x$ is a bijection: We can recover $x$ from $q(x)$ using fast power algorithm and get $q(x)$ from $x$ using baby step giant step algorithm. Now, we construct a new sequence $h_1, h_2, \ldots, h_i, \ldots$ where $h_i = q(f_i)$. Then we can derive the equation that $h_i$ should satisfy: $g^{h_i} \bmod p = \left(\prod_{j = 1}^{k} g^{h_{i - j}{b_j}}\right) \bmod p,$ which yields (applying Fermat's little theorem) $g^{h_i \bmod p - 1} \bmod p = g^{\left(\sum_{j = 1}^{k} {b_j}{h_{i - j}}\right) \bmod p - 1} \bmod p$ Since $g$ is a primitive root of $p$, the equation satisfied if and only if the exponents are the same. Thus $h_i = \left(\sum_{j = 1}^{k} {b_j}{h_{i - j}}\right) \bmod p - 1$ You may obtain the same equation by applying discrete logarithm on both sides of the equation of $f_i$. Note that the equation of $h_i$ is a normal linear recursive equation, which can be solved using matrix exponentiation to get the relationship between $h_n$ and $h_k$. To obtain $h_n$, just apply the baby step giant step algorithm, and the relationship between $h_n$ and $h_k$ can be represented by a congruence equation: $ch_k \equiv h_n \qquad (\bmod p - 1)$ In this equation, $c$ is the corresponding coefficient of $h_k$ obtained by matrix exponentiation. Note that $f_1 = f_2 = \ldots = f_{k - 1} = 1$, which yields $h_1 = h_2 = \ldots = h_{k - 1} = q(1) = 0$. Therefore, we just ignore those items, leaving $ch_k$ alone. This congruence equation can be solved by Extended Euclidean algorithm. If no solution exists for this equation, the original problem has no solution as well. After obtaining $h_k$, $f_k$ can be recovered using fast power algorithm. Time complexity: $\mathcal{O}(k^3 \log n + \sqrt{p} \log p)$ UPD: Now I would add some details about those two algorithms: matrix exponentiation and baby step giant step algorithm. 1. Matrix exponentiation Suppose that we have a linear recursive equation $f_i = \sum_{j = 1}^{k} {b_j}{f_{i - j}}$ where $b_1, b_2, \ldots, b_k$, $f_1, f_2, \ldots, f_k$ are known constants. Then the following equation of matrices holds for some $i$ ($i \geq k$) $\begin{bmatrix} b_1 & b_2 & b_3 & \cdots & b_{k - 1} & b_k \\ 1 & 0 & 0 & \cdots & 0 & 0 \\ 0 & 1 & 0 & \cdots & 0 & 0 \\ 0 & 0 & 1 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & 0 & \cdots & 1 & 0 \\ \end{bmatrix} \cdot \begin{bmatrix} f_i \\ f_{i - 1} \\ f_{i - 2} \\ f_{i - 3} \\ \vdots \\ f_{i - k + 1} \\ \end{bmatrix} = \begin{bmatrix} f_{i + 1} \\ f_i \\ f_{i - 1} \\ f_{i - 2} \\ \vdots \\ f_{i - k + 2} \\ \end{bmatrix}$ Let's call the matrix $\mathbf{A}$ transition matrix, where $\mathbf{A} = \begin{bmatrix} b_1 & b_2 & b_3 & \cdots & b_{k - 1} & b_k \\ 1 & 0 & 0 & \cdots & 0 & 0 \\ 0 & 1 & 0 & \cdots & 0 & 0 \\ 0 & 0 & 1 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & 0 & \cdots & 1 & 0 \\ \end{bmatrix}$ and $\mathbf{f}_i = \begin{bmatrix} f_i \\ f_{i - 1} \\ f_{i - 2} \\ f_{i - 3} \\ \vdots \\ f_{i - k + 1} \\ \end{bmatrix}$ Therefore, the equation shown above can be rewritten as $\mathbf{A} \mathbf{f}_i = \mathbf{f}_{i + 1}$ which yields $\mathbf{A}^{n - k} \mathbf{f}_k = \mathbf{f}_{n}$ So we can obtain $\mathbf{f}_{n}$ in $\mathcal{O}(k^3 \log n)$ time since a single matrix multiplication takes $\mathcal{O}(k^3)$ time. There are two problems that you may consider as your further research on linear recursive equations. Solve this linear recursive equation in $\mathcal{O}(k^2 \log n)$ time or $\mathcal{O}(k \log k \log n)$ if you apply Fast Fourier Transform. Solve the following linear recursive equation in $\mathcal{O}(k^3 \log n)$ time or faster: $f_i = \sum_{j = 1}^{k} {b_j}{f_{i - j}} + c$ where $c$ is a constant. $f_i = \sum_{j = 1}^{k} {b_j}{f_{i - j}} + c$ where $c$ is a constant. 2. Baby step giant step algorithm Consider the following congruence equation $a^z \equiv b \qquad (\bmod p)$ The intuition of the baby step giant step algorithm is meet-in-the-middle. Let's write $z = x \cdot \sqrt{p} + y$ for convenience. In this representation, $x, y < \sqrt{p}$. We store $b \cdot a^{-0}, b \cdot a^{-1}, \ldots, b \cdot a^{-(\sqrt{p} - 1)}$ in a map. Then we try every possible $x$ from $0$ to $\sqrt{p} - 1$. Since $a^{x \cdot \sqrt{p} + y} \equiv b \qquad (\bmod p)$ $a^{x \cdot \sqrt{p}} \equiv b \cdot a^{-y} \qquad (\bmod p)$
[ "math", "matrices", "number theory" ]
2,400
#include <bits/stdc++.h> #define N 210 using namespace std; typedef long long LL; const LL p = 998244353; const LL g = 3; int k; LL n, m, b[N]; struct Matrix{ int n; LL mat[N][N]; Matrix(){ n = 0; memset(mat, 0, sizeof(mat)); } Matrix(int _n, LL diag){ n = _n; memset(mat, 0, sizeof(mat)); for (int i = 1; i <= n; i++){ mat[i][i] = diag; } } Matrix(const Matrix &c){ n = c.n; for (int i = 1; i <= n; i++){ for (int j = 1; j <= n; j++){ mat[i][j] = c.mat[i][j]; } } } Matrix operator * (const Matrix &a) const { Matrix ans = Matrix(n, 0); for (int k = 1; k <= n; k++){ for (int i = 1; i <= n; i++){ for (int j = 1; j <= n; j++){ ans.mat[i][j] += mat[i][k] * a.mat[k][j]; ans.mat[i][j] %= (p - 1); } } } return ans; } Matrix mat_pow(LL t){ Matrix base = Matrix(*this), ans = Matrix(n, 1); while (t){ if (t & 1){ ans = ans * base; } base = base * base; t >>= 1; } return ans; } }; namespace GCD{ LL gcd(LL a, LL b){ if (!b) return a; return gcd(b, a % b); } LL ex_gcd(LL a, LL b, LL &x, LL &y){ if (!b){ x = 1; y = 0; return a; } LL q = ex_gcd(b, a % b, y, x); y -= a / b * x; return q; } } namespace BSGS{ LL qpow(LL a, LL b, LL p){ LL ans = 1, base = a; while (b){ if (b & 1){ (ans *= base) %= p; } (base *= base) %= p; b >>= 1; } return ans; } LL inv(LL x, LL p){ return qpow(x, p - 2, p); } map<LL, LL> tab; LL bsgs(LL a, LL b, LL p){ LL u = (LL) sqrt(p) + 1; LL now = 1, step; for (LL i = 0; i < u; i++){ LL tmp = b * inv(now, p) % p; if (!tab.count(tmp)){ tab[tmp] = i; } (now *= a) %= p; } step = now; now = 1; for (LL i = 0; i < p; i += u){ if (tab.count(now)){ return i + tab[now]; } (now *= step) %= p; } throw; return -1; } } namespace SOL{ LL solve(LL a, LL b, LL c){ if (c == 0) return 0; LL q = GCD::gcd(a, b); if (c % q){ return -1; } a /= q, b /= q, c /= q; LL ans, _; GCD::ex_gcd(a, b, ans, _); (ans *= c) %= b; while (ans < 0) ans += b; return ans; } } int main(){ scanf("%d", &k); for (int i = 1; i <= k; i++){ scanf("%d", &b[i]); b[i] %= (p - 1); } scanf("%lld%lld", &n, &m); Matrix A = Matrix(k, 0); for (int i = 1; i <= k; i++){ A.mat[1][i] = b[i]; } for (int i = 2; i <= k; i++){ A.mat[i][i - 1] = 1; } A = A.mat_pow(n - k); LL ans = SOL::solve(A.mat[1][1], p - 1, BSGS::bsgs(g, m, p)); if (ans >= 0){ printf("%lld\n", BSGS::qpow(g, ans, p)); } else { puts("-1"); } return 0; }
1107
A
Digits Sequence Dividing
You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$. You have to divide it into \textbf{at least two} segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that \textbf{each element belongs to exactly one segment} and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be \textbf{strictly greater} than the previous one. More formally: if the resulting division of the sequence is $t_1, t_2, \dots, t_k$, where $k$ is the number of element in a division, then for each $i$ from $1$ to $k-1$ the condition $t_{i} < t_{i + 1}$ (using \textbf{numerical} comparing, it means that the integer representations of strings are compared) should be satisfied. For example, if $s=654$ then you can divide it into parts $[6, 54]$ and it will be suitable division. But if you will divide it into parts $[65, 4]$ then it will be bad division because $65 > 4$. If $s=123$ then you can divide it into parts $[1, 23]$, $[1, 2, 3]$ but not into parts $[12, 3]$. Your task is to find \textbf{any} suitable division for each of the $q$ independent queries.
The only case when the answer is "NO" - $n=2$ and $s_1 \ge s_2$. Then you cannot divide the initial sequence as needed in the problem. Otherwise you always can divide it into two parts: the first digit of the sequence and the remaining sequence.
[ "greedy", "strings" ]
900
#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; cin >> n >> s; if (n == 2 && s[0] >= s[1]) { cout << "NO" << endl; } else { cout << "YES" << endl << 2 << endl << s[0] << " " << s.substr(1) << endl; } } return 0; }
1107
B
Digital root
Today at the lesson of mathematics, Petya learns about the digital root. The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of $x$ as $S(x)$. Then $S(5)=5$, $S(38)=S(3+8=11)=S(1+1=2)=2$, $S(10)=S(1+0=1)=1$. As a homework Petya got $n$ tasks of the form: find $k$-th positive number whose digital root is $x$. Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $n$ tasks from Petya's homework.
Let's derive the formula $S(x) = (x-1)~mod~9 + 1$ from the digital root properties (that's a known fact but I could only find a link to some russian blog about it). Using that formula, you can easily get that $k$-th number with the digital root of $x$ is $(k-1) \cdot 9 + x$.
[ "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { long long k, x; cin >> k >> x; cout << (k - 1) * 9 + x << endl; } }
1107
C
Brutality
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct. You are given a sequence of hits, the $i$-th hit deals $a_i$ units of damage to the opponent's character. To perform the $i$-th hit you have to press the button $s_i$ on your gamepad. Hits are numbered from $1$ to $n$. You know that if you press some button \textbf{more than} $k$ times \textbf{in a row} then it'll break. You cherish your gamepad and don't want to break any of its buttons. To perform a brutality you have to land some of the hits of the given sequence. \textbf{You are allowed to skip any of them, however changing the initial order of the sequence is prohibited}. The total damage dealt is the sum of $a_i$ over all $i$ for the hits which weren't skipped. \textbf{Note that if you skip the hit then the counter of consecutive presses the button won't reset}. Your task is to skip some hits to deal the \textbf{maximum} possible total damage to the opponent's character and not break your gamepad buttons.
All you need in this problem is two simple technique: two pointers and sorting. Let's consider maximum by inclusion segments of equal letters in the initial string. Let the current segment be $[l; r]$ and its length is $len = r - l + 1$. If $len < k$ then we can press all buttons and deal all damage corresponding to them. Otherwise it is obviously more profitable to press $k$ best (by damage) buttons. So let's create the array $val$, push all values $a_i$ such that $l \le i \le r$ in this array, sort them, take $min(|val|, k)$ best by damage ($|val|$ is the size of the array $val$) and go to the next segment.
[ "greedy", "sortings", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } string s; cin >> s; long long ans = 0; for (int i = 0; i < n; ++i) { int j = i; vector<int> vals; while (j < n && s[i] == s[j]) { vals.push_back(a[j]); ++j; } sort(vals.rbegin(), vals.rend()); ans += accumulate(vals.begin(), vals.begin() + min(k, int(vals.size())), 0ll); i = j - 1; } cout << ans << endl; return 0; }
1107
D
Compression
You are given a binary matrix $A$ of size $n \times n$. Let's denote an $x$-compression of the given matrix as a matrix $B$ of size $\frac{n}{x} \times \frac{n}{x}$ such that for every $i \in [1, n], j \in [1, n]$ the condition $A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$ is met. Obviously, $x$-compression is possible only if $x$ divides $n$, but this condition is not enough. For example, the following matrix of size $2 \times 2$ does not have any $2$-compression: \begin{center} $01$ \end{center} \begin{center} $10$ \end{center} For the given matrix $A$, find maximum $x$ such that an $x$-compression of this matrix is possible. \textbf{Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.}
It is very easy to decompress the input (the input was given in the compressed form to make the constraints bigger but less dependent of the time to read the data). The authors solution is the following: Let $x$ be the answer to the problem and initially it equals to $n$. Let's iterate over all rows of the matrix and calculate lengths of maximum by inclusion segments consisting only of zeros or only of ones. Let the length of the current segment be $len$. Then let's set $x := gcd(x, len)$, where $gcd$ is the function calculating the greatest common divisor. Then let's do the same for columns of the matrix and print the answer. How to prove that this solution works? On the one hand, if some segment of kind $[1 + lx, 1 + (l + 1)x]$, where $l$ is the value from the range $[0; \frac{n}{x} - 1]$, contains different digits then we cannot compress the given matrix. On the other hand, if the previous condition is true, then we can compress each string by the following algorithm: cut off the first $x$ characters of the string and compress the remaining string recursively. After such compression we obtain the matrix of size $n \times \frac{n}{x}$. And because of the first condition we can compress the remaining matrix again by this algorithm if we apply it to columns instead of rows.
[ "dp", "implementation", "math", "number theory" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 5200; int n; bool a[N][N]; void parse_char(int x, int y, char c) { int num = -1; if (isdigit(c)) { num = c - '0'; } else { num = c - 'A' + 10; } for (int i = 0; i < 4; ++i) { a[x][y + 3 - i] = num & 1; num >>= 1; } } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif scanf("%d", &n); char buf[N]; for (int i = 0; i < n; ++i) { scanf("%s", buf); for (int j = 0; j < n / 4; ++j) { parse_char(i, j * 4, buf[j]); } } int g = n; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { int k = j; while (k < n && a[i][k] == a[i][j]) ++k; g = __gcd(g, k - j); j = k - 1; } } for (int j = 0; j < n; ++j) { for (int i = 0; i < n; ++i) { int k = i; while (k < n && a[k][j] == a[i][j]) ++k; g = __gcd(g, k - i); i = k - 1; } } cout << g << endl; return 0; }
1107
E
Vasya and Binary String
Vasya has a string $s$ of length $n$ consisting only of digits 0 and 1. Also he has an array $a$ of length $n$. Vasya performs the following operation until the string becomes empty: choose some \textbf{consecutive} substring of \textbf{equal characters}, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string {1\textbf{111}10} he will get the string 110. Vasya gets $a_x$ points for erasing substring of length $x$. Vasya wants to maximize his total points, so help him with this!
We will solve the problem with dynamic programming. Let $ans_{l, r}$ be the answer for substring $s_{l, l + 1, \dots r}$. If sequence is empty ($l > r$) then $ans_{l, r} = 0$. Let $dp_{dig, l, r, cnt}$ be the maximum score that we can get if we reduce the substring $s_{l, l + r, \dots r}$ into $cnt$ digits equal to $dig$ with some operations. If substring $s_{l, l + r, \dots r}$ does not contain $cnt$ digit $dig$, then $dp_{dig, l, r, cnt} = -10^{18}$. If $cnt = 0$, then $dp_{dig, l, r, cnt} = ans_{l, r}$. To calculate $ans_{l, r}$ just fix the sequence of digits that will be deleted last: $ans_{l, r} = \max\limits_{1 \le cnt \le r - l + 1, 0 \le dig \le 1} a_{cnt} + dp_{dig, l, r, cnt}$. To calculate $dp_{dig, l, r, cnt}$ just fix the first element $mid$ that is left after working with the substring. Note that $s_{mid}$ must be equal to $dig$. $dp_{dig, l, r, cnt} = \max\limits_{1 \le mid \le r, s_{mid} = dig} ans_{l, mid - 1} + dp_{dig, mid + 1, r, cnt - 1}$. All that's left is to transform these formulas into code. Complexity of this solution is $O(n^4)$.
[ "dp" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 102; const long long INF = 1e12; int n; string s; int a[N]; long long ans[N][N]; long long dp[2][N][N][N]; long long calcDp(int c, int l, int r, int cnt); long long calcAns(int l, int r){ if(l >= r) return 0; long long &res = ans[l][r]; if(res != -1) return res; res = 0; for(int cnt = 1; cnt <= r - l; ++cnt){ res = max(res, calcDp(0, l, r, cnt) + a[cnt - 1]); res = max(res, calcDp(1, l, r, cnt) + a[cnt - 1]); } return res; } long long calcDp(int c, int l, int r, int cnt){ if(cnt == 0) return calcAns(l, r); long long &res = dp[c][l][r][cnt]; if(res != -1) return res; res = -INF; for(int i = l; i < r; ++i){ if(c == s[i] - '0') res = max(res, calcAns(l, i) + calcDp(c, i + 1, r, cnt - 1)); } return res; } int main(){ cin >> n >> s; for(int i = 0; i < n; ++i) cin >> a[i]; memset(dp, -1, sizeof dp); memset(ans, -1, sizeof ans); cout << calcAns(0, n) << endl; return 0; }
1107
F
Vasya and Endless Credits
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles. However, the local bank has $n$ credit offers. Each offer can be described with three numbers $a_i$, $b_i$ and $k_i$. Offers are numbered from $1$ to $n$. If Vasya takes the $i$-th offer, then the bank gives him $a_i$ burles at the beginning of the month and then Vasya pays bank $b_i$ burles at the end of each month for the next $k_i$ months (including the month he activated the offer). \textbf{Vasya can take the offers any order he wants}. \textbf{Each month Vasya can take no more than one credit offer}. \textbf{Also each credit offer can not be used more than once}. Several credits can be active at the same time. It implies that Vasya pays bank the sum of $b_i$ over all the $i$ of active credits at the end of each month. Vasya wants to buy a car in the middle of some month. He just takes all the money he currently has and buys the car of that exact price. Vasya don't really care what he'll have to pay the bank back after he buys a car. He just goes out of the country on his car so that the bank can't find him anymore. What is the maximum price that car can have?
Let create the following matrix (zero-indexed): $mat_{i, j} = a_j - min(i, k_j) \cdot b_j$. $i$-th row of this matrix contains Vasya's profits for credit offers as if they were taken $i$ months before the purchase. We need to choose elements from this matrix so that there is no more than one element taken in each row and each column. The sum of the chosen elements should be maximum possible. And that is exactly the problem Hungarian algorithm solves.
[ "dp", "flows", "graph matchings", "graphs", "sortings" ]
2,600
#include <bits/stdc++.h> using namespace std; const int N = 505; const long long INF = 1e18; int n; long long a[N][N]; int up[N], down[N], k[N]; long long u[N], v[N]; int p[N], way[N]; int main(){ cin >> n; for(int i = 0; i < n; ++i) cin >> up[i] >> down[i] >> k[i]; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) a[i + 1][j + 1] = -(up[j] - min(i, k[j]) * 1LL * down[j]); long long res = 0; for(int i = 1; i <= n; ++i){ p[0] = i; int j0 = 0; vector<long long> minv (n + 1, INF); vector<char> used (n + 1, false); do{ used[j0] = true; int i0 = p[j0], j1; long long delta = INF; for (int j = 1; j <= n; ++j) if (!used[j]){ long long cur = a[i0][j] - u[i0] - v[j]; if (cur < minv[j]) minv[j] = cur, way[j] = j0; if (minv[j] < delta) delta = minv[j], j1 = j; } for (int j = 0; j <= n; ++j) if (used[j]) u[p[j]] += delta, v[j] -= delta; else minv[j] -= delta; j0 = j1; }while (p[j0] != 0); do { int j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0); res = max(res, v[0]); } cout << res << endl; return 0; }
1107
G
Vasya and Maximum Profit
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit. Vasya has $n$ problems to choose from. They are numbered from $1$ to $n$. The difficulty of the $i$-th problem is $d_i$. Moreover, the problems are given in the increasing order by their difficulties. \textbf{The difficulties of all tasks are pairwise distinct}. In order to add the $i$-th problem to the contest you need to pay $c_i$ burles to its author. For each problem in the contest Vasya gets $a$ burles. \textbf{In order to create a contest he needs to choose a consecutive subsegment of tasks}. So the total earnings for the contest are calculated as follows: - if Vasya takes problem $i$ to the contest, he needs to pay $c_i$ to its author; - for each problem in the contest Vasya gets $a$ burles; - let $gap(l, r) = \max\limits_{l \le i < r} (d_{i + 1} - d_i)^2$. If Vasya takes all the tasks with indices from $l$ to $r$ to the contest, he also needs to pay $gap(l, r)$. If $l = r$ then $gap(l, r) = 0$. Calculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks.
It is clear that $gap(l, r) \le gap(l, r + 1)$ and $gap(l, r) \le gap(l - 1, r)$. Sort all indices $2, 3, \dots, n$ with comparator based on the value of $d_i - d_{i-1}$. Let's consider all indices in the order discussed above and for fixed index $i$ find the best answer among such segments $(l, r)$ that $gap(l, r) \le d_i$, $gap_(l-1, r) > d_i$ and $gap_(l, r+1) > d_i$. Initially, when we consider $gap = 0$, there are $n$ such segments, each containing only one task. When we consider new index $j$, we need to merge segments $(l, j - 1)$ and $(j, r)$ and update the answer with $best(l, r) - (d_j - d_{j-1})^2$, where $best(l, r)$ is the maximum subsegment in array $a - c_l, a - c_{l+1}, \dots, a - c_r$ (that array represents the profit we get for each task). We can store and merge such segments with $set$ in C++ or $TreeSet$ in Java. We can answer queries $best(l, r)$ using the segment tree (we need to process queries of the form "find a subsegment having maximum sum"). Read more about it here.
[ "binary search", "constructive algorithms", "data structures", "dp", "dsu" ]
2,400
#include<bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; struct node{ long long sum, ans, pref, suf; node () {} node(int x){ sum = x; x = max(x, 0); pref = suf = ans = x; } }; node merge(const node &a, const node &b){ node res; res.sum = a.sum + b.sum; res.pref = max(a.pref, a.sum + b.pref); res.suf = max(b.suf, b.sum + a.suf); res.ans = max(max(a.ans, b.ans), a.suf + b.pref); return res; } int n, x; pair<int, int> p[N]; node t[N * 4]; void upd(int v, int l, int r, int pos, int x){ if(r - l == 1){ assert(pos == l); t[v] = node(x); return; } int mid = (l + r) / 2; if(pos < mid) upd(v * 2 + 1, l, mid, pos, x); else upd(v * 2 + 2, mid, r, pos, x); t[v] = merge(t[v * 2 + 1], t[v * 2 + 2]); } node get(int v, int l, int r, int L, int R){ if(L >= R) return node(0); if(l == L && r == R) return t[v]; int mid = (l + r)/ 2; return merge(get(v * 2 + 1, l, mid, L, min(mid, R)), get(v * 2 + 2, mid, r, max(L, mid), R)); } int main() { scanf("%d %d", &n, &x); for(int i = 0; i < n; ++i){ scanf("%d %d", &p[i].first, &p[i].second); p[i].second = x - p[i].second; } sort(p, p + n); for(int i = 0; i < n; ++i) upd(0, 0, n, i, p[i].second); vector <pair<int, int> > v; for(int i = 1; i < n; ++i) v.emplace_back(p[i].first - p[i - 1].first, i); sort(v.begin(), v.end()); long long res = 0; set <pair<int, int> > s; for(int i = 0; i < n; ++i){ s.insert(make_pair(i, i + 1)); res = max(res, 1LL * p[i].second); } int l = 0; while(l < v.size()){ int r = l + 1; while(r < v.size() && v[l].first == v[r].first) ++r; long long d = v[l].first * 1LL * v[l].first; for(int i = l; i < r; ++i){ int id = v[i].second; auto it = s.upper_bound(make_pair(id, -1)); assert(it->first == id); assert(it != s.begin()); auto R = *it; --it; auto L = *it; s.erase(L), s.erase(R); L.second = R.second; auto nd = get(0, 0, n, L.first, L.second); res = max(res, nd.ans - d); s.insert(L); } l = r; } cout << res << endl; return 0; }
1108
A
Two distinct points
You are given two segments $[l_1; r_1]$ and $[l_2; r_2]$ on the $x$-axis. It is guaranteed that $l_1 < r_1$ and $l_2 < r_2$. Segments \textbf{may intersect, overlap or even coincide with each other}. \begin{center} {\small The example of two segments on the $x$-axis.} \end{center} Your problem is to find two \textbf{integers} $a$ and $b$ such that $l_1 \le a \le r_1$, $l_2 \le b \le r_2$ and $a \ne b$. In other words, you have to choose two \textbf{distinct} integer points in such a way that the first point belongs to the segment $[l_1; r_1]$ and the second one belongs to the segment $[l_2; r_2]$. It is guaranteed that \textbf{the answer exists}. If there are multiple answers, you can print \textbf{any} of them. You have to answer $q$ independent queries.
One of the possible answers is always a pair of endpoints of the given segments. So we can add all endpoints to the array and iterate over all pairs of elements of this array and check if the current pair is suitable or not.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { int l1, r1, l2, r2; cin >> l1 >> r1 >> l2 >> r2; vector<int>a({l1, r1, l2, r2}); int ans1 = 0, ans2 = 0; for (auto it : a) for (auto jt : a) { if (l1 <= it && it <= r1 && l2 <= jt && jt <= r2 && it != jt) { ans1 = it; ans2 = jt; } } cout << ans1 << " " << ans2 << endl; } return 0; }
1108
B
Divisors of Two Integers
Recently you have received two \textbf{positive} integer numbers $x$ and $y$. You forgot them, but you remembered a \textbf{shuffled} list containing all divisors of $x$ (including $1$ and $x$) and all divisors of $y$ (including $1$ and $y$). If $d$ is a divisor of both numbers $x$ and $y$ at the same time, there are two occurrences of $d$ in the list. For example, if $x=4$ and $y=6$ then the given list can be any permutation of the list $[1, 2, 4, 1, 2, 3, 6]$. Some of the possible lists are: $[1, 1, 2, 4, 6, 3, 2]$, $[4, 6, 1, 1, 2, 3, 2]$ or $[1, 6, 3, 2, 4, 1, 2]$. Your problem is to restore suitable \textbf{positive} integer numbers $x$ and $y$ that would yield the same list of divisors (possibly in different order). It is guaranteed that the answer exists, i.e. the given list of divisors corresponds to some \textbf{positive} integers $x$ and $y$.
Let's take a look on the maximum element of the given array. Suddenly, this number is $x$ (or $y$, the order doesn't matter). Okay, what would we do if we know $x$ and merged list of divisors of $x$ and $y$? Let's remove all divisors of $x$ and see what we got. The maximum element in the remaining array is $y$. So, the problem is solved.
[ "brute force", "greedy", "math", "number theory" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; multiset<int> a; for (int i = 0; i < n; ++i) { int x; cin >> x; a.insert(x); } int x = *prev(a.end()); for (int i = 1; i <= x; ++i) { if (x % i == 0) { a.erase(a.find(i)); } } cout << x << " " << *prev(a.end()) << endl; return 0; }
1108
C
Nice Garland
You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is \textbf{nice}. A garland is called \textbf{nice} if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $t$, then for each $i, j$ such that $t_i = t_j$ should be satisfied $|i-j|~ mod~ 3 = 0$. The value $|x|$ means absolute value of $x$, the operation $x~ mod~ y$ means remainder of $x$ when divided by $y$. For example, the following garlands are \textbf{nice}: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not \textbf{nice}: "RR", "RGBG". Among all ways to recolor the initial garland to make it \textbf{nice} you have to choose one with the \textbf{minimum} number of recolored lamps. If there are multiple optimal solutions, print \textbf{any} of them.
It is easy to see that any nice garland has one of the following $6$ patterns: "BGRBGR ... BGR"; "BRGBRG ... BRG"; "GBRGBR ... GBR"; "GRBGRB ... GRB"; "RBGRBG ... RBG"; "RGBRGB ... RGB"; We can hard-code all all this patterns or iterate over all these permutations of letters "BGR" using three nested loops or standard language functions. We can calculate for each pattern the cost to obtain such pattern from the given string and choose one with the minimum cost.
[ "brute force", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; vector<int> p(3); iota(p.begin(), p.end(), 0); string colors = "RGB"; string res = ""; int ans = 1e9; do { string t; int cnt = 0; for (int i = 0; i < n; ++i) { t += colors[p[i % 3]]; cnt += t[i] != s[i]; } if (ans > cnt) { ans = cnt; res = t; } } while (next_permutation(p.begin(), p.end())); cout << ans << endl << res << endl; return 0; }
1108
D
Diverse Garland
You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is \textbf{diverse}. A garland is called \textbf{diverse} if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is $1$) have distinct colors. In other words, if the obtained garland is $t$ then for each $i$ from $1$ to $n-1$ the condition $t_i \ne t_{i + 1}$ should be satisfied. Among all ways to recolor the initial garland to make it \textbf{diverse} you have to choose one with the \textbf{minimum} number of recolored lamps. If there are multiple optimal solutions, print \textbf{any} of them.
Let's divide the initial string into blocks of consecutive equal letters. For example, if we have the string "GGBBBRRBBBB" then have $4$ blocks: the first block is two letters 'G', the second one is three letters 'B', the third one is two letters 'R' and the last one is four letters 'B'. Let's see at the current block (let it has the length $len$) and consider two cases. The first case is when this block has odd length. Then it seems like "XXXXXXX". So, what is the minimum number of recolors we need to make this block correct? It is $\lfloor\frac{len}{2}\rfloor$. Why can we always make this block correct for such number of recolors? Because we can recolor all 'X' at even positions to any 'Y' which differs from 'X'. So our block will be look like "XYXYXYX". The second case is when this block has even length. Then it seems like "XXXXYYY ... YYY" where 'Y' is the next block letter (if the next block exists, because the last block doesn't have the next one). What is the minimum number of recolors in this case? It is $\frac{len}{2}$. How can we recolor this block to make it correct? Let's recolor all 'X' at even positions (again) to any 'Z' which differs from 'X' and differs from 'Y'. So our block will be look like "XZXZYYY ... YYY". So all we have to do is to iterate over all blocks from left to right and apply the algorithm above to recolor them.
[ "constructive algorithms", "dp", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; int ans = 0; for (int i = 0; i < n; ++i) { int j = i; while (j < n && s[i] == s[j]) { ++j; } string q = "RGB"; q.erase(q.find(s[i]), 1); if (j < n) q.erase(q.find(s[j]), 1); for (int k = i + 1; k < j; k += 2) { ++ans; s[k] = q[0]; } i = j - 1; } cout << ans << endl << s << endl; return 0; }
1108
E1
Array and Segments (Easy version)
\textbf{The only difference between easy and hard versions is a number of elements in the array}. You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$. You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (\textbf{independently}). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$. You have to choose some subset of the given segments (\textbf{each segment can be chosen at most once}) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ will be \textbf{maximum} possible. Note that \textbf{you can choose the empty set}. If there are multiple answers, you can print \textbf{any}. \textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
Let's divide all segments to four classes. The first class contains segments which covers both minimum and maximum values (the answer) of the resulting array, the second class contains segments which covers only minimum value of the resulting array, the third class contains segments which covers only maximum value of the resulting array and the fourth class contains segments which covers neither maximum nor minimum of the resulting array. We can easy see that we cannot increase the answer if we apply segments of first and third classes. What is common in this two classes? Right, both of them are cover maximum value. So we can came up with the solution in $O(n^2m)$ or $O(n(n+m))$ (depends on implementation). Let's iterate over position of the supposed maximum value and apply all segments which not cover it. It can be done in $O(n^2m)$ with straight-forward implementation or in $O(n(n+m))$ using prefix sums. After we apply all needed segments we can try to update the answer with the value of the obtained array.
[ "brute force", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; mt19937 rnd(time(NULL)); const int INF = 1e9; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<pair<int, int>> b(m); for (int i = 0; i < m; ++i) { cin >> b[i].first >> b[i].second; --b[i].first; --b[i].second; } int ans = *max_element(a.begin(), a.end()) - *min_element(a.begin(), a.end()); vector<int> res; for (int i = 0; i < n; ++i) { vector<int> add(n + 1); vector<int> cur; for (int j = 0; j < m; ++j) { if (!(b[j].first <= i && i <= b[j].second)) { cur.push_back(j); for (int k = b[j].first; k <= b[j].second; ++k) { --add[k]; } } } int mn = INF, mx = -INF; for (int j = 0; j < n; ++j) { mn = min(mn, a[j] + add[j]); mx = max(mx, a[j] + add[j]); } if (ans < mx - mn) { ans = mx - mn; res = cur; } } cout << ans << endl << res.size() << endl; shuffle(res.begin(), res.end(), rnd); for (auto it : res) cout << it + 1 << " "; cout << endl; return 0; }
1108
E2
Array and Segments (Hard version)
\textbf{The only difference between easy and hard versions is a number of elements in the array}. You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$. You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (\textbf{independently}). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$. You have to choose some subset of the given segments (\textbf{each segment can be chosen at most once}) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$ will be \textbf{maximum} possible. Note that \textbf{you can choose the empty set}. If there are multiple answers, you can print \textbf{any}. \textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
This tutorial is based on the previous problem (easy version) tutorial. At first, I want to say I know that this problem and this approach can be implemented in $O(m \log n)$ with segment tree. So, we iterate over all supposed maximums in the array and trying to apply all segments not covering our current element. How do we can calculate the answer for each element if this element is the supposed maximum? Let's divide all segments we apply into two parts: the first part consists of segments such that their right endpoints is less than the current position and the second part consists of segments such that their left endpoints is greater than the current position. Then let's independently calculate answers for the left and for the right parts and merge them to obtain the answer. I will consider only first part of the solution (first part of segments) because the second part is absolutely symmetric with it. Let's maintain the minimum value on prefix of the array (let it be $mn$ and initially it equals to $+\infty$), maintain the array $ansv$ of length $n$ (initially its values are $-\infty$ and $ansv_i$ means the answer if the $i$-th element of the array will be supposed maximum) and the array $add$ of length $n$, where $add_i$ will be the value for which we decrease the $i$-th element (in other words, the number of segments we apply to the $i$-th element). What do we do for the current position $i$? Firstly, let's update the answer for it with the value $a_i + add_i - mn$ (in other words, set $ansv_i := max(ansv_i, a_i + add_i - mn$)). Then let's apply all segments with right endpoints equals to the current position straight-forward and update the value $mn$ with each new value of covered elements. Just iterate over all positions $j$ of each segment ends in the current position, make $add_j := add_j - 1$ and set $mn := min(mn, a_j + add_j)$. And don't forget to update the value $mn$ with the value $a_i + add_i$ after all changes (because we need to update this value with each element not covered by segments too). So then let's do the same from right to left and then $ansv_i$ will mean the answer if the $i$-th element is the supposed maximum in the resulting array. Then we can find any position of the maximum in the array $ansv$ and apply all segments which don't cover this position. What is time complexity of the solution above? We iterate over all elements in the array, this is $O(n)$ and apply each segment in $O(n)$, so the final time complexity is $O(n + nm) = O(nm)$.
[ "data structures", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; mt19937 rnd(time(NULL)); const int INF = 1e9; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<pair<int, int>> b(m); vector<vector<int>> lf(n), rg(n); for (int i = 0; i < m; ++i) { cin >> b[i].first >> b[i].second; --b[i].first; --b[i].second; lf[b[i].second].push_back(b[i].first); rg[b[i].first].push_back(b[i].second); } vector<int> ansv(n, -INF); vector<int> add(n + 1 , 0); int mn = a[0]; for (int i = 0; i < n; ++i) { ansv[i] = max(ansv[i], a[i] - mn); for (auto l : lf[i]) { for (int j = l; j <= i; ++j) { --add[j]; mn = min(mn, a[j] + add[j]); } } mn = min(mn, a[i] + add[i]); } add = vector<int>(n + 1, 0); mn = a[n - 1]; for (int i = n - 1; i >= 0; --i) { ansv[i] = max(ansv[i], a[i] - mn); for (auto r : rg[i]) { for (int j = i; j <= r; ++j) { --add[j]; mn = min(mn, a[j] + add[j]); } } mn = min(mn, a[i] + add[i]); } int ans = *max_element(ansv.begin(), ansv.end()); vector<int> res; for (int i = 0; i < n; ++i) { if (ansv[i] == ans) { for (int j = 0; j < m; ++j) { if (!(b[j].first <= i && i <= b[j].second)) { res.push_back(j); } } break; } } cout << ans << endl << res.size() << endl; shuffle(res.begin(), res.end(), rnd); for (auto it : res) cout << it + 1 << " "; cout << endl; return 0; }
1108
F
MST Unification
You are given an undirected weighted \textbf{connected} graph with $n$ vertices and $m$ edges \textbf{without loops and multiple edges}. The $i$-th edge is $e_i = (u_i, v_i, w_i)$; the distance between vertices $u_i$ and $v_i$ along the edge $e_i$ is $w_i$ ($1 \le w_i$). The graph is \textbf{connected}, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph. A minimum spanning tree (MST) in case of \textbf{positive} weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges). You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $1$. You \textbf{can} increase the weight of each edge multiple (possibly, zero) times. Suppose that the initial MST cost is $k$. Your problem is to increase weights of some edges \textbf{with minimum possible number of operations} in such a way that the cost of MST in the obtained graph remains $k$, but MST is \textbf{unique} (it means that there is only one way to choose MST in the obtained graph). Your problem is to calculate the \textbf{minimum} number of operations required to do it.
The first (and the most straight-forward) approach is to construct MST with any suitable algorithm, build LCA with the maximum edge on a path with binary lifting technique and then we have to increase the answer for each edge $e_i = (u_i, v_i, w_i)$ such that $w_i$ equals to the maximum edge on a path between $u_i$ and $v_i$ in MST. The second (and the most pretty and easy to implement) solution is the improved Kruskal algorithm. Let's do Kruskal algorithm on the given edges. Sort them, and let's consider all edges of the same weight at once. They can be divided into two classes. The first class contains edges which connect nothing and the second class contains edges which can connect something. Let the number of edges of current weight be $k$, edges of the current weight of the first class be $k_{bad}$ and edges with of current weight of the second class be $k_{good}$. Okay, we can just skip the first class because it will never increase the answer. How to calculate useless edges of the second class? Let's try to merge all components connected with edges of the second class. Suppose we make $q$ merges. Then we have to increase weights of all remaining edges by one. So we add to the answer the value $k_{good} - q$ and go to the next weight. Why is this right? This is right because if the edge of the second class cannot connect anything because of the previously considered edges then the maximum on a path between endpoints of this edge equals to this edge weight. So we have to increase the weight of this edge by one. If we didn't do it we would be able to replace the edge connects these components with our edge. And it is obvious that this edge is totally useless with the weight increased by one. Time complexity is $O(m \log m)$ because of edges sorting.
[ "binary search", "dsu", "graphs", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; #define x first #define y second vector<int> p, rk; int getp(int v) { if (v == p[v]) return v; return p[v] = getp(p[v]); } bool merge(int v, int u) { u = getp(u); v = getp(v); if (u == v) return false; if (rk[u] < rk[v]) swap(u, v); rk[u] += rk[v]; p[v] = u; return true; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(0); int n, m; cin >> n >> m; p = vector<int>(n); iota(p.begin(), p.end(), 0); rk = vector<int>(n, 1); vector<pair<pair<int, int>, int>> e(m); for (int i = 0; i < m; ++i) { cin >> e[i].x.x >> e[i].x.y >> e[i].y; --e[i].x.x; --e[i].x.y; } sort(e.begin(), e.end(), [](pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) { return a.y < b.y; }); int ans = 0; for (int i = 0; i < m; ++i) { int j = i; while (j < m && e[i].y == e[j].y) { ++j; } int cnt = j - i; for (int k = i; k < j; ++k) { if (getp(e[k].x.x) == getp(e[k].x.y)) { --cnt; } } for (int k = i; k < j; ++k) { cnt -= merge(e[k].x.x, e[k].x.y); } ans += cnt; i = j - 1; } cout << ans << endl; return 0; }
1109
A
Sasha and a Bit of Relax
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an \textbf{even} number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation. It is time to continue solving the contest, so Sasha asked you to solve this task.
Notice, that if $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$ then $a_l \oplus a_{l+1} \oplus \ldots \oplus a_r = 0$ (it comes from the fact that for some integers $A$, $B$, $C$ if $A \oplus B = C$ then $A = B \oplus C$). Now we have another task. How many are there pairs $(l, r)$ that $r - l + 1$ is even and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_r = 0$. Precalculate array $pref_i = a_1 \oplus a_2 \oplus \ldots \oplus a_i$. Then $a_l \oplus a_{l+1} \oplus \ldots \oplus a_r = pref_r \oplus pref_{l-1}$. So if $pref_r \oplus pref_{l - 1} = 0$ then $pref_r = pref_{l - 1}$. So again we should solve another thask, which is equivalent to original one. How many are there pairs $(l, r)$ that $r - l + 1$ is even and $pref_r = pref_{l - 1}$. So to count the answer just have two arrays $cnt[0][x]$ to store elements from even positions and $cnt[1][x]$ for odd positions. Then iterate $i$ from $1$ to $n$ and add to the answer $cnt[i \mod 2][pref_i]$. After you processed $i$, increase $cnt[i \mod 2][pref_i]$ by $1$.
[ "dp", "implementation" ]
1,600
"#include <bits/stdc++.h>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nconst int maxn = (int)3e5 + 3;\nconst int maxa = (1 << 20) + 3;\n\n\nint n;\nint a[maxn];\nint cnt[2][maxa];\n\n\nint32_t main() {\n std::ios_base::sync_with_stdio(false);\n\n cin >> n;\n for(int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n cnt[1][0] = 1;\n int x = 0;\n int64_t res = 0;\n for(int i = 0; i < n; ++i) {\n x ^= a[i];\n res += cnt[i % 2][x];\n ++cnt[i % 2][x];\n\n }\n cout << res << endl;\n return 0;\n}\n"
1109
B
Sasha and One More Name
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not." And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $k$, so they got $k+1$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces \textbf{couldn't be turned over}, they could be shuffled. In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $3$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts. More formally, Sasha wants for the given \textbf{palindrome} $s$ find such minimum $k$, that you can cut this string into $k + 1$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $s$. It there is no answer, then print "Impossible" (without quotes).
Let's $s$ be the given string, $n$ - it's length. If $s$ consists of $n$ or $n - 1$ (when $n$ is odd) equal characters, then there is no way to get the answer. Otherwise, let's prove that the answer can be always reached in two cuttings. Let's the longest prefix of $s$, that consists of equal characters has the length equal to $len - 1$. Cut $pref = s[1 \ldots len]$ and $suff = s[n-len+1 \ldots n]$, and call the remaining piece as $mid$. Swap $pref$ and $suff$, then unite all three parts together. The central part ($mid$) will stay unchanged, $pref \neq reverse(pref)$ and $pref \neq suff$ then $pref + mid + suf \neq suf + mid + pref$. So now we can get the answer in two cuttings. Finally you must chech if it is possible to get the result by making just one cutting. As soon as one cutting is equal to some cyclic shift, then our task is to check if there is a cyclic shift which is a palindrome and not equal to $s$. It can be done by fixing each cyclic shift and checking each one separately. Complexity: $O(n^2)$
[ "constructive algorithms", "hashing", "strings" ]
1,800
"#include <bits/stdc++.h>\nusing namespace std;\n\nbool isPalindrome(const string& s) {\n for(int i = 0; i < s.length(); ++i) {\n if (s[i] != s[s.length() - i - 1]) \n return false;\n }\n return true;\n}\n\nbool solve1(string s) {\n string t = s;\n for(int i = 0; i < s.length(); ++i) {\n t = t.back() + t;\n t.pop_back();\n if (s != t && isPalindrome(t)) {\n return true;\n }\n }\n return false;\n}\n\nbool anyAnswer(const string& s) {\n int nt = 0;\n for(int i = 0; i < s.length(); ++i) {\n nt += s[i] != s[0];\n }\n return nt > 1;\n}\n\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr), cout.tie(nullptr);\n\n string s;\n cin >> s;\n if (anyAnswer(s)) {\n cout << (solve1(s) ? 1 : 2) << endl;\n } else {\n cout << \"Impossible\" << endl;\n }\n\n return 0;\n}\n"
1109
C
Sasha and a Patient Friend
Fedya and Sasha are friends, that's why Sasha knows everything about Fedya. Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let $v$ be the number of liters of Fedya's patience, and, as soon as $v$ becomes \textbf{equal} to $0$, the bowl will burst immediately. There is one tap in the bowl which pumps $s$ liters of patience per second. Notice that $s$ can be negative, in that case, the tap pumps out the patience. Sasha can do different things, so he is able to change the tap's speed. All actions that Sasha does can be represented as $q$ queries. There are three types of queries: - "1 t s"  — add a new event, means that starting from the $t$-th second the tap's speed will be equal to $s$. - "2 t"  — delete the event which happens at the $t$-th second. It is guaranteed that such event exists. - "3 l r v" — Sasha wonders: if you take all the events for which $l \le t \le r$ and simulate changes of Fedya's patience from the very beginning of the $l$-th second till the very beginning of the $r$-th second inclusive (the initial volume of patience, at the beginning of the $l$-th second, equals to $v$ liters) then when will be the moment when the bowl will burst. If that does not happen, then the answer will be $-1$. Since Sasha does not want to check what will happen when Fedya's patience ends, and he has already come up with the queries, he is asking you to help him and find the answer for each query of the $3$-rd type. It is guaranteed that at any moment of time, there won't be two events which happen at the same second.
Let's keep not deleted pairs ($t, s$) in a treap where $t$ will be the key of some node. Also we need some auxiliary variables. So each node in the treap will store that: $time$ - time of the event $speed$ - speed of the tap since second $time$ $tL$, $tR$ - the minimum and the maximum $time$ in the subtree of that node $speedR$ - the $speed$ of the event with maximum $time$ in the subtree of that node $res$ - the value of patience after processing all events from the subtree (we assume that the value before $tL$-th second is $0$) $mn$ - what is the minumum value of patience if we process all events from the subtree (also initial value is $0$) links to the left child and to the right child It turns out that this information is enough. Now to make treap work correctly it should be possible to merge two chilrens of some node. Let's look how to do it (suppose that this node has either left child ($LC$) or right child ($RC$)): $time$ doesn't change $speed$ doesn't change $tL = LC.tL$, $tR = RC.tR$, $speedR = RC.speedR$ It is easier to calculate $res$ and $mn$ simulatenously. Look at this block of code: mn = 0, res = 0 mn = min(mn, LC.mn) res += LC.res + LC.speedR * (time - LC.tR) mn = min(mn, res) res += speed * (RC.tL - time) mn = min(mn, res + RC.mn) res += RC.res mn = min(mn, res) It goes through all possible periods of time where $mn$ can be, and finds the best one, during this it calculates $res$. It goes through all possible periods of time where $mn$ can be, and finds the best one, during this it calculates $res$. If there is no left or right child then the calculation doen't change too much. So if you have combine function then you can do insert, delete, split, merge. You can answer queries of the $3$-rd type in the following way. Cut out the needed range from the treap. And go down the treap starting from the root while you can (you go to the left child, if the value of patience becomes equal to $0$ earlier than $time$, you can check that using the imformation stored in nodes, then check the right one if it is needed). So it is left to consider some extreme cases, which I leave you as and exercise, and that is all. The complexity is $O(q \cdot log(q))$. If you don't like treaps, you can actually use segment tree on pointers, or make coordinate compression and write a simple segment tree, the complexity will stay the same.
[ "binary search", "data structures", "implementation" ]
2,800
"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n//mt19937 gen(time(NULL));\nmt19937 gen(200);\n\nstruct node {\n pair<int, int> f, s;\n node *le, *ri;\n ll mn, res;\n int tl, tr;\n node() {\n mn = 228;\n }\n node(int l, int r) {\n tl = l; tr = r;\n mn = 228;\n if (l == r) return;\n le = new node(l, (l+r)/2);\n ri = new node((l+r)/2+1, r);\n }\n node (node* a, node* b) {\n le = a; ri = b;\n tl = le->tl; tr = ri->tr;\n if (le->mn == 228) {\n res = ri->res;\n mn = ri->mn;\n f = ri->f;\n s = ri->s;\n return;\n }\n if (ri->mn == 228) {\n res = le->res;\n mn = le->mn;\n f = le->f;\n s = le->s;\n return;\n }\n f = le->f; s = ri->s;\n ll del = 1ll*le->s.second*(ri->f.first-le->s.first);\n res = le->res+del+ri->res;\n mn = min(le->mn, le->res+del);\n mn = min(mn, ri->mn+le->res+del);\n }\n void combine() {\n node tmp(le, ri);\n *this = tmp;\n }\n void update(int id, int time, int speed) {\n if (tl == tr) {\n mn = res = 0;\n f.first = s.first = time;\n f.second = s.second = speed;\n return;\n }\n if (id <= (tl+tr)/2)\n le->update(id, time, speed);\n else\n ri->update(id, time, speed);\n combine();\n }\n void del(int id) {\n if (tl == tr) {\n mn = 228;\n return;\n }\n if (id <= (tl+tr)/2)\n le->del(id);\n else\n ri->del(id);\n combine();\n }\n node* get_seg(int l, int r) {\n if (tr < l || r < tl) return new node();\n if (l <= tl && tr <= r) {\n return this;;\n }\n return new node(le->get_seg(l, r), ri->get_seg(l, r));\n }\n long double simulate(int r, ll v) {\n if (mn == 228) return -1;\n if (v+mn > 0 && v+res+1ll*s.second*(r-s.first) > 0) return -1;\n if (f == s) return s.first-(long double)v/s.second;\n if (le->mn == 228) return ri->simulate(r, v);\n long double to = le->simulate(le->s.first, v);\n if (to != -1) return to;\n v += le->res;\n ll del = 1ll*le->s.second*((ri->mn==228?r:ri->f.first)-le->s.first);\n if (v+del <= 0) return le->s.first-(long double)v/le->s.second;\n v += del;\n return ri->simulate(r, v);\n }\n long double query(int l, int r, int rr, ll v) {\n node* t = get_seg(l, r);\n return t->simulate(rr, v);\n }\n};\n\nstruct query{\n int time, speed, start;\n int l, r, type;\n query() {}\n};\n\nvector <int> pos;\nvector <query> q;\n\nint main() {\n ios_base::sync_with_stdio(false);\n #ifdef LOCAL\n freopen(\"input.txt\", \"r\", stdin);\n freopen(\"output.txt\", \"w\", stdout);\n #endif // LOCAL\n cout.precision(7);\n int qq; cin >> qq;\n q.resize(qq);\n for (int i = 0; i < qq; ++i) {\n cin >> q[i].type;\n if (q[i].type == 1) {\n cin >> q[i].time >> q[i].speed;\n pos.push_back(q[i].time);\n }\n if (q[i].type == 2) {\n cin >> q[i].time;\n }\n if (q[i].type == 3) {\n cin >> q[i].l >> q[i].r >> q[i].start;\n }\n }\n sort(pos.begin(), pos.end());\n pos.erase(unique(pos.begin(), pos.end()), pos.end());\n if (pos.size() == 0) pos.push_back(0);\n node* t = new node(0, pos.size()-1);\n for (int i = 0; i < qq; ++i) {\n if (q[i].type == 1) {\n int id = lower_bound(pos.begin(), pos.end(), q[i].time)-pos.begin();\n t->update(id, q[i].time, q[i].speed);\n }\n if (q[i].type == 2) {\n int id = lower_bound(pos.begin(), pos.end(), q[i].time)-pos.begin();\n t->del(id);\n }\n if (q[i].type == 3) {\n int l = lower_bound(pos.begin(), pos.end(), q[i].l)-pos.begin();\n int r = --upper_bound(pos.begin(), pos.end(), q[i].r)-pos.begin();\n if (q[i].start == 0)\n cout << fixed << q[i].l << '\\n';\n else\n cout << fixed << t->query(l, r, q[i].r, q[i].start) << '\\n';\n }\n }\n return 0;\n}\n"
1109
D
Sasha and Interesting Fact from Graph Theory
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees. In this task, a tree is a weighted connected graph, consisting of $n$ vertices and $n-1$ edges, and weights of edges are integers from $1$ to $m$. Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices — vertices with numbers $a$ and $b$, and counts the distance between them. The distance between two vertices $x$ and $y$ is the sum of weights of edges on the simple path from $x$ to $y$. If the distance between two vertices $a$ and $b$ is \textbf{equal} to $m$, then the tree is beautiful. Sasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's \textbf{weight matters}. Kefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo $10^9 + 7$.
Let's fix $edges$ - the number of edges on the path between $a$ and $b$. Then on this path there are $edges-1$ vertices between $a$ and $b$, and they can be choosen in $A(n - 2, edges - 1)$ ways. The amount of ways to place numbers on edges in such a way, that their sum is equal to $m$, is $\binom{m-1}{edges-1}$ (stars and bars method). If an edge doesn't belong to out path, then doesn't metter what number is written on it, so we can multiply answer by $m^{n-edges-1}$. Now, we want to form a forest from remaining $n-edges-1$ vertices and to hang it to any of $edges + 1$ vertexes from our path. According to one of generalizations of Cayley's formula, number of forsests of $x$ vertices, where vertices $1,2, \ldots, y$ belong to different trees is $f(x, y) = y \cdot x^{x - y - 1}$. So for fixed $edges$ we got the formula $trees(edges) = A(n - 2, edges - 1) \cdot f(n, edges + 1) \cdot \binom{m - 1}{edges - 1} \cdot m^{n - edges - 1}$ Complexity is $O((n + m) \cdot log(mod))$ or $O(n + m)$, in case you precompute all powers, factorials and thier inverse in linear time.
[ "brute force", "combinatorics", "dp", "math", "trees" ]
2,400
"import java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) {\n InputReader in = new InputReader(System.in);\n OutputWriter out = new OutputWriter(System.out);\n TaskC solver = new TaskC(in, out);\n solver.solve();\n out.close();\n }\n\n static class TaskC {\n\n static int n;\n static int m;\n\n static int[] inv;\n static int[] fact;\n static int[] invfact;\n \n static int[] powN;\n static int[] powM;\n\n InputReader in;\n OutputWriter out;\n\n TaskC(InputReader in, OutputWriter out) {\n this.in = in;\n this.out = out;\n }\n \n private void solve() {\n n = in.readInt();\n m = in.readInt();\n precalc();\n int ans = 0;\n int choosePath = 1;\n for(int k = 1; k < n; ++k) {\n if (k > m) break;\n int cur = MathUtil.mul(choosePath, cayley(n, k + 1));\n cur = MathUtil.mul(cur, binom(m - 1, k - 1));\n cur = MathUtil.mul(cur, powM[n - k - 1]);\n choosePath = MathUtil.mul(choosePath, n - k - 1);\n ans = MathUtil.sum(ans, cur);\n }\n out.print(ans);\n }\n\n private int cayley(int n, int k) {\n if (n - k - 1 < 0) {\n return MathUtil.mul(k, MathUtil.binPow(n, MathUtil.mod - 2));\n }\n return MathUtil.mul(k, powN[n - k - 1]);\n }\n\n private int binom(int n, int k) {\n return MathUtil.mul(fact[n], MathUtil.mul(invfact[k], invfact[n - k]));\n }\n\n private void precalc() {\n powN = new int[n + 1];\n powM = new int[n + 1];\n powN[0] = 1;\n powM[0] = 1;\n for(int i = 1; i <= n; ++i) {\n powN[i] = MathUtil.mul(powN[i - 1], n);\n powM[i] = MathUtil.mul(powM[i - 1], m);\n }\n \n inv = new int[m + 1];\n fact = new int[m + 1];\n invfact = new int[m + 1];\n inv[0] = inv[1] = 1;\n fact[0] = fact[1] = 1;\n invfact[0] = invfact[1] = 1;\n for(int i = 2; i <= m; ++i) {\n inv[i] = MathUtil.mul(inv[MathUtil.mod % i], MathUtil.mod - MathUtil.mod / i);\n fact[i] = MathUtil.mul(fact[i - 1], i);\n invfact[i] = MathUtil.mul(invfact[i - 1], inv[i]);\n }\n }\n }\n static class MathUtil {\n private static final int mod = 1_000_000_007;\n\n static int binPow(int a, int n) {\n int result = 1;\n while (n > 0) {\n if (n % 2 == 1) {\n result = mul(result, a);\n }\n n /= 2;\n a = mul(a, a);\n }\n return result;\n }\n \n static int mul(int a, int b) {\n return (int)((long)a * b % mod);\n }\n\n static int sum(int a, int b) {\n int result = a + b;\n if (result >= mod) result -= mod;\n return result;\n }\n\n }\n\n static class OutputWriter {\n private final PrintWriter writer;\n\n public OutputWriter(OutputStream outputStream) {\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n }\n\n public OutputWriter(Writer writer) {\n this.writer = new PrintWriter(writer);\n }\n\n public void print(Object... objects) {\n for (int i = 0; i < objects.length; i++) {\n if (i != 0) {\n writer.print(' ');\n }\n writer.print(objects[i]);\n }\n writer.println();\n }\n\n public void close() {\n writer.close();\n }\n\n }\n\n static class InputReader {\n private InputStream stream;\n private byte[] buf = new byte[1024];\n private int curChar;\n private int numChars;\n private InputReader.SpaceCharFilter filter;\n\n public InputReader(InputStream stream) {\n this.stream = stream;\n }\n\n public int read() {\n if (numChars == -1) {\n throw new InputMismatchException();\n }\n if (curChar >= numChars) {\n curChar = 0;\n try {\n numChars = stream.read(buf);\n } catch (IOException e) {\n throw new InputMismatchException();\n }\n if (numChars <= 0) {\n return -1;\n }\n }\n return buf[curChar++];\n }\n\n public int readInt() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n int sgn = 1;\n if (c == '-') {\n sgn = -1;\n c = read();\n }\n int res = 0;\n do {\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n res *= 10;\n res += c - '0';\n c = read();\n } while (!isSpaceChar(c));\n return res * sgn;\n }\n\n public boolean isSpaceChar(int c) {\n if (filter != null) {\n return filter.isSpaceChar(c);\n }\n return isWhitespace(c);\n }\n\n public static boolean isWhitespace(int c) {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n\n public double readDouble() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n int sgn = 1;\n if (c == '-') {\n sgn = -1;\n c = read();\n }\n double res = 0;\n while (!isSpaceChar(c) && c != '.') {\n if (c == 'e' || c == 'E') {\n return res * Math.pow(10, readInt());\n }\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n res *= 10;\n res += c - '0';\n c = read();\n }\n if (c == '.') {\n c = read();\n double m = 1;\n while (!isSpaceChar(c)) {\n if (c == 'e' || c == 'E') {\n return res * Math.pow(10, readInt());\n }\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n m /= 10;\n res += (c - '0') * m;\n c = read();\n }\n }\n return res * sgn;\n }\n\n public interface SpaceCharFilter {\n public boolean isSpaceChar(int ch);\n }\n\n }\n}\n"
1109
E
Sasha and a Very Easy Test
Egor likes math, and not so long ago he got the highest degree of recognition in the math community — Egor became a red mathematician. In this regard, Sasha decided to congratulate Egor and give him a math test as a present. This test contains an array $a$ of integers of length $n$ and exactly $q$ queries. Queries were of three types: - "1 l r x" — multiply each number on the range from $l$ to $r$ by $x$. - "2 p x" — divide the number at the position $p$ by $x$ (divisibility guaranteed). - "3 l r" — find the sum of all elements on the range from $l$ to $r$. The sum can be big, so Sasha asked Egor to calculate the sum modulo some integer $mod$. But since Egor is a red mathematician, he doesn't have enough time to solve such easy tasks, at the same time he doesn't want to anger Sasha, that's why he asked you to help and to find answers for all queries of the $3$-rd type.
The main idea: Let's factorize $x$ in every query of the $1$-st and the $2$-nd type. Now $x$ can be presented as $p_1^{\alpha_1} \cdot p_2^{\alpha_2} \cdot \ldots \cdot p_k^{\alpha_k}$, where $p_i$ is a prime divisor of $x$. Then let's split $p_i$ into two sets: those which are divisors of $mod$ and those which are not and process them in different ways. It's easy to see that all primes from the second set are coprime with $mod$. According to Euler's theorem for each coprime with $mod$ there is a modular multiplicative inverse. So you can just build a segment tree with lazy propagation to multiply and divide modulo $mod$. What to do with primes from the first set? Notice, that there are at most $9$ (because $2 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 13 \cdot 17 \cdot 19 \cdot 23 \cdot 29 > 10^9$; let's call such function $DiffPrimes(x)$ to use later) different prime divisors of $mod$. So let's maintain a vector in each node of segment tree, which contains pairs ($p, \alpha$), what means that $\alpha$ is such power of $p$, that each number from the corresponding range should be multiplied by $p^{\alpha}$. So also use lazy propogation to multiply and divide by those primes. Now how to answer queries of the $3$-rd type? Just maintain in each node some auxiliary numbers: sumUnder - the sum from childs mulSecond - equal to the product of primes from the second set, means that each number from the range should be multiplied by mulSecond powersFirst - vector, which contains pairs ($p, \alpha$), also means that each mumber from the range should me multiplied by $p^{\alpha}$ And it is obvious that the sum on the range which is controled by some node is $sumUnder \cdot mulSecond \cdot p_i^{\alpha_i}$. How to write combine function for two nodes from segment tree and push to push modification to children I leave you as an exercise, there is nothing diffcult here. Now combine ideas from the above, and got the complexity $O((n + q) \cdot log_2(n) \cdot log_2(q) \cdot DiffPrimes(10^5))$ (because $x$ in queries doesn't exceed $10^5$). To remove a $log_2(q)$ we can precompute all powers of each prime divisors of $mod$, so we will have no need to use binary exponentiation algorithm in segment tree. But here you have to be careful, because since we have $q$ queries and each of them can increase power of prime by $log_2(10^5)$ in the worst case, so maximal power of prime can be $q \cdot log_2(10^5)$. The complexity is $O((n + q) \cdot log_2(n) \cdot DiffPrimes(10^5))$.
[ "data structures", "number theory" ]
2,700
"#include <bits/stdc++.h>\nusing namespace std;\n\nint phi(int n) {\n\tint res = n;\n\tfor (int i = 2; i*i <= n; ++i)\n\t\tif (n % i == 0) {\n\t\t\twhile (n % i == 0)\n\t\t\t\tn /= i;\n\t\t\tres -= res / i;\n\t\t}\n\tif (n > 1)\n\t\tres -= res / n;\n\treturn res;\n}\n\nvector <int> factorize(int x) {\n vector <int> res;\n for (int i = 2; i*i <= x; ++i) {\n if (x%i == 0) {\n res.push_back(i);\n }\n while (x%i == 0) {\n x /= i;\n }\n }\n if (x > 1) res.push_back(x);\n return res;\n}\n\n#define fmod i_love_pelmeny\n\nint mod;\nvector <int> fmod;\nconst int N = (int)2e5+10;\nvector <pair <int, int> > f[N];\nvector <int> pw[25];\n//vector <int> realpw[25];\nint goodpart[N];\nint inv[N];\nint n, a[N];\nint id[N];\n\nint binpow(int a, int b) {\n int res = 1;\n while (b > 0) {\n if (b&1) res = 1ll*res*a%mod;\n b >>= 1;\n a = 1ll*a*a%mod;\n }\n return res;\n}\n\nstruct node {\n vector <int> degrees;\n int tl, tr;\n int sum, here;\n bool flag = false;\n node *le, *ri;\n\n int calc_real_sum() {\n// if (!flag) return sum;\n int res = here;\n for (int i = 0; i < degrees.size(); ++i) {\n res = 1ll*res*pw[i][degrees[i]]%mod;\n }\n return res;\n }\n void push_down() {\n if (!flag) return;\n int i = 0;\n for (auto & x : degrees) {\n le->degrees[i] += x;\n ri->degrees[i] += x;\n\n le->sum = 1ll*le->sum*pw[i][x]%mod;\n ri->sum = 1ll*ri->sum*pw[i][x]%mod;\n\n x = 0;\n ++i;\n }\n le->here = 1ll*le->here*here%mod;\n le->sum = 1ll*le->sum*here%mod;\n ri->here = 1ll*ri->here*here%mod;\n ri->sum = 1ll*ri->sum*here%mod;\n here = 1;\n flag = false;\n le->flag = ri->flag = true;\n }\n void combine() {\n sum = (le->sum+ri->sum)%mod;\n }\n\n void multiply(int l, int r, int x) {\n if (r < tl || tr < l) return;\n if (l <= tl && tr <= r) {\n flag = true;\n for (auto p : f[x]) {\n degrees[id[p.first]-1] += p.second;\n }\n here = 1ll*here*goodpart[x]%mod;\n sum = 1ll*sum*x%mod;\n return;\n }\n push_down();\n le->multiply(l, r, x);\n ri->multiply(l, r, x);\n combine();\n }\n void divide(int pos, int x) {\n if (tl == tr) {\n for (auto p : f[x]) {\n degrees[id[p.first]-1] -= p.second;\n }\n here = 1ll*here*inv[goodpart[x]]%mod;\n sum = calc_real_sum();\n return;\n }\n push_down();\n if (pos <= (tl+tr)/2) {\n le->divide(pos, x);\n } else {\n ri->divide(pos, x);\n }\n combine();\n }\n int get(int l, int r) {\n if (r < tl || tr < l) {\n return 0;\n }\n if (l <= tl && tr <= r) {\n return sum;\n }\n push_down();\n return (le->get(l, r)+ri->get(l, r))%mod;\n }\n node(int l, int r, int dsize) {\n tl = l;\n tr = r;\n sum = 1;\n here = 1;\n degrees.resize(dsize);\n if (l == r) {\n multiply(l, r, a[l]);\n return;\n }\n le = new node(l, (l+r)/2, dsize);\n ri = new node((l+r)/2+1, r, dsize);\n combine();\n }\n};\n\nstruct query {\n int x, l, r, t;\n query() {}\n};\n\nnode *t;\nvector <query> q;\n\nvoid precalc_base() {\n fmod = factorize(mod);\n if (fmod.back() >= N) fmod.pop_back();\n vector <int> deg(N);\n for (int i = 0; i < fmod.size(); ++i) {\n id[fmod[i]] = i+1;\n for (int j = fmod[i]; j < N; j += fmod[i]) {\n if ((j/fmod[i])%fmod[i]) {\n deg[j] = 1;\n } else {\n deg[j] = deg[j/fmod[i]]+1;\n }\n f[j].emplace_back(fmod[i], deg[j]);\n }\n }\n\n for (int i = 1; i < N; ++i) {\n goodpart[i] = i;\n goodpart[i] = goodpart[i/__gcd(i, mod)];\n }\n}\nvoid precalc_inverse() {\n vector <int> mn(N);\n for (int i = 2; i < N; ++i) {\n if (mn[i]) continue;\n for (int j = i+i; j < N; j += i) {\n if (!mn[j]) mn[j] = i;\n }\n }\n\n int mod_phi = phi(mod);\n inv[1] = 1;\n for (int i = 2; i < N; ++i) {\n if (!mn[i]) inv[i] = binpow(i, mod_phi-1);\n else inv[i] = 1ll*inv[i/mn[i]]*inv[mn[i]]%mod;\n }\n}\nvoid precalc_powers() {\n vector <int> max_entry(fmod.size());\n for (int i = 1; i <= n; ++i) {\n for (auto p : f[a[i]]) {\n max_entry[id[p.first]-1] += p.second;\n }\n }\n\n for (const auto& w : q) {\n if (w.t != 1) continue;\n for (auto p : f[w.x]) {\n max_entry[id[p.first]-1] += p.second;\n }\n }\n\n for (int i = 0; i < fmod.size(); ++i) {\n pw[i].resize(max_entry[i]+1);\n pw[i][0] = 1;\n for (int j = 1; j < pw[i].size(); ++j) {\n pw[i][j] = 1ll*pw[i][j-1]*fmod[i]%mod;\n }\n }\n\n}\nvoid precalc() {\n precalc_base();\n precalc_inverse();\n precalc_powers();\n t = new node(1, n, fmod.size());\n cerr << 1.0*clock()/CLOCKS_PER_SEC << endl;\n}\n\nint main() {\n// ios_base::sync_with_stdio(0);\n #ifdef LOCAL\n freopen(\"input.txt\", \"r\", stdin);\n freopen(\"output.txt\", \"w\", stdout);\n #endif // LOCAL\n scanf(\"%d%d\", &n, &mod);\n for (int i = 1; i <= n; ++i) {\n scanf(\"%d\", &a[i]);\n }\n int m; scanf(\"%d\", &m);\n q.resize(m);\n for (int i = 0; i < m; ++i) {\n scanf(\"%d\", &q[i].t);\n scanf(\"%d\", &q[i].l);\n if (q[i].t != 2)\n scanf(\"%d\", &q[i].r);\n if (q[i].t != 3)\n scanf(\"%d\", &q[i].x);\n }\n precalc();\n for (const auto& p : q) {\n if (p.t == 1) {\n t->multiply(p.l, p.r, p.x);\n }\n if (p.t == 2) {\n t->divide(p.l, p.x);\n }\n if (p.t == 3) {\n printf(\"%d\\n\", t->get(p.l, p.r));\n }\n }\n\n}\n"
1109
F
Sasha and Algorithm of Silence's Sounds
One fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Let's divide the park into $1 \times 1$ meter squares and call them cells, and numerate rows from $1$ to $n$ from up to down, and columns from $1$ to $m$ from left to right. And now, every cell can be described with a pair of two integers $(x, y)$, where $x$ — the number of the row, and $y$ — the number of the column. Sasha knows that the level of silence in the cell $(i, j)$ equals to $f_{i,j}$, and all $f_{i,j}$ form a permutation of numbers from $1$ to $n \cdot m$. Sasha decided to count, how many are there pleasant segments of silence? Let's take some segment $[l \ldots r]$. Denote $S$ as the set of cells $(i, j)$ that $l \le f_{i,j} \le r$. Then, the segment of silence $[l \ldots r]$ is pleasant if there is only \textbf{one simple} path between every pair of cells from $S$ (path can't contain cells, which are not in $S$). In other words, set $S$ should look like a tree on a plain. Sasha has done this task pretty quickly, and called the algorithm — "algorithm of silence's sounds". Time passed, and the only thing left from the algorithm is a legend. To prove the truthfulness of this story, you have to help Sasha and to find the number of \textbf{different} pleasant segments of silence. Two segments $[l_1 \ldots r_1]$, $[l_2 \ldots r_2]$ are different, if $l_1 \neq l_2$ or $r_1 \neq r_2$ or both at the same time.
A range $[l \ldots r]$ - a tree, if the graph formated by it doen't have any cycle and there is only one connected component in this graph. Let's $t_r$ be such minimal position, that $[t_r \ldots r]$ doen't contain cycles (forest). It is obvous that $t_r \leq t_{r+1}$. Suppose for each $r$ we find $t_r$. Then the task now is to count the number of such $t_r \leq l \leq r$ that graph formated by the range $[l \ldots r]$ consists of one connected component. How to find $t_r$ for each $r$. Let's move two pointers: $t_r$ and $r$. For each moment we store a graph formated by that range. If you add $1$ to one of the pointers then you should add/delete up to $4$ edges to the graph. Before adding an edge check whether two verticies are in different components (not to form a cycle), and if they are in one component, then it is needed to delete some edges - move the first pointer. So now we need some structure that can process $3$ types of queries online: add an edge, delete an edge, check if two verticies are in one connected component. As long as the graph will never have a cycle, so it is possible to answer queries using link-cut tree ($O(log(n \cdot m))$ for one query). It is left to count the number of suitable $l$ ($t_r \leq l \leq r$) for each $r$. Let's iterate $r$ from $1$ to $n \cdot m$ and maintain $cmp_i$ - the number of connected components for $[i \ldots r]$. Then for a fixed $r$ you should add to the answer the number of such $i$ that $t_r \leq i \leq r$ and $cmp_i = 1$. What is going on when we move $r$ and add some edge at that moment. Let's that edge be $(x, r+1)$ and $t_r \leq x$ (if $x < t_r$ then you can skip this edge). For $i$, for which $x \lneq i \leq r$, $cmp_i$ won't change after you add an edge, but for $t_r \leq i \leq x$ two trees merge in one - $cmp_i$ decreases by $1$. Let's have a segtree to store $cmp_i$, then decreasing by $1$ is equivalent to adding $-1$ on a range, and the number of $1$ on a range is the number of minimums. All such queries can be done in $O(log(n \cdot m))$. The total complexity is $O(n \cdot m \cdot log(n \cdot m))$.
[ "data structures", "trees" ]
3,200
"import java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) {\n InputReader in = new InputReader(System.in);\n OutputWriter out = new OutputWriter(System.out);\n TaskD solver = new TaskD(in, out);\n solver.solve();\n out.close();\n }\n\n static class TaskD {\n static private final int[] dx = {1, -1, 0, 0};\n static private final int[] dy = {0, 0, 1, -1};\n\n static int n, m;\n static int total;\n\n static int[][] f;\n static int[] posX;\n static int[] posY;\n static int[] leftBound;\n\n List<Integer>[] edges;\n LinkCutTree lct;\n InputReader in;\n OutputWriter out;\n\n TaskD(InputReader in, OutputWriter out) {\n this.in = in;\n this.out = out;\n }\n\n private void solve() {\n n = in.readInt();\n m = in.readInt();\n total = n * m;\n f = new int[n][m];\n posX = new int[total];\n posY = new int[total];\n for(int i = 0; i < n; ++i) {\n for(int j = 0; j < m; ++j) {\n f[i][j] = in.readInt() - 1;\n posX[f[i][j]] = i;\n posY[f[i][j]] = j;\n }\n }\n edges = new ArrayList[total];\n leftBound = new int[total];\n lct = new LinkCutTree(total);\n for(int i = 0; i < total; ++i) {\n edges[i] = new ArrayList<>();\n }\n for(int l = 0, r = 0; r < total; ++r) {\n l = addCell(l, r);\n leftBound[r] = l;\n }\n long ans = 0;\n SegmentTree t = new SegmentTree(total + 4);\n for(int r = 0; r < total; ++r) {\n int x = posX[r];\n int y = posY[r];\n List<Integer> seg = new ArrayList<>();\n for(int i = 0; i < 4; ++i) {\n int px = x + dx[i];\n int py = y + dy[i];\n if (px < 0 || px >= n) continue;\n if (py < 0 || py >= m) continue;\n int to = f[px][py];\n if (to > r) continue;\n seg.add(to);\n }\n seg.add(-1);\n seg.add(r);\n Collections.sort(seg);\n for(int i = seg.size() - 1, comp = 1; i > 0; --i) {\n if (seg.get(i - 1) + 1 > seg.get(i)) {\n --comp;\n continue;\n }\n t.inc(seg.get(i - 1) + 1, seg.get(i) + 1, comp);\n --comp;\n }\n ans += t.query(leftBound[r], r + 1);\n }\n out.print(ans);\n }\n\n private int addCell(int l, int r) {\n int x = posX[r];\n int y = posY[r];\n for(int i = 0; i < 4; ++i) {\n int px = x + dx[i];\n int py = y + dy[i];\n if (px < 0 || px >= n) continue;\n if (py < 0 || py >= m) continue;\n int to = f[px][py];\n while (l <= to && to <= r) {\n if (lct.link(to, r)) {\n edges[to].add(r);\n break;\n }\n removeCell(l);\n ++l;\n }\n }\n return l;\n }\n\n private void removeCell(int c) {\n for(int to : edges[c]) {\n lct.cut(c, to);\n }\n edges[c].clear();\n }\n }\n\n static class SegmentTree {\n int size;\n int height;\n int[] t;\n int[] cnt;\n int[] push;\n\n SegmentTree(int n) {\n this.size = n;\n this.height = 0;\n int temp = n;\n while (temp > 0) {\n temp >>= 1;\n ++this.height;\n }\n t = new int[n << 1];\n cnt = new int[n << 1];\n push = new int[n];\n for(int i = 0; i < n; ++i) {\n cnt[i + n] = 1;\n }\n for(int i = n - 1; i >= 0; --i) {\n cnt[i] = cnt[i << 1] + cnt[i << 1 | 1];\n }\n }\n\n private void apply(int p, int value) {\n t[p] += value;\n if (p < size) push[p] += value;\n }\n\n private void recalc(int p) {\n while (p > 1) {\n p >>= 1;\n t[p] = Math.min(t[p << 1], t[p << 1 | 1]) + push[p];\n cnt[p] = (t[p] == t[p << 1] + push[p] ? cnt[p << 1] : 0)\n + (t[p] == t[p << 1 | 1] + push[p] ? cnt[p << 1 | 1] : 0);\n }\n }\n\n private void push(int p) {\n for (int s = height; s > 0; s--) {\n int i = p >> s;\n if (push[i] != 0) {\n apply(i << 1, push[i]);\n apply(i << 1 | 1, push[i]);\n push[i] = 0;\n }\n }\n }\n\n private void inc(int l, int r, int value) {\n l += size;\n r += size;\n int l0 = l;\n int r0 = r;\n for (; l < r; l >>= 1, r >>= 1) {\n if ((l & 1) != 0) apply(l++, value);\n if ((r & 1) != 0) apply(--r, value);\n }\n recalc(l0);\n recalc(r0 - 1);\n }\n\n private int query(int l, int r) {\n l += size;\n r += size;\n push(l);\n push(r - 1);\n int min = Integer.MAX_VALUE;\n int minCount = 0;\n for (; l < r; l >>= 1, r >>= 1) {\n if ((l & 1) != 0) {\n if (min > t[l]) {\n min = t[l];\n minCount = cnt[l];\n } else if (min == t[l]) {\n minCount += cnt[l];\n }\n ++l;\n }\n if ((r & 1) != 0) {\n --r;\n if (min > t[r]) {\n min = t[r];\n minCount = cnt[r];\n } else if (min == t[r]) {\n minCount += cnt[r];\n }\n }\n }\n return minCount;\n }\n }\n\n static class LinkCutTree {\n\n private static class Node {\n Node left;\n Node right;\n Node parent;\n boolean revert;\n\n boolean isRoot() {\n return parent == null || (parent.left != this && parent.right != this);\n }\n\n void push() {\n if (revert) {\n revert = false;\n Node t = left;\n left = right;\n right = t;\n if (left != null) left.revert = !left.revert;\n if (right != null) right.revert = !right.revert;\n }\n }\n }\n\n static int size;\n Node[] nodes;\n\n LinkCutTree(int n) {\n LinkCutTree.size = n;\n nodes = new Node[n];\n for(int i = 0; i < n; ++i) {\n nodes[i] = new Node();\n }\n }\n\n private boolean link(int x, int y) {\n return link(nodes[x], nodes[y]);\n }\n\n private void cut(int x, int y) {\n cut(nodes[x], nodes[y]);\n }\n\n private static boolean link(Node x, Node y) {\n if (connected(x, y))\n return false;\n makeRoot(x);\n x.parent = y;\n return true;\n }\n\n private static void cut(Node x, Node y) {\n makeRoot(x);\n expose(y);\n if (y.right != x || x.left != null || x.right != null) {\n throw new RuntimeException(\"error: no edge (x,y)\");\n }\n y.right.parent = null;\n y.right = null;\n }\n\n static void connect(Node ch, Node p, Boolean isLeftChild) {\n if (ch != null)\n ch.parent = p;\n if (isLeftChild != null) {\n if (isLeftChild)\n p.left = ch;\n else\n p.right = ch;\n }\n }\n\n static void rotate(Node x) {\n Node p = x.parent;\n Node g = p.parent;\n boolean isRootP = p.isRoot();\n boolean leftChildX = (x == p.left);\n connect(leftChildX ? x.right : x.left, p, leftChildX);\n connect(p, x, !leftChildX);\n connect(x, g, !isRootP ? p == g.left : null);\n }\n\n static void splay(Node x) {\n while (!x.isRoot()) {\n Node p = x.parent;\n Node g = p.parent;\n if (!p.isRoot())\n g.push();\n p.push();\n x.push();\n if (!p.isRoot())\n rotate((x == p.left) == (p == g.left) ? p/*zig-zig*/ : x/*zig-zag*/);\n rotate(x);\n }\n x.push();\n }\n\n // makes node x the root of the virtual tree, and also x becomes the leftmost node in its splay tree\n static Node expose(Node x) {\n Node last = null;\n for (Node y = x; y != null; y = y.parent) {\n splay(y);\n y.left = last;\n last = y;\n }\n splay(x);\n return last;\n }\n\n private static void makeRoot(Node x) {\n expose(x);\n x.revert = !x.revert;\n }\n\n private static boolean connected(Node x, Node y) {\n if (x == y)\n return true;\n expose(x);\n expose(y);\n return x.parent != null;\n }\n }\n\n static class OutputWriter {\n private final PrintWriter writer;\n\n public OutputWriter(OutputStream outputStream) {\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n }\n\n public OutputWriter(Writer writer) {\n this.writer = new PrintWriter(writer);\n }\n\n public void print(Object... objects) {\n for (int i = 0; i < objects.length; i++) {\n if (i != 0) {\n writer.print(' ');\n }\n writer.print(objects[i]);\n }\n writer.println();\n }\n\n public void close() {\n writer.close();\n }\n\n }\n\n static class InputReader {\n private InputStream stream;\n private byte[] buf = new byte[1024];\n private int curChar;\n private int numChars;\n private InputReader.SpaceCharFilter filter;\n\n public InputReader(InputStream stream) {\n this.stream = stream;\n }\n\n public int read() {\n if (numChars == -1) {\n throw new InputMismatchException();\n }\n if (curChar >= numChars) {\n curChar = 0;\n try {\n numChars = stream.read(buf);\n } catch (IOException e) {\n throw new InputMismatchException();\n }\n if (numChars <= 0) {\n return -1;\n }\n }\n return buf[curChar++];\n }\n\n public int readInt() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n int sgn = 1;\n if (c == '-') {\n sgn = -1;\n c = read();\n }\n int res = 0;\n do {\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n res *= 10;\n res += c - '0';\n c = read();\n } while (!isSpaceChar(c));\n return res * sgn;\n }\n\n public boolean isSpaceChar(int c) {\n if (filter != null) {\n return filter.isSpaceChar(c);\n }\n return isWhitespace(c);\n }\n\n public static boolean isWhitespace(int c) {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n\n public double readDouble() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n int sgn = 1;\n if (c == '-') {\n sgn = -1;\n c = read();\n }\n double res = 0;\n while (!isSpaceChar(c) && c != '.') {\n if (c == 'e' || c == 'E') {\n return res * Math.pow(10, readInt());\n }\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n res *= 10;\n res += c - '0';\n c = read();\n }\n if (c == '.') {\n c = read();\n double m = 1;\n while (!isSpaceChar(c)) {\n if (c == 'e' || c == 'E') {\n return res * Math.pow(10, readInt());\n }\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n m /= 10;\n res += (c - '0') * m;\n c = read();\n }\n }\n return res * sgn;\n }\n\n public interface SpaceCharFilter {\n public boolean isSpaceChar(int ch);\n }\n\n }\n}"
1110
A
Parity
You are given an integer $n$ ($n \ge 0$) represented with $k$ digits in base (radix) $b$. So, $$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$ For example, if $b=17, k=3$ and $a=[11, 15, 7]$ then $n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$. Determine whether $n$ is even or odd.
If $b$ is even, then only the last digit matters. Otherwise $b^k$ is odd for any $k$, so each digit is multiplied by odd number. A sum of several summands is even if and only if the number of odd summands is even. So we should just compute the number of even digits.
[ "math" ]
900
null
1110
B
Tape
You have a long stick, consisting of $m$ segments enumerated from $1$ to $m$. Each segment is $1$ centimeter long. Sadly, some segments are broken and need to be repaired. You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $t$ placed at some position $s$ will cover segments $s, s+1, \ldots, s+t-1$. You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap. Time is money, so you want to cut at most $k$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?
Let's start with $n$ pieces of length $1$ covering only broken segments and then decrease the number of pieces used. After reducing the number of segments by $x$, some $x$ of long uncovered initial segments of unbroken places will be covered. It's easy to see that you should cover the shortest $x$ segments. Thus, to make at most $k$ segments, you should cover $n - k$ shortest initial segments. You can find their total length using sort.
[ "greedy", "sortings" ]
1,400
null
1110
C
Meaningless Operations
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer $a$. You want to choose some integer $b$ from $1$ to $a - 1$ inclusive in such a way that the greatest common divisor (GCD) of integers $a \oplus b$ and $a \> \& \> b$ is as large as possible. In other words, you'd like to compute the following function: $$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$ Here $\oplus$ denotes the bitwise XOR operation, and $\&$ denotes the bitwise AND operation. The greatest common divisor of two integers $x$ and $y$ is the largest integer $g$ such that both $x$ and $y$ are divided by $g$ without remainder. You are given $q$ integers $a_1, a_2, \ldots, a_q$. For each of these integers compute the largest possible value of the greatest common divisor (when $b$ is chosen optimally).
Denote the highest bit of $a$ as $x$ (that is largest number $x$, such that $2^x \le a$) and consider $b = (2^x - 1) \> \oplus a$. It's easy to see that if $a \neq 2^x - 1$ then $0 < b < a$ holds. In this, $gcd$ is maximum possible, because $a \> \& b = 0$ and $gcd(2 ^ x - 1, 0) = 2^x - 1$. Now consider the case when $a = 2^x - 1$. This implies $gcd(a \oplus b, a \& b) = gcd(2^x - 1 - b, b) = gcd(2^x - 1, b)$, since $gcd(x, x + y) = gcd(x, y)$ (for all $x$ and $y$), hence it's sufficient to find the largest non trivial divisor of $a$ - it will be the desired answer. Finding the largest divisor can be done in sqrt time which leads to the time $O(q \sqrt{m})$ or it's possible to calculate answers for all $a = 2^x - 1$ beforehand.
[ "constructive algorithms", "math", "number theory" ]
1,500
null
1110
D
Jongmah
You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have $n$ tiles in your hand. Each tile has an integer between $1$ and $m$ written on it. To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, $7, 7, 7$ is a valid triple, and so is $12, 13, 14$, but $2,2,3$ or $2,4,6$ are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple. To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.
First thing to note is that one can try solving this problem with different greedy approaches, but authors don't know any correct greedy. To solve this problem, note that you can always replace $3$ triples of type $[x, x + 1, x + 2]$ with triples $[x, x, x]$, $[x + 1, x + 1, x + 1]$ and $[x + 2, x + 2, x + 2]$. So we can assume that there are at most $2$ triples of type $[x, x + 1, x + 2]$ for each $x$. Having noted this, you can write dynamic programming solution. Let ans[i][t1][t2] be the answer considering only the first $i$ denominations, and there are $t_1$ triples of type $[i - 1, i, i + 1]$ and $t_2$ triples of type $[i, i + 1, i + 2]$. Try all possible number $t_3$ of triples of type $[i + 1, i + 2, i + 3]$, put all the remaining tiles of denomination $i + 1$ into triples $[i + 1, i + 1, i + 1]$ and make a transition to ans[i + 1][t2][t3].
[ "dp" ]
2,200
null
1110
E
Magic Stones
Grigory has $n$ magic stones, conveniently numbered from $1$ to $n$. The charge of the $i$-th stone is equal to $c_i$. Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index $i$, where $2 \le i \le n - 1$), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge $c_i$ changes to $c_i' = c_{i + 1} + c_{i - 1} - c_i$. Andrew, Grigory's friend, also has $n$ stones with charges $t_i$. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes $c_i$ into $t_i$ for all $i$?
Consider the difference array $d_1, d_2, \ldots, d_{n - 1}$, where $d_i = c_{i + 1} - c_i$. Let's see what happens if we apply synchronization. Pick an arbitrary index $j$ and transform $c_j$ to $c_j' = c_{j + 1} + c_{j - 1} - c_j$. Then: $d_{j - 1}' = c_j' - c_{j - 1} = (c_{j + 1} + c_{j - 1} - c_j) - c{j - 1} = c_{j + 1} - c_j = d_j$; $d_j' = c_{j + 1} - c_j' = c_{j + 1} - (c_{j + 1} + c_{j - 1} - c_j) = c_j - c{j - 1} = d_{j - 1}$. In other words, synchronization simply transposes two adjacent differences. That means that it's sufficient to check whether the difference arrays of two sets of stones are equal and make sure that $s_1 = t_1$.
[ "constructive algorithms", "math", "sortings" ]
2,200
null
1110
F
Nearest Leaf
Let's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number $1$ and then recursively runs from all vertices which are connected with an edge with the current vertex and are not yet visited in increasing numbers order. Formally, you can describe this function using the following pseudocode: \begin{verbatim} next_id = 1 id = array of length n filled with -1 visited = array of length n filled with false function dfs(v): visited[v] = true id[v] = next_id next_id += 1 for to in neighbors of v in increasing order: if not visited[to]: dfs(to) \end{verbatim} You are given a weighted tree, the vertices of which were enumerated with integers from $1$ to $n$ using the algorithm described above. A leaf is a vertex of the tree which is connected with only one other vertex. In the tree given to you, the vertex $1$ is not a leaf. The distance between two vertices in the tree is the sum of weights of the edges on the simple path between them. You have to answer $q$ queries of the following type: given integers $v$, $l$ and $r$, find the shortest distance from vertex $v$ to one of the leaves with indices from $l$ to $r$ inclusive.
Let's answer the queries offline: for each vertex we'll remember all queries for it. Let's make vertex $1$ root and find distances from it to all leaves using DFS. Now for answering queries for vertex $1$ we should simply answer some range minimum queries, so we'll build a segment tree for it. For answering queries for other vertices we will make segment trees with distances to leaves (like we did for handling queries for vertex $1$) for all vertices. We will traverse vertices of a tree using DFS and maintain actual distances to leaves in segment tree. Suppose, DFS went through edge $(u, v)$ with weight $w$ where $u$ is an ancestor of $v$. Distances to leaves in subtree of $v$ will decrease by $w$ and distances to other vertices will increase by $w$. Since set of leaves in subtree of some vertex is a subsegment of vertices written in euler traversal order, we should simply make range additions/subtractions on segment tree to maintain distances to leaves when passing through an edge. This way we got a solution with $O(n \log n + q \log n)$ complexity.
[ "data structures", "trees" ]
2,600
null
1110
G
Tree-Tac-Toe
The tic-tac-toe game is starting on a tree of $n$ vertices. Some vertices are already colored in white while the remaining are uncolored. There are two players — white and black. The players make moves alternatively. The white player starts the game. In his turn, a player must select one uncolored vertex and paint it in his color. The player wins if he paints some path of three vertices in his color. In case all vertices are colored and neither player won, the game ends in a draw. Could you please find who will win the game or whether it ends as a draw, assuming both players play optimally?
To start with, let's notice that the white vertices are not necessary. Actually, you can solve the problem analyzing the cases with the whites as well, but there is an easy way to get rid of them: Examine the following construction: That is, replace the white $A$ with some set of four non-white vertices. One can notice, that neither white nor black can win on these four vertices. That means that they are actually interested in getting the color of the end of this graph, connected to the remaining graph being of their color - it can help them later. Let's start the game as white player and paint a vertex $A$ white. If black player will not paint the vertex $B$ black, we have a win. Otherwise, two turns have passed now and that means that the "parity" has preserved and it is our turn again. Then we can play as we would have played in the original game, except if the black player paints $C$ or $D$ in some point, we should color the remaining one (and the parity will preserve again). ------- Now let's solve the problem assuming there are no white vertices. Note, that if there is a vertex of degree $4$ or more, then the white player wins, maing the first move into that vertex, and then two moves in some leaves of this vertex. In case there is a vertex of degree $3$ having at least two non-white neighbors, then it's a win as well: we can either collect a path going through this vertex or going through non-leave neighbor somewhere else. Now, note that if there are at least $3$ vertexes of degree $3$, this implies the case above. So we are left with a case when there are at most three vertices of degree $3$ and all other have degree $1$ or $2$. It's natural to claim (and many got wa2 for that), that all remaining cases are draws. But it's not true: It's easy to see, that this game (picture above) is winning for white. Applying the same argument, as before, we can deduce that the game above is equivalent to the game below. Which is clearly winning for white. Actually, any path having odd number of vertices and colored in white on both ends is winning for white (make a move into the vertex colored blue on the picture below): This actually meains, that in our solution, in which we got rid of all white vertices, the winning cases are <<bones>> having odd number of vertices. It's possible to show, that in all other cases the game will end in draw.
[ "constructive algorithms", "games", "trees" ]
3,100
null
1110
H
Modest Substrings
You are given two integers $l$ and $r$. Let's call an integer $x$ modest, if $l \le x \le r$. Find a string of length $n$, consisting of digits, which has the largest possible number of substrings, which make a modest integer. Substring having leading zeros are not counted. If there are many answers, find lexicographically smallest one. If some number occurs multiple times as a substring, then in the counting of the number of modest substrings it is counted multiple times as well.
Set of modest numbers could be represented by set of size approximately $(|l| + |r|) \cdot 10$ of regular expressions of form $d_0 d_1 d_2 \dots d_{k - 1} [0-9]\{e\}$, where $|l|$ and $|r|$ are lengths of numbers $l$ and $r$ correspondingly, and $d_i$ are digits. Set of regular expressions can be build in the following way. Consider prefix of $l$ of length $x$. Then for every $q > l_x$ let's make the following expression: $l_0 l_1 l_2 \dots l_{x - 1} q [0-9]\{|l| - x - 1\}$. Similarly for $r$, but here $q < r_x$. Also for all $|l| < x < |r|$ we should make regular expressions $[1-9][0-9]\{x - 1\}$, this is equal to nine expressions of our form. Notice that every modest number would satisfy exactly one regular expression and no other number would satisfy any expression. Let's call wildcard of length $x$ tail of regular expression of form $[0-9]\{x\}$. Let's build Aho-Corasick automaton for all prefixes of regular expressions until wildcards. For every regular expression put in corresponding node length of wildcard. After that task could be solved using dynamic programming. State would be length of prefix of answer and node of the automaton. From state $(i, v)$ we can go by digit $d$ to the state $(i + 1, u)$, $u$ is node where $d$ leads from $v$. Value for $(i + 1, u)$ should be updated by value for $(i, v)$ plus number of wildcards with lengths not exceeding $n - i - 1$, placed in nodes reachable from $u$ by suffix links in automaton. This value can be calculated beforehand for every pair node and length. Asymptotics of solution is $O((|l| + |r|) \cdot n \cdot \Sigma ^ 2)$, where $\Sigma$ is size of alphabet, i.e. $10$.
[ "dp", "strings" ]
3,500
null
1111
A
Superhero Transformation
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $s$ can transform to another superhero with name $t$ if $s$ can be made equal to $t$ by changing any vowel in $s$ to any other vowel and any consonant in $s$ to any other consonant. Multiple changes can be made. \textbf{In this problem}, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants. Given the names of two superheroes, determine if the superhero with name $s$ can be transformed to the Superhero with name $t$.
Check lengths of $s$ and $t$. If they are different, $s$ can never be converted to $t$ and answer is "No". If for all indexes $i$ either both $s[i]$ and $t[i]$ are vowels or both $s[i]$ and $t[i]$ are consonants, then answer is "Yes", else answer is "No".
[ "implementation", "strings" ]
1,000
#include "bits/stdc++.h" using namespace std; // Checking if a character is vowel bool isVowel(char a) { if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return true; return false; } int main() { string S, T; cin >> S; cin >> T; // Answer is no if size of strings is differents if(S.size() != T.size()) { cout << "No\n"; return 0; } int flag = 1; // Checking the condition on all characters one by one for(int i = 0; i < S.size(); ++i) { if((isVowel(S[i]) && isVowel(T[i])) || (isVowel(S[i]) == false && isVowel(T[i]) == false)) { continue; } flag = 0; break; } if(flag) cout << "Yes\n"; else cout << "No\n"; return 0; }
1111
B
Average Superhero Gang Power
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations. Initially, there are $n$ superheroes in avengers team having powers $a_1, a_2, \ldots, a_n$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $1$. They can do at most $m$ operations. Also, on a particular superhero at most $k$ operations can be done. Can you help the avengers team to maximize the average power of their crew?
If we want to remove an element to increase the average it should be the smallest element in our current set. For each deletion, $1$ operation is used. Lets try finding $f(i)$ = maximum average by deleting $i$ smallest elements. If we delete $i$ elements, then for the remaining $n-i$ elements the maximum increase can be $min(m-i,k*(n-i))$ since $m-i$ operations can be now at max used, and at one particular index at most $k$ operations can be done. So $f(i) =$( sum of largest $(n-i$) elements $+ min(m-i,k*(n-i)) )/ (n-i)$ The sum of largest $(n-i)$ terms can be computed using prefix sums. $ans =$max $f(i)$ over all $i$ from $0$ to $min(m,n-1)$ The min condition comes because there is no use of deleting all elements, and the number of deletions is limited by the maximum number of operations possible.
[ "brute force", "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; const long long N = 100010; long long a[N]; int main() { long long n, k, m, i, sum=0, tp; long double mx; cin>>n>>k>>m; for(int i=1;i<=n;i++) { cin>>a[i]; sum += a[i]; } // Sorting the array sort(a+1, a+n+1); // Checking for the case where none of the avengers is removed mx = (long double)(sum+min(m, n*k))/(long double)(n); for(int i=1;i<=min(n-1, m);i++) { sum -= a[i]; tp = sum + min(m-i, (n-i)*k); mx = max(mx, (long double)(tp)/(long double)(n-i)); } cout<<fixed<<setprecision(20)<<mx<<endl; return 0; }
1111
C
Creative Snap
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base. Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $2$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: - if the current length is at least $2$, divide the base into $2$ equal halves and destroy them separately, or - burn the current base. If it contains no avenger in it, it takes $A$ amount of power, otherwise it takes his $B \cdot n_a \cdot l$ amount of power, where $n_a$ is the number of avengers and $l$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
Make a recursive function rec($l,r$) where l and r are start and end indexes of subarray to be considered. Start with $l=1$ and $r=2^n$. If there is no avenger in l to r return A (power consumed). Else either power consumed to burn it directly is $b*x*len$ (where x is number of avengers in l to r and len is length of array ($r-l+1$) ) or by dividing the array is the result of recursion($l,mid$) + recursion($mid+1,r$) where $mid=(l+r)/2$. Return the minimum power consumed. If l is equal to r then do not go into recursion further, return power consumed according to first operation. One thing is remaining, the value of x, given l and r. Sort the array containing indices of avengers and then find positions of l and r in that array using binary search. Difference is positions of l and r in array will give x. Time Complexity : $O(n*k*log(k))$. Explanation : Reaching any subarray will take maximum of n operations and we can have maximum k subarrays (each having one avenger), it will take $O(n*k)$. $O(log(k))$ time needed for binary search (calculating x). So net complexity is $O(n*k*log(k))$.
[ "binary search", "brute force", "divide and conquer", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; vector<long long> avengers; long long n,k,A,B; // rec(l,r) returns minimum power needed to destroy l to r (inclusive) long long rec(long long l, long long r) { long long i=lower_bound(avengers.begin(),avengers.end(),l)-avengers.begin(); long long j=upper_bound(avengers.begin(),avengers.end(),r)-avengers.begin(); j--; // calculating positions of l and r in avengers array to calculate x long long x=j-i+1; long long power_consumed; // if there is no avenger in that subarray if(x==0) power_consumed=A; else { power_consumed=B*x*(r-l+1); // power consumed for operation 2. (r-l+1 is length of subarray) } // if l is equal to r or if there is no avenger in the subarray, then do not go into recursion further if(l==r || x==0) return power_consumed; long long mid=(l+r)/2; // taking minimum of two operations. long long minPower=min(power_consumed, rec(l,mid)+rec(mid+1,r)); return minPower; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin>>n>>k>>A>>B; int i; for(i=0;i<k;i++) { int val; cin>>val; avengers.push_back(val); } sort(avengers.begin(),avengers.end()); long long x = (long long)1<<n; cout<<rec(1,x)<<endl; return 0; }
1111
D
Destroy the Colony
There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain. Each colony arrangement can be expressed as a string of \textbf{even} length, where the $i$-th character of the string represents the type of villain in the $i$-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony. His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times. Now Iron Man asks Jarvis $q$ questions. In each question, he gives Jarvis two numbers $x$ and $y$. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in $x$-th hole or $y$-th hole live in the same half and the Iron Man can destroy that colony arrangement. Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.
The question reduces to the following. Given a string s with lowercase and uppercase characters,a good string is one which can be generated by reshuffling characters, such that all occurences of a particular alphabet are in the same half. ( (1 to n/2) or (n/2+1 to n)) and this condition is true for all alphabets. Now given a pair $i$ and $j$, you want to find the number of good strings such that all the occurences of $s[i]$ and $s[j]$ in the string are also in the same half in the string. Lets first try to find the number of good strings. $k$ = total number of alphabets. Store the frequencies of the alphabets as their order does not matter, and let them be $c1,c2,c3..ck$ Now if we can select indices $i_1, i_2, \ldots, i_p$ such that $ci_1 + ci_2 + \ldots, ci_p$ = n/2 then we can arrange those alphabets in the first half, and the remaining in the second half. Total ways for arranging in first half = $(n/2!)/(ci1!* ci2!* ci3!.. cip!)$ Similarly total ways for arranging in 2nd half = $(n/2!)/$(product of factorials of remaining frequencies.) Thus total ways = $((n/2!)*(n/2!))/$(product of factorials of frequencies of all alphabets) $= W$(say) Thus notice that, for all combinations of frequencies adding upto $n/2$, the number of ways comes out to be constant. Hence now the total number of good strings $= W*$ (number of combinations of frequencies adding to $n/2$) The part for the number of combinations adding upto $n/2$ can be computed using standard knapsack dp. Now let's try to solve for the condition that all occurrences of $s[i]$ and $s[j]$, should all also be in the same half, apart from the condition of the string being a good string. This basically means now we want to select alphabet frequencies adding upto $n/2$ from the remaining frequencies ( excluding the frequency of alphabet $s[i]$ and $s[j]$). One way is to use the same method we did above for all good strings. This gives complexity O$(n*k)$ for every pair, taking a total of O$(n*k^3)$ for $k^2$ pairs. Now using the idea of adding items to a knapsack, we can also extend it to remove items. In short, we can use the pre-computed dp table to remove the number of ways which included the ith item, by reversing the direction of the loop and the operation ( addition becomes subtraction). Let the frequency of the element we want to remove be $x$. dp[j] = number of ways to get sum as j using all elements. for (int j=x;j<=n;j++) $\quad$dp[j]-=dp[j-x]; ( see the code for more details) In this way for every pair $(x,y)$, you copy the precomputed dp into a temporary array, remove ways using characters $x$ and $y,$ and then the answer will be $2*dp[n/2]*W$ ( 2 because you can choose the first or the second half for putting the group containing $x$ and $y$). After precomputation, each query is answered in O$(1)$. Total time O$(2*n)$, for every pair and there are $(k*(k-1))/2$ pairs. Final time complexity O$(n*k^2)$
[ "combinatorics", "dp", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; #define pb push_back #define fr(i,n) for(i=0;i<n;i++) #define rep(i,st,en) for(i=st;i<=en;i++) typedef long long ll; typedef pair<int,int> pii; const int N = 100010; ll mod = 1e9+7; ll fmod(ll b,ll exp){ ll res =1; while(exp){if(exp&1ll)res=(res*b)%mod; b =(b*b)%mod;exp/=2ll; } return res; } ll buc[101]; ll fac[N],inv[N]; ll dp[N],temp_dp[N]; ll ans[55][55]; string s,s1,s2; int find(char c) { if(c>='A' && c<='Z')return (int)(c-'A'+26); else return (c-'a'); } inline void add(ll &a,ll b) { a+=b; if(a>=mod)a-=mod; } inline void sub(ll &a,ll b) { a-=b; if(a<0)a+=mod; } int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); ios_base::sync_with_stdio(false);cin.tie(NULL); int t=1,n,i,j,m,q; cin>>s; n = s.length(); //Store the frequencies in buc for(int i=0;i<n;i++)buc[find(s[i])]++; //Compte factorial and inverse factorials modulo mod fac[0]=1; rep(i,1,n)fac[i]=(fac[i-1]*1ll*i)%mod; inv[n] = fmod(fac[n],mod-2); for(int i=n-1;i>=0;i--)inv[i]=(inv[i+1]*1ll*(i+1))%mod; //Compute n/2! * n/2! divided by factorials of frequencies of all ll num = (fac[n/2]*fac[n/2])%mod; for(int i=0;i<52;i++)num = (num*inv[buc[i]])%mod; //DP for subset sum dp[0]=1; for(int i=0;i<52;i++) { if(!buc[i])continue; for(int j=n;j>=buc[i];j--) add(dp[j],dp[j-buc[i]]); } fr(i,52)ans[i][i]=dp[n/2]; fr(i,52) { if(!buc[i])continue; //Temporrily store dp using all characters in an array for(int k=0;k<=n;k++) temp_dp[k]= dp[k]; //Remove all ways consisting of the ith character from temp array for(int k=buc[i];k<=n;k++) sub(temp_dp[k],temp_dp[k-buc[i]]); for(int j=i+1;j<52;j++) { if(!buc[j])continue; //Now remove the jth character from the temp for(int k=buc[j];k<=n;k++) sub(temp_dp[k],temp_dp[k-buc[j]]); // Answer will be twice since ith and jth can be in 1st or 2nd half ans[i][j]= (2ll*temp_dp[n/2])%mod; ans[j][i]= ans[i][j]; //Symmetric //Restore condition by adding ways using jth to reset temp to without i for(int k=n;k>=buc[j];k--) add(temp_dp[k],temp_dp[k-buc[j]]); } } cin>>q; int x,y; while(q--) { cin>>x>>y; int l = find(s[x-1]); int r = find(s[y-1]); //Use precomputed num and ans, for all queries cout<<(num*ans[l][r])%mod<<"\n"; } return 0; }
1111
E
Tree
You are given a tree with $n$ nodes and $q$ queries. Every query starts with three integers $k$, $m$ and $r$, followed by $k$ nodes of the tree $a_1, a_2, \ldots, a_k$. To answer a query, assume that the tree is rooted at $r$. We want to divide the $k$ given nodes into \textbf{at most} $m$ groups such that the following conditions are met: - Each node should be in exactly one group and each group should have at least one node. - In any group, there should be no two distinct nodes such that one node is an ancestor (direct or indirect) of the other. You need to output the number of ways modulo $10^{9}+7$ for every query.
Assume that we didn't have to root at Y in each query. Lets first solve the problem for all queries having root at 1. While processing the query, let's sort the given set of nodes according to the dfs order. Let dp[i][j] denotes the number of ways to divide the first i nodes in the set into j non-empty groups. For a node i, let h[i] denote the number of ancestors in the query set. Now, dp[i][j] = dp[i-1][j]$\cdot$(j-h[i]) + dp[i-1][j-1] The first part basically says, that apart from the groups of the ancestors of i, it can be included in any other group, hence (j-h[i]) choices for allocating a group to i. The second part is including $i$-th node in a completely new group. Thus our final answer would have been the sum of dp[n][j] for all j from 1 to x. Now how to find h[i]? If we mark all the nodes which have appeared in the query, h[i] is the number of marked nodes from i to the root. This can be computed using standard range updates and point queries on Euler tree. For all nodes i, perform a range update on the range [ST(i),EN(i)] and h[i] basically becomes query(ST[i]). Now a key observation. Notice that actually we only care that for node i, before updating its dp, all its ancestors are visited. This means we actually do not need the dfs order, instead just the level-wise order. So all we need to do is sort all nodes in the query set according to the h[i] values. By removing the condition for dfs order on the ordering of the dp, the condition for rerooting can also be handled. If the tree is rooted at Y, Now hnew[i] becomes the number of marked nodes between i and root Y. This can be computed using the same technique of range update and query. hnew[i] = h[i] + h[Y] - 2$\cdot$h[ LCA(i,Y)] + (mark[LCA(i,Y)]==true) -1 (-1 because we do not want to include i in hnew[i]) Now we do the same dp and compute the answer. For every query: Sorting = O(KlogK), LCA computation = O(KlogN), bit update and query= O(KlogN) LCA precomputation = O(NlogN) Thus final complexity = O( NlogN + logN$\cdot$(summation over all values of K)) (where summation of K <= 10^5)
[ "data structures", "dfs and similar", "dp", "graphs", "trees" ]
2,500
#include<bits/stdc++.h> using namespace std; #define pb push_back #define rep(i,st,en) for(i=st;i<=en;i++) typedef long long ll; typedef pair<int,int> pii; const int N = 200010; const int LN = 20; ll mod = 1e9+7; ll fmod(ll b,ll exp){ ll res =1; while(exp){if(exp&1ll)res=(res*b)%mod; b =(b*b)%mod;exp/=2ll; } return res; } int ver[2*N]; // gives the id of the vertex in the euler array ll bit[2*N]; int st[N],en[N],A[N]; // st and en are the start and end time of node i int f[N]; ll dp[N]; int par[N][LN]; int mark[N],lev[N]; vector<int> adj[N]; int tim = 0,n; /* Normal DFS and LCA functions */ void dfs(int i,int p=-1) { if (p+1) { lev[i]=lev[p]+1; par[i][0]=p; for(int j=1;j<LN;j++) if (par[i][j-1]+1) par[i][j]=par[par[i][j-1]][j-1]; } st[i]=(++tim); ver[tim]= i; for(auto ve:adj[i]) if(p-ve) dfs(ve,i); en[i]=(++tim); ver[tim]= i; } int lca(int u,int v) { if (lev[u]<lev[v]) swap(u,v); for(int j=LN-1;j>=0;j--) if (par[u][j]+1 && lev[par[u][j]]>=lev[v]) u=par[u][j]; if (u==v) return u; for(int j=LN-1;j>=0;j--) { if (par[u][j]+1 && par[u][j]!=par[v][j]) { u=par[u][j]; v=par[v][j]; } } return par[u][0]; } /* Helper functions */ inline ll add(ll a,ll b) { a+=b; if(a>=mod)a-=mod; return a; } void upd(int ind,int val) { for(int i=ind;i<=2*n;i+=(i&-i)) bit[i]+=val; } ll query(int ind) { ll res = 0; for(int i=ind;i>0;i-=(i&-i)) res+=bit[i]; return res; // returns the number of marked nodes from 1 to ind inclusive. } int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); ios_base::sync_with_stdio(false);cin.tie(NULL); int t=1,i,j,m,q,u,v,w,typ,e,k,x; memset(par,-1,sizeof(par)); cin>>n>>q; rep(i,1,n-1) { cin>>u>>v; adj[u].pb(v); adj[v].pb(u); } dfs(1,-1); int root; while(q--) { cin>>k>>x>>root; rep(i,1,k){ cin>>A[i]; mark[A[i]]=1; //mark nodes given in the set upd(st[A[i]],1); // range update by updating at start and end time in bit upd(en[A[i]]+1,-1); } int ans_root = query(st[root]); rep(i,1,k){ int lp = lca(A[i],root); //query function is inclusive, hence subtract 1 to remove current node from answer f[i]= query(st[A[i]])+ans_root-2*query(st[lp])+(mark[lp]==1)-1; } //Sorting level-wise using f[i] values sort(f+1,f+k+1); rep(i,1,k){ upd(st[A[i]],-1); // reverse the updates to nullify effect upd(en[A[i]]+1,1); mark[A[i]]=0; // unmark nodes in the set } rep(i,0,x)dp[i]=0; dp[0]=1; //If number of groups less than maximum height no way possible int fl = 0; rep(i,1,k)if(f[i]>=x)fl=1; if(fl)cout<<"0\n"; else{ dp[0]=1; //For every value of f[i], update dp. Note loop for j will be reverse. rep(i,1,k){ for(int j=min(i,x);j>=0;j--) { if(j<=f[i])dp[j]=0; //no way possible since less than height else dp[j]= add(((dp[j]*1ll*(j-f[i]))%mod),dp[j-1]); } } ll ans = 0; // AT MOST x in the question rep(i,1,x){ ans = add(ans,dp[i]); } cout<<ans<<"\n"; } } return 0; }
1113
A
Sasha and His Trip
Sasha is a very happy guy, that's why he is always on the move. There are $n$ cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from $1$ to $n$ in increasing order. The distance between any two adjacent cities is equal to $1$ kilometer. Since all roads in the country are directed, it's possible to reach the city $y$ from the city $x$ only if $x < y$. Once Sasha decided to go on a trip around the country and to visit all $n$ cities. He will move with the help of his car, Cheetah-2677. The tank capacity of this model is $v$ liters, and it spends exactly $1$ liter of fuel for $1$ kilometer of the way. At the beginning of the journey, the tank is empty. Sasha is located in the city with the number $1$ and wants to get to the city with the number $n$. There is a gas station in each city. In the $i$-th city, the price of $1$ liter of fuel is $i$ dollars. It is obvious that at any moment of time, the tank can contain at most $v$ liters of fuel. Sasha doesn't like to waste money, that's why he wants to know what is the minimum amount of money is needed to finish the trip if he can buy fuel in any city he wants. Help him to figure it out!
When $n - 1 < v$ the answer is $n - 1$. Else you must notice, that it is optimal to fill the tank as soon as possible, because if you don't do that, you will have to spend more money in future. So to drive first $v - 1$ kilometers just buy $v - 1$ liters in the first city, then to drive between cities with numbers $i$ and $i + 1$, buy liter in the city with number $i - v + 1$.
[ "dp", "greedy", "math" ]
900
"#include <bits/stdc++.h>\nusing namespace std;\n\n\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr), cout.tie(nullptr);\n \n int n, v;\n cin >> n >> v;\n if (n-1 <= v) {\n cout << n-1 << endl;\n return 0;\n }\n int result = v - 1;\n for(int i = 1; i <= n - v; ++i) {\n result += i;\n }\n cout << result << endl;\n\n return 0;\n}\n"
1113
B
Sasha and Magnetic Machines
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can \textbf{at most once} choose an arbitrary integer $x$, then choose one machine and reduce the power of its machine by $x$ times, and at the same time increase the power of one another machine by $x$ times (powers of all the machines must stay \textbf{positive integers}). Note that he may not do that if he wants. More formally, 2D can choose two such indices $i$ and $j$, and one integer $x$ such that $x$ is a divisor of $a_i$, and change powers as following: $a_i = \frac{a_i}{x}$, $a_j = a_j \cdot x$ Sasha is very curious, that's why he wants to calculate the \textbf{minimum} total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!
First notice that if we divide some number by $x$, then to get the minimal sum, it is optimal to multiply by $x$ the smallest number in the array. So now precalculate the sum of the initial array and the minimal $a_i$, then you can check all possible $x$ for every $a_i$, and choose the best variant. So the complexity is $O(n \cdot a_i)$.
[ "greedy", "number theory" ]
1,300
"#include <bits/stdc++.h>\nusing namespace std;\n\n\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr), cout.tie(nullptr);\n \n int n;\n cin >> n;\n vector<int> a(n);\n for(int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n int mn = *min_element(a.begin(), a.end());\n int sum = accumulate(a.begin(), a.end(), 0);\n int res = sum;\n for(int i = 0; i < n; ++i) {\n for(int d = 1; d <= a[i]; ++d) {\n if (a[i] % d != 0) continue;\n int cur = sum - mn - a[i];\n cur += mn * d + a[i] / d;\n res = min(res, cur);\n }\n }\n cout << res << endl;\n\n return 0;\n}\n"
1114
A
Got Any Grapes?
\begin{quote} The Duck song \end{quote} For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: - Andrew, Dmitry and Michal should eat at least $x$, $y$ and $z$ grapes, respectively. - Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. - On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. - Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient. Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with $a$ green grapes, $b$ purple grapes and $c$ black grapes. However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes? It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
First of all, we can see the grape preference is hierarchically inclusive: the grapes' types Andrew enjoys are some of those that Dmitry does, and Dmitry's favorites are included in Michal's. Let's distribute the grapes to satisfy Andrew first, then to Dmitry, then Michal. If any of the following criteria is not satisfied (which means one of our friends is not happy), then we can immediately say that no distributions are available: Andrew must have at least $a$ green grapes. So we need, $x \le a$. Dmitry can have purple grapes and/or the remaining green grapes. In other words, $y \le a + b - x$ (the minus $x$ is because $x$ green grapes have been given to Andrew already). Michal can have grapes of any kinds. In other words, $z \le a + b + c - x - y$ (similar explanations like above for both minus $x$ and minus $y$). If all three criteria are satisfied, then a grape distribution is possible. Total complexity: $O\left(1\right)$.
[ "brute force", "greedy", "implementation" ]
800
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' int x, y, z, a, b, c; void Input() { cin >> x >> y >> z; cin >> a >> b >> c; } void Solve() { if (x > a) {cout << "NO\n"; return;} if (x + y > a + b) {cout << "NO\n"; return;} if (x + y + z > a + b + c) {cout << "NO\n"; return;} cout << "YES\n"; } int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); Input(); Solve(); return 0; }
1114
B
Yet Another Array Partitioning Task
An array $b$ is called to be a subarray of $a$ if it forms a continuous subsequence of $a$, that is, if it is equal to $a_l$, $a_{l + 1}$, $\ldots$, $a_r$ for some $l, r$. Suppose $m$ is some known constant. For any array, having $m$ or more elements, let's define it's beauty as the sum of $m$ largest elements of that array. For example: - For array $x = [4, 3, 1, 5, 2]$ and $m = 3$, the $3$ largest elements of $x$ are $5$, $4$ and $3$, so the beauty of $x$ is $5 + 4 + 3 = 12$. - For array $x = [10, 10, 10]$ and $m = 2$, the beauty of $x$ is $10 + 10 = 20$. You are given an array $a_1, a_2, \ldots, a_n$, the value of the said constant $m$ and an integer $k$. Your need to split the array $a$ into exactly $k$ subarrays such that: - Each element from $a$ belongs to exactly one subarray. - Each subarray has at least $m$ elements. - The sum of all beauties of $k$ subarrays is maximum possible.
In a perfect scenario, the maximum beauty of the original array is just a sum of $m \cdot k$ largest elements. In fact, such scenario is always available regardless of the elements. Let's denote $A$ as the set of these $m \cdot k$ largest elements. The solution for us will be dividing the array into $k$ segments, such that each segment contains exactly $m$ elements of $A$. Just make a split between corresponding elements in the set $A$. Depending on the way we find $m \cdot k$ largest elements, the time complexity might differ. If we simply do so after sorting the entire array by usual means, the time complexity will be $O\left(n\cdot\log(n)\right)$. However, we can use std::nth_element function instead of sorting the entire array. The idea is to sort the array in such a way that, every elements not higher than a value $v$ will be stored in the left side, other elements will stay on the right, and this works in linear time (a.k.a. $O\left(n\right)$ time complexity). An example implementation of such ordering can be shown here.
[ "constructive algorithms", "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); int n, m, k; cin >> n >> m >> k; vector<pii> a(n); for(int i = 0; i < n; ++i) { cin >> a[i].first; a[i].second = i; } sort(a.begin(), a.end(), greater<pii>()); vector<int> ind(m*k); ll sumBeauty = 0; for(int i = 0; i < m*k; ++i) { sumBeauty += a[i].first; ind[i] = a[i].second; } sort(ind.begin(), ind.end()); vector<int> division(k-1); for(int i = 0; i < k-1; ++i) division[i] = ind[(i+1)*m - 1]; cout << sumBeauty << endl; for(int p: division) cout << p + 1 << " "; return 0; }
1114
C
Trailing Loves (or L'oeufs?)
\begin{quote} The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis. \end{quote} Aki is fond of numbers, especially those with trailing zeros. For example, the number $9200$ has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is. However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers. Given two integers $n$ and $b$ (in decimal notation), your task is to calculate the number of trailing zero digits in the $b$-ary (in the base/radix of $b$) representation of $n\,!$ (factorial of $n$).
The problem can be reduced to the following: finding the maximum $r$ that $n !$ is divisible by $b^{r}$. By prime factorization, we will have the following: $b = p_{1}^{y1} \cdot p_{2}^{y2} \cdot ... \cdot p_{m}^{ym}$. In a similar manner, we will also have: $n ! = p_{1}^{x1} \cdot p_{2}^{x2} \cdot ... \cdot p_{m}^{xm} \cdot Q$ (with $Q$ being coprime to any $p_{i}$ presented above). The process of finding $p_{1}$, $p_{2}$, $...$, $p_{m}$, $y_{1}$, $y_{2}$, $...$, $y_{m}$ can be done by normal prime factorization of the value $b$. The process of finding $x_{1}$, $x_{2}$, $...$, $x_{m}$ is a little bit more tricky since the integer they were originated ($n !$) is too huge to be factorized manually. Still the factorial properties gave us another approach: for each $p_{i}$, we can do the following: Initially, denote $x_{i} = 0$. Initially, denote $x_{i} = 0$. Repeatedly do the following: add $\textstyle\left|{\frac{n}{p_{i}}}\right|$ to $x_{i}$, then divide $n$ by $p_{i}$. The loop ends when $n$ is zero. Repeatedly do the following: add $\textstyle\left|{\frac{n}{p_{i}}}\right|$ to $x_{i}$, then divide $n$ by $p_{i}$. The loop ends when $n$ is zero. After all, we can obtain the final value $r$ as of following: $r=\operatorname*{min}_{i\in[1,m]}|{\frac{x_{i}}{y_{i}}}|$. Total complexity: $O\left({\sqrt{b}}+\log(b)\cdot\log(n)\right)$ (as the number of prime factors of an integer $b$ will not surpass $\log(b)$).
[ "brute force", "implementation", "math", "number theory" ]
1,700
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' long long n, b; void Input() { cin >> n >> b; } void Solve() { long long ans = 1000000000000000000LL; for (long long i=2; i<=b; i++) { if (1LL * i * i > b) i = b; int cnt = 0; while (b % i == 0) {b /= i; cnt++;} if (cnt == 0) continue; long long tmp = 0, mul = 1; while (mul <= n / i) {mul *= i; tmp += n / mul;} ans = min(ans, tmp / cnt); } cout << ans << endl; } int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); Input(); Solve(); return 0; }
1114
D
Flood Fill
You are given a line of $n$ colored squares in a row, numbered from $1$ to $n$ from left to right. The $i$-th square initially has the color $c_i$. Let's say, that two squares $i$ and $j$ belong to the same connected component if $c_i = c_j$, and $c_i = c_k$ for all $k$ satisfying $i < k < j$. In other words, all squares on the segment from $i$ to $j$ should have the same color. For example, the line $[3, 3, 3]$ has $1$ connected component, while the line $[5, 2, 4, 4]$ has $3$ connected components. The game "flood fill" is played on the given line as follows: - At the start of the game you pick any starting square (this is not counted as a turn). - Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color.
This problem was inspired by the game Flood-it. It is apparently NP-hard. You can try out the game here. https://www.chiark.greenend.org.uk/\%7Esgtatham/puzzles/js/flood.html The first solution is rather straightforward. Suppose squares $[L, R]$ are flooded, then they are either of color $c_{L}$ or $c_{R}$. We can define $d p(L,R,d i r)$ as the minimum number of moves required to make the segment $[L, R]$ monochromic: $d p\left(L,R,0\right)$ is the least moves required to make the segment having color $c_{L}$. $d p\left(L,R,1\right)$ is the least moves required to make the segment having color $c_{R}$. The second solution, which is the author's intended solution, is less so. Note that the size of the component doesn't matter, so first "compress" the array so that every adjacent elements are different. We will work on this compressed array instead. We want to maximize the number of turns that we can fill two adjacent squares instead of one. From a starting square, this maximum number of "saved" turns is equal to the longest common subsequence (LCS) of the array expanding to the two sides. The answer is the $N$ - (maximum LCS over all starting squares) This is equivalent to finding the longest odd size palindrome subsequence. In fact, it is the longest palindrome subsequence. For every even-sized palindrome subsequence, since adjacent elements are different, we can just insert an element in the middle and obtain a longer palindrome subsequence. To find the longest palindrome subsequence, we can make a reversed copy of the array and find LCS of it with the original array. Alternatively, we can also use the first solution on the compressed array, without needing the third parameter. Time complexity: $O\left(n^{2}\right)$.
[ "dp" ]
1,900
#include <bits/stdc++.h> using namespace std; const int maxN = 5008; int n; int dp[maxN][maxN]; vector<int> a(1), b; vector<int> ans; void input() { cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; if (x != a.back()) a.push_back(x); } n = a.size() - 1; b = a; reverse(b.begin() + 1, b.end()); } void solve() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (a[i] == b[j]) {dp[i][j] = dp[i-1][j-1] + 1;} else {dp[i][j] = max(dp[i-1][j], dp[i][j-1]);} } } } void output() { cout << n - (dp[n][n] + 1)/2 << '\n'; } int main() { input(); solve(); output(); return 0; }
1114
E
Arithmetic Progression
This is an interactive problem! An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($x_i - x_{i - 1}$, where $i \ge 2$) is constant — such difference is called a common difference of the sequence. That is, an arithmetic progression is a sequence of form $x_i = x_1 + (i - 1) d$, where $d$ is a common difference of the sequence. There is a secret list of $n$ integers $a_1, a_2, \ldots, a_n$. It is guaranteed that all elements $a_1, a_2, \ldots, a_n$ are between $0$ and $10^9$, inclusive. This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference ($d > 0$). For example, the list $[14, 24, 9, 19]$ satisfies this requirement, after sorting it makes a list $[9, 14, 19, 24]$, which can be produced as $x_n = 9 + 5 \cdot (n - 1)$. Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most $60$ queries of following two types: - Given a value $i$ ($1 \le i \le n$), the device will show the value of the $a_i$. - Given a value $x$ ($0 \le x \le 10^9$), the device will return $1$ if an element with a value strictly greater than $x$ exists, and it will return $0$ otherwise. Your can use this special device for at most $60$ queries. Could you please find out the smallest element and the common difference of the sequence? That is, values $x_1$ and $d$ in the definition of the arithmetic progression. Note that the array $a$ is not sorted.
The > query type allows you to find the max value of the array through binary searching, which will cost $\lceil\log_{2}(10^{9})\rceil=30$ queries. The remaining queries will be spent for the queries of the ? type to get some random elements of the array. $d$ will be calculated as greatest common divisors of all difference between all consecutive elements, provided all elements found (yes, including the max one) is kept into a list sorted by increasing order. Having d and max, we can easily find the min value: $min = max - d \cdot (n - 1)$. The number of allowed queries seem small ($30$ queries to be exact), yet it's enough for us to have reasonable probability of passing the problem. By some maths, we can find out the probability of our solution to fail being relatively small - approximately $1.86185 \cdot 10^{ - 9}$. For simplicity, assumed that the sequence $a$ is $[0, 1, 2, ..., n - 1]$. Suppose that we randomly (and uniformly) select a subsequence $S$ containing $k$ elements from sequence $a$ (when $k$ is the number of ? query asked). Denote $S = [s_{1}, s_{2}, ..., s_{k}]$. Let $D$ the GCD of all difference between consecutive elements in $S$. In other word, $D=\operatorname*{gcd}(s_{i}-s_{i-1}\mid2\leq i\leq k)$. Our solution will success if $D = 1$ and will fail otherwise. Let $P$ the probability that our solution will pass ($D = 1$). Then the failing probability is $1 - P$. We will apply Möbius inversion to calculate $P$: Let $f(x)$ the probability that $D$ is divisible by $x$. Then, $P=\sum_{i=1}^{n}f(i)\cdot\mu(i)$ (where $ \mu (x)$ is the Möbius function). Now we need to calculate $f(x)$. It can be shown that $D$ is divisible by $x$ if and only if $s_{i}\equiv s_{i-1}(\mathrm{\boldmath~\mod~}x)$ for all $2 \le i \le k$. In other word, there is some $r$ from $0$ to $x - 1$ such that $s_{i}\equiv r\left(\begin{array}{l}{{\mathrm{mod}\ x\right)}}\end{array}\right.$ for all $1 \le i \le k$. Let $g(r)$ the number of ways to select a subsequence $S$ such that $s_{i}\equiv r\left(\begin{array}{l}{{\mathrm{\mod}\ x\right)}}\end{array}\right.$ for all $1 \le i \le k$. Then, according to definition: $f(x)=\frac{\displaystyle\sum_{r=0}^{x-1}g(r)}{\displaystyle\frac{\displaystyle\sum_{r=0}^{x-1}g(r)}{\displaystyle\mathrm{number~of~way~to~subsequence~}}s}.$ The denominator is simply $\binom{k}{n}$. To calculate $g(r)$, notice that for each $i$, the value of $s_{i}$ can be $x \cdot j + r$ for some integer $j$. In other word, $S$ must be a subsequence of the sequence $a_{r} = [r, x + r, 2x + r, ...]$. Let $q=\left\lfloor{\frac{n}{x}}\right\rfloor$. If $r<n\ \ \mathrm{mod}\ x$, $a_{r}$ has $q + 1$ elements. Therefore, $g(r)={\binom{k}{q+1}}$ If $n\mathrm{\mod\}x\leq r<x$, $a_{r}$ has $q$ elements. Therefore, $g(r)=\left(k_{q}\right)$. In summary: $f(x)={\frac{\sum_{r=0}^{x-1}g(r)}{\binom{k}{n}}}={\frac{(n{\pmod{x}}\cdot{\binom{k}{q+1}}+(n-n\mathrm{\mod}\ x)\cdot\binom{k}{q}}{k}}$ The complexity of this calculating method is $O(n)$. My implementation of the above method can be found here. Keep in mind to use a good random number generator and a seed which is hard to obtain, thus making your solution truly random and not falling into corner cases. Some of the tutorials of neal might be helpful: Don't use rand(): a guide to random number generators in C++ How randomized solutions can be hacked, and how to make your solution unhackable
[ "binary search", "interactive", "number theory", "probabilities" ]
2,200
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); int n, Max = -1000000000, d = 0; int queryRemaining = 60; vector<int> id; void findMax() { int top = -1000000000, bot = +1000000000; while (top <= bot) { int hasHigher; int mid = (top + bot) / 2; cout << "> " << mid << endl; fflush(stdout); cin >> hasHigher; queryRemaining--; if (hasHigher) top = mid + 1; else {bot = mid - 1; Max = mid;} } } void findD() { vector<int> List; int RandomRange = n; while (queryRemaining > 0 && RandomRange > 0) { int demandedIndex = rng32() % RandomRange; cout << "? " << id[demandedIndex] << endl; fflush(stdout); int z; cin >> z; List.push_back(z); RandomRange--; queryRemaining--; swap(id[demandedIndex], id[RandomRange]); } sort(List.begin(), List.end()); if (List.back() != Max) List.push_back(Max); for (int i=1; i<List.size(); i++) { d = __gcd(d, List[i] - List[i-1]); } } void Input() { cin >> n; id.resize(n); for (int i=0; i<n; i++) id[i] = i+1; } void Solve() { findMax(); findD(); int Min = Max - d * (n - 1); cout << "! " << Min << " " << d; cout << endl; fflush(stdout); } int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); Input(); Solve(); return 0; }
1114
F
Please, another Queries on Array?
You are given an array $a_1, a_2, \ldots, a_n$. You need to perform $q$ queries of the following two types: - "MULTIPLY l r x" — for every $i$ ($l \le i \le r$) multiply $a_i$ by $x$. - "TOTIENT l r" — print $\varphi(\prod \limits_{i=l}^{r} a_i)$ taken modulo $10^9+7$, where $\varphi$ denotes Euler's totient function. The Euler's totient function of a positive integer $n$ (denoted as $\varphi(n)$) is the number of integers $x$ ($1 \le x \le n$) such that $\gcd(n,x) = 1$.
There's a few fundamentals about Euler's totient we need to know: $ \phi (p) = p - 1$ and $ \phi (p^{k}) = p^{k - 1} \cdot (p - 1)$, provided $p$ is a prime number and $k$ is a positive integer. You can easily prove these equations through the definition of the function itself. Euler's totient is a multiplicative function. $f(x)$ is considered a multiplicative function when $\operatorname*{gcd}(a,b)=1$ means $f(a) \cdot f(b) = f(a \cdot b)$. Keep in mind that we can rewrite $ \phi (p^{k})$ as of following: $\varphi(p^{k})=p^{k}\cdot{\frac{p-1}{p}}$. Let's denote $P$ as the set of prime factors of $\prod_{i=l}^{r}a_{i}$. Thus, the answer for each query will simply be: $\varphi(\prod_{i=l}^{r}a_{i})=\prod_{i=l}^{r}a_{i}\cdot\prod_{p\in P}{\frac{p-1}{p}}$. So, for each query we'll need to know the product of the elements, and which primes are included in that product. There are a few ways to work around with it. One of the most effective way is as following: Create a product segment tree to maintain the segment products. Since $\prod_{p\in P}{\frac{p-1}{p}}$ only depends on the appearance or non-appearance of the primes, and the constraints guaranteed us to have at most $62$ prime factors, we can use bitmasks and an or-sum segment tree to maintain this part. Also, the bitmasks and range products can be maintained in a sqrt-decomposition fashion (please refer to GreenGrape's solution), making each query's complexity to be somewhat around $O\left({\sqrt{n}}\right)$. Still, this complexity is quite high and surpassed time limit on a pretty thin margin. Complexity for initializing segment trees: $O\left(n\cdot\log(n)\right)$. Complexity for each update query: $O\left(62+\log^{2}(n)\right)$. Complexity for each return query: $O\left(62+\log^{2}(n)\right)$.
[ "bitmasks", "data structures", "divide and conquer", "math", "number theory" ]
2,400
#define _CRT_SECURE_NO_WARNINGS #pragma GCC optimize("unroll-loops") #include <iostream> #include <algorithm> #include <vector> #include <ctime> #include <unordered_set> #include <string> #include <map> #include <unordered_map> #include <random> #include <set> #include <cassert> #include <functional> #include <iomanip> #include <queue> #include <numeric> #include <bitset> #include <iterator> using namespace std; const int N = 100001; mt19937 gen(time(NULL)); #define forn(i, n) for (int i = 0; i < n; i++) #define ford(i, n) for (int i = n - 1; i >= 0; i--) #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define all(a) (a).begin(), (a).end() #define pii pair<int, int> #define mp make_pair #define endl '\n' #define vi vector<int> typedef long long ll; template<typename T = int> inline T read() { T val = 0, sign = 1; char ch; for (ch = getchar(); ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') sign = -1; for (; ch >= '0' && ch <= '9'; ch = getchar()) val = val * 10 + ch - '0'; return sign * val; } const int mod = 1e9 + 7; const int phi = 1e9 + 6; const int M = 301, B = 500; int P = 0; inline int mul(int a, int b) { return (a * 1LL * b) % mod; } int mpow(int u, int p) { if (!p) return 1; return mul(mpow(mul(u, u), p / 2), (p & 1) ? u : 1); } vector<int> primes; vector<int> pi; int pw[M]; int lg[N]; bool pr(int x) { if (x <= 1) return false; for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } void precalc() { forn(i, M) if (pr(i)) { primes.push_back(i); P++; } pi.resize(P); forn(i, M) { int x = 1; forn(j, B) { x = mul(x, i); } pw[i] = x; } forn(i, P) pi[i] = mpow(primes[i], phi - 1); } struct product_tree { vector<int> arr, block_product, block_update, single_update; int n; product_tree(vector<int>& a) : n(a.size()) { arr = a; while (n % B) { n++, arr.push_back(1); } block_product.resize(n / B, 1); block_update.resize(n / B, -1); single_update.resize(n / B, -1); for (int i = 0; i < n; i += B) { int x = 1; int pos = i / B; forn(j, B) x = mul(x, arr[i + j]); block_product[pos] = x; } } inline void add(int& u, int x, int mode) { if (mode) { if (u == -1) u = x; else u = mul(u, x); } else { if (u == -1) u = pw[x]; else u = mul(u, pw[x]); } } void update(int pos, int x) { add(block_update[pos], x, 0); add(single_update[pos], x, 1); } void reconstruct(int pos) { int e = single_update[pos]; if (e == -1) return; int x = 1; int l = pos * B, r = l + B; for (int i = l; i < r; i++) { arr[i] = mul(arr[i], e); x = mul(x, arr[i]); } single_update[pos] = block_update[pos] = -1; block_product[pos] = x; } void apply(int l, int r, int x) { int L = l / B, R = r / B; if (L == R) { reconstruct(L); for (int i = l; i <= r; i++) { arr[i] = mul(arr[i], x); block_product[L] = mul(block_product[L], x); } return; } reconstruct(L); for (int i = l; i < (L + 1) * B; i++) { arr[i] = mul(arr[i], x); block_product[L] = mul(block_product[L], x); } reconstruct(R); for (int i = R * B; i <= r; i++) { arr[i] = mul(arr[i], x); block_product[R] = mul(block_product[R], x); } for (int j = L + 1; j < R; j++) update(j, x); } int get(int l, int r) { int L = l / B, R = r / B; int ans = 1; if (L == R) { reconstruct(L); for (int i = l; i <= r; i++) { ans = mul(ans, arr[i]); } return ans; } reconstruct(L); for (int i = l; i < (L + 1) * B; i++) { ans = mul(ans, arr[i]); } reconstruct(R); for (int i = R * B; i <= r; i++) { ans = mul(ans, arr[i]); } for (int j = L + 1; j < R; j++) { ans = mul(ans, block_product[j]); if (block_update[j] != -1) ans = mul(ans, block_update[j]); } return ans; } }; struct prime_tree { vector<ll> t, d; int n; prime_tree(vector<ll>& a) : n(a.size()) { t.resize(4 * n); d.resize(4 * n, -1); build(1, 0, n, a); } ll build(int u, int l, int r, vector<ll>& a) { if (l == r - 1) { return t[u] = a[l]; } int m = (l + r) / 2; return t[u] = build(u << 1, l, m, a) | build(u << 1 | 1, m, r, a); } inline void add(ll& u, ll x) { if (u == -1) u = x; else u |= x; } void push(int u, int l, int r) { if (d[u] == -1) return; t[u] |= d[u]; if (r - l > 1) { add(d[u << 1], d[u]); add(d[u << 1 | 1], d[u]); } d[u] = -1; } void update(int u, int l, int r, int L, int R, ll x) { push(u, l, r); if (L >= R || l > L || r < R) return; if (l == L && r == R) { add(d[u], x); push(u, l, r); return; } int m = (l + r) / 2; update(u << 1, l, m, L, min(m, R), x); update(u << 1 | 1, m, r, max(L, m), R, x); t[u] = t[u << 1] | t[u << 1 | 1]; } ll get(int u, int l, int r, int L, int R) { push(u, l, r); if (L >= R || l > L || r < R) return 0; if (l == L && r == R) { return t[u]; } int m = (l + r) / 2; return get(u << 1, l, m, L, min(m, R)) | get(u << 1 | 1, m, r, max(L, m), R); } ll get(int l, int r) { return get(1, 0, n, l, r + 1); } void apply(int l, int r, ll x) { update(1, 0, n, l, r + 1, x); } }; ll transform(int x) { ll mask = 0; forn(i, P) if (x % primes[i] == 0) { mask |= (1LL << i); } return mask; } void solve() { int n, q; cin >> n >> q; vi a(n); vector<ll> _a; for (auto& v : a) { cin >> v; _a.push_back(transform(v)); } auto Ptree = product_tree(a); auto Mtree = prime_tree(_a); int l, r, x; forn(i, q) { string s; cin >> s; if (s == "MULTIPLY") { cin >> l >> r >> x; l--, r--; Ptree.apply(l, r, x); Mtree.apply(l, r, transform(x)); } else { cin >> l >> r; l--, r--; int product = Ptree.get(l, r); ll mask = Mtree.get(l, r); forn(j, 63) if (mask >> j & 1) { product = mul(product, primes[j] - 1); product = mul(product, pi[j]); } cout << product << endl; } } } signed main() { int t = 1; ios_base::sync_with_stdio(0); cin.tie(0); precalc(); while (t--) { clock_t z = clock(); solve(); debug("Total Time: %.3f\n", (double)(clock() - z) / CLOCKS_PER_SEC); } }
1117
A
Best Subsegment
You are given array $a_1, a_2, \dots, a_n$. Find the subsegment $a_l, a_{l+1}, \dots, a_r$ ($1 \le l \le r \le n$) with maximum arithmetic mean $\frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i}$ (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the \textbf{longest} one.
There is a property of arithmetic mean: $\frac{1}{k}\sum\limits_{i=1}^{k}{c_i} \le \max\limits_{1 \le i \le k}{c_i}$ and the equality holds when $c_1 = c_2 = \dots = c_k$. Obviously, we can always gain maximum arithmetic mean equal to $\max\limits_{1 \le i \le n}{a_i}$ by taking single maximum element from $a$. Considering the property above, we need to take only maximum elements in our subsegment, that's why we need to find the longest subsegment consisting only of maximum elements.
[ "implementation", "math" ]
1,100
#include<iostream> using namespace std; int main() { int n; cin >> n; int mx = -1, lenMx = 0; int curEl = -1, curLen = 0; for(int i = 0; i < n; i++) { int a; cin >> a; if(curEl != a) curEl = a, curLen = 0; curLen++; if(mx < curEl) mx = curEl, lenMx = 0; if(mx == curEl) lenMx = max(lenMx, curLen); } cout << lenMx << endl; return 0; }
1117
B
Emotes
There are $n$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $i$-th emote increases the opponent's happiness by $a_i$ units (we all know that emotes in this game are used to make opponents happy). You have time to use some emotes only $m$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you \textbf{cannot use the same emote more than $k$ times in a row} (otherwise the opponent will think that you're trolling him). \textbf{Note that two emotes $i$ and $j$ ($i \ne j$) such that $a_i = a_j$ are considered different}. You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.
It is obvious that we always can use only two emotes with maximum $a_i$. Let their values be $x$ and $y$ ($x \ge y$). We have to solve the problem by some formula. The best way to use emotes - use the emote with the value $x$ $k$ times, then use the emotion with the value $y$, then again use the emote with value $x$ $k$ times, and so on. So the "cycle" has length $k+1$, and we can use the emote with the value $x$ the remaining number of times. So the answer is $\lfloor\frac{m}{k+1}\rfloor \cdot (x \cdot k + y) + (m \% (k + 1)) \cdot x$, where $x$ is the first maximum of $a$, $y$ is the second maximum of $a$, $\lfloor\frac{p}{q}\rfloor$ is $p$ divided by $q$ rounded down, and $p \% q$ is $p$ modulo $q$.
[ "greedy", "math", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, k; cin >> n >> m >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); cout << m / (k + 1) * 1ll * (a[0] * 1ll * k + a[1]) + m % (k + 1) * 1ll * a[0] << endl; return 0; }
1117
C
Magic Ship
You a captain of a ship. Initially you are standing in a point $(x_1, y_1)$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $(x_2, y_2)$. You know the weather forecast — the string $s$ of length $n$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $s_1$, the second day — $s_2$, the $n$-th day — $s_n$ and $(n+1)$-th day — $s_1$ again and so on. Ship coordinates change the following way: - if wind blows the direction U, then the ship moves from $(x, y)$ to $(x, y + 1)$; - if wind blows the direction D, then the ship moves from $(x, y)$ to $(x, y - 1)$; - if wind blows the direction L, then the ship moves from $(x, y)$ to $(x - 1, y)$; - if wind blows the direction R, then the ship moves from $(x, y)$ to $(x + 1, y)$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $(x, y)$ it will move to the point $(x - 1, y + 1)$, and if it goes the direction U, then it will move to the point $(x, y + 2)$. You task is to determine the minimal number of days required for the ship to reach the point $(x_2, y_2)$.
Note, that if we can reach the destination in $x$ days, so we can reach it in $y \ge x$ days, since we can stay in the destination point by moving to the opposite to the wind direction. So, we can binary search the answer. To check the possibility to reach the destination point $(x_2, y_2)$ in $k$ days we should at first look at the position $(x_3, y_3)$ the wind moves ship to. Now we can calculate where we can go: since each day we can move in one of four directions or not move at all, we can reach any point $(x, y)$ with Manhattan distance $|x - x_3| + |y - y_3| \le k$. So we need to check that $|x_2 - x_3| + |y_2 - y_3| \le k$. To calculate $(x_3, y_3)$ we can note, that there were $\lfloor \frac{k}{n} \rfloor$ full cycles and $k \bmod n$ extra days. So it can be calculated with $O(1)$ time using prefix sums. Finally, about borders of binary search: to reach the destination point we need to move closer at least by one (it terms of Manhattan distance) from the full cycle of the wind. So, if answer exists then it doesn't exceed $(|x_1 - x_2| + |y_1 - y_2|) \cdot n \le 2\cdot 10^{14}$.
[ "binary search" ]
1,900
#include <bits/stdc++.h> using namespace std; #define x first #define y second const int N = 100009; pair<int, int> st, fi; int n; string s; string mv = "UDLR"; int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; pair<int, int> d[N]; int main(){ cin >> st.x >> st.y >> fi.x >> fi.y; cin >> n >> s; for(int i = 0; i < n; ++i){ int id = -1; for(int j = 0; j < 4; ++j) if(mv[j] == s[i]) id = j; assert(id != -1); d[i + 1] = make_pair(d[i].x + dx[id], d[i].y + dy[id]); } long long l = 0, r = 1e18; while(r - l > 1){ long long mid = (l + r) / 2; long long cnt = mid / n, rem = mid % n; long long x = st.x + d[rem].x + cnt * 1LL * d[n].x; long long y = st.y + d[rem].y + cnt * 1LL * d[n].y; long long dist = abs(x - fi.x) + abs(y - fi.y); if(dist <= mid) r = mid; else l = mid; } if(r > 5e17) r = -1; cout << r << endl; return 0; }
1117
D
Magic Gems
Reziba has many magic gems. Each magic gem can be split into $M$ normal gems. The amount of space each magic (and normal) gem takes is $1$ unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is $N$ units. If a magic gem is chosen and split, it takes $M$ units of space (since it is split into $M$ gems); if a magic gem is not split, it takes $1$ unit. How many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is $N$ units? Print the answer modulo $1000000007$ ($10^9+7$). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ.
Let's reformulate the solution to the form of dynamic programming. $dp_n$ - the number of ways to split the gems so that the total amount of space taken is $n$. Then there are obvious transitions of either splitting the last gem or not. $dp_n = dp_{n - m} + dp_{n - 1}$. And that can be easily rewritten in such a way that matrix exponentiation becomes the solution. Overall complexity: $O(m^3 \cdot \log n)$.
[ "dp", "math", "matrices" ]
2,100
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second #define MOD 1000000007 #define MOD9 1000000009 #define pi 3.1415926535 #define ms(s, n) memset(s, n, sizeof(s)) #define prec(n) fixed<<setprecision(n) #define eps 0.000001 #define all(v) v.begin(), v.end() #define allr(v) v.rbegin(), v.rend() #define bolt ios::sync_with_stdio(0) #define light cin.tie(0);cout.tie(0) #define forr(i,p,n) for(ll i=p;i<n;i++) #define MAXN 1000003 typedef long long ll; using namespace std; ll mult(ll a,ll b, ll p=MOD){return ((a%p)*(b%p))%p;} ll add(ll a, ll b, ll p=MOD){return (a%p + b%p)%p;} ll fpow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1) {if (k & 1) r = r * n%p; n = n * n%p;} return r;} ll inv(ll a, ll p = MOD) {return fpow(a, p - 2, p);} ll inv_euclid(ll a, ll m = MOD){ll m0 = m;ll y = 0, x = 1;if (m == 1)return 0;while (a > 1){ll q = a / m;ll t = m;m = a % m, a = t;t = y;y = x - q * y;x = t;}if (x < 0)x += m0;return x;} ll bin[103][103]; void mult_mat(ll m, ll ans[][100], ll bin[][100]){ ll mult[m][m]; forr(i,0,m){ forr(j,0,m){ mult[i][j]=0; forr(k,0,m){ mult[i][j]+=ans[i][k]*bin[k][j]; if(mult[i][j]>=MOD){ mult[i][j]%=MOD; } } } } forr(i,0,m){ forr(j,0,m){ ans[i][j]=mult[i][j]; } } } void pow_mat(ll n, ll fin[][100], ll m){ ll ans[m][100]; ll b[m][100]; forr(i,0,m){ forr(j,0,m){ ans[i][j]=bin[i][j]; b[i][j]=bin[i][j]; } } n--; while(n>0){ if(n%2==1){ mult_mat(m,ans,b); n--; }else{ n=n/2; mult_mat(m,b,b); } } forr(i,0,m){ forr(j,0,m){ fin[i][j]=ans[i][j]; } } } int main(){ bolt; ll n,m; cin>>n>>m; bin[0][0]=1; bin[0][m-1]=1; for(ll i=1;i<m;i++){ bin[i][i-1]=1; } if(n<m){ cout<<1<<"\n"; }else{ ll fin[m+1][100]; pow_mat(n-m+1,fin,m); ll ans=0; forr(i,0,m){ ans+=fin[0][i]; if(ans>=MOD){ ans-=MOD; } } cout<<ans<<"\n"; } }
1117
E
Decypher the String
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307. You are given a string $t$ consisting of $n$ lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string $s$ consisting of $n$ lowercase Latin letters. Then they applied a sequence of no more than $n$ (possibly zero) operations. $i$-th operation is denoted by two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$), and means swapping two elements of the string with indices $a_i$ and $b_i$. All operations were done in the order they were placed in the sequence. For example, if $s$ is xyz and $2$ following operations are performed: $a_1 = 1, b_1 = 2$; $a_2 = 2, b_2 = 3$, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so $t$ is yzx. You are asked to restore the original string $s$. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is $n$, and get the resulting string after those operations. Can you guess the original string $s$ asking the testing system to run the sequence of swaps no more than $3$ times? \textbf{The string $s$ and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution}.
Since a sequence of swaps denotes some permutation, let's try to restore the permutation $p$ that was used to transform $s$ into $t$, and then get $s$ by applying inverse permutation. If $n$ was $26$ or less, then we could get $p$ just by asking one query: send a string where no character occurs twice, and the resulting positions of characters uniquely determine the permutation. Unfortunately, $n$ may be greater than $26$ - but we can ask more than one query. The main idea is the following: for each index $i \in [1, n]$, we may choose a triple of characters, so all triples are distinct. There are $26^3$ different triples, and that's greater than $10^4$, so each index can be uniquely determined. Then, after we choose a triple for each index, ask three queries as follows: in the first query, the $i$-th character of the string is the first character in the triple representing index $i$; in the second query we use the second characters from all triples, and in the third query - the third characters. Let $s_1$, $s_2$ and $s_3$ be the strings we sent, and $t_1$, $t_2$ and $t_3$ be the strings we received as answers. The permutation maps index $i$ to index $j$ if and only if $s_1[i] = t_1[j]$, $s_2[i] = t_2[j]$ and $s_3[i] = t_3[j]$ - because if some other index is mapped to $j$, then at least one of the aforementioned equalities is false since all triples of characters are distinct. Using this fact, we may recover the permutation $p$.
[ "bitmasks", "chinese remainder theorem", "constructive algorithms", "interactive", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { string t; cin >> t; int n = t.size(); string s1(n, 'a'), s2(n, 'a'), s3(n, 'a'); for(int i = 0; i < n; i++) { s1[i] = char('a' + (i % 26)); s2[i] = char('a' + ((i / 26) % 26)); s3[i] = char('a' + ((i / 26 / 26) % 26)); } cout << "? " << s1 << endl; string t1; cin >> t1; cout << "? " << s2 << endl; string t2; cin >> t2; cout << "? " << s3 << endl; string t3; cin >> t3; vector<int> p(n); for(int i = 0; i < n; i++) p[i] = (t1[i] - 'a') + (t2[i] - 'a') * 26 + (t3[i] - 'a') * 26 * 26; string s(n, 'a'); for(int i = 0; i < n; i++) s[p[i]] = t[i]; cout << "! " << s << endl; return 0; }
1117
F
Crisp String
You are given a string of length $n$. Each character is one of the first $p$ lowercase Latin letters. You are also given a matrix $A$ with binary values of size $p \times p$. This matrix is symmetric ($A_{ij} = A_{ji}$). $A_{ij} = 1$ means that the string can have the $i$-th and $j$-th letters of Latin alphabet adjacent. Let's call the string crisp if \textbf{all of the adjacent characters} in it can be adjacent (have 1 in the corresponding cell of matrix $A$). You are allowed to do the following move. Choose any letter, remove \textbf{all its occurrences} and join the remaining parts of the string without changing their order. For example, removing letter 'a' from "abacaba" will yield "bcb". The string you are given is crisp. The string should remain crisp \textbf{after every move you make}. You are allowed to do arbitrary number of moves (possible zero). What is the shortest resulting string you can obtain?
Each state of the string can be denoted as the set of characters we deleted from it, and each such set can be represented as a $p$-bit binary mask, where $i$-th bit is equal to $0$ if $i$-th character of the alphabet is already deleted, and $1$ otherwise. Let's call a mask bad if the string formed by this mask is not crisp. Let's also say that a pair of characters $a, b$ forbids mask $m$ if $a, b$ is a pair of characters that should not be adjacent, but they are adjacent in the string formed by mask $m$. If we somehow find all bad masks, then the solution would be writing simple bitmask dp to find the best mask that is not bad and reachable from the initial mask (the one having all bits set to $1$). So let's focus on finding all bad masks. Obviously, if some pair of characters forbids a mask, then it's bad, and vice versa. Let's pick some pair of characters $a, b$ and find all masks forbidden by it (we will do the same for every pair of characters that cannot be adjacent). Let's check every occurence of $a$ in the initial string. For each occurence, we will find the closest occurence of $b$ to the right of it. If there's no any, or if there's another $a$ between them, let's ignore the occurence of $a$ we have chosen and move to the next one. Otherwise, let's find all characters that occur at least once between the fixed occurences of $a$ and $b$. If all those characters are deleted, then these occurences of $a$ and $b$ will be adjacent - so pair $a, b$ forbids any mask that has bits representing $a$ and $b$ set to $1$, bits representing every character occuring in between to $0$, and all other bits to any values. Let's mark all these masks as forbidden as follows: we will write a recursive function $mark(m, a, b)$ that marks mask $m$ and every its submask that has bits $a$ and $b$ set to $1$ as forbidden. This function should check if $m$ is not forbidden; if not, then mark it as forbidden, iterate on the bit $i$ we may remove from $m$, and call $mark(m \oplus 2^i, a, b)$ recursively (but only if $i$ is set to $1$ in mask $m$, and if $i \ne a$ and $i \ne b$). If we implement it in such a way, then for each pair $a, b$, it will take $O(n + p 2^p)$ operations to mark all masks forbidden by this pair of characters, so overall complexity will be $O(np^2 + p^3 2^p)$ or $O(np + p^3 2^p)$, depending on your implementation.
[ "bitmasks", "dp" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 100 * 1000 + 13; const int P = 17; int n, p; string s; int A[P][P]; vector<int> pos[P]; int pr[P][N]; bitset<(1 << P)> legal, cur, dp; int cnt[P]; int main() { scanf("%d%d", &n, &p); char buf[N]; scanf("%s", buf); s = buf; forn(i, p) forn(j, p) scanf("%d", &A[i][j]); forn(i, n){ pos[s[i] - 'a'].push_back(i); forn(j, p) pr[j][i + 1] = pr[j][i] + (s[i] == 'a' + j); } legal.reset(); legal.flip(); int fl = (1 << p) - 1; forn(c, p) forn(d, c + 1){ if (A[c][d]) continue; cur.reset(); cur.flip(); int i = 0, j = 0; while (i < pos[c].size() && j < pos[d].size()){ if (c == d && i == j){ ++j; continue; } int mask = 0; if (pos[c][i] < pos[d][j]){ forn(e, p) if ((pr[e][pos[d][j]] - pr[e][pos[c][i] + 1]) != 0) mask |= (1 << e); ++i; } else{ forn(e, p) if ((pr[e][pos[c][i]] - pr[e][pos[d][j] + 1]) != 0) mask |= (1 << e); ++j; } if ((mask >> c) & 1) continue; if ((mask >> d) & 1) continue; cur[mask ^ fl] = 0; } for (int mask = fl; mask > 0; --mask){ if (cur[mask]) continue; forn(e, p) if (c != e && d != e && ((mask >> e) & 1)) cur[mask ^ (1 << e)] = 0; } legal &= cur; } dp[fl] = 1; for (int mask = fl; mask > 0; --mask){ if (!dp[mask]) continue; forn(i, p) if ((mask >> i) & 1){ int nmask = mask ^ (1 << i); if (dp[nmask]) continue; dp[nmask] = legal[nmask]; } } forn(i, n) ++cnt[s[i] - 'a']; int ans = n; forn(mask, 1 << p) if (dp[mask]){ int cur = 0; forn(i, p) if ((mask >> i) & 1) cur += cnt[i]; ans = min(ans, cur); } printf("%d\n", ans); return 0; }
1117
G
Recursive Queries
You are given a permutation $p_1, p_2, \dots, p_n$. You should answer $q$ queries. Each query is a pair $(l_i, r_i)$, and you should calculate $f(l_i, r_i)$. Let's denote $m_{l, r}$ as the position of the maximum in subsegment $p_l, p_{l+1}, \dots, p_r$. Then $f(l, r) = (r - l + 1) + f(l, m_{l,r} - 1) + f(m_{l,r} + 1, r)$ if $l \le r$ or $0$ otherwise.
Let's denote $fl(l, r) = (m_{l,r} - l) + fl(l, m_{l,r} - 1) + fl(m_{l,r} + 1, r)$ and, analogically, $fr(l, r) = (r - m_{l,r}) + fr(l, m_{l,r} - 1) + fr(m_{l,r} + 1, r)$. Then, we can note that $f(l, r) = (r - l + 1) + fl(l, r) + fr(l, r)$. So we can switch to calculating $fl$ (and $fr$). Let's $lf[i]$ be the closest from the left to $i$ element such that $a[lf[i]] > a[i]$. To calculate $fl(l, r)$ we will look from the other side: we will look at it as the sum of lengths of segments induced by each element from $[l, r]$. Each element $a_i$ ($l \le i \le r)$ will add to $fl(l, r)$ value equal to $\min(i - lf[i] - 1, i - l)$, or a piecewise linear function if we look at $l$ as a variable. And $fl(l, r)$ is a value of a sum of linear functions induced by $a[i]$ in a point $x = l$. To process it efficiently we can one by one add induced linear functions to the corresponding subsegments using BIT or Segment Tree and if we've added functions induced by $a[k]$ we can calculate answer for all queries which looks like $(l_i, k)$. To calculate $fr(l, r)$ we can just reverse array and all queries. Result time complexity is $O((n + q) \log{n})$. Note, that it's still works quite slow, so you should use fast data structures like BIT of iterative segment tree.
[ "data structures" ]
2,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; int n, q; vector<int> a; vector< pair<pt, int> > qs; inline bool read() { if(!(cin >> n >> q)) return false; a.resize(n); qs.resize(q); fore(i, 0, n) cin >> a[i]; fore(i, 0, q) { cin >> qs[i].x.x; qs[i].x.x--; } fore(i, 0, q) { cin >> qs[i].x.y; qs[i].x.y--; qs[i].y = i; } return true; } bool cmp(const pair<pt, int> &a, const pair<pt, int> &b) { if(a.x.y != b.x.y) return a.x.y < b.x.y; if(a.x.x != b.x.x) return a.x.x < b.x.x; return a.y < b.y; } typedef pair<li, li> func; func operator +=(func &a, const func &b) { a.x += b.x, a.y += b.y; return a; } vector<func> t; void add(int l, int r, const func &f) { for(l += n, r += n; l < r; l >>= 1, r >>= 1) { if(l & 1) t[l++] += f; if(r & 1) t[--r] += f; } } func sum(int pos) { func ans(0, 0); for(pos += n; pos > 0; pos >>= 1) ans += t[pos]; return ans; } inline void solve() { vector<li> ans(q, 0); fore(i, 0, q) ans[i] = qs[i].x.y - qs[i].x.x + 1; fore(_, 0, 2) { vector<int> st; vector<int> lf(n, -1); fore(i, 0, n) { while(!st.empty() && a[st.back()] < a[i]) st.pop_back(); if(!st.empty()) lf[i] = st.back(); st.push_back(i); } sort(qs.begin(), qs.end(), cmp); t.assign(2 * n, {0, 0}); int uk = 0; fore(i, 0, n) { add(0, lf[i] + 1, {0, i - lf[i] - 1}); add(lf[i] + 1, i, {-1, i}); while(uk < q && qs[uk].x.y == i) { auto f = sum(qs[uk].x.x); ans[qs[uk].y] += f.x * qs[uk].x.x + f.y; uk++; } } reverse(a.begin(), a.end()); for(auto &p : qs) { p.x.x = n - 1 - p.x.x; p.x.y = n - 1 - p.x.y; swap(p.x.x, p.x.y); } } for(auto v : ans) cout << v << ' '; cout << 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; }
1118
A
Water Buying
Polycarp wants to cook a soup. To do it, he needs to buy exactly $n$ liters of water. There are only two types of water bottles in the nearby shop — $1$-liter bottles and $2$-liter bottles. There are infinitely many bottles of these two types in the shop. The bottle of the first type costs $a$ burles and the bottle of the second type costs $b$ burles correspondingly. Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $n$ liters of water in the nearby shop if the bottle of the first type costs $a$ burles and the bottle of the second type costs $b$ burles. You also have to answer $q$ independent queries.
The answer can be calculated by easy formula: $\lfloor\frac{n}{2}\rfloor \cdot min(2a, b) + (n~ \%~ 2) \cdot a$, where $\lfloor\frac{x}{y}\rfloor$ is $x$ divided by $y$ rounded down and $x~ \%~ y$ is $x$ modulo $y$.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { long long n; int a, b; cin >> n >> a >> b; cout << (n / 2) * min(2 * a, b) + (n % 2) * a << endl; } return 0; }
1118
B
Tanya and Candies
Tanya has $n$ candies numbered from $1$ to $n$. The $i$-th candy has the weight $a_i$. She plans to eat exactly $n-1$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, \textbf{exactly one candy per day}. Your task is to find the number of such candies $i$ (let's call these candies \textbf{good}) that if dad gets the $i$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one. For example, $n=4$ and weights are $[1, 4, 3, 3]$. Consider all possible cases to give a candy to dad: - Tanya gives the $1$-st candy to dad ($a_1=1$), the remaining candies are $[4, 3, 3]$. She will eat $a_2=4$ in the first day, $a_3=3$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $4+3=7$ and in even days she will eat $3$. Since $7 \ne 3$ this case shouldn't be counted to the answer (this candy isn't \textbf{good}). - Tanya gives the $2$-nd candy to dad ($a_2=4$), the remaining candies are $[1, 3, 3]$. She will eat $a_1=1$ in the first day, $a_3=3$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $3$. Since $4 \ne 3$ this case shouldn't be counted to the answer (this candy isn't \textbf{good}). - Tanya gives the $3$-rd candy to dad ($a_3=3$), the remaining candies are $[1, 4, 3]$. She will eat $a_1=1$ in the first day, $a_2=4$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $4$. Since $4 = 4$ this case \textbf{should be counted} to the answer (this candy is \textbf{good}). - Tanya gives the $4$-th candy to dad ($a_4=3$), the remaining candies are $[1, 4, 3]$. She will eat $a_1=1$ in the first day, $a_2=4$ in the second day, $a_3=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $4$. Since $4 = 4$ this case \textbf{should be counted} to the answer (this candy is \textbf{good}). In total there $2$ cases which should counted (these candies are \textbf{good}), so the answer is $2$.
Let's maintain four variables $oddPref$, $evenPref$, $oddSuf$ and $evenSuf$, which will mean the sum of $a_i$ with odd $i$ on prefix, even $i$ on prefix, odd $i$ on suffix and even $i$ on suffix. Initially, $oddPref$ and $evenPref$ are $0$, $oddSuf$ equals to the sum of $a_i$ with odd $i$ in a whole array and $evenSuf$ equals to the sum of $a_i$ with even $i$ in a whole array. Let's iterate from left to right over all elements of the array. Let's consider the current element $a_i$. If $i$ is even, then set $evenSuf := evenSuf - a_i$, otherwise let's set $oddSuf := oddSuf - a_i$. Then let's consider we give the current candy to dad. Then we have to increase the answer if $oddPref = evenSuf$ and $evenPref = oddSuf$. Then if $i$ is even then let's set $evenPref := evenPref + a_i$, otherwise let's set $oddPref := oddPref + a_i$.
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); int ePref = 0, oPref = 0, eSuf = 0, oSuf = 0; for (int i = 0; i < n; ++i) { cin >> a[i]; if (i & 1) eSuf += a[i]; else oSuf += a[i]; } int ans = 0; for (int i = 0; i < n; ++i) { if (i & 1) eSuf -= a[i]; else oSuf -= a[i]; if (ePref + oSuf == oPref + eSuf) { ++ans; } if (i & 1) ePref += a[i]; else oPref += a[i]; } cout << ans << endl; return 0; }
1118
C
Palindromic Matrix
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed. For example, the following matrices are \textbf{palindromic}: The following matrices are \textbf{not palindromic} because they change after the order of rows is reversed: The following matrices are \textbf{not palindromic} because they change after the order of columns is reversed: You are given $n^2$ integers. Put them into a matrix of $n$ rows and $n$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
Basically, what does the matrix being palindromic imply? For each $i, j$ values in cells $(i, j)$, $(i, n - j - 1)$, $(n - i - 1, j)$ and $(n - i - 1, n - j - 1)$ are equal (all zero-indexed). You can easily prove it by reversing the order of rows or columns and checking the overlapping cells in them. Thus, all cells can be split up into equivalence classes. The even $n$ case is simple: all classes have size $4$. The odd $n$ case has classes of sizes $1$, $2$ and $4$. Let's fill the classes one by one. Obviously, the order between the classes of the same size doesn't matter. I claim that filling the classes in order $4, 2, 1$ in sizes construct the answer if any exists. The key observation is that each next size is divisible by the previous one. The implementation can come in lots of different forms and complexities. Mine works in $O(MAXVAL + n^2)$, you can refer to it in attachment.
[ "constructive algorithms", "implementation" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef pair<int, int> pt; const int N = 1000 + 7; int cnt[N]; int a[20][20]; int main() { int n; scanf("%d", &n); forn(i, n * n){ int x; scanf("%d", &x); ++cnt[x]; } vector<pair<int, pt>> cells; forn(i, (n + 1) / 2) forn(j, (n + 1) / 2){ if (i != n - i - 1 && j != n - j - 1) cells.push_back({4, {i, j}}); else if ((i != n - i - 1) ^ (j != n - j - 1)) cells.push_back({2, {i, j}}); else cells.push_back({1, {i, j}}); } for (auto cur : {4, 2, 1}){ int lst = 1; for (auto it : cells){ if (it.first != cur) continue; int i = it.second.first; int j = it.second.second; while (lst < N && cnt[lst] < cur) ++lst; if (lst == N){ puts("NO"); return 0; } a[i][j] = a[n - i - 1][j] = a[i][n - j - 1] = a[n - i - 1][n - j - 1] = lst; cnt[lst] -= cur; } } puts("YES"); forn(i, n){ forn(j, n) printf("%d ", a[i][j]); puts(""); } return 0; }
1118
D1
Coffee and Coursework (Easy version)
\textbf{The only difference between easy and hard versions is the constraints}. Polycarp has to write a coursework. The coursework consists of $m$ pages. Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in \textbf{any order}. Polycarp drinks each cup \textbf{instantly} and \textbf{completely} (i.e. he cannot split any cup into several days). Surely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work. Let's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages. If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day. Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.
Since the number of days doesn't exceed $n$, let's iterate over this value (from $1$ to $n$). So now we have to check (somehow), if the current number of days is enough to write a coursework. Let the current number of days be $k$. The best way to distribute first cups of coffee for each day is to take $k$ maximums in the array. Then we have to distribute second cups for each day. Let's also take the next $k$ maximums in the remaining array, and so on. How do we can calculate such a thing easily? Let's sort the array $a$ in the reversed order (before iterating over all numbers of days), then the following formula will work fine for the current number of days $k$: $\sum\limits_{i=1}^{n}max(0, a_i - \lfloor\frac{i - 1}{k}\rfloor)$. So if the value of the formula above is greater than or equal to $m$ then the current number of days is enough. If there is no any suitable number of days, the answer is -1.
[ "brute force", "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; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); for (int i = 1; i <= n; ++i) { int sum = 0; for (int j = 0; j < n; ++j) { sum += max(a[j] - j / i, 0); } if (sum >= m) { cout << i << endl; return 0; } } cout << -1 << endl; return 0; }
1118
D2
Coffee and Coursework (Hard Version)
\textbf{The only difference between easy and hard versions is the constraints}. Polycarp has to write a coursework. The coursework consists of $m$ pages. Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup Polycarp has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in \textbf{any order}. Polycarp drinks each cup \textbf{instantly} and \textbf{completely} (i.e. he cannot split any cup into several days). Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least). Let's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages. If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day. Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.
Well, the main idea is described in the previous (D1) problem editorial. Read it firstly. So, now we have to improve our solution somehow. How can we do it? Wait... What is it? We iterate over all numbers of days... And the number of pages Polycarp can write when we consider $k+1$ days instead of $k$ is strictly increases... (because we always can drink any cup even with the minimum value of $a_i$ as a first during the new day, and the number of pages will increase). So, what is it? Oh, this is binary search! So all we need is to replace linear search to binary search, submit the written code and get AC.
[ "binary search", "greedy" ]
1,700
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> a; bool can(int i) { long long sum = 0; // there can be a bug for (int j = 0; j < n; ++j) { sum += max(a[j] - j / i, 0); } return sum >= m; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n >> m; a = vector<int>(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); int l = 1, r = n; while (r - l > 1) { int mid = (l + r) >> 1; if (can(mid)) r = mid; else l = mid; } if (can(l)) cout << l << endl; else if (can(r)) cout << r << endl; else cout << -1 << endl; return 0; }
1118
E
Yet Another Ball Problem
The king of Berland organizes a ball! $n$ pair are invited to the ball, they are numbered from $1$ to $n$. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from $1$ to $k$, inclusive. Let $b_i$ be the color of the man's costume and $g_i$ be the color of the woman's costume in the $i$-th pair. You have to choose a color for each dancer's costume (i.e. values $b_1, b_2, \dots, b_n$ and $g_1, g_2, \dots g_n$) in such a way that: - for every $i$: $b_i$ and $g_i$ are integers between $1$ and $k$, inclusive; - there are no two completely identical pairs, i.e. no two indices $i, j$ ($i \ne j$) such that $b_i = b_j$ and $g_i = g_j$ at the same time; - there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. $b_i \ne g_i$ for every $i$; - for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every $i$ from $1$ to $n-1$ the conditions $b_i \ne b_{i + 1}$ and $g_i \ne g_{i + 1}$ hold. Let's take a look at the examples of bad and good color choosing (for $n=4$ and $k=3$, man is the first in a pair and woman is the second): Bad color choosing: - $(1, 2)$, $(2, 3)$, $(3, 2)$, $(1, 2)$ — contradiction with the second rule (there are equal pairs); - $(2, 3)$, $(1, 1)$, $(3, 2)$, $(1, 3)$ — contradiction with the third rule (there is a pair with costumes of the same color); - $(1, 2)$, $(2, 3)$, $(1, 3)$, $(2, 1)$ — contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same). Good color choosing: - $(1, 2)$, $(2, 1)$, $(1, 3)$, $(3, 1)$; - $(1, 2)$, $(3, 1)$, $(2, 3)$, $(3, 2)$; - $(3, 1)$, $(1, 2)$, $(2, 3)$, $(3, 2)$. You have to find \textbf{any} suitable color choosing or say that no suitable choosing exists.
The first observation: we cannot construct more than $k(k-1)$ pairs at all due to second and third rules. The second observation: we always can construct an answer which will contain all $k(k-1)$ pairs (and get some prefix of this answer if we need less than $k(k-1)$ pairs). Ho do we do that? Let man's costumes colors be in the following order: $1, 2, \dots, k; 1, 2, \dots, k; 1, 2, \dots, k$ and so on. Now we have to set some colors to woman's costumes. The first thing comes to mind is to use some cyclic shift of $1, 2, \dots, k$. And it is the best thing we can do! So let women's costumes colors be in the following order: $2, 3, \dots, k, 1; 3, 4, \dots, k, 1, 2; 4, 5, \dots, k, 1, 2, 3$ ans so on. So we use each cyclic shift of $1, 2, \dots, k$ in order from second to last. The maximum number of pairs can be obtained when $k=447$ and the number of such pairs is $n=199362$. So now we have to prove that second, third and fourth rules are satisfied (or write a stress test, it is not so hard to do it). The easiest way to prove all rules are satisfied is the following: if some element $x$ in the left part has position $i$ (let's consider all positions modulo $k$) then each element $x$ in the right part will have all positions expect $i$ in order $i-1, i-2, \dots, i-k+1$ (you can see it from our placement). Now we can see that all rules are satisfied because of such a placement.
[ "constructive algorithms", "implementation" ]
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, k; cin >> n >> k; if (n > k * 1ll * (k - 1)) { cout << "NO" << endl; } else { cout << "YES" << endl; int cur = 0; for (int i = 0; i < n; ++i) { cur += (i % k == 0); cout << i % k + 1 << " " << (cur + i % k) % k + 1 << endl; } } return 0; }
1118
F1
Tree Cutting (Easy Version)
You are given an undirected tree of $n$ vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree?
Let's root the tree by some vertex. The edge $(v, u)$, where $v$ is the parent of $u$, is now nice if and only if the subtree of $u$ contains either all red vertices of the tree and no blue vertices or all blue vertices of the tree and no red vertices. That's because removing that edge splits the tree into the subtree of $u$ and the component of every other vertex. Thus, the task is to calculate the number of red and blue vertices in each subtree with dfs and check a couple of conditions. Overall complexity: $O(n)$.
[ "dfs and similar", "trees" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 300 * 1000 + 13; int n; int a[N]; vector<int> g[N]; int red, blue; int ans; pair<int, int> dfs(int v, int p = -1){ int r = (a[v] == 1), b = (a[v] == 2); for (auto u : g[v]) if (u != p){ auto tmp = dfs(u, v); ans += (tmp.first == red && tmp.second == 0); ans += (tmp.first == 0 && tmp.second == blue); r += tmp.first; b += tmp.second; } return make_pair(r, b); } int main() { int n; scanf("%d", &n); forn(i, n){ scanf("%d", &a[i]); red += (a[i] == 1); blue += (a[i] == 2); } forn(i, n - 1){ int v, u; scanf("%d%d", &v, &u); --v, --u; g[v].push_back(u); g[u].push_back(v); } ans = 0; dfs(0); printf("%d\n", ans); return 0; }
1118
F2
Tree Cutting (Hard Version)
You are given an undirected tree of $n$ vertices. Some vertices are colored one of the $k$ colors, some are uncolored. It is guaranteed that the tree contains at least one vertex of each of the $k$ colors. There might be no uncolored vertices. You choose a subset of \textbf{exactly $k - 1$ edges} and remove it from the tree. Tree falls apart into $k$ connected components. Let's call this subset of edges nice if none of the resulting components contain vertices of different colors. How many nice subsets of edges are there in the given tree? Two subsets are considered different if there is some edge that is present in one subset and absent in the other. The answer may be large, so print it modulo $998244353$.
Okay, this solution is really complicated and I would like to hear nicer approaches from you in comments if you have any. However, I still feel like it's ok to have this problem in a contest specifically as a harder version of F1. Let's start with the following thing. Root the tree by some vertex. For each color take all vertices of this color and paint their lowest common ancestor the same color as them. The purpose of that will come clear later. Why can we do this? The case with lca = some vertex of that color is trivial. Now, take a look at the edges from lca to its subtrees. At least two of them contain a vertex of that color. You can't cut the edges to these subtrees because this will make vertices of the same color belong to different components. Thus, lca will always be in the same component as these vertices. If lca is already painted the other color then the answer is 0. That's because lca once again make vertices of the same color belong to different components. Now everything will be calculated in a single dfs. Let $dfs(v)$ return one of the following values: $0$, if there is no colored vertex in the subtree of $v$; $x$, if there exists some color $x$ such that vertex $v$ has vertices of color $x$ in its subtree and vertex $v$ has ancestors of color $x$ (not necesserily direct parent); $-1$, otherwise. I claim that if there are multiple suitable colors for some vertex $v$ then the answer is 0. Let's take a look at any two of them and call them colors $x_1$ and $x_2$. For both colors take a path from arbitrary vertex of that color in subtree to arbitrary vertex of that color that is ancestor of $v$. You can't cut any edge on these paths because that will divide the vertices of the same color. Now, either path for color $x_1$ contains vertex of color $x_2$ or path for color $x_2$ contains vertex of color $x_1$. That vertex is the upper end of the corresponding path. That means that component of one color includes the vertex of the other color, which is impossible. Moreover, that's the last specific check for the answer being 0. The step with lca helped us to move to the ancestor instead of any vertex in the upper subtree of $v$. I truly believe that you can avoid lca in this solution, however, that will make both implementation and proof harder. Now let's do $dp[v][2]$ - the number of ways to cut some edges in the subtree of $v$ so that: 0 - the component with vertex $v$ has no colored vertices in it, 1 - has some colored vertices. Generally, the color itself for 1 doesn't matter. If for some child $u$ of $v$: $dfs(u)$ returned color $x$ then it must be color $x$ in that component, otherwise the color doesn't matter. For $-1$ all vertices of each color presented in the subtree of $u$ are contained within the subtree of $u$. The transitions will be of form "do we cut the edge from $v$ to $u$ or not" for all children $u$ of $v$. That is the most tedious part so I'm sorry if I mess up something the way I did with my author solution :D Here from now I'll ignore the children that returned $0$ (if I say all children, I will mean all non-zero returning children) as they add nothing to the answer. If there are no children, then the vertices with $a_v = 0$ will have $dp[v][0] = 1$, $dp[v][1] = 0$ and the other vertices will have $dp[v][0] = 0$, $dp[v][1] = 1$. Basically, there are two main cases. I would recommend to follow the code in attachment while reading this, tbh. $a_v = 0$ and all children dfs returned $-1$. Then for each edge to the child you can either cut it if there are colored vertices (take $dp[u][1]$) or don't cut it if it has no colored vertices (take $dp[u][0]$). So $dp[v][0] = \prod \limits_{u \in g(v)} (dp[u][0] + dp[u][1])$. For $v$ to have some color you'll need to push that color from exactly one of the children. You can't choose two subtrees because they are guaranteed to have different colors in them (otherwise they wouldn't return $-1$). So $dp[v][1] = \sum \limits_{x \in g(v)} \prod \limits_{u \in g(v), u \ne x} dp[x][1] \cdot (dp[u][0] + dp[u][1])$. To calculate that fast enough you'll need to precalculate prefix and suffix products of $(dp[u][0] + dp[u][1])$. $a_v \ne 0$ or $a_v = 0$ but some children returned the same value $x \ne -1$. Then you are required to make $v$ the part of component with vertices of color $x$. That means that $dp[v][0] = 0$ for that case. For children, who returned $x$, you don't cut their edge (take $dp[u][1]$). For the other children you can either cut it if there are colored vertices (take $dp[u][1]$) or don't cut it if it has no colored vertices (take $dp[u][0]$). Thus, $dp[v][1] = (\prod \limits_{u \in g(v), dfs(u) = -1} (dp[u][0] + dp[u][1])) \cdot (\prod \limits_{u \in g(v), dfs(u) \ne -1} dp[u][1])$. The answer will be stored in $dp[root][1]$ after that. Overall complexity: $O(n \log n)$ but I'm sure this can be rewritten in such a manner that it becomes $O(n)$.
[ "combinatorics", "dfs and similar", "dp", "trees" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 300 * 1000 + 13; const int LOGN = 19; const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int a[N]; vector<int> g[N]; int up[N][LOGN]; int d[N]; void init(int v, int p = -1){ for (auto u : g[v]) if (u != p){ up[u][0] = v; for (int i = 1; i < LOGN; ++i) up[u][i] = up[up[u][i - 1]][i - 1]; d[u] = d[v] + 1; init(u, v); } } int lca(int v, int u){ if (d[v] < d[u]) swap(v, u); for (int i = LOGN - 1; i >= 0; --i) if (d[up[v][i]] >= d[u]) v = up[v][i]; if (v == u) return v; for (int i = LOGN - 1; i >= 0; --i) if (up[v][i] != up[u][i]){ v = up[v][i]; u = up[u][i]; } return up[v][0]; } int l[N]; int dp[N][2]; int dfs(int v, int p = -1){ vector<pair<int, int>> cur; for (auto u : g[v]) if (u != p){ int c = dfs(u, v); if (c != 0) cur.push_back(make_pair(c, u)); } vector<int> vals; forn(i, cur.size()) if (cur[i].first > 0) vals.push_back(cur[i].first); sort(vals.begin(), vals.end()); vals.resize(unique(vals.begin(), vals.end()) - vals.begin()); if (int(vals.size()) > 1){ puts("0"); exit(0); } if (a[v] != 0 && !vals.empty() && vals[0] != a[v]){ puts("0"); exit(0); } if (a[v] == 0 && cur.empty()) return 0; if (a[v] == 0 && vals.empty()){ vector<int> pr(1, 1), su(1, 1); forn(i, cur.size()) pr.push_back(mul(pr.back(), add(dp[cur[i].second][0], dp[cur[i].second][1]))); for (int i = int(cur.size()) - 1; i >= 0; --i) su.push_back(mul(su.back(), add(dp[cur[i].second][0], dp[cur[i].second][1]))); reverse(su.begin(), su.end()); dp[v][1] = 0; forn(i, cur.size()) dp[v][1] = add(dp[v][1], mul(mul(pr[i], su[i + 1]), dp[cur[i].second][1])); dp[v][0] = add(dp[v][0], pr[cur.size()]); return -1; } dp[v][1] = 1; for (auto it : cur){ if (it.first == -1) dp[v][1] = mul(dp[v][1], add(dp[it.second][0], dp[it.second][1])); else dp[v][1] = mul(dp[v][1], dp[it.second][1]); } if (a[v] == 0) return vals[0]; return (l[a[v]] == v ? -1 : a[v]); } int main() { int n, k; 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); } init(0); memset(l, -1, sizeof(l)); forn(i, n) if (a[i] != 0) l[a[i]] = (l[a[i]] == -1 ? i : lca(l[a[i]], i)); for (int i = 1; i <= k; ++i){ if (a[l[i]] != 0 && a[l[i]] != i){ puts("0"); exit(0); } a[l[i]] = i; } dfs(0); printf("%d\n", dp[0][1]); return 0; }
1119
A
Ilya and a Colorful Walk
Ilya lives in a beautiful city of Chordalsk. There are $n$ houses on the street Ilya lives, they are numerated from $1$ to $n$ from left to right; the distance between every two neighboring houses is equal to $1$ unit. The neighboring houses are $1$ and $2$, $2$ and $3$, ..., $n-1$ and $n$. The houses $n$ and $1$ are not neighboring. The houses are colored in colors $c_1, c_2, \ldots, c_n$ so that the $i$-th house is colored in the color $c_i$. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors. Ilya wants to select two houses $i$ and $j$ so that $1 \leq i < j \leq n$, and they have different colors: $c_i \neq c_j$. He will then walk from the house $i$ to the house $j$ the distance of $(j-i)$ units. Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible. Help Ilya, find this maximum possible distance.
It is enough to find the last color different from the $c_1$ and the first color different from $c_n$ and print the maximum of the two distances.
[ "greedy", "implementation" ]
1,100
null
1119
B
Alyona and a Narrow Fridge
Alyona has recently bought a miniature fridge that can be represented as a matrix with $h$ rows and $2$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part. \begin{center} {\small An example of a fridge with $h = 7$ and two shelves. The shelves are shown in black. The picture corresponds to the first example.} \end{center} Alyona has $n$ bottles of milk that she wants to put in the fridge. The $i$-th bottle is $a_i$ cells tall and $1$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can \textbf{not} put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell. Alyona is interested in the largest integer $k$ such that she can put bottles $1$, $2$, ..., $k$ in the fridge at the same time. Find this largest $k$.
For a fixed set of bottles the optimal way to put them in the fridge is to sort them in decreasing order and then put the tallest next to the second tallest, the third next to the fourth and so on. The total required height is then $h_1 + h_3 + h_5 + \ldots$, where $h$ is the sorted array of heights. Now just try all possible $k$, sort the heights of the first $k$ bottles, and output the last $k$ when the bottles fit. The total complexity is $O(n^2 \log{n})$. Bonus 1: solve the problem in $O(n \log^2{n})$. Bonus 2: solve the problem in $O(n \log{n})$. Aleks5d invites you to compete in the shortest solution challenge for this problem. His code (155 bytes):
[ "binary search", "flows", "greedy", "sortings" ]
1,300
[n, k], arr = [int(i) for i in input().split()], [int(i) for i in input().split()] print([i for i in range(n + 1) if sum(sorted(arr[0:i])[::-2]) <= k][-1])
1119
C
Ramesses and Corner Inversion
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task. You are given two matrices $A$ and $B$ of size $n \times m$, each of which consists of $0$ and $1$ only. You can apply the following operation to the matrix $A$ arbitrary number of times: take any \textbf{submatrix} of the matrix $A$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $0$, will be replaced by $1$, and all corners of the submatrix that contain $1$, will be replaced by $0$). You have to answer whether you can obtain the matrix $B$ from the matrix $A$. \begin{center} {\small An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow.} \end{center} Ramesses don't want to perform these operations by himself, so he asks you to answer this question. A submatrix of matrix $M$ is a matrix which consist of all elements which come from one of the rows with indices $x_1, x_1+1, \ldots, x_2$ of matrix $M$ and one of the columns with indices $y_1, y_1+1, \ldots, y_2$ of matrix $M$, where $x_1, x_2, y_1, y_2$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$, where the cell $(i,j)$ denotes the cell on the intersection of the $i$-th row and the $j$-th column.
One can notice that the operation does not change the total parity of the matrix. So, if the total parity of $A$ and $B$ do not match, then the answer is No. However, this is not the only case when the answer is no. You can also notice that the operation does not change the total parity of each row/column independently. Thus, if in at least one row or column the parity of $A$ and $B$ do not match, then the answer is No. It turns out that if all these parities match, then the answer is Yes. We will prove this constructing a sequence of operations that transforms $A$ to $B$ whenever parities in all rows and column match. Let's perform an operation $(1, 1, x, y)$ for all such $x > 1$ and $y > 1$ that $A_{xy} \ne B_{xy}$. After all these operations the whole matrices except maybe the first column and the first row match. But the first column and the first row also match because of the parity! So $A$ is now $B$.
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,500
null
1119
D
Frets On Fire
Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day. In return, the fleas made a bigger ukulele for her: it has $n$ strings, and each string has $(10^{18} + 1)$ frets numerated from $0$ to $10^{18}$. The fleas use the array $s_1, s_2, \ldots, s_n$ to describe the ukulele's tuning, that is, the pitch of the $j$-th fret on the $i$-th string is the integer $s_i + j$. Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them. Each question is in the form of: "How many different pitches are there, if we consider frets between $l$ and $r$ (inclusive) on all strings?" Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task! Formally, you are given a matrix with $n$ rows and $(10^{18}+1)$ columns, where the cell in the $i$-th row and $j$-th column ($0 \le j \le 10^{18}$) contains the integer $s_i + j$. You are to answer $q$ queries, in the $k$-th query you have to answer the number of distinct integers in the matrix from the $l_k$-th to the $r_k$-th columns, inclusive.
Let's sort all $s_i$'s in ascending order. This does not affect the answers, but now we notice that for some $i$, as soon as $r - l$ exceeds $s_{i+1} - s_i$ we don't need to consider row $i$ any more. This is because from then on, any integer that appears in row $i$ also appears in row $i + 1$. Taking this observation one step further, we approach the problem considering the contribution of row $i$, i.e. the number of integers that appear in the queried range in row $i$, but not row $i + 1$. The answer to a query is the sum of contributions of all rows. From this definition we know that the contribution of row $i$ is $\min\{s_{i+1} - s_i, r - l + 1\}$ for $1 \leq i < n$ and $r - l + 1$ for $i = n$. In other words, it is $\min\{d_i, w\}$, where $d_i = s_{i+1} - s_i$, $d_n = +\infty$ and $w = r - l + 1$. Now come the queries. Given a fixed value of $w$, we need to quickly compute $\left(\sum_{i=1}^{n=1} \min\{d_i, w\}\right) + w$. From another perspective, this equals the sum of value times the number of occurrences, namely $\left(\sum_{k=0}^w k \cdot \mathrm{count}(k)\right) + \left(\sum_{k=w+1}^\infty w \cdot \mathrm{count}(k)\right) + w$, where $\mathrm{count}(k)$ denotes the number of times that integer $k$ occurs in $d_{1 \ldots n-1}$. This problem can be solved by representing $\mathrm{count}(*)$ values with an array, combined with partial sums. However, as $d_i$ (and thus the size of such array) can be as large as $10^{18}$, it's required to compress the coordinates (discretize) and find desired indices with binary search. Please refer to the model solution attached below. The overall time complexity is $\mathcal O((n + q) \log n)$.
[ "binary search", "sortings" ]
1,800
#include <cstdio> #include <algorithm> static const int MAXN = 1e5; static int n, q; static long long s[MAXN]; static long long t[MAXN]; int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%lld", &s[i]); std::sort(s, s + n); for (int i = 0; i < n - 1; ++i) s[i] = s[i + 1] - s[i]; std::sort(s, s + n - 1); for (int i = n - 1; i >= 1; --i) s[i] = s[i - 1]; s[0] = 0; for (int i = 1; i < n; ++i) t[i] = t[i - 1] + (s[i] - s[i - 1]) * (n + 1 - i); scanf("%d", &q); for (int i = 0; i < q; ++i) { long long l, r; scanf("%lld%lld", &l, &r); l = r - l + 1; int p = std::lower_bound(s, s + n, l) - &s[0] - 1; printf("%lld%c", t[p] + (l - s[p]) * (n - p), i == q - 1 ? '\n' : ' '); } return 0; }
1119
E
Pavel and Triangles
Pavel has several sticks with lengths equal to powers of two. He has $a_0$ sticks of length $2^0 = 1$, $a_1$ sticks of length $2^1 = 2$, ..., $a_{n-1}$ sticks of length $2^{n-1}$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle. It is forbidden to break sticks, and each triangle should consist of exactly three sticks. Find the maximum possible number of triangles.
First, possible triangles have sides $(2^i, 2^j, 2^j)$ where $i \le j$. There are several correct greedies to finish the solution, let's discuss one of them. The greedy is to loop through the values of $j$ in increasing order, then first try to match as many pairs $(j, j)$ to some unmatched $i$ as possible, after that create as many triples $(j, j, j)$ as possible and continue to the next $j$. To prove correctness, let's take our solution and one of the optimal solutions. Let's find the first difference in them if we consider the triples in the same order as our solutions considers them. There can be only one type of difference: we take some triple while the optimal solution skippes it. It can't be be the other way around because we always take a triple if there is one. So there are a few cases now: the triple is $(i, j, j)$ where $i < j$. Let's see where the corresponding $i$, $j$ and $j$ are used in the optimal solution: all three are used in different triples: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $(t_3, k_3, k_3)$, $\{t_1, t_2, t_3\} = \{i, j, j\}$, $j \le k_1 \le k_2 \le k_3$. Remove these triples and replace them with $(i, j, j)$, $(k_1, k_2, k_2)$, $(k_1, k_3, k_3)$. two are used in the same triple, one in another: the only case is $(i, k, k)$, $(j, j, j)$, $j < k$. Remove these, add $(i, j, j)$ and $(j, k, k)$. two of them are used in different triples, one not used: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $\{t_1, t_2\} \subset \{i, j, j\}$, $j \le k_1 \le k_2$. Remove these triples, replace with $(i, j, j)$ and $(k_1, k_2, k_2)$. two of them are used in the same triple, one not used: the only case is $(j, j, j)$. Remove this, add $(i, j, j)$. one of them in used in some triple, two are not used: $(t, k, k)$, $t \in \{i, j, j\}$, $j \le k$. Remove this, add $(i, j, j)$. none of them is used. This is not possible because it is the optimal solution. all three are used in different triples: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $(t_3, k_3, k_3)$, $\{t_1, t_2, t_3\} = \{i, j, j\}$, $j \le k_1 \le k_2 \le k_3$. Remove these triples and replace them with $(i, j, j)$, $(k_1, k_2, k_2)$, $(k_1, k_3, k_3)$. two are used in the same triple, one in another: the only case is $(i, k, k)$, $(j, j, j)$, $j < k$. Remove these, add $(i, j, j)$ and $(j, k, k)$. two of them are used in different triples, one not used: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $\{t_1, t_2\} \subset \{i, j, j\}$, $j \le k_1 \le k_2$. Remove these triples, replace with $(i, j, j)$ and $(k_1, k_2, k_2)$. two of them are used in the same triple, one not used: the only case is $(j, j, j)$. Remove this, add $(i, j, j)$. one of them in used in some triple, two are not used: $(t, k, k)$, $t \in \{i, j, j\}$, $j \le k$. Remove this, add $(i, j, j)$. none of them is used. This is not possible because it is the optimal solution. the triple is $(j, j, j)$. Let's see where these $j$s are used. They can only be used in three different triples $(j, k_1, k_1)$, $(j, k_2, k_2)$, $(j, k_3, k_3)$, $j \le k_1 \le k_2 \le k_3$. Remove these triples and replace them with $(j, j, j)$, $(k_1, k_2, k_2)$, $(k_1, k_3, k_3)$.
[ "brute force", "dp", "fft", "greedy", "ternary search" ]
1,900
null
1119
F
Niyaz and Small Degrees
Niyaz has a tree with $n$ vertices numerated from $1$ to $n$. A tree is a connected graph without cycles. Each edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex. Niyaz does not like when vertices in the tree have too large degrees. For each $x$ from $0$ to $(n-1)$, he wants to find the smallest total weight of a set of edges to be deleted so that degrees of all vertices become at most $x$.
First, let's learn how to solve for a fixed $x$ in $O(n \log n)$. We can calculate the dp on subtrees, $dp_{v, flag}$, denoting the minimum total weight of edges to be removed, if we consider the subtree of the vertex $v$, and $flag$ is zero, if the vertex has the degree $\leq x$, and one, if $\leq x+1$. Then to recalculate it you need to sort the children by $dp_{to, 1} - dp_{to, 0}$, and add to the sum $dp_{to, 0}$ $(deg_v - (x + flag))$ minimum values, depending on $flag$ which we consider for the dp answer for the vertex $v$. Then, it is obvious that the sum of degrees in the tree is equal to twice the number of edges, which is $2(n-1)$. It follows that the sum of all $x$ values <<number of vertices, with degree $\geq x$>>, equal to the sum of degrees, is also $2(n-1)$. Therefore, if for each $x$ we will know how to answer the query, for the time of the order of the number of vertices with a sufficiently large degree, we will solve the problem. Let's call a vertex interesting if its degree is $> x$. We will support the forest only on interesting vertices, and also in some data structure (for example, two heaps perfectly fit this) for each interesting vertex of the weight of edges to the uninteresting. Then, to calculate the same dynamics for each vertex in the forest, it is enough to iterate over how many edges from it down to interesting vertices we will take (in the forest $\leq$ <<number of interesting vertices>> $- 1$ edges, so we can iterate over it). And also add to the answer the sum of a sufficient number of edges in uninteresting vertices from the data structure. This solution works for <<number of interesting vertices>> $\cdot \log$, and all necessary data structures can also be maintained as $x$ increases. In total, we got the solution for $O(n \log n)$.
[ "data structures", "dp", "trees" ]
3,400
null
1119
G
Get Ready for the Battle
Recently Evlampy installed one interesting computer game, one of aspects of which is to split army into several groups and then fight with enemy's groups. Let us consider a simplified version of the battle. In the nearest battle Evlampy should fight an enemy army that consists of $m$ groups, the $i$-th of which has $hp_i$ health points. Evlampy's army consists of $n$ equal soldiers. Before each battle he should split his army in exactly $m$ groups (possibly, empty) so that the total size of the groups is $n$. The battle is played step-by-step. On each step each of Evlampy's groups attacks exactly one enemy group. Thus, each step is described with an array of $m$ integers $a_1, a_2, \ldots, a_m$, meaning that the $i$-th Evlampy's group attacks the $a_i$-th enemy group. Different groups can attack same group, on each step the array $a$ is chosen independently. After each step the health points of each enemy group decreases by the total number of soldiers in Evlampy's groups that attacked this enemy group at this step. Enemy group is destroyed once its health points are zero or negative. Evlampy's soldiers do not lose health. \begin{center} {\small An example of a step. The numbers in green circles represent the number of soldiers in Evlampy's groups, the arrows represent attacks, the numbers in red circles represent health points of enemy groups, the blue numbers represent how much the health points will decrease after the step.} \end{center} Evlampy understands that the upcoming battle will take the whole night. He became sad because this way he won't have enough time to finish his homework. Now Evlampy wants you to write a program that will help him win in the smallest possible number of steps. Can you help him? In other words, find the smallest number of steps needed to destroy all enemy groups and show a possible way of doing this. Find the requires splitting of the army into $m$ groups and the arrays $a$ for each step.
Note that on each turn the total health of enemy groups decreases by $n$. When all groups are destroyed, their health does not exceed $0$, and thus the answer is at least $\left\lceil{\frac{\sum_{i=1}^n hp_i}{n}}\right\rceil$. Now let's construct a way to win in this number of steps. Let's emulate the battle and split the soldiers in groups at the same time. Let's start with one group $n$, and attack the first enemy on each step. Once its health becomes less than $n$, say $k_1$, let's assume that some of our groups have total size exactly $k_1$ and they attack the first enemy on this step, while all the other groups start attacking the second enemy. After that let's attack the second enemy with all $n$ soldiers until its health is $k_2 < n$. Let's assume that some of our groups have total size $k_2$ and they attack the second soldier on this step, while the other groups start attacking the third. Continue with this process until all enemies are destroyed. We won't add the constraint on $k_n$, we will just assume that all soldiers attack the last enemy on the last step. Note that the total number of steps is exactly $\left\lceil{\frac{\sum_{i=1}^n hp_i}{n}}\right\rceil$, because we have "extra" hits only on the very last step. Now we have $m - 1$ assumptions of type "some of our groups have total size $k_i$". It's easy to satisfy them by sorting $k_i$ and stating that the $i$-th groups has size $k_i - k_{i - 1}$. This way the first $i$ groups will have size $k_i$ (after sorting). In order to reconstruct the attacks we have to simulate the process again.
[ "constructive algorithms", "implementation" ]
3,100
null
1119
H
Triple
You have received your birthday gifts — $n$ triples of integers! The $i$-th of them is $\lbrace a_{i}, b_{i}, c_{i} \rbrace$. All numbers are greater than or equal to $0$, and strictly smaller than $2^{k}$, where $k$ is a fixed integer. One day, you felt tired playing with triples. So you came up with three new integers $x$, $y$, $z$, and then formed $n$ arrays. The $i$-th array consists of $a_i$ repeated $x$ times, $b_i$ repeated $y$ times and $c_i$ repeated $z$ times. Thus, each array has length $(x + y + z)$. You want to choose exactly one integer from each array such that the XOR (bitwise exclusive or) of them is equal to $t$. Output the number of ways to choose the numbers for each $t$ between $0$ and $2^{k} - 1$, inclusive, modulo $998244353$.
If we form $n$ arrays, $i$-th of them is $F_{i}$, and set $F_{i,A_{i}}=a$, $F_{i,B_{i}}=b$, $F_{i,C_{i}}=c$ and others zero. It's easy to find that the xor-convolution of all the arrays is the answer we want. Implementation with the Fast Walsh-Hadamard Transform works in $O(n \times 2^{k} \times k)$, this is too slow. To make it easier, we set $A_{i} = 0$, $B_{i} = B_{i} xor A_{i}$, $C_{i} = C_{i} xor A_{i}$. The answer won't change if we xor all $x$ by the xor sum of all $A_{i}$. That is $F_{i,0}=a$, $F_{i,B_{i} xor A_{i}}=b$, $F_{i,C_{i} xor A_{i}}=c$. Note we only have $4$ values in each array after FWHT of the array: $a+b+c$, $a+b-c$, $a-b+c$, $a-b-c$. Let's fix some position, let the occurrences of them in all $n$ arrays be $x,y,z,w$. Obviously, $x+y+z+w = n$. For each position, if we can figure out the values of $x,y,z,w$, it's easy to count the final answer by FWHT. If we add all arrays together and make a FWHT, we can form a new equation. $(a+b+c) \cdot x + (a+b-c) \cdot y + (a-b+c) \cdot z + (a-b-c) \cdot w = p$, where $p$ is the value we get in this position. Take two different $(a,b,c)$ to form 2 equations. Now we have 3 equations in total, including $(x+y+z+w=n)$ . More equations formed by this operation (take $a,b,c$ and compute FWHT) are useless because the equation $x,y,z,w$ lies in the same linear span, so we already have three equations. However, if we set up a new array, $F_{i,B_{i} xor C_{i}} += 1$, other is zero, and do the FWHT (add them together of course). We can get a new equation $x - y - z + w = p$. The equation can be easily proved. Now we can solve a system of $4$ equations to calculate $x,y,z,w$ for each position and get the final array. Then do the reverse FWHT and get the answer.
[ "fft", "math" ]
3,200
null
1120
A
Diana and Liana
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $k$ flowers. The work material for the wreaths for all $n$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $a_1$, $a_2$, ..., $a_m$, where $a_i$ is an integer that denotes the type of flower at the position $i$. This year the liana is very long ($m \ge n \cdot k$), and that means every citizen will get a wreath. Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $k$ flowers from the beginning of the liana, then another $k$ flowers and so on. Each such piece of $k$ flowers is called a workpiece. The machine works until there are less than $k$ flowers on the liana. Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $k$ flowers must contain flowers of types $b_1$, $b_2$, ..., $b_s$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter. Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $n$ workpieces?
First of all, let's learn how to check if a perfect wreath can be obtained from the subsegment $[l, r]$ of our liana (that is, if we can remove some flowers so that the remaining ones on $[l, r]$ represent a perfect wreath, and this whole wreath will be cut). First, the number of other wreaths must be $n - 1$, so the inequality $\left\lfloor\frac{l - 1}{k}\right\rfloor\cdot k + \left\lfloor\frac{m - r}{k}\right\rfloor\cdot k \ge n - 1$ must hold. Second, the segment $[l, r]$ has to contain flowers of all required types. Finally, $r - l + 1$ must be at least $k$. One can see that these conditions also guarantee that $[l, r]$ can become a cut perfect wreath. Now let's find for every $l$ the minimal possible $r$ for which the second condition holds. It can be done with the two pointers technique: if we iterate for all $l$ from $1$ to $m$ then this $r$ cannot become less than it was, and it's easy to update all counts and the number of insufficient flowers types both when increase $l$ and $r$. So what remains is to find out if there is any $l$ such that the segment $[l, \max(r, l + k - 1)]$ satisfies the first requirement, and if it does, then print some flowers before $l$ which we delete (we must ensure that what remains before $l$ is divisible by $k$ and does not exceed $(n - 1)k$) and some flowers from $[l, r]$ we delete (without breaking the conditions). It's not necessary to delete anything after $r$, though.
[ "greedy", "implementation", "two pointers" ]
1,900
null
1120
B
Once in a casino
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow. A positive integer $a$ is initially on the screen. The player can put a coin into the machine and then add $1$ to or subtract $1$ from any two adjacent digits. All digits must remain from $0$ to $9$ after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add $1$ to $9$, to subtract $1$ from $0$ and to subtract $1$ from the leading $1$. Once the number on the screen becomes equal to $b$, the player wins the jackpot. $a$ and $b$ have the same number of digits. Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
Since each operation saves the alternating series of the digits, if it's different for $a$ and $b$, then the answer is '-1'. Now we prove that otherwise it's possible to win. Let's imagine that digits can be negative or bigger than 9 (that is, for example, number 19 can become the number with digits 2 and 10). Denote by $a_i$ the $i$-th digit of $a$ (and similarly for $b$). Now there is no difference between any two orders of the same set of operations, so we can do allowed operations from left to right. After we do all operations with first digit (there are at least $|a_1 - b_1|$ such operations), $a_2$ will become equal to $a_2 + b_1 - a_1$. After we do all operations with $a_2$ and $a_3$ (there are at least $|a_2 + b_1 - a_1 - b_2|$ such operations), $a_3$ will be equal to $a_3 + b_2 - a_2 - b_1 + a_1$, and so on. Thus we can calculate the minimal total number of operations and find their set. The goal is to prove that it's possible to perform them in some order and never break the rules about the correctness of intermediate numbers. Indeed, let's just perform these operations from left to right. Assume that we can't perform the current operation. Without loss of generality assume that we can't decrease two digits: one of $a_k$ and $a_{k + 1}$ is 0 now. It's easy to see that $a_k > 0$ because after we perform the set of our operations ignoring the rules, $a_k$ will become $b_k$, which is nonnegative. Hence $a_{k + 1} = 0$. Then we must increase $a_{k + 1}$ and $a_{k + 2}$ at least once (again because we can ignore the rules and get $b_{k + 1}$ in the end). If we can do it then we do it and then decrease $a_k$ and $a_{k + 1}$ just as planned and then continue performing the operations. Otherwise, $a_{k + 2} = 9$. Reasoning similarly, either we can decrease $a_{k + 2}$ and $a_{k + 3}$, or $a_{k + 3} = 0$, et cetera. As it can't continue infinitely, we can perform some operations from our set and decrease $a_k$ and $a_{k + 1}$, so we can reach the goal doing the minimal number of operations.
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,700
null
1120
C
Compress String
Suppose you are given a string $s$ of length $n$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins. To compress the string, you have to represent $s$ as a concatenation of several non-empty strings: $s = t_{1} t_{2} \ldots t_{k}$. The $i$-th of these strings should be encoded with one of the two ways: - if $|t_{i}| = 1$, meaning that the current string consists of a single character, you can encode it paying $a$ coins; - if $t_{i}$ is a substring of $t_{1} t_{2} \ldots t_{i - 1}$, then you can encode it paying $b$ coins. A string $x$ is a substring of a string $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string $s$.
Let's say that $dp[p]$ is the minimal cost to encode the prefix of $s$ with length $p$, the answer is $dp[n]$. If we want to encode the prefix with length $p$ then the last symbol in our encoded string either equals $s_p$, or represents some substring $s_{[l,p]}$ so that it occurs in the prefix of length $l - 1$. Therefore one can see that $dp[0] = 0,$ $dp[p] = \min\left(a + dp[p - 1], \min\left(b + dp[l - 1]\,\mid\,s_{[l, p]}\text{ is a substring of }s_{[1, l - 1]}\right)\right).$ One way to implement this is to calculate this $dp$ forward and use hashes, but it may require some efforts to avoid collisions and fit into the time limit. Another way is to find for each $p$ all appropriate $l$'s by calculating z-function on the reverse of $s_{[1, p]}$. The total complexity in this case is $O\left(n^2\right)$.
[ "dp", "strings" ]
2,100
null
1120
D
Power Tree
You are given a rooted tree with $n$ vertices, the root of the tree is the vertex $1$. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree $1$. Arkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empty set of vertices of the tree. On the second stage Vasily puts some integers into all leaves of the tree. On the third stage Arkady can perform several (possibly none) operations of the following kind: choose some vertex $v$ he bought on the first stage and some integer $x$, and then add $x$ to all integers in the leaves in the subtree of $v$. The integer $x$ can be positive, negative of zero. A leaf $a$ is in the subtree of a vertex $b$ if and only if the simple path between $a$ and the root goes through $b$. Arkady's task is to make all integers in the leaves equal to zero. What is the minimum total cost $s$ he has to pay on the first stage to guarantee his own win independently of the integers Vasily puts on the second stage? Also, we ask you to find all such vertices that there is an optimal (i.e. with cost $s$) set of vertices containing this one such that Arkady can guarantee his own win buying this set on the first stage.
One can see that the problem doesn't change if we want to be able to obtain any possible combination of numbers in leaves from the all-zero combination. Solution 1. Let $v_1$, $v_2$, ..., $v_l$ be the indices of all leaves in the order of any Euler tour. Let $a_i$ be the number written in $v_i$. We say that $v_0 = v_{l+1} = 0$. Denote the difference $a_{i + 1} - a_i$ by $d_i$. We want to be able to obtain an arbitrary sequence $d_0$, ..., $d_l$ with zero sum. Imagine that we bought a vertex $u$ whose subtree contains exactly leaves from $v_i$ to $v_j$. Applying the operation to this vertex with number $x$ means increasing $d_{i-1}$ by $x$ and decreasing $d_j$ by $x$ without affecting all other differences. Let's build new graph with vertices from $0$ to $l$. Each such vertex $u$ represents an edge connecting vertices $(i - 1)$ and $j$ with weight $c_u$. To be able to get every possible sequence with zero sum it's needed and sufficient for the graph with picked edges be connected. Now we want to know what is the weight of a minimal spanning tree and which edges can be in it. Both can be found by, for example, Kruskal's algorithm. Solution 2. We say that a vertex $u$ covers a leaf $v$ if it's in $u$'s subtree. One can see that we can buy a set of vertices iff for each vertex $u$ there is at most one leaf in its subtree which is not covered by any of bought vertices from the subtree. Indeed, if there are at least two such leaves then the difference between their values never change. On the other hand, if this holds, we can set the required values in the bought vertices in the order of increasing depth, performing the needed operation each time we are in vertex whose subtree contains a leaf which is not covered by any bought vertex in the subtree except the one we consider. So we calculate $ans[v][k]$ where $0\le k\le 1$ where this value means the minimal possible cost where in the subtree of $v$ there are $k$ not covered leaves. It can be shown that these values are enough to calculate the answer.
[ "dfs and similar", "dp", "dsu", "graphs", "greedy", "trees" ]
2,500
null
1120
E
The very same Munchhausen
A positive integer $a$ is given. Baron Munchausen claims that he knows such a positive integer $n$ that if one multiplies $n$ by $a$, the sum of its digits decreases $a$ times. In other words, $S(an) = S(n)/a$, where $S(x)$ denotes the sum of digits of the number $x$. Find out if what Baron told can be true.
Define the balance of a number $x$ as $S(nx) \cdot n - S(x)$. By the balance of a digit string we mean the balance of the corresponding number. Solution 1. We are gonna do the following: Find out if the solution exists. If no, print -1 and exit. Find any string with negative balance. Find any string with positive balance. Take their linear combination with zero balance (maybe we pad the numbers we found by leading zeroes before this). By linear combination of several strings we mean their concatenation where each of them can occur several times. It is quite clear how to perform the last step. To perform the initial step it's convenient to introduce some lemmas. Lemma 1. $S(a + b) \le S(a) + S(b)$. Proof. It's obvious more or less since if we write both numbers one under another and start calculating their sum then the result will have sum of digits being equal to $S(a) + S(b)$ minus $9$ times the number of carries. Lemma 2. $S(ab) \le aS(b)$. Proof. $S(ab) = S(b + b + \ldots + b) \le S(b) + S(b) + \ldots S(b) = aS(b)$. Here the inequality holds according to Lemma 1. Lemma 3. $S(ab) \le S(a)S(b)$. Proof. Let $a = \overline{a_{n-1}a_{n-2}\ldots a_1a_0}$. Then $S(ab) = S(a_{n-1}b\cdot10^{n-1} + a_{n-2}b\cdot10^{n-2} + \ldots + a_0b) \le S(a_{n-1}b\cdot10^{n-1}) + S(a_{n-2}b\cdot10^{n-2}) + \ldots + S(a_0b) =$ $= S(a_{n-1}b) + S(a_{n-2}b) + \ldots + S(a_0b) \le (a_{n-1} + a_{n-2} + \ldots + a_0)S(b) = S(a)S(b).$ Now consider two cases. $a = 2^{d_1}\cdot5^{d_2}$.Let $b = 10^{\max(d_1, d_2)}$. One can see that $a\cdot S(an) = a \cdot S\left(\frac{bn}{b/a}\right) = \frac{a}{S(b/a)}\cdot S(b/a)\cdot S\left(\frac{bn}{b/a}\right) \ge \frac{a}{S(b/a)}\cdot S(bn) = \frac{a}{S(b/a)}\cdot S(n).$ That means that if $a > S(b/a)$ then the answer doesn't exist, otherwise the number $b/a$ has non-positive balance. One can easily see that the number $1$ always has non-negative balance, so in this case the problem is solved. Let $b = 10^{\max(d_1, d_2)}$. One can see that $a\cdot S(an) = a \cdot S\left(\frac{bn}{b/a}\right) = \frac{a}{S(b/a)}\cdot S(b/a)\cdot S\left(\frac{bn}{b/a}\right) \ge \frac{a}{S(b/a)}\cdot S(bn) = \frac{a}{S(b/a)}\cdot S(n).$ That means that if $a > S(b/a)$ then the answer doesn't exist, otherwise the number $b/a$ has non-positive balance. One can easily see that the number $1$ always has non-negative balance, so in this case the problem is solved. $a$ has a prime divisor which is not $2$ and not $5$.It turns out that in this case the answer always exists. Indeed, the decimal fraction $1/a$ is infinite, that means that $S\left(\frac{10^k}{a}\right)$ in nondecreasing and can be sufficiently large; and so can be $S\left(\frac{10^k}{a} + 1\right)$ since the number of trailing $9$-s of $\frac{10^k}{a}$ is bounded. Meanwhile $S\left(a\cdot\left(\frac{10^k}{a} + 1\right)\right)$ is bounded by, say, $1 + 9\cdot len(a)$, so we always can find a string with negative balance, and, as we mentioned above, the number $1$ always has nonnegative balance. It turns out that in this case the answer always exists. Indeed, the decimal fraction $1/a$ is infinite, that means that $S\left(\frac{10^k}{a}\right)$ in nondecreasing and can be sufficiently large; and so can be $S\left(\frac{10^k}{a} + 1\right)$ since the number of trailing $9$-s of $\frac{10^k}{a}$ is bounded. Meanwhile $S\left(a\cdot\left(\frac{10^k}{a} + 1\right)\right)$ is bounded by, say, $1 + 9\cdot len(a)$, so we always can find a string with negative balance, and, as we mentioned above, the number $1$ always has nonnegative balance. We know two ways to perform the second step. Divide $1$ by $a$ and find the period. Let's say that the period can be represented as a string $s$ and the part before it by a string $t$ (possibly empty). Let $s'$ have the same length as $s$ and equal $(s + 1)$ when being treated as an integer. We are looking for a string of type $tsss\ldots ss'$ with negative balance. One can calculate the impact on balance of strings $t$, $s$ and $s'$ and therefore find the minimal required number of stings $s$. Construct a weighted directed graph. Its vertices are numbers from $0$ to $a - 1$, and for each pair of numbers $(c, x)\neq(0, 0)$ with $0\le c < a$ and $0 \le x \le 9$ there is an edge from $c$ to $\left\lfloor\frac{ax + c}{10}\right\rfloor$ with weight $(ax + c)\pmod{10}$ and label $x$. Informally, if we traverse through some path from $0$, and labels of the edges on this path are digits of some number $n$ from right to left, then the sum of weights are the current balance of $an$ (that is, if we consider only last $len(n)$ digits when calculating the balance) and the last vertex represents the current carry. Now we can find a negative cycle in this graph via Ford-Bellman algorithm and then construct a path from $0$ to this cycle, go through the cycle required number of times (so that the final sum of weights is negative) and then return to the zero vertex. This solution has a disadvantage: the final answer can have a length up to $S(n)\cdot n^2$. One workaround is to find, say, $300$ different possibilities of negative balance (by taking more periods/negative cycles) and find the positive balance string by trying all numbers from $1$ to $10000$ and constructing a string with a small balance divisible by any of negative balances. It can be done by a sort of knapsack on found positive balances. The idea is to get a big gcd of the two found balances so that we don't need to repeat the negative-balance-string too many times (because among the two found strings it is the one which can have a superlinear length). Solution 2. Imagine we have infinite time and memory. Then we can say that we have states of kind $(carry, balance)$ similar to the states of the graph from solution 1, where for each state $(carry, balance)$ and each digit $x$ (except state $(0, 0)$ and digit $0$ at the same time) there is a transition to $\left((carry + a\cdot x)\pmod{10}, balance + a\left\lfloor\frac{carry + a\cdot x}{10}\right\rfloor - x\right)$. Our goal is to reach $(0, 0)$ again. One can bfs over this (infinite) graph with creating new states, when needed. However, traversing over this graph consume too much memory. It turns out that if we don't consider states with $|balance| > a$ then there always is a solution, and this is relatively easy to come up with (and definitely easier to pass than the previous one).
[ "brute force" ]
2,600
null
1120
F
Secret Letters
Little W and Little P decided to send letters to each other regarding the most important events during a day. There are $n$ events during a day: at time moment $t_i$ something happens to the person $p_i$ ($p_i$ is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the other person. They can send a letter using one of the two ways: - Ask Friendly O to deliver the letter directly. Friendly O takes $d$ acorns for each letter. - Leave the letter at Wise R's den. Wise R values free space, so he takes $c \cdot T$ acorns for storing a letter for a time segment of length $T$. The recipient can take a letter from Wise R either when he leaves his own letter at Wise R's den, or at time moment $t_{n + 1}$, when everybody comes to Wise R for a tea. It is not possible to take a letter from Wise R's den at other time moments. The friends can store as many letters at Wise R's den as they want, paying for each one separately. Help the friends determine the minimum possible total cost of sending all letters.
Consider any optimal solution. Consider all letters of W between two times when P visits R. It's clear that maybe the first of these messages is sent via R, some of the last messages are also sent via R, all other messages are sent via O. The sense behind shipping the first message via R is to obtain all messages which are currently stored there. If the first message is sent via O, and some of the others is sent via R, then we can swap them thus paying less. On the other hand, once we got all these letters, it makes sense to send something through R iff $ct \le d$ where $t$ is the time between the moments when we send this message and when P visits R to obtain it. The same holds if we swap W and P. Denote by $ans[i]$ the minimal possible cost of the first $(i - 1)$ letters if the $i$-th is sent through R. Also denote by $ans\_delay[i]$ the minimal possible cost of the first $(i - 1)$ letters if the $i$-th is sent through R and if R has already kept exaclty one letter. To calculate these values we can each time try every possible number of last letters sent through R. This takes $O(n^2)$ time. One can observe that if we fix the left bound of letters sent through R then the cost depends linearly on the time $t_i$ which we are calculating this for, and since we need the minimum of linear functions each time then we can use convex-hull trick which gives us $O(n)$ or $O(n\,\log{n})$ complexity.
[ "data structures", "dp", "greedy" ]
3,100
null
1121
A
Technogoblet of Fire
Everybody knows that the $m$-coder Tournament will happen soon. $m$ schools participate in the tournament, and only one student from each school participates. There are a total of $n$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $k$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too. You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $k$ Chosen Ones would be selected by the Technogoblet.
First of all, each time we move someone to another school the number of schools which contain at least one Chosen One can increase at most by one. Second, if a school contains $c > 0$ Chosen Ones, but the strongest guy in this school is not one of them, then we need to move someone at least $c$ times to make all these chosen ones selected. Combining these two statements one can see that the answer to the problem equals the number of Chosen Ones which are currently not the strongest ones in their schools.
[ "implementation", "sortings" ]
1,100
null
1121
B
Mike and Children
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child \textbf{two} sweets. Mike has $n$ sweets with sizes $a_1, a_2, \ldots, a_n$. All his sweets have \textbf{different} sizes. That is, there is no such pair $(i, j)$ ($1 \leq i, j \leq n$) such that $i \ne j$ and $a_i = a_j$. Since Mike has taught for many years, he knows that if he gives two sweets with sizes $a_i$ and $a_j$ to one child and $a_k$ and $a_p$ to another, where $(a_i + a_j) \neq (a_k + a_p)$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them \textbf{two} sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.
Notice that the sum of sweets each child gets cannot exceed $2\cdot 10^5$, so for each of numbers no more than this threshold we can store the number of ways to obtain it as the sum of two sweets. It can be done just by considering all possible (unordered) pairs of sweets and printing the maximal obtained number (of ways to represent something as sum of two sweets). Indeed, if $x$ can be represented as a sum of two sweets in several ways then no two of them share a sweet since if $a_i + a_j$ = $a_i + a_k$ then $a_j = a_k$ and therefore $j = k$.
[ "brute force", "implementation" ]
1,200
null
1121
C
System Testing
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab. There are $n$ solutions, the $i$-th of them should be tested on $a_i$ tests, testing one solution on one test takes $1$ second. The solutions are judged in the order from $1$ to $n$. There are $k$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time. At any time moment $t$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $i$, then it is being tested on the first test from time moment $t$ till time moment $t + 1$, then on the second test till time moment $t + 2$ and so on. This solution is fully tested at time moment $t + a_i$, and after that the testing process immediately starts testing another solution. Consider some time moment, let there be exactly $m$ fully tested solutions by this moment. There is a caption "System testing: $d$%" on the page with solutions, where $d$ is calculated as $$d = round\left(100\cdot\frac{m}{n}\right),$$ where $round(x) = \lfloor{x + 0.5}\rfloor$ is a function which maps every real to the nearest integer. Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $q$, and the caption says "System testing: $q$%". Find the number of interesting solutions. Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Let's determine for each solution when it begins being tested. It can be done, for example, by the following algorithm: let's store for each testing process the time when it becomes free to test something (initially all these $k$ numbers are zeroes), then iterate over all solutions in the queue and for each of them we pick a process with minimal time, say that it's the time when this solution begins being tested, and then update the time when this process stops testing. After we determined this, we can easily know for each moment the number of solutions which are completely tested before this moment, and then for each test of each solution just check the required condition of being interesting on this test.
[ "implementation" ]
1,600
null
1129
A2
Toy Train
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described. Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). \begin{center} {\small The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.} \end{center} The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only \textbf{at most one} candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible. Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
We can consider the pickup requests from each station individually. The overall answer for some fixed starting station is simply the maximum time needed to fulfill deliveries among all pickup stations. Suppose the starting station for the train is fixed at some station $s$ ($1 \leq s \leq n$). Consider some station $i$ ($1 \leq i \leq n$). Let $out(i)$ denote the number of candies that need to be picked up from station $i$. If $out(i) = 0$, we do not consider this station. From now on, we assume $out(i) \geq 1$. Each time that the train visits station $i$ to pick up a candy, we can choose which candy it should pick up. Therefore, we should find an order that would minimize the time needed to fulfill all deliveries from pickup station $i$. It turns out, however, that the only thing that matters is the last candy to be delivered. Suppose the last candy is to be delivered to station $e$, the total time needed to fulfill all pickup requests from station $i$ would be: $dist(s, i) + n*(out(i)-1) + dist(i, e)$, where $dist(a, b)$ represents the time needed to travel from station $a$ to station $b$. Take some time to think why this is the case! With this formulated, it is now clear that we have to choose the last candy to deliver that minimizes $dist(i, e)$. All of this can be done in $\mathcal{O}(n)$ (with an $\mathcal{O}(n+m)$ pre-process only once to find the optimal last candy for each pickup station). To find the answer for every starting station for the train, we can simply run the above algorithm $n$ times. The time complexity is $\mathcal{O}(n^2+m)$.
[ "brute force", "greedy" ]
1,800
null
1129
B
Wrong Answer
Consider the following problem: given an array $a$ containing $n$ integers (indexed from $0$ to $n-1$), find $\max\limits_{0 \leq l \leq r \leq n-1} \sum\limits_{l \leq i \leq r} (r-l+1) \cdot a_i$. In this problem, $1 \leq n \leq 2\,000$ and $|a_i| \leq 10^6$. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it. Her implementation in pseudocode is as follows: \begin{verbatim} function find_answer(n, a) # Assumes n is an integer between 1 and 2000, inclusive # Assumes a is a list containing n integers: a[0], a[1], ..., a[n-1] res = 0 cur = 0 k = -1 for i = 0 to i = n-1 cur = cur + a[i] if cur < 0 cur = 0 k = i res = max(res, (i-k)*cur) return res \end{verbatim} Also, as you can see, Alice's idea is not entirely correct. For example, suppose $n = 4$ and $a = [6, -8, 7, -42]$. Then, find_answer(n, a) would return $7$, but the correct answer is $3 \cdot (6-8+7) = 15$. You told Alice that her solution is incorrect, but she did not believe what you said. Given an integer $k$, you are to find any sequence $a$ of $n$ integers such that the correct answer and the answer produced by Alice's algorithm differ by exactly $k$. Note that although the choice of $n$ and the content of the sequence is yours, you must still follow the constraints earlier given: that $1 \leq n \leq 2\,000$ and that the absolute value of each element does not exceed $10^6$. If there is no such sequence, determine so.
Suppose $a_0 = -1$ and $a_i \geq 1$ for each $1 \leq i < n$. Let $S = \sum\limits_{i=0}^{n-1} a_i$. Assume also that $n \geq 2$. It is easy to see that Alice's algorithm produces $(n-1)(S+1)$ as the answer. Meanwhile, there are two possible correct answers: either $nS$ or $(n-1)(S+1)$, whichever is greater. Assume further that $a_1 \geq 2$. The correct answer for this array is then $nS$. The difference between these two results is $nS-(n-1)(S+1) = S-n+1$. Now, we can easily create array $a$ greedily so that $S-n+1 = k$. The time complexity is $\mathcal{O}(n)$.
[ "constructive algorithms" ]
2,000
null
1129
C
Morse Code
In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1". Because there are $2^1+2^2+2^3+2^4 = 30$ strings with length $1$ to $4$ containing only "0" and/or "1", not all of them correspond to one of the $26$ English letters. In particular, each string of "0" and/or "1" of length \textbf{at most} $4$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111". You will work with a string $S$, which is initially empty. For $m$ times, either a dot or a dash will be appended to $S$, one at a time. Your task is to find and report, after each of these modifications to string $S$, the number of non-empty sequences of English letters that are represented with some substring of $S$ in Morse code. Since the answers can be incredibly tremendous, print them modulo $10^9 + 7$.
We will be computing the answers offline instead of doing so immediately after each modification. Let $T = S_{reversed}$. Now, we need to find the number of English sequences that, if considered backward, would translate into some substring of each suffix of T. Let $f(l, r)$ be the number of English sequences that translate to exactly $T[l..r]$. Let $g(l, r)$ be sum of $f(l, x)$ over all $l \leq x \leq r$. Note that $f(l, r)$ can be calculated with dynamic programming for all $1 \leq l \leq r \leq m$ in $\mathcal{O}(km^2)$ where $k$ denotes the longest length of an English alphabet in Morse code (which is $4$). Following that, we can calculate $g(l, r)$ for all $1 \leq l \leq r \leq m$ in $\mathcal{O}(m^2)$. The answer for the suffix $T[x..m]$ is simply the sum of $g(i, m)$ over all $x \leq i \leq m$ subtracted by the number of over-counted English sequences. The number of over-counted sequences can be calculated by considering the suffix array of $T$. Namely, for each two adjacent suffixes in the list, we over-counted them by $g(l, r)$ with $l$ and $r$ denoting the corresponding indices of their longest common prefix (LCP). Therefore, the answer for $T[1..m]$ is $\sum\limits_{1 \leq i \leq m} g(i, m)$ subtracted by the sum of $g(l, r)$ of the LCP between each pair of adjacent suffixes. Transitioning to solve the problem for $T[x'..m]$ where $x' = x+1$ can be done efficiently, since the removal character of the string affects only one entry in the suffix list. To sum up, we find $g(l, r)$ for all valid $l$ and $r$ in $\mathcal{O}(km^2)$. Then, we sort the suffixes naively in $O(m^2 \log m)$, before computing the answer in the final step in $\mathcal{O}(m^2)$. The time complexity is $\mathcal{O}(km^2 + m^2 \log m)$.
[ "binary search", "data structures", "dp", "hashing", "sortings", "string suffix structures", "strings" ]
2,400
null
1129
D
Isolation
Find the number of ways to divide an array $a$ of $n$ integers into any number of disjoint non-empty segments so that, in each segment, there exist at most $k$ distinct integers that appear exactly once. Since the answer can be large, find it modulo $998\,244\,353$.
Let $f(l, r)$ be the number of integers that appear exactly once in the segment $a[l..r]$. We can use the following recurrence to compute the answer: $dp(n) = \sum\limits_{0 \leq i < n \wedge f(i+1, n) \leq k} dp(i)$, where $dp(0) = 1$. A naive $\mathcal{O}(n^2)$ implementation will definitely be too slow. To compute the said recurrence efficiently, we will do as follows. Preparation First, let's design an array $b$ so that $f(l, r)$ is the sum of elements in segment $b[l..r]$ for some fixed $r$. Ideally, it should be easy (i.e., require only a few operations) to transform this array $b$ into another array $b'$ that would work with $r' = r+1$ instead. One design is as follows. First, let each entry of $b$ be $0$. This array now works imaginarily when $r = 0$. To make it work for $r' = r+1$, consider the element $a_{r+1}$. If this value appeared before at least twice, set $b_i = 0$ where $i$ is the second-last appearance of $a_{r+1}$ (not counting the appearance at index $r+1$). If this value appeared before at least once, set $b_i = -1$ where $i$ is the last appearance of $a_{r+1}$. Finally, set $b_{r+1} = 1$. Now, you can see that the sum in the segment $b[l..(r+1)]$ correctly represents $f(l, r+1)$ for any $1 \leq l \leq r+1$! The Real Thing Let us divide the array into $k$ blocks so that each block contains $\frac{n}{k}$ elements (assume for simplicity that $k$ divides $n$). Each block corresponding to some segment $[L..R]$ should store (1) sum of elements in $b[L..R]$ (i.e., $f(L, R)$) and (2), for each $-\frac{n}{k} \leq i \leq \frac{n}{k}$, $q(i) =$ sum of $dp(x-1)$ where $f(x, R)$ is less than or equal to $i$. A modification to $b_j$ for some index $j$ will require an $\mathcal{O}(\frac{n}{k})$ update. With array $b$ ready for our $r$, we are ready to compute $dp(r)$. Let $t$ be a temporary variable initially equal to $0$. For each $l \leq r$ that belongs to the same block as $r$, add $dp(l-1)$ to $dp(r)$ if $f(l, r) \leq k$, and also add $b_l$ to $t$. This runs in $\mathcal{O}(\frac{n}{k})$. To account for the left possible endpoints from other blocks, for each block, starting from one directly to the left of the block that contains $r$ to the leftmost block: Suppose this block corresponds to the segment $[L..R]$. Let $x = k-t$. If $x < -\frac{n}{k}$, do nothing. If $-\frac{n}{k} \leq x \leq \frac{n}{k}$, add $q(x)$ to $dp(r)$. If $\frac{n}{k} < x$, add $q(\frac{n}{k})$ to $dp(r)$. Add $f(L, R)$ to $t$. The step above runs in $\mathcal{O}(k)$. That is, our algorithm takes $\mathcal{O}(k + \frac{n}{k})$ time to compute $dp(r)$ for some $r$. The time complexity is $\mathcal{O}(nk + \frac{n^2}{k})$, since there are $n$ values of $r$ that we need to compute $dp(r)$ for. If we choose $k = \sqrt{n}$, our solution would run in $\mathcal{O}(n\sqrt{n})$.
[ "data structures", "dp" ]
2,900
null
1129
E
Legendary Tree
This is an interactive problem. A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster. To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains $n$ vertices, enumerated from $1$ through $n$. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two \textbf{disjoint} non-empty sets of vertices $S$ and $T$, along with any vertex $v$ that you like. Then, Mikaela will count and give you the number of pairs of vertices $(s, t)$ where $s \in S$ and $t \in T$ such that the simple path from $s$ to $t$ contains $v$. Mikaela the Goddess is busy and will be available to answer at most $11\,111$ questions. This is your only chance. Your task is to determine the tree and report its edges.
In this analysis, let $V$ be the set of all vertices. We will use tuples of the form $(S, T, v)$ to represent queries. First, we will root the tree at vertex $1$. The size of each subtree can be found in $n-1$ queries by asking $(\{1\}, \{2, 3, \ldots, n\}, i)$, for each $1 \leq i \leq n$. Suppose $sz(i)$ denotes the size of the subtree rooted at vertex $i$. Let us sort the vertices (and store the results in $v$) so that $sz(v_i) \leq sz(v_{i+1})$ for each $1 \leq i < n$. We will find all children of each vertex $v_i$ in the ascending order of $i$. While we do so, we will maintain a set $X$, initially containing only $v_1$. It will store the processed-so-far vertices whose parents have not been found. Namely, for each $2 \leq i \leq n$: Let $k = (\{1\}, X, v_i)$. This is the number of direct children that $v_i$ has. Let $x_1, x_2, \ldots, x_{|X|}$ be the vertices in $X$ in an arbitrary order. For $k$ times: binary search to find the smallest $m$ such that querying $(\{1\}, \{x_1, x_2, \ldots, x_m\}, v_i)$ returns a non-zero result and remove $x_m$ from $X$. For each such $m$, we know that there is an edge $(x_m, v_i)$. Add $v_i$ to $X$. This solution asks at most $2(n-1) + (n-1) \log_2 n$ queries. Time complexity: $\mathcal{O}(n^2 \log n)$
[ "binary search", "interactive", "trees" ]
3,100
null