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
797
B
Odd sum
You are given sequence $a_{1}, a_{2}, ..., a_{n}$ of integer numbers of length $n$. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence.
The answer to this problem can be constructed this way: Sum up all positive numbers Find maximum $max_{odd}$ of negative odd numbers Find minimum $min_{odd}$ of positive odd numbers If sum was even then subtract $min(min_{odd}, - max_{odd})$ Overall complexity: $O(n)$.
[ "dp", "greedy", "implementation" ]
1,400
null
797
C
Minimal string
Petya recieved a gift of a string $s$ with length up to $10^{5}$ characters for his birthday. He took two more empty strings $t$ and $u$ and decided to play a game. This game has two possible moves: - Extract the \textbf{first} character of $s$ and append $t$ with this character. - Extract the \textbf{last} character of $t$ and append $u$ with this character. Petya wants to get strings $s$ and $t$ empty and string $u$ lexicographically minimal. You should write a program that will help Petya win the game.
On every step you should maintain minimal alphabetic letter in current string $s$ (this can be done by keeping array of 26 cells with number of times each letter appear in string nd updating it on every step). Let's call string $t$ a stack and use its terms. Now you extract letters from $s$ one by one. Put the letter to the top of the stack. Pop letters from the top of stack and push them to answer while they are less or equal than any letter left in string $s$. After string $s$ becomes empty push all the letters from stack to answer. The answer will be lexicographically minimal. It is obvious if we consider the case when current top of stack is strictly greater than any character from the remaining string $s$, or there is a character in $s$ that is strictly less than current top. If current top is equal to some character then appending answer with the letter from top won't make answer worse. Overall complexity: $O(n * |AL|)$, where $|AL|$ is the length of the alpabet, $26$ in our case.
[ "data structures", "greedy", "strings" ]
1,700
null
797
D
Broken BST
Let $T$ be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree $T$: - Set pointer to the root of a tree. - Return success if the value in the current vertex is equal to the number you are looking for - Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for - Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for - Return fail if you try to go to the vertex that doesn't exist Here is the pseudo-code of the described algorithm: \begin{verbatim} bool find(TreeNode t, int x) { if (t == null) return false; if (t.value == x) return true; if (x < t.value) return find(t.left, x); else return find(t.right, x); } find(root, x); \end{verbatim} The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree. Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree. If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Let's firstly consider tree with only distinct values in its nodes. Then value will be reached if and only if all the jumps to the left children on the path from the root were done from the vertices with values greater than the current one and all the jumps to the right children on the path from the root were done from the vertices with values less than the current one. Thus let's run dfs from the root and maintain maximal transition to the left child on current path and minimal transition to the right child on current path. If the value of current node is greater than left bound and less than right bound then it will be found. Now let's return to the original problem. Notice that transitions and comparations won't change. Store every found value in set and just calculate how many values of vertices isn't present there. Overall complexity: $O(n \cdot log(n))$.
[ "data structures", "dfs and similar" ]
2,100
null
797
E
Array Queries
$a$ is an array of $n$ positive integers, all of which are not greater than $n$. You have to process $q$ queries to this array. Each query is represented by two numbers $p$ and $k$. Several operations are performed in each query; each operation changes $p$ to $p + a_{p} + k$. There operations are applied until $p$ becomes greater than $n$. The answer to the query is the number of performed operations.
There are two possible solutions in $O(n^{2})$ time. First of them answers each query using simple iteration - changes $p$ to $p + a_{p} + k$ for each query until $p$ becomes greater than $n$, as stated in the problem. But it is too slow. Second solution precalculates answers for each $p$ and $k$: if $p + a_{p} + k > n$, then $ans_{p, k} = 1$, else $ans_{p, k} = ans_{p + ap + k, k} + 1$. But this uses $O(n^{2})$ memory and can be done in $O(n^{2})$ time. Now we can notice that if $k<{\sqrt{n}}$, then second solution will use only $O(n{\sqrt{n}})$ time and memory, and if $k\geqslant{\sqrt{n}}$, then first solution will do not more than $\sqrt{n}$ operations on each query. So we can combine these two solutions. Time complexity: $O(n{\sqrt{n}})$.
[ "brute force", "data structures", "dp" ]
2,000
null
797
F
Mice and Holes
One day Masha came home and noticed $n$ mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor. The corridor can be represeted as a numeric axis with $n$ mice and $m$ holes on it. $i$th mouse is at the coordinate $x_{i}$, and $j$th hole — at coordinate $p_{j}$. $j$th hole has enough room for $c_{j}$ mice, so not more than $c_{j}$ mice can enter this hole. What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If $i$th mouse goes to the hole $j$, then its distance is $|x_{i} - p_{j}|$. Print the minimum sum of distances.
This problem can be solved using dynamic programming. Let $dp_{i, j}$ be the answer for first $i$ holes and $j$ mice. If the constraints were smaller, then we could calculate it in $O(n^{2}m)$ just trying to update $dp_{i, j}$ by all values of $dp_{i - 1, k}$ where $k \le j$ and calculating the cost to transport all mice from the segment to $i$th hole. To calculate this in $O(nm)$, we will use a deque maintaining the minimum (or a queue implemented on two stacks, for example). We iterate on $i$ and update all the values of $dp_{i + 1, j}$ with the help of this deque: for each index $j$ we insert a value in the deque equal to $dp_{i, j} - cost$, where $cost$ is the total distance required to move first $j$ mice to hole $i + 1$. Updating the value is just extracting the minimum and adding this $cost$ to it. Don't forget to delete values from the deque to ensure that we don't send too much mice to the hole. Time complexity: $O(nm)$.
[ "data structures", "dp", "greedy", "sortings" ]
2,600
null
798
A
Mike and palindrome
Mike has a string $s$ consisting of only lowercase English letters. He wants to \textbf{change exactly one} character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.
Let $cnt$ be the number of $1\leq i\leq{\frac{n}{2}}$ such that $s_{i} \neq s_{n - i + 1}$. If $cnt \ge 2$ then the answer is NO since we must change more than 1 character. If $cnt = 1$ then the answer is YES. If $cnt = 0$ and $n$ is odd answer is YES since we can change the character in the middle, otherwise if $n$ is even the answer is NO because we must change at least one character. Complexity is $O(|s|)$.
[ "brute force", "constructive algorithms", "strings" ]
1,000
"# include <bits/stdc++.h>\nusing namespace std;\nint main(void)\n{\n string s;\n cin>>s;\n s = '#' + s;\n int n = s.length() - 1;\n int cnt = 0;\n for (int i = 1;i + i <= n;++i)\n if (s[i] != s[n - i + 1])\n ++cnt;\n if ((cnt <= 1 && (n&1)) || cnt == 1) puts(\"YES\");\n else puts(\"NO\");\n return 0;\n}\n"
798
B
Mike and strings
Mike has $n$ strings $s_{1}, s_{2}, ..., s_{n}$ each consisting of lowercase English letters. In one move he can choose a string $s_{i}$, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec". Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
First of all, you must notice that the operation of removing the first character and appending it to the left is equivalent to cyclically shifting the string one position to the left. Let's denote by $dp_{i, j}$ the smallest number of operations for making the first $i$ strings equal to string $s_{i}$ moved $j$ times. Let $f(i, j)$ be the the string $s_{i}$ moved $j$ times,then $d p_{i,j}=\operatorname*{min}_{k=0,f(i-1,k)=f(i,j)}d p_{i-1,k}+j$. The answer is $min(dp_{n, 0}, dp_{n, 1}, ..., dp_{n, |sn| - 1})$. The complexity is $O(|S|^{3} \times n)$.
[ "brute force", "dp", "strings" ]
1,300
"# include <bits/stdc++.h>\nusing namespace std;\n# define fi cin\n# define fo cout\nstring s[512];\nint dp[512][512];\nint main(void)\n{\n int n;\n fi>>n;\n for (int i = 1;i <= n;++i)\n fi>>s[i];\n int k = s[1].length();\n for (int i = 1;i <= n;++i)\n for (int j = 0;j < k;++j)\n dp[i][j] = 1e9;\n for (int i = 1;i <= n;++i)\n s[i] = s[i] + s[i];\n for (int i = 0;i < k;++i)\n dp[1][i] = i;\n for (int i = 2;i <= n;++i)\n {\n for (int j = 0;j < k;++j)\n for (int prev = 0;prev < k;++prev)\n if (s[i].substr(j,k) == s[i-1].substr(prev,k))\n dp[i][j] = min(dp[i][j],dp[i-1][prev] + j);\n }\n int ans = 1e9;\n for (int i = 0;i < k;++i)\n ans = min(ans,dp[n][i]);\n if (ans == 1e9)\n puts(\"-1\");\n else\n fo << ans << '\\n';\n return 0;\n}\n\n\n"
798
C
Mike and gcd problem
Mike has a sequence $A = [a_{1}, a_{2}, ..., a_{n}]$ of length $n$. He considers the sequence $B = [b_{1}, b_{2}, ..., b_{n}]$ beautiful if the $gcd$ of all its elements is bigger than $1$, i.e. $\operatorname*{gcd}(b_{1},b_{2},\dots,b_{n})>1$. Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index $i$ ($1 ≤ i < n$), delete numbers $a_{i}, a_{i + 1}$ and put numbers $a_{i} - a_{i + 1}, a_{i} + a_{i + 1}$ in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence $A$ beautiful if it's possible, or tell him that it is impossible to do so. $\operatorname*{gcd}(b_{1},b_{2},\cdot\cdot\cdot,b_{n})$ is the biggest non-negative number $d$ such that $d$ divides $b_{i}$ for every $i$ ($1 ≤ i ≤ n$).
First of all, the answer is always YES. If $\operatorname*{gcd}(a_{1},a_{2},...,a_{n})\neq1$ then the answer is $0$. Now suppose that the gcd of the sequence is $1$. After we perform one operation on $a_{i}$ and $a_{i + 1}$, the new gcd $d$ must satisfy $d|a_{i} - a_{i + 1}$ and $d|a_{i} + a_{i + 1}$ $\longrightarrow\bigcup$ $d|2a_{i}$ and $d|2a_{i + 1}$. Similarly, because $d$ is the gcd of the new sequence, it must satisfy $d|a_{j}, j \neq i, i + 1$. Using the above observations we can conclude that $\left.d\right|\mathrm{gc}|\bigl(u_{1,}\cdot\cdot\cdot\cdot\cdot\bigr)d_{i}\cdot\cdot d_{i}\G\!d_{i+1,}\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\bigr(u_{n}\bigr)|^{\cdot}\mathrm{gc}\!\left((u_{1,}\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\bigr)=\mathrm{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$, so the gcd of the sequence can become at most $2$ times bigger after an operation. This means that in order to make the gcd of the sequence bigger than $1$ we need to make all numbers even. Now the problem is reduced to the following problem: Given a sequence $v_{1}, v_{2}, ... , v_{n}$ of zero or one,in one move we can change numbers $v_{i}, v_{i + 1}$ with $2$ numbers equal to $v_{i}\oplus v_{i+1}$. Find the minimal number of moves to make the whole sequence equal to $0$. It can be proved that it is optimal to solve the task for consecutive ones independently so we divide the array into the minimal number of subarrays full of ones, if their lengths are $s_{1}, s_{2}, ... , s_{t}$,the answer is $\textstyle\sum_{i=1}^{t}\left[{\frac{s_{i}}{2}}\right]^{}+\left(s_{i}\mod2\right)$. Complexity is $O(N\log M A X)$.
[ "dp", "greedy", "number theory" ]
1,700
"# include <bits/stdc++.h>\nusing namespace std;\n# define fi cin\n# define fo cout\nint main(void)\n{\n int n;\n fi>>n;\n int g = 0,v,cnt = 0,ans = 0;\n while (n --)\n {\n int v;\n fi>>v;\n g = __gcd(g,v);\n if (v & 1) ++cnt;\n else ans += (cnt / 2) + 2 * (cnt & 1),cnt = 0;\n }\n ans += (cnt / 2) + 2 * (cnt & 1);\n fo << \"YES\\n\";\n if (g == 1)\n fo << ans << '\\n';\n else\n fo << \"0\\n\";\n cerr << \"Time elapsed :\" << clock() * 1000.0 / CLOCKS_PER_SEC << \" ms\" << '\\n';\n return 0;\n}\n"
798
D
Mike and distribution
Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers $A = [a_{1}, a_{2}, ..., a_{n}]$ and $B = [b_{1}, b_{2}, ..., b_{n}]$ of length $n$ each which he uses to ask people some quite peculiar questions. To test you on how good are you at spotting inequality in life, he wants you to find an "unfair" subset of the original sequence. To be more precise, he wants you to select $k$ numbers $P = [p_{1}, p_{2}, ..., p_{k}]$ such that $1 ≤ p_{i} ≤ n$ for $1 ≤ i ≤ k$ and elements in $P$ are distinct. Sequence $P$ will represent indices of elements that you'll select from both sequences. He calls such a subset $P$ "unfair" if and only if the following conditions are satisfied: $2·(a_{p1} + ... + a_{pk})$ is \textbf{greater} than the sum of all elements from sequence $A$, and $2·(b_{p1} + ... + b_{pk})$ is \textbf{greater} than the sum of all elements from the sequence $B$. Also, $k$ should be smaller or equal to $\lfloor{\frac{n}{2}}\rfloor+1$ because it will be to easy to find sequence $P$ if he allowed you to select too many elements! Mike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!
In the beginning, it's quite easy to notice that the condition " $2 \cdot (a_{p1} + ... + a_{pk})$ is greater than the sum of all elements in $A$ " is equivalent to " $a_{p1} + ... + a_{pk}$ is greater than the sum of the remaining elements in $A$ ". Now, let's store an array of indices $C$ with $C_{i} = i$ and then sort it in decreasing order according to array $A$, that is we must have $A_{Ci} \ge A_{Ci + 1}$. Our answer will always have size $\lfloor{\frac{N}{2}}\rfloor+1$. First suppose that $N$ is odd. Add the first index to our set, that is make $p_{1} = C_{1}$. Now, for the remaining elements, we will consider them consecutively in pairs. Suppose we are at the moment inspecting $A_{C2k}$ and $A_{C2k + 1}$. If $B_{C2k} \ge B_{C2k + 1}$ we make $p_{k + 1} = C_{2k}$, else we make $p_{k + 1} = C_{2k + 1}$. Why does this subset work? Well, it satisfies the condition for $B$ because each time for consecutive non-intersecting pairs of elements we select the bigger one, and we also add $B_{C1}$ to the set, so in the end the sum of the selected elements will be bigger than the sum of the remaining ones. It also satisfies the condition for $A$, because $A_{p1}$ is equal or greater than the complement element of $p_{2}$ (that is - the index which we could've selected instead of $p_{2}$ from the above procedure - if we selected $C_{2k}$ then it would be $C_{2k + 1}$ and vice-versa). Similarly $A_{p2}$ is greater than the complement of $p_{3}$ and so on. In the end we also add the last element from the last pair and this makes the sum of the chosen subset strictly bigger than the sum of the remaining elements. The case when $N$ is even can be done exactly the same as when $N$ is odd, we just pick the last remaining index in the end. The complexity is $O(N\log N)$.
[ "constructive algorithms", "sortings" ]
2,400
"# include <bits/stdc++.h>\nusing namespace std;\n# define vi vector < int >\n# define pb push_back\nint a[1 << 20];\nint b[1 << 20];\nint p[1 << 20];\nint main(void)\n{\n int n;\n scanf(\"%d\",&n);\n for (int i = 1;i <= n;++i)\n scanf(\"%d\",&a[i]);\n for (int i = 1;i <= n;++i)\n scanf(\"%d\",&b[i]);\n for (int i = 1;i <= n;++i)\n p[i] = i;\n sort(p + 1,p + 1 + n,[&](int xx,int yy) {return a[xx] > a[yy];});\n vi answer;\n answer.pb(p[1]);\n for (int i = 2;i <= n;i += 2)\n {\n int bst = p[i];\n if (i + 1 <= n && b[p[i + 1]] > b[bst])\n bst = p[i + 1];\n answer.pb(bst);\n }\n int sz = answer.size();\n printf(\"%d\\n\",sz);\n for (int i = 0;i < sz;++i)\n printf(\"%d%c\",answer[i],\" \\n\"[i == sz - 1]);\n cerr << \"Time elapsed :\" << clock() * 1000.0 / CLOCKS_PER_SEC << \" ms\" << '\\n';\n return 0;\n}\n"
798
E
Mike and code of a permutation
Mike has discovered a new way to encode permutations. If he has a permutation $P = [p_{1}, p_{2}, ..., p_{n}]$, he will encode it in the following way: Denote by $A = [a_{1}, a_{2}, ..., a_{n}]$ a sequence of length $n$ which will represent the code of the permutation. For each $i$ from $1$ to $n$ sequentially, he will choose the smallest unmarked $j$ ($1 ≤ j ≤ n$) such that $p_{i} < p_{j}$ and will assign to $a_{i}$ the number $j$ (in other words he performs $a_{i} = j$) and will mark $j$. If there is no such $j$, he'll assign to $a_{i}$ the number $ - 1$ (he performs $a_{i} = - 1$). Mike forgot his original permutation but he remembers its code. Your task is simple: find \textbf{any} permutation such that its code is the same as the code of Mike's original permutation. You may assume that there will always be at least one valid permutation.
Let's consider $a_{i} = n + 1$ instead of $a_{i} = - 1$. Let's also define the sequence $b$, where $b_{i} = j$ such that $a_{j} = i$ or $b_{i} = n + 1$ if there is no such $j$. Lets make a directed graph with vertices be the indices of the permutation $p$ with edges of type $(a, b)$ representing that $p_{a} > p_{b}$. If we topologically sort this graph then we can come up with a possible permutation: if $S$ is the topologically sorted graph then we can assign to $p_{Si}$ number $i$. In this problem we will use this implementation of topological sort. But how we can find the edges? First of all there are edges of the form $(i, b_{i})$ if $b_{i} \neq n + 1$ .For a vertex $i$ he visited all the unmarked vertices $j$ $(1 \le j < a_{i}, j \neq i)$ and you know for sure that for all these $j, p_{j} < p_{i}$. But how we can check if $j$ was already marked? The vertex $j$ will become marked after turn of vertex $b_{j}$ or will never become unmarked if $b_{j} = n + 1$. So there is a direct edge from $i$ to $j$ if $j = b_{i}$ or $1 \le j < a_{i}, j \neq i$ and $b_{j} > i$. Suppose we already visited a set of vertices and for every visited vertex $node$ we assigned to $b_{node}$ value $0$ (for simplicity just to forget about all visited vertices) and now we want to find quickly for a fixed vertex $i$ an unvisited vertex $j$ with condition that there is edge $(i, j)$ or say it there isn't such $j$, if we can do that in subquadratic time then the task is solved. As stated above the first condition is $j = b_{i}$ if $1 \le b_{i} \le n$, this condition is easy to check. The second condition is $1 \le j < a_{i}$ and $b_{j} > i$, now consider vertices with indices from interval $1..a_{i} - 1$ and take $j$ with maximal $b_{j}$. If $b_{j} > i$ we found edge $(i, j)$ otherwise there are no remaining edges. We can find such vertex $j$ using segment tree and updating values while we visit a new vertex. In total we will visit $n$ vertices and query the segment tree at most $2 \times (n - 1)$ times ($n - 1$ for every new vertex and $n - 1$ for finding that there aren't remaining edges). Complexity and memory are $O(N\log N)$ and $O(N)$.
[ "constructive algorithms", "data structures", "graphs", "sortings" ]
3,000
"# include <bits/stdc++.h>\nusing namespace std;\n# define fi cin\n# define fo cout\n# define x first\n# define y second\n# define IOS ios_base :: sync_with_stdio(0)\nint a[1 << 20];\nint b[1 << 20];\npair < int , int > t[1 << 22];\nvoid build(int p,int u,int node)\n{\n if (p == u) t[node] = {b[p],p};\n else\n {\n int m = (p + u) / 2;\n build(p,m,node << 1);\n build(m+1,u,node << 1 | 1);\n t[node] = max(t[node << 1],t[node << 1 | 1]);\n }\n}\n// building the tree \nvoid Del(int p,int u,int v,int node)\n{\n if (p == u) t[node] = {0,p};\n else\n {\n int m = (p + u) / 2;\n if (v <= m) Del(p,m,v,node << 1);\n else Del(m+1,u,v,node << 1 | 1);\n t[node] = max(t[node << 1],t[node << 1 | 1]);\n }\n}\n// deleting a visited vertex\npair < int , int > query(int p,int u,int l,int r,int node)\n{\n if (l > r) return {0,0};\n if (l <= p && u <= r) return t[node];\n int m = (p + u) / 2;\n pair < int , int > ans = {0,0};\n if (l <= m) ans = max(ans,query(p,m,l,r,node << 1));\n if (m+1<=r) ans = max(ans,query(m+1,u,l,r,node << 1 | 1));\n return ans;\n}\n// find edge for a fixed interval\nint was[1 << 20];\n// visited/not\nint n;\nvector < int > Sort;\n//sorted graph\nvoid dfs(int node)\n{\n\t//node = i from tutorial\n Del(1,n,node,1);\n was[node] = 1;\n if (b[node] != n + 1 && !was[b[node]]) dfs(b[node]);\n //edges of first type\n while (1)\n {\n auto it = query(1,n,1,a[node] - 1,1);\n //it.y = j from tutorial,it.x is b[j]\n if (it.x > node) dfs(it.y);//there is edge\n else break;//there aren't remaining\n }\n //edges of second type\n Sort.push_back(node);\n}\nint ans[1 << 20];\nint main(void)\n{\n scanf(\"%d\\n\",&n);\n for (int i = 1;i <= n;++i) b[i] = n + 1;\n for (int i = 1;i <= n;++i) scanf(\"%d\",&a[i]);\n for (int i = 1;i <= n;++i)\n if (a[i] != -1)\n b[a[i]] = i;\n //b from tutorial\n for (int i = 1;i <= n;++i)\n if (a[i] == -1)\n a[i] = n + 1;\n //just replacing\n build(1,n,1);\n //building the tree\n for (int i = 1;i <= n;++i)\n if (!was[i])\n dfs(i);\n //sorting the graph\n int cnt = 0;\n for (auto it : Sort)\n ans[it] = ++cnt;\n //assigning p[ans[i]] = i as stated in tutorial\n for (int i = 1;i <= n;++i)\n printf(\"%d%c\",ans[i],\" \\n\"[i == n]);\n //printing one possible permutation\n return 0;\n}"
799
A
Carrot Cakes
In some game by Playrix it takes $t$ minutes for an oven to bake $k$ carrot cakes, all cakes are ready at the same moment $t$ minutes after they started baking. Arkady needs at least $n$ cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take $d$ minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven. Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get $n$ cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
One of possible solutions - to simply simulate described process. To make it we need two variables - $t_{1}$ and $t_{2}$. In them we will store the time when each of the ovens will become free. In the beginning $t_{1}$ equals to $0$ and $t_{2}$ equals to $d$. After simulating the process we will get a time for which possible to make $n$ cakes with $2$ ovens (this time equals to maximum from $t_{1}$ and $t_{2}$). It is only left to compare this time with value $(n + k - 1) / k \cdot t$ - a time for which possible to make $n$ cakes using only one oven.
[ "brute force", "implementation" ]
1,100
null
799
B
T-shirt buying
A new pack of $n$ t-shirts came to a shop. Each of the t-shirts is characterized by three integers $p_{i}$, $a_{i}$ and $b_{i}$, where $p_{i}$ is the price of the $i$-th t-shirt, $a_{i}$ is front color of the $i$-th t-shirt and $b_{i}$ is back color of the $i$-th t-shirt. All values $p_{i}$ are distinct, and values $a_{i}$ and $b_{i}$ are integers from $1$ to $3$. $m$ buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the $j$-th buyer we know his favorite color $c_{j}$. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts.
Let's store in three arrays t-shirts which have appropriate color. About each t-shirt is enough to store its index, but we will additionally store its cost. It is possible that one t-shirt will be in two arrays (if this t-shirt colorful). Then we need to sort t-shirts in each array in increasing order of cost. After that we will process buyers. Also for each array we will store the pointer to leftmost t-shirt which was not purchased yet. For a new buyer we need to look on array with t-shirts which appropriate to his favorite color. Using appropriate pointer let's iterate to the right until there are t-shirts or until we not found unsold t-shirt (to this we can store one more array $used$ with type bool - did we sell or no appropriate t-shirt). If there are no t-shirt with needed color - print -1. In the other case, print the cost of founded t-shirt and tag in array $used$ that we sold this t-shirt.
[ "data structures", "implementation" ]
1,400
null
799
C
Fountains
Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are $n$ available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed. Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.
There are three ways - Arkady builds one fountain for coins and other for diamonds, Arkady builds both fountains for coins and Arkady builds both fountains for diamonds. In the end we need to choose a way with maximum total beauty. The first way is simple - we need to choose one fountain of each type with maximum beauty on which is enough coins and diamonds which Arkady has. To make it we can easily iterate though all given fountains. The other two ways are treated similarly to each other. Consider the way when Arkady builds both fountains for coins. Let's write out all the fountains for a coins in a separate array. We will store them as pairs - cost and beauty. Then sort the array in ascending order of cost. Let Arkady will build fountains with cost $p_{1}$ and $p_{2}$ coins and $p_{1} \le p_{2}$ and $p_{1} + p_{2} \le c$. Additionally we need an array $maxB$, where $maxB_{i}$ equals to maximum fountain beauty on the prefix of sorted fountains for coins which ends in position $i$. The option when $p_{1}$ equals to $p_{2}$ should be considered separately. It can be done in one iteration through the fountains - from fountains with same cost we need to choose two with maximum beauty and update the answer with the resulting value. It is only left case when $p_{1} < p_{2}$. Let's brute the fountain with cost equals to $p_{2}$. After that, Arcady will have $c - p_{2}$ coins. After that with help of binary search we need to find the fountains prefix which Arkay can build for the remaining coins. With help of array $maxB$ we can determine the maximum beauty of fountain which Arkady can build. Similarly, the third way is solved when both fountains will be built for diamonds.
[ "binary search", "data structures", "implementation" ]
1,800
null
799
D
Field expansion
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are $n$ extensions, the $i$-th of them multiplies the width or the length (by Arkady's choice) by $a_{i}$. Each extension can't be used more than once, the extensions can be used in any order. Now Arkady's field has size $h × w$. He wants to enlarge it so that it is possible to place a rectangle of size $a × b$ on it (along the width or along the length, with sides parallel to the field sides). Find the minimum number of extensions needed to reach Arkady's goal.
At first let's check if rectangle can be placed on given field - if it is possible print 0. In the other case we need to expand the field. Let's sort all extensions in descending order and take only $34$ from them - it is always enough based on given constraints. After that we need to calculate linear dynamic where $d_{i}$ equals to maximum width which we got for the length $i$. Let's iterate through extensions in sorted order and recalculate $d$. For each length $i$ we need to expand itself or to expand the width $d_{i}$. To avoid overflow we will not store the width and length which more than $10^{5}$. On each recalculate value of $d$ we need to check if rectangle can be places on current field. If it is possible - we found the answer and we need to print the number of extensions which we already used.
[ "brute force", "dp", "meet-in-the-middle" ]
2,100
null
799
E
Aquarium decoration
Arkady and Masha want to choose decorations for thier aquarium in Fishdom game. They have $n$ decorations to choose from, each of them has some cost. To complete a task Arkady and Masha need to choose \textbf{exactly} $m$ decorations from given, and they want to spend as little money as possible. There is one difficulty: Masha likes some $a$ of the given decorations, Arkady likes some $b$ of the given decorations. Some decorations may be liked by both Arkady and Masha, or not be liked by both. The friends want to choose such decorations so that each of them likes \textbf{at least} $k$ decorations among the chosen. Help Masha and Arkady find the minimum sum of money they need to spend.
Let's divide the decorations in four groups: that aren't liked by anybody (group 0), that are liked only by Masha (group 1), that are liked only by Arkady (group 2), that are liked by both (group 3). Sort each group by the cost. Then, it's obvious that in optimal solution we should take several (or 0) first elements in each group. Take a look at the group 3. It's easy to see that if we take $x$ decorations from it, then we should take first $k - x$ decorations from each of the groups 1 and 2. Let's call these decorations ($x$ from the group 3 and $k - x$ from each of the groups 1 and 2) obligatory, and let's call the other decorations free. If the number of obligatory decorations is less than $m$, we need to take several cheapest free decorations. It's easy to construct an $O(n^{2})$ solution then: for each $x$ we can construct the answer described in linear time and then choose minimum among these answers. To speed up the algorithm, let's try all $x$ from the minimum possible (it's easy to get it from integers $k$, $m$ and groups 1 and 2 sizes), making transfers from $x$ to $x + 1$. We should maintain the set of costs of free decorations, and let's also keep integer $y$, which is the number of free decorations that we should add to the current answer, and also the sum of the $y$ cheapest free decorations. When we increase $x$ by 1, in groups 1 and 2 the most expensive obligatory decoration becomes free (because the value $k - x$ decreases by one 1). These decorations (if any) we should add to our free set. We should also add one obligatory decoration from the group 3, so, the number of free decorations could change by one. So, we need at most $2$ operations of adding an integer to a set, and an operation that changes $y$ with the corresponding change of the sum. We can perform these operations in $O(log(n))$, for example, using two std::set objects in C++ (or its analogues in other languages) one set for the smallest $y$ integers and one for the others. The overall complexity to change $x$ to $x + 1$ is now $O(log(n))$, so the overall complexity is $O(n * log(n))$.
[ "data structures", "greedy", "two pointers" ]
2,500
null
799
F
Beautiful fountains rows
Butler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not. The butler wants to show Arkady $n$ gardens. Each garden is a row of $m$ cells, the $i$-th garden has one fountain in each of the cells between $l_{i}$ and $r_{i}$ inclusive, and there are no more fountains in that garden. The issue is that some of the gardens contain even number of fountains, it is wrong to show them to Arkady. Ostin wants to choose two integers $a ≤ b$ and show only part of each of the gardens that starts at cell $a$ and ends at cell $b$. Of course, only such segments suit Ostin that each garden has either zero or odd number of fountains on this segment. Also, it is necessary that at least one garden has at least one fountain on the segment from $a$ to $b$. Help Ostin to find the total length of all such segments, i.e. sum up the value $(b - a + 1)$ for each suitable pair $(a, b)$.
Let's describe an $O((n + m)^{2})$ solution first. Let's try all possible pairs $(a, b)$ and check if they suit us. Let's try all values of $a$ from $1$ to $m$. Let garden $(x, y)$ denote a garden with fountains from $x$ to $y$, and let's say that a garden bans a position $x$ for a fixed $a$ if there is non-zero even number of fountains on the segment $[a, x]$, i.e. the pair $(a, x)$ doesn't suit Ostin due to this garden. Now there are two types of gardens we want consider: gardens of the first type start have form $(x, y)$ where $x < a$, $y \ge a$, and gardens of the second type have form $(x, y)$ where $a \le x \le y$. The gardens of the second type ban such positions equal to $x + 1, x + 3, ...$, and maybe $y, y + 1, y + 2, ..., m$ if $(y - x + 1)$ is even. These positions do not depend on $a$, we can keep an array that tells us how many gardens ban each position of $b$. Initially, we add $1$ to all such positions for each garden, and we remove that $1$ when the $a$ passes beyond the left bound of that garden. Let $R$ be the set of right ends of all gardens of the first type. These gardens ban positions $a + 1, a + 3, ..., x$, where $x$ is bounded by the maximum element in $R$. Also, if there is a value $t$ in $R$ such that $(t - a + 1)$ is even, then all positions $t, t + 1, t + 2, ..., m$ are banned as well. We're interested in the minimum value of $t$ such that $(t - a + 1)$ is even, so, we can keep two separate sets $R_{even}$ and $R_{odd}$ for even and odd values, and look for the minimum in one of them. So, it's easy now to determine if a pair $(a, b)$ is suitable or not. We can try all $b$, check is there is at least one fountain on $[a, b]$ and add $(b - a + 1)$ to the answer if the pair is suitable. Let's improve the solution to $O(n\log\left(m+n\right))$. We can note that each operation that changes banned positions for the second type gardens is a range query over odd or even numbers. So we can handle it with segment tree with range queries. Similarly, the gardens of the first type reduce non-banned positions of each parity to some segment, so we can do a range query to count the number of non-banned positions in the two trees described. The overall complexity is $O(n\log\left(m+n\right))$.
[ "data structures" ]
3,500
null
799
G
Cut the pie
Arkady reached the $n$-th level in Township game, so Masha decided to bake a pie for him! Of course, the pie has a shape of convex $n$-gon, i.e. a polygon with $n$ vertices. Arkady decided to cut the pie in two equal in area parts by cutting it by a straight line, so that he can eat one of them and give the other to Masha. There is a difficulty because Arkady has already put a knife at some point of the pie, so he now has to cut the pie by a straight line passing trough this point. Help Arkady: find a line that passes through the point Arkady has put a knife into and cuts the pie into two parts of equal area, or determine that it's impossible. Your program has to quickly answer many queries with the same pie, but different points in which Arkady puts a knife.
Let's first prove that solution always exists. Define $f( \alpha )$ as the difference between the area of the polygon part contained in the halfplane with polar angles in range $[ \alpha , \alpha + \pi ]$ and the area of the polygon part contained in the halfplane with polar angles in range $[ \alpha + \pi , \alpha + 2 \pi ]$. Note that $f(0) = - f( \pi )$, and since $f$ is a continuous function, it reaches zero somewhere on $[0, \pi ]$. The proof leads us to the concept of a solution. If we can compute $f( \alpha )$ fast, we can do a binary search over $ \alpha $ to find the root. Computing $f( \alpha )$ consists of two parts. First, we should find the intersection points of the line with the polygon, it is a known problem which can be solved in $O(n\log n)$. Second, we should compute the area, and there we can use prefix sums for oriented triangle (the origin and a polygon edge) areas that we use to compute the area of the whole polygon. The only thing we have to add is the oriented area of three new segments, that is easy to compute. The overall complexity is $O(n\log n\log\varepsilon)$, where $ \epsilon $ is the required precision. Note that the angle precision should be more accurate than the required area precision.
[ "binary search", "data structures", "geometry" ]
3,500
null
801
A
Vicious Keyboard
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string $s$ with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.
We can count the number of times the string "VK" appears as a substring. Then, we can try to replace each character with "V" or "K", do the count, and return the maximum such count. Alternatively, we can notice if there are currently $X$ occurrences of "VK" in the string, then we can either have $X$ or $X + 1$ after modifying at most one character. Try to see if you can find a necessary and sufficient condition for it being $X + 1$ (or see the second solution.
[ "brute force" ]
1,100
print (lambda s: s.count("VK") + int(any(x*3 in "K" + s + "V" for x in "VK")))(raw_input())
801
B
Valued Keys
You found a mysterious function $f$. The function takes two strings $s_{1}$ and $s_{2}$. These strings must consist only of lowercase English letters, and must be the same length. The output of the function $f$ is another string of the same length. The $i$-th character of the output is equal to the minimum of the $i$-th character of $s_{1}$ and the $i$-th character of $s_{2}$. For example, $f($"ab", "ba"$)$ = "aa", and $f($"nzwzl", "zizez"$)$ = "niwel". You found two strings $x$ and $y$ of the same length and consisting of only lowercase English letters. Find any string $z$ such that $f(x, z) = y$, or print -1 if no such string $z$ exists.
First, let's check for impossible cases. If there exists a position $i$ such that the $i$-th character of $x$ is less than the $i$-th character of $y$, then it is impossible. Now, let's assume it's always possible and construct an answer. We can notice that each position is independent, so let's simplify the problem to given two characters $a$ and $b$ with $a > = b$, find a character $c$ such that $min(a, c) = b$. Here, we can choose $c = b$. So, for the original problem, if the answer is possible, we can print $y$.
[ "constructive algorithms", "greedy", "strings" ]
900
x,y = raw_input(), raw_input() print all(a>=b for a,b in zip(x,y)) * y or "-1"
803
A
Maximal Binary Matrix
You are given matrix with $n$ rows and $n$ columns filled with zeroes. You should put $k$ ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal. One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one. If there exists no such matrix then output -1.
Let's construct matrix from top to bottom, from left to right. At current step we consider position $(i, j)$. Look at contents of cells $a[i][j]$ and $a[j][i]$. If number of zeroes in them doesn't exceed $k$, then let's fill those cells with ones and decrease $k$ by this number. If $k$ isn't equal to $0$ in the end of algorithm, then there is no answer. Overall complexity: $O(n^{2})$.
[ "constructive algorithms" ]
1,400
null
803
B
Distances to Zero
You are given the array of integer numbers $a_{0}, a_{1}, ..., a_{n - 1}$. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.
Let's divide the solution into two parts: firstly check the closest zero to the left and then the closest zero to the right. After that we can take minimum of these numbers. Initialize distance with infinity. Iterate over array from left to right. If value in current position is $0$ then set distance to $0$, otherwise increase distance by $1$. On each step write value of distance to the answer array. Do the same thing but going from right to left. This will find closest zero to the right. Now you should write minimum of current value of distance and value that's already in answer array. Finally you should retrieve the answer from distances. Overall complexity: $O(n)$.
[ "constructive algorithms" ]
1,200
null
803
C
Maximal GCD
You are given positive integer number $n$. You should create such \textbf{strictly increasing} sequence of $k$ positive numbers $a_{1}, a_{2}, ..., a_{k}$, that their sum is equal to $n$ and greatest common divisor is maximal. Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them. If there is no possible sequence then output -1.
Notice that GCD of the resulting sequence is always a divisor of $n$. Now let's iterate over all divisors up to $\sqrt{n}$. Current divisor is $d$. One of the ways to retrieve resulting sequence is to take $d, 2d, 3d, ..., (k - 1) \cdot d$, their sum is $s$. The last number is $n - s$. You should check if $n - s > (k - 1) \cdot d$. $s$ is the sum of arithmetic progression, its equal to $d\cdot{\frac{k\cdot(k-1)}{2}}$. Don't forget that you should consider $d$ and $\textstyle{\frac{n}{d}}$, if you check divisors up to $\sqrt{n}$. Take maximum of possible divisors or output -1 if there were no such divisors. Overall complexity: $O({\sqrt{n}})$.
[ "constructive algorithms", "greedy", "math" ]
1,900
null
803
D
Magazine Ad
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this: There are space-separated non-empty words of lowercase and uppercase Latin letters. There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding. The ad can occupy no more that $k$ lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it. You should write a program that will find minimal width of the ad.
Firstly notice that there is no difference between space and hyphen, you can replace them with the same character, if you want. Let's run binary search on answer. Fix width and greedily construct ad - wrap word only if you don't option to continue on the same line. Then check if number of lines doesn't exceed $k$. Overall complexity: $O(|s|\cdot\log|s|)$.
[ "binary search", "greedy" ]
1,900
null
803
E
Roma and Poker
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes $1$ virtual bourle from the loser. Last evening Roma started to play poker. He decided to spend no more than $k$ virtual bourles — he will stop immediately if the number of his loses exceeds the number of his wins by $k$. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by $k$. Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won $k$ bourles or he lost. The sequence written by Roma is a string $s$ consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: - In the end the absolute difference between the number of wins and loses is equal to $k$; - There is no hand such that the absolute difference before this hand was equal to $k$. Help Roma to restore any such sequence.
This problem can be solved using dynamic programming: $dp_{i, j}$ is true if Roma could play first $i$ games with balance $j$. $dp_{0, 0}$ is true; and for each $dp_{i, j}$ such that $0 \le i < n$ and $- k < j < k$ we update $dp_{i + 1, j + 1}$ if $s_{i} = W$, $dp_{i + 1, j}$ if $s_{i} = D$, $dp_{i + 1, j - 1}$ if $s_{i} = L$, and all three states if $s_{i} =$ ?. If either of $dp_{n, k}$ and $dp_{n, - k}$ is true, then we can restore the sequence. Time and memory complexity is $O(n \cdot k)$. As an exercise, you can think about linear solution.
[ "dp", "graphs" ]
2,000
null
803
F
Coprime Subsequences
Let's call a non-empty sequence of positive integers $a_{1}, a_{2}... a_{k}$ coprime if the greatest common divisor of all elements of this sequence is equal to $1$. Given an array $a$ consisting of $n$ positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo $10^{9} + 7$. Note that two subsequences are considered different if chosen indices are different. For example, in the array $[1, 1]$ there are $3$ different subsequences: $[1]$, $[1]$ and $[1, 1]$.
This problem can be solved using inclusion-exclusion. Let $f(x)$ be the number of subsequences such that all elements of the subsequence are divisible by $x$. We can calculate $cnt(x)$, which is the number of elements divisible by $x$, by factorizing all elements of the sequence and generating their divisors, and $f(x) = 2^{cnt(x)} - 1$. Then we can apply the inclusion-exclusion principle and get the resulting formula: $\textstyle\sum_{i=1}^{10^{5}}\mu(x)f(x)$, where $ \mu $ is the Möbius function.
[ "bitmasks", "combinatorics", "number theory" ]
2,000
null
803
G
Periodic RMQ Problem
You are given an array $a$ consisting of positive integers and $q$ queries to this array. There are two types of queries: - $1$ $l$ $r$ $x$ — for each index $i$ such that $l ≤ i ≤ r$ set $a_{i} = x$. - $2$ $l$ $r$ — find the minimum among such $a_{i}$ that $l ≤ i ≤ r$. We decided that this problem is too easy. So the array $a$ is given in a compressed form: there is an array $b$ consisting of $n$ elements and a number $k$ in the input, and before all queries $a$ is equal to the concatenation of $k$ arrays $b$ (so the size of $a$ is $n·k$).
Most of the solutions used the fact that we can read all the queries, compress them and process after the compression using simple segment tree. But there is also an online solution: Let's build a sparse table on array $b$ to answer queries on segments that are not modified in $O(1)$. To process modification segments, we will use implicit segment tree and lazy propagation technique. We do not build the whole segment tree; instead, in the beginning we have only one node for segment $[1, n \cdot k]$, and if some modification query accesses some node, but does not modify the complete segment this node maintains, only then we create the children of this node. So, the leaves of the segment tree are the nodes such that their segments are completely set to some value or not modified at all. Since each modification query affects only $O(log(n \cdot k))$ nodes, the resulting complexity will be $O(qlog(n \cdot k) + nlogn)$.
[ "data structures" ]
2,300
null
804
A
Find Amir
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are $n$ schools numerated from $1$ to $n$. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools $i$ and $j$ costs $(i+j)\operatorname*{mad}\left(n+1\right)$ and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Consider pairs of schools cost of their traverse is $0$: $\{1,n\},\;\{2,n-1\},\;\{3,n-2\}\ldots,\;\{\lfloor{\frac{x}{2}}\},\;\}{\frac{x}{2}}\}+1\}$. Connect this pairs with traversing from the second of each pair to the first of the next pair. So if $n = 2 \cdot k$ the answer is $k - 1$ and if $n = 2 \cdot k + 1$ the answer is $k$. The minimum number of direct paths should be $n - 1$, so because of using all of $0$s and make the other direct paths with $1$s the path is minimum possible spanning tree. From: saliii, Writer: saliii Time Complexity: $O(1)$ Time Complexity: $O(1)$ Memory complexity: $O(1)$
[ "constructive algorithms", "greedy", "math" ]
1,000
int main(){ int n; scanf("%d", &n); printf("%d\n", (n-1)/2); }
804
B
Minimum number of steps
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo $10^{9} + 7$. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.
The final state will be some character $'a'$ after $'b'$: $"bbb...baaa...a"$ It's obvious to prove all $'b'$s are distinctive to each other(i.e. Each $'b'$ in the initial state, will add some number of $'b'$s to the final state disjoint from other $'b'$s). For a character $'b'$ from the initial state it will double after seeing a character $'a'$. For each $i$-th character $'b'$, consider $t_{i}$ the number of $a$ before it. So the final number of $'b'$s can be defined as $\textstyle\sum_{i}2^{l_{i}}$. From: MohammadJA, Writer: MohammadJA Time Complexity: $O(1)$ Time Complexity: ${\cal O}(n)$ Memory complexity: ${\mathcal{O}}(n)$
[ "combinatorics", "greedy", "implementation", "math" ]
1,400
int c,d,i,n,m,k,x,j=1000000007; string s; main(){ cin>>s; for(i=s.size()-1;i>=0;i--){ if(s[i]=='b')c++;else{ k+=c;c*=2;k%=j;c%=j; } } cout<<k; }
804
C
Ice cream coloring
Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?" We have a tree $T$ with $n$ vertices and $m$ types of ice cream numerated from $1$ to $m$. Each vertex $i$ has a set of $s_{i}$ types of ice cream. Vertices which have the $i$-th ($1 ≤ i ≤ m$) type of ice cream form a connected subgraph. We build a new graph $G$ with $m$ vertices. We put an edge between the $v$-th and the $u$-th ($1 ≤ u, v ≤ m$, $u ≠ v$) vertices in $G$ if and only if there exists a vertex in $T$ that has both the $v$-th and the $u$-th types of ice cream in its set. The problem is to paint the vertices of $G$ with minimum possible number of colors in a way that no adjacent vertices have the same color. Please note that we consider that empty set of vertices form a connected subgraph in this problem. As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.
Let's guess as obvious as possible. We can get the answer is at least $\begin{array}{r}{\mathbf{Hax}\mathbf{S}{\hat{z}}_{i}}\\ {\mathbf{k}{\hat{-}}i\leq n}\end{array}$.We'll just use a dfs to paint the graph with this answer. Run dfs and in each step, when we are in vertex $v$ with parent $par$, for each ice cream, if it is in the set of $par$, then its color is given in the par's set. If not, we'll paint it with a color that isn't used in this set. To prove the algorithm works, assume the first step we paint an ice cream by $(answer + 1)$-th color, you know the number of ice creams is at last equal to answer, some of these ice creams was painted in the par's set and obviously we don't need to more than $sz_{v}$ color to paint them. From: saliii, Writer: saliii Time Complexity: $O(n+\sum_{i}s_{i}\cdot\log(\sum_{i}s_{i}))$ Memory complexity: $O(n+\sum_{i}s i)$ Time Complexity: $O(n+\sum_{i}s_{i})$ Memory complexity: $O(n+\sum_{i}s i)$
[ "constructive algorithms", "dfs and similar", "greedy" ]
2,200
vector <int> Vs[300050]; vector <int> conn[300050]; int ans[300050]; bool chk[500050]; bool dchk[300050]; vector <int> Vu; void DFS(int n) { dchk[n] = true; for (auto it : Vs[n]) { if (ans[it]) chk[ans[it]] = true; else Vu.push_back(it); } int a = 1; for (auto it : Vu) { while (chk[a]) a++; ans[it] = a++; } for (auto it : Vs[n]) chk[ans[it]] = false; Vu.clear(); for (auto it : conn[n]) { if (dchk[it]) continue; DFS(it); } } int main() { int N, M, i; scanf("%d %d", &N, &M); for (i = 1; i <= N; i++) { int t1, t2; scanf("%d", &t1); while (t1--) { scanf("%d", &t2); Vs[i].push_back(t2); } } for (i = 1; i < N; i++) { int t1, t2; scanf("%d %d", &t1, &t2); conn[t1].push_back(t2); conn[t2].push_back(t1); } DFS(1); int mx = 0; for (i = 1; i <= M; i++) { mx = max(mx, ans[i]); if (ans[i] == 0) ans[i] = 1; } mx = max(mx, 1); printf("%d\n", mx); for (i = 1; i <= M; i++) printf("%d ", ans[i]); return !printf("\n"); }
804
D
Expected diameter of a tree
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem. We have a forest (acyclic undirected graph) with $n$ vertices and $m$ edges. There are $q$ queries we should answer. In each query two vertices $v$ and $u$ are given. Let $V$ be the set of vertices in the connected component of the graph that contains $v$, and $U$ be the set of vertices in the connected component of the graph that contains $u$. Let's add an edge between some vertex $a\in V$ and some vertex in $b\in U$ and compute the value $d$ of the resulting component. If the resulting component is a tree, the value $d$ is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of $d$, if we choose vertices $a$ and $b$ from the sets uniformly at random? Can you help Pasha to solve this problem? The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices. Note that queries don't add edges to the initial forest.
Let's solve the problem for two trees. Define $d_{t}$ as diameter of $t$-th tree and $f_{ti}$ as the maximum path starting from $i$-th vertex of $t$-th tree, for all valid $i$ and $j$, assume that the edge is between them and find the diameter with $max(f_{1i} + f_{2j} + 1, max(d_{1}, d_{2}))$. The answer will be: $\frac{\sum\sum\operatorname*{max}(f_{1_{i}}+f_{2_{j}+1,\operatorname*{max}(d_{1},d_{2}))}}{s z_{1}.s z_{2}}$ Let's improve the $O(n^{2})\,$ solution to $O(n\cdot\log\left(n\right))$. Let's sort the arrays $f_{1}$ and $f_{2}$ decreasingly and make two partial sums of them, $p_{1}$ and $p_{2}$, such that $p_{t_{i}}=\sum_{j=1}^{t-1}f_{t_{j}}$. Iterate on $f_{t}$, in step $i$, we will check all of the valid edges which $i$-th vertex is an endpoint of that: Consider the first element in $f_{1 - t}$ as $j$ such that $f_{ti} + f_{(1 - t)j} > max(d_{1}, d_{2})$, by binary search, according to the previous solution for $i$-th step, we should add it to the answer: $p_{(1 - t)j} + n - j - 1 \cdot max(d_{1}, d_{2})$ Let's prove if in each query, we choose $t$, the smaller tree, the solution will be accepted. There is two simple modes we should consider: $1$- If $\operatorname*{min}(s z_{1},s z_{2})<{\sqrt{(}}n)$: The time complexity will be $O(\sqrt{(n)}\cdot\log(n)$ per query. $2$- If $\operatorname*{min}(s z_{1},s z_{2})\geq{\sqrt{(n)}}$: Number of trees with $s z\geq{\sqrt{(}}n)$ is at last ${\sqrt{(}}n\mathbf{)}$. If we don't calculate the answer for two same pairs of vertices by memoization, at last ${\sqrt{(}}n\mathbf{)}$ time we need to these bigger trees, so it yields $O(\sum s z_{i}\cdot{\sqrt{(}}n)\cdot\log(n))=O(n\cdot{\sqrt{(}}n)\cdot\log(n))$. From: MohammadJA, Writer: MohammadJA Time Complexity: $O(q\cdot{\sqrt{(}}(n)\cdot\log(n)+n\cdot{\sqrt{(}}n)\cdot\log(n))$ Memory complexity: ${\mathcal{O}}(n)$
[ "binary search", "brute force", "dfs and similar", "dp", "sortings", "trees" ]
2,500
using namespace std ; #define int long long const int MAXN = 1e5 + 100 ; vector<int>ver[MAXN] , com[MAXN] , ps[MAXN] ; int vis[MAXN] , dis[MAXN] ; int mxr , mxid ; void dfs(int v , int col = -1 , int h = 0 , int par = -1){ vis[v] = max(vis[v] , col) ; if(mxr < h)mxid = v , mxr = h ; dis[v] = max(h , dis[v]) ; if(col > 0)com[col] . push_back(dis[v]) ; for(auto u : ver[v]){ if(u == par)continue ; dfs(u , col , h + 1 , v) ; } } map<pair<int , int> , int> check ; int32_t main(){ ios_base::sync_with_stdio(0) ; cin . tie(0) ; cout . tie(0) ; int n , m , q ; cin >> n >> m >> q ; for(int i = 0 ; i < m ; i ++){ int x , y ; cin >> x >> y ; x -- , y -- ; ver[x] . push_back(y) ; ver[y] . push_back(x) ; } int cnt = 0 ; for(int i = 0 ; i < n ; i ++){ if(vis[i])continue ; mxr = 0 , mxid = i ; dfs(i) ; mxr = 0 ; dfs(mxid) ; dfs(mxid , ++ cnt) ; sort(com[cnt] . begin() , com[cnt] . end()) ; ps[cnt] . push_back(0) ; for(auto v : com[cnt])ps[cnt] . push_back(ps[cnt] . back() + v) ; } cout << fixed << setprecision(10) ; while(q --){ int x , y ; cin >> x >> y ; x -- , y -- ; x = vis[x] ; y = vis[y] ; if(com[x] . size() > com[y] . size())swap(x , y) ; if(x == y){cout << -1 << '\n' ; continue ; } if(check[{x , y}] > 0){cout << double(check[{x , y}]) / (1ll * com[x] . size() * com[y] . size()) << '\n' ; continue ; } int ans = 0 , mxd = max(com[x] . back() , com[y] . back()) ; for(auto v : com[x]){ int num = lower_bound(com[y] . begin() , com[y] . end() , mxd - v - 1) - com[y] . begin() ; ans += num * mxd + (com[y] . size() - num) * (v + 1) + ps[y] . back() - ps[y][num] ; } check[{x , y}] = ans ; cout << double(check[{x , y}]) / (1ll * com[x] . size() * com[y] . size()) << '\n' ; } }
804
E
The same permutation
Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions $(i, j)$, where $i < j$, exactly once. MoJaK doesn't like to upset Sajjad. Given the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that.
If $\textstyle{{\binom{n}{2}}\mod2=1}$ then it is simply provable the answer is "NO". So we just need to check $n = 4 \cdot k, 4 \cdot k + 1$. There is a constructive solution to do that. Assume that $n = 4 \cdot k$. Partition numbers to $k$ classes, each class contains a $4$ consecutive numbers. We can solve each class itself by these swaps to reach the same permutation: $(3, 4) (1, 3) (2, 4) (2, 3) (1, 4) (1, 2)$ We can do swaps between two different classes as follows to reach the same permutation, assume that the first element of the first class is $i$ and for the second class is $j$: $(i + 3, j + 2) (i + 2, j + 2) (i + 3, j + 1) (i, j + 1) (i + 1, j + 3) (i + 2, j + 3) (i + 1, j + 2) (i + 1, j + 1)$ $(i + 3, j) (i + 3, j + 3) (i, j + 2) (i, j + 3) (i + 2, j) (i + 2, j + 1) (i + 1, j) (i, j)$ Now assume that $n = 4 \cdot k + 1$. Do the swaps above with first $4 \cdot k$ numbers with these changes in place of swaps in the classes itself to satisfy the last number: $(3, n) (3, 4) (4, n) (1, 3) (2, 4) (2, 3) (1, 4) (1, n) (1, 2) (2, n)$ From: saliii, Writer: saliii Time Complexity: $O(n^{2})\,$ Memory complexity: $O(1)$
[ "constructive algorithms" ]
3,100
int n; int main() { scanf("%d",&n); if(n%4>1)return printf("NO\n"),0; printf("YES\n"); for(int i=1;i<n;i+=4) { if(n%4)printf("%d %d\n%d %d\n%d %d\n",i+2,n,i+2,i+3,i+3,n); else printf("%d %d\n",i+2,i+3); printf("%d %d\n",i,i+2); printf("%d %d\n",i+1,i+3); printf("%d %d\n",i+1,i+2); printf("%d %d\n",i,i+3); if(n%4)printf("%d %d\n%d %d\n%d %d\n",i,n,i,i+1,i+1,n); else printf("%d %d\n",i,i+1); } for(int i=1;i<n;i+=4) for(int j=i+4;j<n;j+=4) { printf("%d %d\n",i+3,j+2); printf("%d %d\n",i+2,j+2); printf("%d %d\n",i+3,j+1); printf("%d %d\n",i,j+1); printf("%d %d\n",i+1,j+3); printf("%d %d\n",i+2,j+3); printf("%d %d\n",i+1,j+2); printf("%d %d\n",i+1,j+1); printf("%d %d\n",i+3,j); printf("%d %d\n",i+3,j+3); printf("%d %d\n",i,j+2); printf("%d %d\n",i,j+3); printf("%d %d\n",i+2,j); printf("%d %d\n",i+2,j+1); printf("%d %d\n",i+1,j); printf("%d %d\n",i,j); } return 0; }
804
F
Fake bullions
In Isart people don't die. There are $n$ gangs of criminals. The $i$-th gang contains $s_{i}$ evil people numerated from $0$ to $s_{i} - 1$. Some of these people took part in a big mine robbery and picked \textbf{one} gold bullion each (these people are given in the input). That happened $10^{100}$ years ago and then all of the gangs escaped to a remote area, far from towns. During the years, they were copying some gold bullions according to an organized plan in order to not get arrested. They constructed a \textbf{tournament} directed graph (a graph where there is exactly one directed edge between every pair of vertices) of gangs (the graph is given in the input). In this graph an edge from $u$ to $v$ means that in the $i$-th hour the person $i\mathrm{~mod~}s_{n}$ of the gang $u$ can send a fake gold bullion to person $i\mathrm{~mod~}s_{n}$ of gang $v$. He sends it if he has some bullion (real or fake), while the receiver doesn't have any. Thus, at any moment each of the gangsters has zero or one gold bullion. Some of them have real bullions, and some of them have fake ones. In the beginning of this year, the police has finally found the gangs, but they couldn't catch them, as usual. The police decided to open a jewelry store so that the gangsters would sell the bullions. Thus, every gangster that has a bullion (fake or real) will try to sell it. If he has a real gold bullion, he sells it without problems, but if he has a fake one, there is a choice of two events that can happen: - The person sells the gold bullion successfully. - The person is arrested by police. The power of a gang is the number of people in it that successfully sold their bullion. After all selling is done, the police arrests $b$ gangs out of top gangs. Sort the gangs by powers, we call the first $a$ gang top gangs(you can sort the equal powers in each order). Consider all possible results of selling fake gold bullions and all possible choice of $b$ gangs among the top gangs. Count the number of different sets of these $b$ gangs modulo $10^{9} + 7$. Two sets $X$ and $Y$ are considered different if some gang is in $X$ and isn't in $Y$.
As the hints said this problem have two part: First we want to solve the first part that is evaluating the $mn_{i}$ and $mx_{i}$ for gangs. Obviously $mn_{i}$ will be the number of thieves have a gold in $i$-th gang. $lemma1$:Consider there is just a single edge from $v$ to $u$; as hints said if one thief in $v$ with index $i$ has a gold it copied its gold to every $j$ in $u$ if and only if $i\mathrm{\boldmath~\nod~}g c d(s_{v},s_{u})=j\;\;\mathrm{\boldmath~\nod~}g c d(s_{v},s_{u})$ . Now we call $f(v, g)$ that $g|sz_{v}$ as a gang with size $g$ that thief number $i$ has a gold in this gang if and only if one of the thiefs with index $j$ in $v$-th gang has a gold such that $jmod g=i$. $lemma2$: Consider two edge like $v\sim u$ and $u\sim w$. as thing said in hints and above we can consider that $v$ affect in $w$ like this edge: $f(v,g c d(s z_{v},s z_{u}))\sim w$. $lemma3$: Consider a directed walk like $w_{1}, w_{2}, , ..., w_{n}$. from two last lemmas we can consider the affect of $w_{1}$ on $w_{n}$ as: $f(w_{1},g c d(w_{1},w_{2},\ldots,w_{n}))\sim w_{n}$ $lemma4$: Consider a closed directed walk from $v$ like $v, w_{1}, w_{2}, ..., w_{n}, v$ from three last lemmas we can consider $m x_{v}=m x_{u}\cdot{\frac{s_{\mathrm{{B}}}}{s_{\mathrm{{a}}}}}$ in which u is $f(v, gcd(v, w_{1}, w_{2}, ..., w_{n}))$. So now decompose graph of gangs to maximal strongly connected components from $lemma4$ for every component like $a_{1}, a_{2}, ..., a_{n}$, we can consider in place of all of them gang $v$ with size equal to $g = gcd(a_{1}, a_{2}, ..., a_{n})$ such that $i$-th thief has a gold in $v$ if and only if there is a $j$ such that $i$-th thief in $f(a_{j}, g)$ has a gold. So we decreased the problem to a dag tournament, Let's sort the vertices with topological sort. We'll find a Hamiltonian path of vertices such that for every different $i$ and $j$ there is directed edge from $i$-th vertex of the path to $j$-th vertex of the path if and only if $i < j$. By the lemma 2 it's sufficient to solve the problem for the path itself. So we decreased the problem to a only path. For the path, just do greedily, for each $i$ from $1$ to $n$ affect the $i$-th vertex on the $i + 1$-th vertex, it can be done with complexity $O(\sum_{i=1}^{n}s_{i})$. So $mx_{i}$ is equal to the number of ones after doing all of the things. For every vertex we'll consider a $mx_{i}$ and $mn_{i}$.We sort this scores in an array T. $|T| = 2 \cdot n$. Starting from biggest to smallest one. When we reach maximum of $i$-th vertex and, we fix this vertex and count number of sets he is in which and it has the minimum score of the set: There is two kinds of vertices, $q$ element of array $mn$ are more than or equal to $mn_{i}$, and of the others, $p$ elements of array $mx$ are more than $mx_{i}$(means if $j$-th vertex is in the second kind then $mn_{i} \le mx_{i} < mx_{j}$. So we have to fix number of second kind of vertices as $j$($1 \le j \le min(b - 1, p)$) and for all $j$ do this: $\mathrm{~f~}(q+j<a)~a n s=a n s+(\underline{{{p}}})\cdot\left(\l_{B-1-j}\right)$ It is clear when we fix maximum of $j$-th and $i$-th vertex as the minimum score of the set, we didn't count one such sets twice and when fixing $i$-th vertex the fact holds. Also it is clear we count all of the situations. The complexity of this part is $O(n\cdot b)$. From: saliii, Writer: amsen Time Complexity: $O(\sum_{i}s_{i}+n\cdot b)$ Memory complexity: $O(n^{2}+\sum_{i}s_{i})$
[ "combinatorics", "dfs and similar", "dp", "graphs", "number theory" ]
3,400
#include <bits/stdc++.h> #define xx first #define yy second #define mp make_pair #define pb push_back #define fill( x, y ) memset( x, y, sizeof x ) #define copy( x, y ) memcpy( x, y, sizeof x ) using namespace std; typedef long long LL; typedef pair < int, int > pa; inline int read() { int sc = 0, f = 1; char ch = getchar(); while( ch < '0' || ch > '9' ) { if( ch == '-' ) f = -1; ch = getchar(); } while( ch >= '0' && ch <= '9' ) sc = sc * 10 + ch - '0', ch = getchar(); return sc * f; } const int MAXN = 5005; const int MAXM = 2000005; const int mod = 1e9 + 7; int n, a, b, len[MAXN], can[MAXM], id_cnt, L[MAXN], R[MAXN], C[MAXN][MAXN]; int dfn[MAXN], scc[MAXN], low[MAXN], tim, num, st[MAXN], top, w[MAXN], ans; vector < int > G[MAXN], id[MAXN], scc_bit[MAXN], v[MAXN]; char ch[MAXM]; inline void inc(int &x, int y) { x += y; if( x >= mod ) x -= mod; } inline void dfs(int x) { dfn[ x ] = low[ x ] = ++tim; st[ ++top ] = x; for( auto y : G[ x ] ) if( !dfn[ y ] ) dfs( y ), low[ x ] = min( low[ x ], low[ y ] ); else if( !scc[ y ] ) low[ x ] = min( low[ x ], dfn[ y ] ); if( dfn[ x ] == low[ x ] ) { num++; int t = 0; while( t ^ x ) { scc[ t = st[ top-- ] ] = num; w[ num ] = __gcd( w[ num ], len[ t ] ); v[ num ].pb( t ); } scc_bit[ num ].resize( w[ num ] ); for( auto y : v[ num ] ) for( int d = 0 ; d < len[ y ] ; d++ ) if( can[ id[ y ][ d ] ] ) scc_bit[ num ][ d % w[ num ] ] = 1; } } int main() { #ifdef wxh010910 freopen( "data.in", "r", stdin ); #endif n = read(), a = read(), b = read(); for( int i = 0 ; i <= n ; i++ ) { C[ i ][ 0 ] = 1; for( int j = 1 ; j <= i ; j++ ) inc( C[ i ][ j ] = C[ i - 1 ][ j ], C[ i - 1 ][ j - 1 ] ); } for( int i = 1 ; i <= n ; i++ ) { scanf( "%s", ch + 1 ); for( int j = 1 ; j <= n ; j++ ) if( ch[ j ] == '1' ) G[ i ].pb( j ); } for( int i = 1 ; i <= n ; i++ ) { len[ i ] = read(); scanf( "%s", ch ); for( int j = 0 ; j < len[ i ] ; j++ ) id[ i ].pb( ++id_cnt ), can[ id_cnt ] = ch[ j ] == '1', L[ i ] += can[ id_cnt ]; } for( int i = 1 ; i <= n ; i++ ) if( !dfn[ i ] ) dfs( i ); for( int i = num ; i > 1 ; i-- ) { int g = __gcd( w[ i ], w[ i - 1 ] ); w[ i - 1 ] = g; for( int j = 0 ; j < w[ i ] ; j++ ) scc_bit[ i - 1 ][ j % g ] |= scc_bit[ i ][ j ]; } for( int i = 1 ; i <= n ; i++ ) { int x = scc[ i ]; for( int j = 0 ; j < len[ i ] ; j++ ) R[ i ] += scc_bit[ x ][ j % w[ x ] ]; } for( int i = 1 ; i <= n ; i++ ) { int t1 = 0, t2 = 0; for( int j = 1 ; j <= n ; j++ ) if( L[ j ] > R[ i ] ) t1++; if( t1 >= a ) continue; for( int j = 1 ; j <= n ; j++ ) if( L[ j ] <= R[ i ] && mp( R[ j ], j ) > mp( R[ i ], i ) ) t2++; for( int j = 0 ; j < b && j <= t2 && j + t1 < a ; j++ ) inc( ans, 1LL * C[ t2 ][ j ] * C[ t1 ][ b - j - 1 ] % mod ); } return printf( "%d\n", ans ), 0; }
805
A
Fake NP
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given $l$ and $r$. For all integers from $l$ to $r$, inclusive, we wrote down all of their integer divisors except $1$. Find the integer that we wrote down the maximum number of times. Solve the problem to show that it's not a NP problem.
If $l \le r$ the answer is 2, other wise l. To prove this phrase, assume the answer is $x$ ($2 < x$), consider all of multiples of $x$ from $l$ to $r$ as $z_{1}, z_{2}, ..., z_{k}$. If $k = = 1$, $2$ is also a correct answer, otherwise numbers from $l$ to $z_{2} - 1$ make at least $3$ even number, and for each multiple from $z_{2}$ to $z_{k - 1}$ as $Z$, $Z$ or $Z + 1$ is even, so 2 is also a correct answer. Bounce: Find the maximum number, occurs maximum number of times in the segment. From: saliii, Writer: saliii Time Complexity: $O(1)$ Memory complexity: $O(1)$
[ "greedy", "math" ]
1,000
int main(){ int l, r; scanf("%d%d", &l, &r); printf("%d", l == r ? l : 2); }
805
B
3-palindrome
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given $n$ he wants to obtain a string of $n$ characters, each of which is either 'a', 'b' or 'c', with no palindromes of length $3$ appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
The answer is constructive as follows: $"aabbaabbaabb..."$ From: saliii, Writer: saliii Time Complexity: $O(1)$ Time Complexity: ${\mathcal{O}}(n)$ Memory complexity: ${\mathcal{O}}(n)$
[ "constructive algorithms" ]
1,000
int N; int main() { scanf("%d", &N); for (int i = 0; i < N; i++) putchar(i & 2 ? 'b' : 'a'); puts(""); }
807
A
Is it rated?
\underline{Is it rated?} Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it. Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known. It's known that if at least one participant's rating has changed, then the round was rated for sure. It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed. In this problem, you should not make any other assumptions about the rating system. Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
To solve this problem, you just had to read the problem statement carefully. Looking through the explanations for the example cases was pretty useful. How do we check if the round is rated for sure? The round is rated for sure if anyone's rating has changed, that is, if $a_{i} \neq b_{i}$ for some $i$. How do we check if the round is unrated for sure? Given that all $a_{i} = b_{i}$, the round is unrated for sure if for some $i < j$ we have $a_{i} < a_{j}$. This can be checked using two nested for-loops over $i$ and $j$. Exercise: can you check the same using one for-loop? How do we find that it's impossible to determine if the round is rated or not? If none of the conditions from steps 1 and 2 is satisfied, the answer is "maybe".
[ "implementation", "sortings" ]
900
n = int(input()) results = [] for i in range(n): results.append(list(map(int, input().split()))) for r in results: if r[0] != r[1]: print("rated") exit() for i in range(n): for j in range(i): if results[i][0] > results[j][0]: print("unrated") exit() print("maybe")
807
B
T-Shirt Hunt
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt. Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place $p$. Now the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let $s$ be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed: \begin{verbatim} i := (s div 50) mod 475 repeat 25 times: i := (i * 96 + 42) mod 475 print (26 + i) \end{verbatim} Here "div" is the integer division operator, "mod" is the modulo (the remainder of division) operator. As the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of $s$. You're in the lead of the elimination round of 8VC Venture Cup 2017, having $x$ points. You believe that having at least $y$ points in the current round will be enough for victory. To change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though. You want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of \textbf{successful} hacks you have to do to achieve that?
This problem was inspired by this comment: http://codeforces.com/blog/entry/49663#comment-337281. The hacks don't necessarily have to be stupid, though :) Initially, we have $x$ points. To win the current round, we need to score any number of points $s$ such that $s \ge y$. If we know our final score $s$, we can check if we get the T-shirt using the given pseudocode. Moreover, since hacks change our score only by multiples of 50, the difference $s - x$ has to be divisible by 50. Naturally, out of all $s$ satisfying the conditions above, we need to aim at the smallest possible $s$, since it's easy to decrease our score, but difficult to increase. How many successful hacks do we need to make our score equal to $s$? If $s \le x$, we need 0 successful hacks, since we can just make $(x - s) / 50$ unsuccessful hacks. If $s > x$ and $s - x$ is divisible by 100, we need exactly $(s - x) / 100$ successful hacks. If $s > x$ and $s - x$ is not divisible by 100, we need $(s - x + 50) / 100$ successful hacks and one unsuccessful hack. All these cases can be described by a single formula for the number of successful hacks: $(max(0, s - x) + 50) / 100$ (here "$/$" denotes integer division). The constraints were low enough, and the number of required hacks was also low enough. A less effective but easier solution can be achieved if we just iterate over both the number of successful and unsuccessful hacks we make. Once we know these two numbers, we know our final score $s$ and we can explicitly check if this score gives us both the victory and the T-shirt.
[ "brute force", "implementation" ]
1,300
p, x, y = map(int, input().split()) def check(s): i = (s // 50) % 475 for t in range(25): i = (i * 96 + 42) % 475 if 26 + i == p: return True return False for up in range(500): for down in range(500): if x + 100 * up - 50 * down >= y and check(x + 100 * up - 50 * down): print(up) exit() assert(False)
808
A
Lucky Year
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Notice that the next lucky year always looks like (first digit of the current + 1) $ \cdot $ 10^(number of digits of the current - 1). It holds also for numbers starting with 9, it will be 10 $ \cdot $ 10^(number of digits - 1). The answer is the difference between the next lucky year and current year.
[ "implementation" ]
900
null
808
B
Average Sleep Time
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts $k$ days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last $n$ days. So now he has a sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the sleep time on the $i$-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider $k$ consecutive days as a week. So there will be $n - k + 1$ weeks to take into consideration. For example, if $k = 2$, $n = 3$ and $a = [3, 4, 7]$, then the result is ${\frac{(3+4)+(4+7)}{2}}=9$. You should write a program which will calculate average sleep times of Polycarp over all weeks.
To get the sum for $i$-th week you need to take sum of ($i - 1$)-th week, subtract first element of ($i - 1$)-th week from it and add up last element of $i$-th week. All common elements will remain. Thus by moving right week by week calculate sum of all weeks and divide it by $n - k + 1$. Overall complexity: $O(n)$.
[ "data structures", "implementation", "math" ]
1,300
null
808
C
Tea Party
Polycarp invited all his friends to the tea party to celebrate the holiday. He has $n$ cups, one for each of his $n$ friends, with volumes $a_{1}, a_{2}, ..., a_{n}$. His teapot stores $w$ milliliters of tea ($w ≤ a_{1} + a_{2} + ... + a_{n}$). Polycarp wants to pour tea in cups in such a way that: - Every cup will contain tea for at least half of its volume - Every cup will contain integer number of milliliters of tea - All the tea from the teapot will be poured into cups - All friends will be satisfied. Friend with cup $i$ won't be satisfied, if there exists such cup $j$ that cup $i$ contains less tea than cup $j$ but $a_{i} > a_{j}$. For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
At first, let's pour minimal amount of tea in each cup, that is $\left|{\frac{a_{1}}{2}}\right|$. If it requires more tea than available then it's -1. Now let's sort cups in non-increasing order by volume and start filling up them until we run out of tea in the teapot. It's easy to see that everyone will be satisfied that way. If sequence of $a_{i}$ is non-increasing then sequence of $\left|{\frac{a_{1}}{2}}\right|$ is also non-increasing. So we can't make someone unsatisfied by filling the cup with maximal possible volume. And finally get the right order of cups back and print the answer. Overall complexity: $O(n\log n)$.
[ "constructive algorithms", "greedy", "sortings" ]
1,400
null
808
D
Array Division
Vasya has an array $a$ consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position). \textbf{Inserting an element in the same position he was erased from is also considered moving.} Can Vasya divide the array after choosing the right element to move and its new position?
Suppose we want to move an element from the prefix to the suffix (if we need to move an element from the suffix to the prefix, we can just reverse the array and do the same thing). Suppose the resulting prefix will contain $m$ elements. Then we need to check that the prefix with $m + 1$ elements contains an element such that the sum of this prefix without this element is equal to the half of the sum of the whole array (and then we can move this element to the suffix). To check all the prefixes, we can scan the array from left to right while maintaining the set of elements on the prefix and the sum of these elements.
[ "binary search", "data structures", "implementation" ]
1,900
null
808
E
Selling Souvenirs
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market. This morning, as usual, Petya will come to the market. Petya has $n$ different souvenirs to sell; $i$th souvenir is characterised by its weight $w_{i}$ and cost $c_{i}$. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than $m$, and total cost is maximum possible. Help Petya to determine maximum possible total cost.
There are lots of different solutions for this problem. We can iterate on the number of $3$-elements we will take (in this editorial $k$-element is a souvenir with weight $k$). When fixing the number of $3$-elements (let it be $x$), we want to know the best possible answer for the weight $m - 3x$, while taking into account only $1$-elements and $2$-elements. To answer these queries, we can precalculate the values $dp[w]$ - triples $(cost, cnt1, cnt2)$, where $cost$ is the best possible answer for the weight $w$, and $cnt1$ and $cnt2$ is the number of $1$-elements and $2$-elements we are taking to get this answer. Of course, $dp[0] = (0, 0, 0)$, and we can update $dp[i + 1]$ and $dp[i + 2]$ using value of $dp[i]$. After precalculating $dp[w]$ for each possible $w$ we can iterate on the number of $3$-elements. There are also several binary/ternary search solutions.
[ "binary search", "dp", "greedy", "ternary search" ]
2,300
null
808
F
Card Game
Digital collectible card games have become very popular recently. So Vova decided to try one of these. Vova has $n$ cards in his collection. Each of these cards is characterised by its power $p_{i}$, magic number $c_{i}$ and level $l_{i}$. Vova wants to build a deck with total power not less than $k$, but magic numbers may not allow him to do so — Vova can't place two cards in a deck if the sum of the magic numbers written on these cards is a prime number. Also Vova cannot use a card if its level is greater than the level of Vova's character. At the moment Vova's character's level is $1$. Help Vova to determine the minimum level he needs to reach in order to build a deck with the required total power.
The most tricky part of the problem is how to check if some set of cards allows us to build a deck with the required power (not taking the levels of cards into account). Suppose we have not more than one card with magic number $1$ (if there are multiple cards with this magic number, then we obviously can use only one of these). Then two cards may conflict only if one of them has an odd magic number, and another has an even magic number - otherwise their sum is even and not less than $4$, so it's not a prime number. This allows us to solve this problem as follows: Construct a bipartite graph: each vertex represents a card, and two vertices are connected by an edge if the corresponding pair of cards can't be put in a deck. Then we have to find the maximum weight of independent set in this graph. This can be solved using maximum flow algorithm: construct a network where source is connected with every "odd" vertex (a vertex that represents a card with an odd magic number) by an edge with capacity equal to the power of this card; then connect every "odd" vertex to all "even" vertices that are conflicting with this vertex by edges with infinite capacities; and then connect every "even" vertex to the sink by an edge with capacity equal to the power of the card (all edges have to be directed). Then the maximum power of the deck is equal to $sum - mincut$, where $sum$ is the sum of all powers and $mincut$ is the minimum cut value between the source and the sink (which is equal to the maximum flow). This allows us to check if we can build a deck of required power using only some set of cards (for example, only cards with level less than or equal to some $x$).
[ "binary search", "flows", "graphs" ]
2,400
null
808
G
Anthem of Berland
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem. Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible. He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work. The anthem is the string $s$ of no more than $10^{5}$ small Latin letters and question marks. The most glorious victory is the string $t$ of no more than $10^{5}$ small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string $t$ in string $s$ is maximal. Note that the occurrences of string $t$ in $s$ can overlap. Check the third example for clarification.
Let's denote the string obtained by concatenation $t + # + s$ (where $#$ is some dividing character that isn't a part of the alphabet) as $ts$. Recall that KMP algorithm builds the prefix function for this string. We can calculate $dp[i][j]$ on this string, where $i$ is the position in this string and $j$ is the value of prefix function in this position. The value of $dp[i][j]$ is the maximum number of occurences of $t$ found so far (or $- 1$ if this situation is impossible). If $(i + 1)$th character is a Latin letter, then we just recalculate prefix function for this position (the fact that in KMP the value of prefix function won't exceed $|t|$ allows us to do so). If $(i + 1)$th character is a question mark, then we check all $26$ possible characters and recalculate prefix function for all of these characters (and update the corresponding $dp$ values). The size of $s$ and $t$ is pretty big, so we need to recalculate these values in $O(1)$ time; this can be done by precalculating the values of $next[i][j]$ ($i$ is the value of prefix function, $j$ is a new character and $next[i][j]$ is the value of prefix function after adding this character).
[ "dp", "strings" ]
2,300
null
809
A
Do you want a date?
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to $n$ computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis. Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from $1$ to $n$. So the $i$-th hacked computer is located at the point $x_{i}$. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task. Leha should calculate a sum of $F(a)$ for all $a$, where $a$ is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote $A$ the set of all integers from $1$ to $n$. Noora asks the hacker to find value of the expression $\sum_{a\subset A a s s o}F(a)$. Here $F(a)$ is calculated as the maximum among the distances between all pairs of computers from the set $a$. Formally, $F(a)=\operatorname*{max}_{i,j\in a}|x_{i}-x_{j}|$. Since the required sum can be quite large Noora asks to find it modulo $10^{9} + 7$. Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
We know, that a lot of different solutions exists on this task, I will describe the easiest in my opinion. Let's sort the coordinates in ascending order and iterate through the pairs of neighbours $x_{i}$ and $x_{i + 1}$. They are adding to the answer $x_{i + 1} - x_{i}$ in all the subsets, in which there is at least one point $a \le i$ and at least one point $b \ge i + 1$. The number of such subsets is equal to $(2^{i} - 1) * (2^{n - i} - 1)$.
[ "implementation", "math", "sortings" ]
1,500
st[0] = 1; for ( int j = 1; j < maxn; j++ ) st[j] = ( 2 * st[j - 1] ) % base; int n; scanf ( "%d", &n ); for ( int j = 0; j < n; j++ ) scanf ( "%d", &a[j] ); sort( a, a + n ); int ans = 0; for ( int j = 1; j < n; j++ ) { int len = a[j] - a[j - 1]; int cntL = j; int cntR = n - j; int add = ( 1LL * ( st[cntL] - 1 + base ) * ( st[cntR] - 1 + base ) ) % base; ans = ( 1LL * ans + 1LL * len * add ) % base; } printf ( "%d\n", ans );
809
B
Glad to see you!
\textbf{This is an interactive problem. In the output section below you will see the information about flushing the output.} On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building. In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of $n$ dishes. It is interesting that all dishes in the menu are numbered with integers from $1$ to $n$. After a little thought, the girl ordered exactly $k$ different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better. The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers $x$ and $y$ $(1 ≤ x, y ≤ n)$. After that Noora chooses some dish $a$ for the number $x$ such that, at first, $a$ is among the dishes Noora ordered ($x$ can be equal to $a$), and, secondly, the value $|x-a|$ is the minimum possible. By the same rules the girl chooses dish $b$ for $y$. After that Noora says «TAK» to Leha, if $|x-a|\leq|y-b|$, and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than $60$ questions. After that he should name numbers of any two dishes Noora ordered. Help Leha to solve this problem!
Let's start with searching the first point. We can do it using this binary search: let's ask points $mid$ and $mid + 1$ each time, when we calculated the center of search interval. So we always know in which of the halves $[l, mid], [mid + 1, r]$ exists at least one point. Since in the initial interval there is at least one point and any point in the interval of search is closer, than any point out of the interval, we will never lose this point out of the search. Now let's run two binsearches more, similarly for everything to the left and to the right of the first found point. Again, any point in the interval of search is closer, than any point out of the interval. Now it is not guaranteed that initially exist at least one point, so we have to check the found one using one query.
[ "binary search", "interactive" ]
2,200
int query(int x,int y){ if(x==-1)return 0; cout<<1<<' '<<x<<' '<<y<<endl; string ret; cin>>ret; return ("TAK"==ret); } int get(int l,int r){ if(l>r)return -1; while(l<r){ int m=(l+r)/2; if(query(m,m+1)){ r=m; }else l=m+1; } return l; } int main() { int n,k; cin>>n>>k; int x=get(1,n); int y=get(1,x-1); if(!query(y,x))y=get(x+1,n); cout<<2<<' '<<x<<' '<<y<<endl; return 0; }
809
C
Find a car
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help. Formally the parking can be represented as a matrix $10^{9} × 10^{9}$. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from $1$ to $10^{9}$ from left to right and the rows by integers from $1$ to $10^{9}$ from top to bottom. By coincidence it turned out, that for every cell $(x, y)$ the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells $(i, y)$ and $(x, j)$, $1 ≤ i < x, 1 ≤ j < y$. \begin{center} {\small The upper left fragment $5 × 5$ of the parking} \end{center} Leha wants to ask the watchman $q$ requests, which can help him to find his car. Every request is represented as five integers $x_{1}, y_{1}, x_{2}, y_{2}, k$. The watchman have to consider all cells $(x, y)$ of the matrix, such that $x_{1} ≤ x ≤ x_{2}$ and $y_{1} ≤ y ≤ y_{2}$, and if the number of the car in cell $(x, y)$ does not exceed $k$, increase the answer to the request by the number of the car in cell $(x, y)$. For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo $10^{9} + 7$. However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.
At first, let's examine that numbers in the matrix are equal to binary xor of the row and column. Precisely, the number in cell $i, j$ is equal to $(i-1)\oplus(j-1)+1$. Now let's split the query into 4 queries to the matrix prefix, as we usually do it in matrix sum queries. In order to find the answer to the query, we have to maintain 2 dp-on-bits: $cnt[prefix][flagX][flagY][flagK]$ and $dp[prefix][flagX][flagY][flagK]$, where $prefix$ - the number of placed bits, $flagX, flagY$ - flags of equality $x, y$ in query and $flagK$ - flag of equality of row and column xor with $k$. Flag of equality is a boolean, equal to $0$, if our number became less then prefix, and $1$ if prefix is still equal. If you aren't familiar with such dp, please try to solve another task with dp on prefix with less number of flags. $cnt$ will maintain the number of cells that are suitable for the arguments and $dp$ - accumulated sum.
[ "combinatorics", "divide and conquer", "dp" ]
2,600
ll dp[32][2][2][2]; ll sum[32][2][2][2]; void add(ll &x,ll y){ x+=y; if(x>=mod)x-=mod; } void sub(ll &x,ll y){ x-=y; if(x<0)x+=mod; } ll mul(ll x,ll y){ return x*y%mod; } ll pot[32]; ll solve(int x,int y,int z){ if(x<0||y<0||z<0)return 0; memset(dp,0,sizeof dp); memset(sum,0,sizeof sum); vi A,B,C; rep(j,0,31){ A.pb(x%2);x/=2; B.pb(y%2);y/=2; C.pb(z%2);z/=2; } reverse(all(A)); reverse(all(B)); reverse(all(C)); dp[0][1][1][1]=1; sum[0][1][1][1]=0; rep(i,0,31){ rep(a,0,2)rep(b,0,2)rep(c,0,2){ rep(x,0,2)rep(y,0,2){ int z=x^y; if(a==1&&A[i]==0&&x==1)continue; if(b==1&&B[i]==0&&y==1)continue; if(c==1&&C[i]==0&&z==1)continue; add(dp[i+1][a&(A[i]==x)][b&(B[i]==y)][c&(C[i]==z)],dp[i][a][b][c]); add(sum[i+1][a&(A[i]==x)][b&(B[i]==y)][c&(C[i]==z)],sum[i][a][b][c]); add(sum[i+1][a&(A[i]==x)][b&(B[i]==y)][c&(C[i]==z)],mul(z<<(30-i),dp[i][a][b][c])); } } } ll res=0; rep(a,0,2)rep(b,0,2)rep(c,0,2){ add(res,sum[31][a][b][c]); add(res,dp[31][a][b][c]); } return res; } int main(){ int T; cin>>T; while(T--){ int x,y,x2,y2,k; cin>>x>>y>>x2>>y2>>k; --x;--y;--x2;--y2;--k; ll res=0; add(res,solve(x2,y2,k)); sub(res,solve(x2,y-1,k)); sub(res,solve(x-1,y2,k)); add(res,solve(x-1,y-1,k)); cout<<res<<'\n'; } return 0; }
809
D
Hitchhiking in the Baltic States
Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit $n$ towns. However it turned out that sights in $i$-th town are open for visitors only on days from $l_{i}$ to $r_{i}$. What to do? Leha proposed to choose for each town $i$ a day, when they will visit this town, i.e any integer $x_{i}$ in interval $[l_{i}, r_{i}]$. After that Noora choses some subsequence of towns $id_{1}, id_{2}, ..., id_{k}$, which friends are going to visit, that at first they are strictly increasing, i.e $id_{i} < id_{i + 1}$ is for all integers $i$ from $1$ to $k - 1$, but also the dates of the friends visits are strictly increasing, i.e $x_{idi} < x_{idi + 1}$ is true for all integers $i$ from $1$ to $k - 1$. Please help Leha and Noora in choosing such $x_{i}$ for each town $i$, and such subsequence of towns $id_{1}, id_{2}, ..., id_{k}$, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day.
Let $dp_{i}$ - minimal number that can be last in strictly increasing subsequence with length $i$. Iterate through prefixes of intervals and maintain this dp. Obviously this dp is strictly increasing. What happens when we add new interval $l, r$: Thinking from the facts above, we can solve this task maintaining dp in cartesian tree (treap). Let's find and split interval from $i + 1$ to $j$. Add to every number in this tree $1$. Delete $j + 1$-t node. And merge everything adding one more node with key $l$.
[ "data structures", "dp" ]
2,900
struct node { int prior, sz, dp, add; node *l, *r; node ( int x ) { prior = ( rand() << 15 ) | rand(); // sz = 1; dp = x; l = r = NULL; add = 0; } }; typedef node * pnode; void push( pnode T ) { T -> dp += T -> add; if ( T -> l ) T -> l -> add += T -> add; if ( T -> r ) T -> r -> add += T -> add; T -> add = 0; } void merge( pnode &T, pnode L, pnode R ) { if ( !L ) { T = R; return; } if ( !R ) { T = L; return; } if ( L -> prior > R -> prior ) { push( L ); merge( L -> r, L -> r, R ); T = L; return; } push( R ); merge( R -> l, L, R -> l ); T = R; } void split( pnode T, int value, pnode &L, pnode &R ) { if ( !T ) { L = R = NULL; return; } push( T ); if ( T -> dp >= value ) { split( T -> l, value, L, T -> l ); R = T; return; } split( T -> r, value, T -> r, R ); L = T; } int findBegin( pnode T ) { push( T ); if ( !T -> l ) return T -> dp; return findBegin( T -> l ); } int findMax( pnode T, int n ) { if ( !T ) return 0; push( T ); return findMax( T -> l, n ) + findMax( T -> r, n ) + ( T -> dp <= inf ? 1 : 0 ); } pair < int, int > a[maxn]; pnode T = new node( 0 ); pnode L = NULL; pnode M = NULL; pnode R = NULL; pnode rubbish = NULL; void solve() { int n; scanf ( "%d", &n ); for ( int j = 1; j <= n; j++ ) scanf ( "%d%d", &a[j].f, &a[j].s ); for ( int j = 1; j <= n; j++ ) merge( T, T, new node( inf + j ) ); for ( int j = 1; j <= n; j++ ) { split( T, a[j].f, L, R ); split( R, a[j].s, M, R ); if ( M ) M -> add += 1; int cnt = findBegin( R ); split( R, cnt + 1, rubbish, R ); merge( T, L, new node( a[j].f ) ); merge( T, T, M ); merge( T, T, R ); } printf ( "%d\n", findMax( T, n ) - 1 ); }
809
E
Surprise me!
Tired of boring dates, Leha and Noora decided to play a game. Leha found a tree with $n$ vertices numbered from $1$ to $n$. We remind you that tree is an undirected graph without cycles. Each vertex $v$ of a tree has a number $a_{v}$ written on it. Quite by accident it turned out that all values written on vertices are distinct and are natural numbers between $1$ and $n$. The game goes in the following way. Noora chooses some vertex $u$ of a tree uniformly at random and passes a move to Leha. Leha, in his turn, chooses (also uniformly at random) some vertex $v$ from remaining vertices of a tree $(v ≠ u)$. As you could guess there are $n(n - 1)$ variants of choosing vertices by players. After that players calculate the value of a function $f(u, v) = φ(a_{u}·a_{v})$ $·$ $d(u, v)$ of the chosen vertices where $φ(x)$ is Euler's totient function and $d(x, y)$ is the shortest distance between vertices $x$ and $y$ in a tree. Soon the game became boring for Noora, so Leha decided to defuse the situation and calculate expected value of function $f$ over all variants of choosing vertices $u$ and $v$, hoping of at least somehow surprise the girl. Leha asks for your help in calculating this expected value. Let this value be representable in the form of an irreducible fraction $\frac{P}{Q}$. To further surprise Noora, he wants to name her the value $P\cdot Q^{-1}\ \ \mathrm{mod}\ 10^{9}+7$. Help Leha!
Here $ \phi (x)$ denotes Euler's totient function of $x$, $gcd(x, y)$ is the greatest common divisor of $x$ and $y$ and $f(x)$ denotes the amount of divisors of $x$. Small remark. We need to find the answer in the form of $\frac{P}{Q}$, where $gcd(P, Q) = 1$. Let $A$ will be the sum of all pairwise values $f(u, v)$ and $B$ is the amount of such pairs i.e. $n(n - 1)$ and let $g = gcd(A, B)$. Then $P = A \cdot g^{ - 1}, Q = B \cdot g^{ - 1}$ and the answer for the problem is $P \cdot Q^{ - 1} = A \cdot g^{ - 1} \cdot B^{ - 1} \cdot g$ = $A \cdot B^{ - 1}$ which means there is no need to know $g$. As it often happens in the problems where you are required to calc anything over all paths of a tree it's a good idea to use so-called centroid decomposition of a tree. Shortly, decomposition chooses some node of a tree, processes each path going through it and then deletes this node and solves the problem in the remaining forest recursively. It's obvious there is no matter what node we choose the answer will be always calculated correctly but total run-time depends on choosing this node. It's claimed each tree contains such a vertex with the removal of which all the remaining trees will have a size at least twice less then a size of this tree. So if we always choose such a vertex, each node of a tree will exist no more than in $\log N$ trees built by desomposition which is good enough. Let's build centroid decomposition of the given tree. Let's $root$ is the root of the current tree. Let's solve the problem for this tree (let's call it 'layer') and solve it for the sons of $root$ recursively after that. At first, $\phi(a b)=\frac{\phi(a)\cdot\phi(b)\cdot g}{\phi(g)}$ where $g = gcd(a, b)$. Also for the current layer $dist(u, v) = d_{u} + d_{v}$ where $d_{x}$ is the distance from $root$ to $x$. Let's fix some vertex $v$. How to calc the sum $ \phi (a_{v} \cdot a_{v}) \cdot dist(u, v)$ inside our layer over all such $u$ that the path $u\rightarrow v$ goes through $root$? Let's denote the set of such $u$ as $A(v)$. We want to add to the answer $\sum_{u\in A(v)}\phi(a_{v}\cdot a_{u})\cdot d i s t(v,u)=\sum_{u\in A(v)}\phi(a_{v})\cdot\phi(a_{u})\cdot\frac{g}{\phi(g)}\cdot\left(d_{u}+d_{v}\right)$ $=\sum_{u\in A(v)}\left(\phi(a_{v})\cdot\phi(a_{u})\cdot\vartheta(a_{u})\cdot\vartheta(a_{v})\cdot\phi(a_{u})\cdot\vartheta(a_{u})\cdot\frac{g}{\phi(g)}\cdot d_{u}\right)$, where $g = gcd(a_{u}, a_{v})$. Considering we need to sum up all such sums over each $v$ from the layer, the sum current layer increases the total sum equals to $2\sum_{v}\left(\sum_{u\in A(v)}\phi(a_{v})\cdot d_{v}\cdot\frac{\phi(a_{u})\cdot g}{\phi(g)}\right)=2\sum_{v}\phi(a_{v})\cdot d_{v}\cdot\left(\sum_{u\in A(v)}\frac{\phi(a_{u})\cdot g}{\phi(g)}\right)$. So we need to be able to sum up $\sum_{u\in A(v)}{\frac{\phi(a_{u})\cdot g}{\phi(g)}}$, $g = gcd(a_{u}, a_{v})$ for each $v$. Let's understand how to calc $sum_{g}$ for each $g$ which means the sum of Euler's totient functions of all such vertices $u$, that has $gcd(a_{v}, a_{u}) = g$. Let's imagine we know $sumphi_{c}$ which denotes the sum of $ \phi (a_{u})$ for such $u$ that $a_{u}\ \ \mathrm{mod}\ c=0$. Then the following statement is true: $s u m_{g}=s u m p h i_{g}-\sum_{x\neq g,x}\sum_{\mathrm{mod}~g=0}s u m_{3}$. We can calculate values of $sumphi$ in $O(n\ln n\log n)$ time: each divisor of each number in range from $1$ to $n$ (which is, as it known, $O(n\ln n)$) will be counted in $O(\log n)$ layers of the centroid decomposition. So we're already able to calc $sum$ values in the time apparently proprtional to $O(n\log^{2}n)$. More precisely, the number of operations we waste for calculating $sum$ will be equal to $\textstyle\sum f(x)$ over all such $i$ and $x$ that $(1 \le x, i \le n$, $i\mod x=0)$, where $f(x)$ is the amount of divisors of $x$. This sum is equivalent to $\sum_{i=1}^{n}{\frac{n}{i}}\cdot f(i)$. Coding this solution carefully can give you Accepted thanks to high TL we set to Java solution. I can prove only $O(n\log^{3}n)$ complexity for this solution which is a very high upper bound. Can anyone give any better complexity for $\sum_{i=1}^{n}{\frac{n}{i}}\cdot f(i)$? However we can speed up this solution. Here we calculated $\sum_{g,a_{v}{\ \ \mathrm{mod}\ g=0}}s u m_{g}\cdot{\frac{g}{\phi(g)}}$ giving that $sum_{g}$ was equal to $s u p\bar{u}_{g}-\sum_{x\neq g,x}\sum_{\mathrm{mod}\ g=0}s u p n_{o}$ leading to $O{\biggl(}\sum_{q,a_{v}}\sum_{\mathrm{mod}~q=0}f(g){\biggr)}$ complexity for each $v$ in the layer. Actually the sum $\sum_{g,x\ \ \mathrm{mod}\ g=0}{\frac{g}{\phi(g)}}\cdot\,S u m_{g}$ for each $x$ can be showed as $\sum_{g,x{\mathrm{~mod~}}g=0}c_{x}[g]\cdot s u m p h i_{g}$ using some coefficients $c_{x}[]$. If we find them we'll be able to process each $v$ of the layer in $O(f(a_{v}))$ time which leads to final $O(n\ln n\log n)$ complexity. Let's precalculate these coefficients in ascending order for each $x$. It's easy to see that $c_{1}[1] = 1$ and for a prime $p$ $c_{p}[1]=1,c_{p}[p]={\frac{1}{p-1}}$. Now let's $x$ is a composite number and let's $p$ is it's least prime divisor and $ \alpha $ is such maximum number that $x$ is divisible by $p^{ \alpha }$, and $q={\frac{x}{p^{\alpha}}}$. Then coefficients for any divisor $z$ of $x$ can be calculated in the following way: Total complexity: $O(n\ln n\log n)$.
[ "divide and conquer", "math", "number theory", "trees" ]
3,100
#include <functional> #include <algorithm> #include <iostream> #include <fstream> #include <cstdlib> #include <numeric> #include <iomanip> #include <cstdio> #include <cstring> #include <cassert> #include <vector> #include <math.h> #include <queue> #include <stack> #include <ctime> #include <set> #include <map> using namespace std; typedef long long ll; typedef long double ld; template <typename T> T nextInt() { T x = 0, p = 1; char ch; do { ch = getchar(); } while(ch <= ' '); if (ch == '-') { p = -1; ch = getchar(); } while(ch >= '0' && ch <= '9') { x = x * 10 + (ch - '0'); ch = getchar(); } return x * p; } const int maxN = (int)2e5 + 10; const int maxL = 17; const int INF = (int)1e9; const int mod = (int)1e9 + 7; const ll LLINF = (ll)1e18 + 5; int mul(int x, int y) { return 1LL * x * y % mod; } void add(int &x, int y) { x += y; if (x >= mod) x -= mod; } void sub(int &x, int y) { x -= y; if (x < 0) x += mod; } int n; vector <int> g[maxN]; vector <int> d[maxN]; vector <int> coefs[maxN]; int phi[maxN]; int inv[maxN]; int a[maxN]; int tmp[maxN]; void productToTmp(int a, int b) { for (size_t it = 0; it < d[a].size(); it++) { for (size_t jt = 0; jt < d[b].size(); jt++) { int x = d[a][it]; int cx = coefs[a][it]; int y = d[b][jt]; int cy = coefs[b][jt]; add(tmp[x * y], mul(cx, cy)); } } } void precalc() { inv[1] = 1; for (int i = 1; i < maxN; ++i) { phi[i] = i; if(i > 1) inv[i] = mul(mod - mod / i, inv[mod % i]); } for (int i = 1; i < maxN; ++i) { for (int j = i; j < maxN; j += i) { d[j].push_back(i); if (j != i) phi[j] -= phi[i]; } } for (int i = 1; i < maxN; ++i) { coefs[i].resize(d[i].size()); } coefs[1][0] = 1; for (int x = 2; x < maxN; x++) { if ((int)d[x].size() == 2) { coefs[x][0] = 1; coefs[x][1] = inv[x - 1]; } else { int lp = d[x][1]; int z = x; while (z % lp == 0) { z /= lp; } for (int y: d[x]) { tmp[y] = 0; } productToTmp(lp, z); for (size_t it = 0; it < d[x].size(); it++) { coefs[x][it] = tmp[d[x][it]]; } } } } int nodes[maxN]; int len = 0; int sz[maxN]; int blocked[maxN]; int level[maxN]; int anc[maxN]; void calc_sizes(int v, int p = -1) { nodes[len++] = v; sz[v] = 1; anc[v] = p; for (int x: g[v]){ if (blocked[x] || x == p) continue; calc_sizes(x, v); sz[v] += sz[x]; } } int sum_phi[maxN]; int list_len; int list[maxN]; int depth[maxN]; void get_list(int v, int par = -1, int dpth = 1) { list[list_len] = v; depth[list_len++] = dpth; for (int x: g[v]) { if (par == x || blocked[x]) continue; get_list(x, v, dpth + 1); } } int sum[maxN]; int calc(int value) { int cur = 0; for(size_t i = 0; i < d[value].size(); ++i) { int x = d[value][i]; add(cur, mul(sum_phi[x], coefs[value][i])); } return mul(cur, phi[value]); } int total = 0; void solve(int root) { //root is a centroid for (int i = 0; i < len; ++i) { int u = nodes[i]; int y = a[u]; for (int x: d[y]) { add(sum_phi[x], phi[y]); } } for (int child: g[root]) { if (blocked[child]) continue; list_len = 0; get_list(child, root); { //excluding everything which can be counted twice for(int i = 0; i < list_len; ++i) { int u = list[i]; int y = a[u]; for(int x: d[y]) { sub(sum_phi[x], phi[y]); } } } { for (int i = 0; i < list_len; ++i) { int u = list[i]; int d = depth[i]; int value = a[u]; add(total, mul(d, calc(value))); } } { //including back for(int i = 0; i < list_len; ++i) { int u = list[i]; int y = a[u]; for(int x: d[y]) { add(sum_phi[x], phi[y]); } } } } //clear for (int i = 0; i < len; ++i) { int u = nodes[i]; int y = a[u]; for (int x: d[y]) { sum_phi[x] = 0; } } } void build(int v, int lev) { len = 0; calc_sizes(v); int centroid = -1; for (int i = 0; i < len; ++i) { int u = nodes[i]; int maxChildSize = len - sz[u]; for (int x: g[u]) { if (x != anc[u] && !blocked[x]) { maxChildSize = max(maxChildSize, sz[x]); } } if (maxChildSize <= len / 2) { centroid = u; } } blocked[centroid] = true; level[centroid] = lev; solve(centroid); for (int x: g[centroid]) { if (blocked[x]) continue; build(x, lev + 1); } } int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); ios_base::sync_with_stdio(0); precalc(); cin >> n; for (int i = 0; i < n; ++i) { cin >> a[i]; } for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; --x; --y; g[x].push_back(y); g[y].push_back(x); } build(0, 0); total = mul(total, inv[n]); total = mul(total, inv[n - 1]); total = mul(total, 2); cout << total << endl; return 0; }
810
A
Straight <<A>>
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one. In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from $1$ to $k$. The worst mark is $1$, the best is $k$. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, $7.3$ is rounded to $7$, but $7.5$ and $7.8784$ — to $8$. For instance, if Noora has marks $[8, 9]$, then the mark to the certificate is $9$, because the average is equal to $8.5$ and rounded to $9$, but if the marks are $[8, 8, 9]$, Noora will have graduation certificate with $8$. To graduate with «A» certificate, Noora \textbf{has to have mark} $k$. Noora got $n$ marks in register this year. However, she is afraid that her marks are not enough to get final mark $k$. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from $1$ to $k$. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to $k$.
It is obvious that add any marks less than $k$ isn't optimal. Therefore, iterate on how many $k$ marks we add to the registry and find minimal sufficient number.
[ "implementation", "math" ]
900
int n, k, s = 0; cin >> n >> k; for (int i = 0; i < n; ++i) { int x; cin >> x; s += x; } for (int ans = 0;; ans++) { int a = 2 * (s + ans * k); int b = (2 * k - 1) * (ans + n); if (a >= b) { cout << ans; return 0; } }
810
B
Summer sell-off
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following $n$ days. For each day sales manager knows exactly, that in $i$-th day $k_{i}$ products will be put up for sale and exactly $l_{i}$ clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump. For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any $f$ days from $n$ next for sell-outs. On each of $f$ chosen days the number of products were put up for sale would be doubled. Thus, if on $i$-th day shop planned to put up for sale $k_{i}$ products and Noora has chosen this day for sell-out, shelves of the shop would keep $2·k_{i}$ products. Consequently, there is an opportunity to sell two times more products on days of sell-out. Noora's task is to choose $f$ days to maximize total number of sold products. She asks you to help her with such a difficult problem.
Initially, the number of sold products on $i$-th day is $min(k_{i}, l_{i})$ and in sell-out day is $min(2 * k_{i}, l_{i})$. Let's sort days in descending of $min(2 * k_{i}, l_{i}) - min(k_{i}, l_{i})$ and take first $f$ days as sell-out days.
[ "greedy", "sortings" ]
1,300
for (int i = 0; i < n; i++) { cin >> k[i] >> l[i]; a.push_back(make_pair(min(2 * k[i], l[i]) - min(k[i], l[i]), i)); } sort(a.rbegin(), a.rend()); long long ans = 0; for (int i = 0; i < f; i++) { int pos = a[i].second; ans += min(2 * k[pos], l[pos]); } for (int i = f; i < n; i++) { int pos = a[i].second; ans += min(k[pos], l[pos]); } cout << ans;
811
A
Vladik and Courtesy
At regular competition Vladik and Valera won $a$ and $b$ candies respectively. Vladik offered $1$ his candy to Valera. After that Valera gave Vladik $2$ his candies, so that no one thought that he was less generous. Vladik for same reason gave $3$ candies to Valera in next turn. More formally, the guys take turns giving each other one candy more than they received in the previous turn. This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they \textbf{don’t consider as their own}. You need to know, who is the first who can’t give the right amount of candy.
Let's simulate process, described in problem statement. I.e subtract from $a$ and $b$ numbers $1, 2, 3, ...$, until any of them is less than zero. The process would terminate less than in $\sqrt{10^{9}}$ iterations, because sum of arithmetical progression with $n$ members is approximately equal to $n^{2}$.
[ "brute force", "implementation" ]
800
null
811
B
Vladik and Complicated Book
Vladik had started reading a complicated book about algorithms containing $n$ pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation $P = [p_{1}, p_{2}, ..., p_{n}]$, where $p_{i}$ denotes the number of page that should be read $i$-th in turn. Sometimes Vladik’s mom sorted some subsegment of permutation $P$ from position $l$ to position $r$ inclusive, because she loves the order. For every of such sorting Vladik knows number $x$ — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has $p_{x}$ changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.
Obviously, that all the elements in range, which are less than $p_{x}$ will go to the left of $p_{x}$ after sort. So the new position will be $l + cnt_{less}$. Let's find $cnt_{less}$ with simple iterating through all the elements in the segment. $O(n * m)$ Challenge. Can you solve the problem with $n, m \le 10^{6}$?
[ "implementation", "sortings" ]
1,200
null
811
C
Vladik and Memorable Trip
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips: Vladik is at initial train station, and now $n$ people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code $a_{i}$ is known (the code of the city in which they are going to). Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is \textbf{not necessary}). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city $x$, then all people who are going to city $x$ should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city $x$, either go to it and in the same railway carriage, or do not go anywhere at all. Comfort of a train trip with people on segment from position $l$ to position $r$ is equal to XOR of all distinct codes of cities for people on the segment from position $l$ to position $r$. XOR operation also known as exclusive OR. Total comfort of a train trip is equal to sum of comfort for each segment. Help Vladik to know maximal possible total comfort.
Let's precalc for each $x$ it's $fr_{x}$ and $ls_{x}$ - it's leftmost and rightmost occurrences in the array respectively. Now for each range $[l, r]$ we can check, if it can be a separate train carriage, just checking for each $a_{i}$ $(l \le i \le r)$, that $fr_{ai}$ and $ls_{ai}$ are also in this range. Now let's define $dp_{i}$ as the answer to the problem for $i$ first people. To update $dp$ we can make two transitions: Assume, that there was such train carriage, that finished at position $i$. Then iterate it's start from right to left, also maintaining maximal $ls$, minimal $fr$ and xor of distinct codes $cur$. If current range $[j, i]$ is ok for forming the train carriage, update $dp_i$ with value $dp_j - 1 + cur$. If there wasn't such train carriage, then last element didn't belong to any train carriage, so we can update $dp_i$ with value $dp_i - 1$. $O(n^{2})$
[ "dp", "implementation" ]
1,900
null
811
D
Vladik and Favorite Game
\textbf{This is an interactive problem.} Vladik has favorite game, in which he plays all his free time. Game field could be represented as $n × m$ matrix which consists of cells of three types: - «.» — normal cell, player can visit it. - «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type. - «*» — dangerous cell, if player comes to this cell, he loses. Initially player is located in the left top cell with coordinates $(1, 1)$. Player has access to $4$ buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively. But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game. Help Vladik win the game!
It's clear, that to reach finish without stepping into dangerous cells we have to know, whether our buttons are broken. Firstly, let's find any route to the finish using bfs / dfs. At the first moment of this route, when we have to go down, we would find out, if our button is broken, because we are still at the first row of the matrix and if the button is broken, we just won't move anywhere. Similarly for left and right pair of buttons. After that we found out, that button was broken, we can change in our route moves to opposite ones.
[ "constructive algorithms", "dfs and similar", "graphs", "interactive" ]
2,100
null
811
E
Vladik and Entertaining Flags
In his spare time Vladik estimates beauty of the flags. Every flag could be represented as the matrix $n × m$ which consists of positive integers. Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at $(1, l)$ and $(n, r)$, where conditions $1 ≤ l ≤ r ≤ m$ are satisfied. Help Vladik to calculate the beauty for some segments of the given flag.
Let's use interval tree, maintaining in each vertex two arrays of $n$ numbers: left and right profile of the interval corresponding to the vertex. Each number in this arrays would be in range from $1$ to $2 * n$ denoting component, in which cell is. For merging such structures we would iterate on splice of two vertices and unite components, if two adjacent cells have same colors and than recalculate components of left and right profile of the new structure.
[ "data structures", "dsu", "graphs" ]
2,600
null
812
A
Sagheer and Crossroads
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has $3$ lanes getting into the intersection (one for each direction) and $3$ lanes getting out of the intersection, so we have $4$ parts in total. Each part has $4$ lights, one for each lane getting into the intersection ($l$ — left, $s$ — straight, $r$ — right) and a light $p$ for a pedestrian crossing. An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time. Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.
For pedestrian crossing $i$ ($1 \le i \le 4)$, lanes $l_{i}, s_{i}, r_{i}, s_{i + 2}, l_{i + 1}, r_{i - 1}$ are the only lanes that can cross it. So, we have to check that either $p_{i} = 0$ or all mentioned lanes are $0$. Complexity: $O(1)$
[ "implementation" ]
1,200
"import java.io.PrintWriter;\nimport java.util.Scanner;\n\npublic class SagheerAndCrossroads_MainSolution {\n\n\tpublic static void main(String[] args) {\n\t\t\n\t\tScanner sc = new Scanner(System.in);\n\t\tPrintWriter out = new PrintWriter(System.out);\n\t\t\n\t\tint[][] part = new int[4][4];\n\t\tfor(int i = 0; i < 4; ++i)\n\t\t\tfor(int j = 0; j < 4; ++j)\n\t\t\t\tpart[i][j] = sc.nextInt();\n\t\tint[] crossed = new int[4];\n\t\tfor(int i = 0; i < 4; ++i)\n\t\t\tfor(int j = 1; j <= 3; ++j)\n\t\t {\n\t\t \tcrossed[i] |= part[i][3 - j];\n\t\t\t\tcrossed[(i + j) % 4] |= part[i][3 - j];\n\t\t }\n\t\t\n\t\tboolean accident = false;\n\t\tfor(int i = 0; i < 4; ++i)\n\t\t\taccident |= crossed[i] + part[i][3] == 2;\n\t\tout.println(accident ? \"YES\" : \"NO\");\n\t\t\n\t\tsc.close();\n\t\tout.close();\n\t}\n}\n"
812
B
Sagheer, the Hausmeister
Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off. The building consists of $n$ floors with stairs at the left and the right sides. Each floor has $m$ rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with $n$ rows and $m + 2$ columns, where the first and the last columns represent the stairs, and the $m$ columns in the middle represent rooms. Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights. Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.
When Sagheer reaches a floor for the first time, he will be standing at either left or right stairs. If he is standing at the left stairs, then he will go to the rightmost room with lights on. If he is standing at the right stairs, then he will go to the leftmost room with lights on. Next, he will either take the left stairs or the right stairs to go to the next floor. We will brute force on the choice of the stairs at each floor. Note that Sagheer doesn't have to go to the last floor, so he will go to the highest floor that has a room with lights on. Complexity: $O(n \cdot 2^{n})$
[ "bitmasks", "brute force", "dp" ]
1,600
"import java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Main {\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tScanner sc = new Scanner(System.in);\n\t\t\n\t\tint n = sc.nextInt(), m = sc.nextInt();\n\t\t\n\t\tint[] leftMost = new int[n], rightMost = new int[n];\n\t\tint maxFloor = -1;\n\t\tArrays.fill(leftMost, m + 1);\n\t\tfor(int i = n - 1; i >= 0; --i)\n\t\t{\n\t\t\tString s = sc.next();\n\t\t\tfor(int j = 0; j < m + 2; ++j)\n\t\t\t\tif(s.charAt(j) == '1')\n\t\t\t\t{\n\t\t\t\t rightMost[i] = j;\n\t\t\t\t if(maxFloor == -1)\n\t\t\t\t maxFloor = i;\n\t\t\t\t}\n\t\t\t\t\n\t\t\tfor(int j = m + 1; j >= 0; --j)\n\t\t\t\tif(s.charAt(j) == '1')\n\t\t\t\t\tleftMost[i] = j;\n\t\t}\n\t\t\n\t\tint ans = 10000000;\n\t\t\n\t\tfor(int stairs = 0; stairs < (1 << n - 1); ++stairs)\n\t\t{\n\t\t\tint cur = 0, room = 0, floor = 0;\n\t\t\twhile(floor <= maxFloor)\n\t\t\t{\n\t\t\t\tif(room == 0)\n\t\t\t\t{\n\t\t\t\t\tcur += rightMost[floor] - room;\n\t\t\t\t\troom = rightMost[floor];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcur += room - leftMost[floor];\n\t\t\t\t\troom = leftMost[floor];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(floor == maxFloor)\n\t\t\t\t\tbreak;\n\t\t\t\tint nxtStairs = (stairs & (1 << floor)) == 0 ? 0 : m + 1;\n\t\t\t\tcur += Math.abs(nxtStairs - room) + 1;\n\t\t\t\t\n\t\t\t\troom = nxtStairs;\n\t\t\t\t++floor;\n\t\t\t}\n\t\t\tans = Math.min(ans, cur);\n\t\t}\n\t\t\n\t\tSystem.out.println(ans);\n\t\t\n\t\tsc.close();\n\t}\n}"
812
C
Sagheer and Nubian Market
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains $n$ different items numbered from $1$ to $n$. The $i$-th item has base cost $a_{i}$ Egyptian pounds. If Sagheer buys $k$ items with indices $x_{1}, x_{2}, ..., x_{k}$, then the cost of item $x_{j}$ is $a_{xj} + x_{j}·k$ for $1 ≤ j ≤ k$. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor $k$. Sagheer wants to buy as many souvenirs as possible without paying more than $S$ Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?
If Sagheer can buy $k$ items, then he can also buy less than $k$ items because they will be within his budget. If he can't buy $k$ items, then can't also buy more than $k$ items because they will exceed his budget. So, we can apply binary search to find the best value for $k$. For each value $k$, we will compute the new prices, sort them and pick the minimum $k$ prices to find the best minimum cost for $k$ items. Complexity: $O(n\log^{2}n)$
[ "binary search", "sortings" ]
1,500
"/**\n * code generated by JHelper\n * More info: https://g...content-available-to-author-only...b.com/AlexeyDmitriev/JHelper\n * @author gainullin.ildar\n */\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 1e5 + 7;\n\nint n, S;\nint a[N];\nll b[N];\n\nll res(int k)\n{\n for (int i = 0; i < n; i++)\n {\n b[i] = a[i] + (i + 1) * (ll) k;\n }\n sort(b, b + n);\n ll ans = 0;\n for (int i = 0; i < k; i++)\n {\n ans += b[i];\n }\n return ans;\n}\n\nclass Main\n{\npublic:\n void solve(std::istream &in, std::ostream &out)\n {\n in >> n >> S;\n for (int i = 0; i < n; i++)\n {\n in >> a[i];\n }\n int l = 0, r = n + 1;\n while (l < r - 1)\n {\n int m = (l + r) / 2;\n if (res(m) <= S)\n {\n l = m;\n }\n else\n {\n r = m;\n }\n }\n out << l << ' ' << res(l) << '\\n';\n }\n};\n\n\nint main()\n{\n ios::sync_with_stdio(0);\n Main solver;\n std::istream &in(std::cin);\n std::ostream &out(std::cout);\n solver.solve(in, out);\n return 0;\n}\n"
812
D
Sagheer and Kindergarten
Sagheer is working at a kindergarten. There are $n$ children and $m$ different toys. These children use well-defined protocols for playing with the toys: - Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set. - If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever. - Children request toys at distinct moments of time. No two children request a toy at the same time. - If a child is granted a toy, he never gives it back until he finishes playing with his lovely set. - If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting. - If two children are waiting for the same toy, then the child who requested it first will take the toy first. Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy. Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set. Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child $x$ that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child $x$ is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child $x$ will make his last request, how many children will start crying? You will be given the scenario and $q$ \textbf{independent} queries. Each query will be of the form $x$ $y$ meaning that the last request of the child $x$ is for the toy $y$. Your task is to help Sagheer find the size of the \textbf{maximal} crying set when child $x$ makes his last request.
Let's go through scenario requests one by one. For request $a$ $b$, if toy $b$ is free, then child $a$ can take it. Otherwise, child $a$ will wait until the last child $c$ who requested toy $b$ finishes playing. Since, no child can wait for two toys at the same time, each child depends on at most one other child. So we can put an edge from the $a$ to $c$. Thus, we can model the scenario as a forest (set of rooted trees) as each node has at most one outgoing edge (to its parent). For query $x$ $y$, if toy $y$ is free, then child $x$ can take it and no child will cry. Otherwise, toy $y$ is held by another child. Lets denote $z$ to be the last child who requested toy $y$. So $x$ now depends on $z$. If $z$ is in the subtree of $x$, then all children in the subtree of $x$ will cry. Otherwise, no child will cry. We can check that a node is in the subtree of another node using euler walk ($t_{in}$ and $t_{out}$) with preprocessing in $O(n)$ and query time $O(1)$ Complexity: $O(k + n + q)$
[ "dfs and similar", "graphs", "implementation", "trees" ]
2,700
"/**\n * code generated by JHelper\n * More info: https://g...content-available-to-author-only...b.com/AlexeyDmitriev/JHelper\n * @author gainullin.ildar\n */\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n\nusing namespace std;\n\nconst int N = 1e5 + 7;\n\nvector<int> g[N];\nint tin[N], tout[N];\nint sz[N];\nint tt = 1;\n\nvoid dfs(int v)\n{\n tin[v] = tt++;\n sz[v] = 1;\n for (auto to : g[v])\n {\n dfs(to);\n sz[v] += sz[to];\n }\n tout[v] = tt++;\n}\n\nbool pr(int a, int b)\n{\n return (tin[a] <= tin[b] && tout[a] >= tout[b]);\n}\n\nclass Main\n{\npublic:\n void solve(std::istream &in, std::ostream &out)\n {\n int n, m, k, q;\n in >> n >> m >> k >> q;\n tt = 1;\n for (int i = 1; i <= n; i++)\n {\n tin[i] = tout[i] = 0;\n g[i].clear();\n }\n vector<int> ind(m + 1, -1);\n vector<bool> root(n + 1, true);\n for (int i = 0; i < k; i++)\n {\n int v, a;\n in >> v >> a;\n if (ind[a] != -1)\n {\n g[ind[a]].push_back(v);\n root[v] = false;\n }\n ind[a] = v;\n }\n for (int i = 1; i <= n; i++)\n {\n if (root[i])\n {\n dfs(i);\n }\n }\n for (int i = 0; i < q; i++)\n {\n int v, a;\n in >> v >> a;\n a = ind[a];\n if (a == -1)\n {\n out << 0 << '\\n';\n }\n else\n {\n if (pr(v, a))\n {\n out << sz[v] << '\\n';\n }\n else\n {\n out << 0 << '\\n';\n }\n }\n }\n }\n};\n\n\nint main()\n{\n ios::sync_with_stdio(0);\n Main solver;\n std::istream &in(std::cin);\n std::ostream &out(std::cout);\n solver.solve(in, out);\n return 0;\n}\n"
812
E
Sagheer and Apple Tree
Sagheer is playing a game with his best friend Soliman. He brought a tree with $n$ nodes numbered from $1$ to $n$ and rooted at node $1$. The $i$-th node has $a_{i}$ apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length). Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses. In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: - eat the apples, if the node is a leaf. - move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make \textbf{exactly one change} to the tree. He will pick two different nodes $u$ and $v$ and swap the apples of $u$ with the apples of $v$. Can you help Sagheer count the number of ways to make the swap (i.e. to choose $u$ and $v$) after which he will win the game if both players play optimally? $(u, v)$ and $(v, u)$ are considered to be the same pair.
In the standard nim game, we xor the values of all piles, and if the xor value is $0$, then the first player loses. Otherwise, he has a winning strategy. One variant of the nim game has an extra move that allows players to add positive number of stones to a single pile (given some conditions to make the game finite). The solution for this variant is similar to the standard nim game because this extra move will be used by the winning player, and whenever the losing player does it, the winning player can cancel it by throwing away these added stones. This problem can be modeled as the mentioned variant. Lets color leaf nodes with blue. The parent of a blue node is red and the parent of a red node is blue (that's why all paths from root to leaves must have the same parity). Blue nodes are our piles while red nodes allow discarding apples or increasing piles. If the xor value of blue nodes $s = 0$, then Soliman loses on the initial tree. To keep this state after the swap, Sagheer can: swap any two blue nodes or any two red nodes. swap a blue node with a red node if they have the same number of apples. If the xor value of blue nodes $s \neq 0$, then Sagheer loses on the initial tree. To flip this state after the swap, Sagheer must swap a blue node $u$ with a red node $v$ such that $s\oplus a[u]\oplus a[v]=0$ Complexity: $O(n + maxA)$ where $maxA$ is the maximum value for apples in a single node.
[ "games", "trees" ]
2,300
"import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.StringTokenizer;\n\npublic class SagheerAppleTree_AC1 {\n\n\tstatic final int MAXA = 10000000;\n\tstatic ArrayList<Integer>[] adjList;\n\tstatic boolean[] blue;\n\tstatic int xorValue, cnt, cntBlue[], cntRed[],a[];\n\t\n\tstatic void dfs(int u)\n\t{\n\t\tfor(int v: adjList[u])\n\t\t\tdfs(v);\n\t\tblue[u] = adjList[u].size() == 0 || !blue[adjList[u].get(0)]; \n\t\tif(blue[u])\n\t\t{\n\t\t\txorValue ^= a[u];\n\t\t\tcntBlue[a[u]]++;\n\t\t\t++cnt;\n\t\t}\n\t\telse\n\t\t\tcntRed[a[u]]++;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException {\n\t\tScanner sc = new Scanner(System.in);\n\t\tPrintWriter out = new PrintWriter(System.out);\n\t\t\n\t\tint n = sc.nextInt();\n\t\ta = new int[n];\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\ta[i] = sc.nextInt();\n\t\tadjList = new ArrayList[n];\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tadjList[i] = new ArrayList<>(1);\n\t\tfor(int i = 1; i < n; ++i)\n\t\t\tadjList[sc.nextInt() - 1].add(i);\n\t\tblue = new boolean[n];\n\t\tcntBlue = new int[MAXA + 1];\n\t\tcntRed = new int[MAXA + 1];\n\t\tdfs(0);\n\t\tlong ans = 0;\n\t\tif(xorValue == 0)\n\t\t{\n\t\t\tfor(int i = 1; i <= MAXA; ++i)\n\t\t\t\tans += 1l * cntBlue[i] * cntRed[i];\n\t\t\tlong x = cnt, y = n - x;\n\t\t\tans += x * (x - 1) / 2 + y * (y - 1) / 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i = 1; i <= MAXA; ++i)\n\t\t\t{\n\t\t\t\tint j = xorValue ^ i;\n\t\t\t\tif(j <= MAXA)\n\t\t\t\t\tans += 1l * cntBlue[i] * cntRed[j];\n\t\t\t}\n\t\t}\n\t\tout.println(ans);\n\t\tout.flush();\n\t\tout.close();\n\t}\n\n\tstatic class Scanner \n\t{\n\t\tStringTokenizer st;\n\t\tBufferedReader br;\n\n\t\tpublic Scanner(InputStream s){\tbr = new BufferedReader(new InputStreamReader(s));}\n\n\t\tpublic String next() throws IOException \n\t\t{\n\t\t\twhile (st == null || !st.hasMoreTokens()) \n\t\t\t\tst = new StringTokenizer(br.readLine());\n\t\t\treturn st.nextToken();\n\t\t}\n\n\t\tpublic int nextInt() throws IOException {return Integer.parseInt(next());}\n\n\t\tpublic long nextLong() throws IOException {return Long.parseLong(next());}\n\n\t\tpublic String nextLine() throws IOException {return br.readLine();}\n\n\t\tpublic double nextDouble() throws IOException { return Double.parseDouble(next()); }\n\n\t\tpublic boolean ready() throws IOException {return br.ready();} \n\t}\n}\n"
813
A
The Contest
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place! This contest consists of $n$ problems, and Pasha solves $i$th problem in $a_{i}$ time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. \textbf{Pasha can send any number of solutions at the same moment.} Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during $m$ time periods, $j$th period is represented by its starting moment $l_{j}$ and ending moment $r_{j}$. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment $T$ iff there exists a period $x$ such that $l_{x} ≤ T ≤ r_{x}$. Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have \textbf{solutions to all problems submitted}, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.
Notice that we can keep solved tasks and then submit all at once. So the solution goes down to this: you should find the first moment of time $t$ that the site works at that moment and $t\geq\sum_{i=1}^{n}a_{i}$. Also it's convinient that the intervals are already sorted in increasing order. Let's sum up all elements of array $a$ and write it to some variable $sum$. The answer is obtained this way: if the sum lies in the current interval then the answer is the sum. Otherwise there are two cases. If there exists some interval $j$ that $l_{j} \ge sum$ then the answer is $l_{j}$. In other case the answer is "-1".
[ "implementation" ]
1,100
null
813
B
The Golden Age
Unlucky year in Berland is such a year that its number $n$ can be represented as $n = x^{a} + y^{b}$, where $a$ and $b$ are non-negative integer numbers. For example, if $x = 2$ and $y = 3$ then the years 4 and 17 are unlucky ($4 = 2^{0} + 3^{1}$, $17 = 2^{3} + 3^{2} = 2^{4} + 3^{0}$) and year 18 isn't unlucky as there is no such representation for it. Such interval of years that there are no unlucky years in it is called The Golden Age. You should write a program which will find maximum length of The Golden Age which starts no earlier than the year $l$ and ends no later than the year $r$. If all years in the interval $[l, r]$ are unlucky then the answer is 0.
Notice that $x^{a}$ for $x \ge 2$ has no more than 60 powers which give numbers no greater than $10^{18}$. So let's store all possible sums of all powers of $x$ and $y$. Now the answer to the query can be obtained in linear time by checking difference between neighbouring unlucky years in sorted order. Don't forget that you should handle multiplying of such big numbers very carefully. For example, instead of writing or you should write to avoid getting overflow errors of 64-bit type. Integer division will work fine in that case because $num \cdot x$ will never exceed $10^{18}$ if $num$ doesn't exceed $\textstyle{\frac{|0^{18}\rangle}{x}}$. Overall complexity: $O(n\cdot\log n)$.
[ "brute force", "math" ]
1,800
null
813
C
The Tag Game
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of $n$ vertices. Vertex 1 is the root of the tree. Alice starts at vertex 1 and Bob starts at vertex $x$ ($x ≠ 1$). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one. The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it. You should write a program which will determine how many moves will the game last.
If you check some games then you will notice that the most optimal strategy for Bob is always like this: Climb up for some steps (possibly zero) Go to the lowest vertex from it Stay in this vertex till the end Thus let's precalc the depth (the distance from the root) of the lowest vertex of each subtree (using dfs), distance from Alice's starting node and from Bob's starting node to the vertex (again dfs/bfs). Now iterate over all vertices and check if Bob can reach this vertex earlier than Alice. If he can then update the answer with the lowest vertex that can be reached from this one. The answer is doubled depth of the obtained lowest reachable vertex. That is the time which will take Alice to get there. Overall complexity: $O(n)$.
[ "dfs and similar", "graphs" ]
1,700
null
813
D
Two Melodies
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with $n$ notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.
Let's solve this problem with dynamic programming. Let $dp[x][y]$ be the maximum answer if one melody finishes in note number $x$ and another melody - in note number $y$. $x$ and $y$ are $1$-indexed; if one of them is $0$, then the melody is empty. How shall we update $dp[x][y]$? First of all, we will update from previous $dp$ values only if $x > y$. If $x = y$, then obviously answer is $0$, and if $x < y$, then we take the answer for $dp[y][x]$. Secondly, to avoid intersections, we will update $dp[x][y]$ only using values of $dp[i][y]$, where $i \neq y$ and $i < x$. Why? Because if we update $dp[x][y]$ from some $dp[x][i]$, and $x > y$, then it can lead to some intersection (we can't guarantee we didn't use $i$ in the first melody). How can we make fast updates? We will count $dp$ from $y = 0$ to $y = n$. Then, while counting $dp$ for some specific $y$, we will maintain two arrays: $maxmod[j]$ - the maximum value of $dp[i][y]$ encountered so far where $a[i] mod 7 = j$; $maxnum[j]$ - the maximum value of $dp[i][y]$ encountered so far where $a[i] = j$. So when we need to count $dp[x][y]$, it will be the maximum of four values: $maxmod[a[x] mod 7] + 1$ - if we add a note which is congruent modulo $7$ with the last one; $maxnum[a[x] + 1] + 1$ - if we add a note which is less by $1$ than the last note; $maxnum[a[x] - 1] + 1$ - if we add a note which is greater by $1$ than the last note; $dp[0][y] + 1$ - if we just start a melody. These values can be calculated in $O(n^{2})$.
[ "dp", "flows" ]
2,600
null
813
E
Army Creation
As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires. In the game Vova can hire $n$ different warriors; $i$th warrior has the type $a_{i}$. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if for each type of warrior present in the game there are not more than $k$ warriors of this type in the army. Of course, Vova wants his army to be as large as possible. To make things more complicated, Vova has to consider $q$ different plans of creating his army. $i$th plan allows him to hire only warriors whose numbers are not less than $l_{i}$ and not greater than $r_{i}$. Help Vova to determine the largest size of a balanced army for each plan. \textbf{Be aware that the plans are given in a modified way. See input section for details.}
Every time we process a plan, let's count only the first $k$ warriors of some type. When will the warrior on position $i$ be counted? Of course, he has to be present in the plan, so $l \le i \le r$. But also he has to be among $k$ first warriors of his type in this plan. Let's denote a function $prev(x, y)$: $prev(x, 1)$ is the position of previous warrior of the same type before warrior $x$ (that is, the greatest $i$ such that $i < x$ and $a_{i} = a_{x}$). If there's no any, then $prev(x, 1) = - 1$; $prev(x, y) = prev(prev(x, 1), y - 1))$ if $y > 1$. It is easy to prove that the warrior $x$ will be among $k$ first warriors in some plan iff $l > prev(x, k)$ and $x \le r$. So we can make a new array $b$: $b_{i} = prev(i, k)$. Then we build a segment tree on this array. The node of the segment tree will store all values of $b_{i}$ from the segment corresponding to this node (in sorted order). Then to get answer to the plan, we have to count the number of elements on segment $[l, r]$ that are less than $l$. Complexity is $O((n+q)\log^{2}n)$, or $O((n+q)\log n)$ if you use fractional cascading technique.
[ "binary search", "data structures" ]
2,200
null
813
F
Bipartite Checking
You are given an undirected graph consisting of $n$ vertices. Initially there are no edges in the graph. Also you are given $q$ queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color).
If the edges were only added and not deleted, it would be a common problem that is solved with disjoint set union. All you need to do in that problem is implement a DSU which maintains not only the leader in the class of some vertex, but also the distance to this leader. Then, if we try to connect two vertices that have the same leader in DSU and the sum of distances to this leader is even, then we get a cycle with odd length, and graph is no longer bipartite. But in this problem we need to somehow process removing edges from the graph. In the algorithm I will describe below we will need to somehow remove the last added edge from DSU (or even some number of last added edges). How can we process that? Each time we change some variable in DSU, we can store an address of this variable and its previous value somewhere (for example, in a stack). Then to remove last added edge, we rollback these changes - we rewrite the previous values of the variables we changed by adding the last edge. Now we can add a new edge and remove last added edge. All these operations cost $(O(logn))$ because we won't use path compression in DSU - path compression doesn't work in intended time if we have to rollback. Let's actually start solving the problem. For convinience, we change all information to queries like "edge $(x, y)$ exists from query number $l$ till query number $r$". It's obvious that there are no more than $q$ such queries. Let's use divide-and-conquer technique to make a function that answers whether the graph is bipartite or not after every query from some segment of queries $[a, b]$. First of all, we add to DSU all the edges that are present in the whole segment (and not added yet); then we solve it recursively for $\left[a,\left[{\frac{a+b}{2}}\right]\right]$ and $\left[\left({\frac{a+b}{2}}\right)+1,b\right]$; then we remove edges from DSU using the rollback technique described above. When we arrive to some segment $[a, a]$, then after adding the edges present in this segment we can answer if the graph is bipartite after query $a$. Remember to get rid of the edges that are already added and the edges that are not present at all in the segment when you make a recursive call. Of course, to solve the whole problem, we need to call our function from segment $[1, q]$. Time complexity is $O(q\log^{2}q)$, because every edge will be added only in $O(\log q)$ calls of the function.
[ "data structures", "dsu", "graphs" ]
2,500
null
814
A
An abandoned sentiment from past
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed. To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long time, but now Kaiki provides an opportunity. Hitagi's sequence $a$ has a length of $n$. Lost elements in it are denoted by zeros. Kaiki provides another sequence $b$, whose length $k$ equals the number of lost elements in $a$ (i.e. the number of zeros). Hitagi is to replace each zero in $a$ with an element from $b$ so that \textbf{each element in $b$ should be used exactly once}. Hitagi knows, however, that, \textbf{apart from $0$, no integer occurs in $a$ and $b$ more than once in total.} If the resulting sequence is \textbf{not} an increasing sequence, then it has the power to recover Hitagi from the oddity. You are to determine whether this is possible, or Kaiki's sequence is just another fake. In other words, you should detect whether it is possible to replace each zero in $a$ with an integer from $b$ so that each integer from $b$ is used exactly once, and the resulting sequence is \textbf{not} increasing.
The statement laid emphasis on the constraint that the elements are pairwise distinct. How is this important? In fact, this implies that if the resulting sequence is increasing, then swapping any two of its elements will result in another sequence which is not increasing. And we're able to perform a swap on any resulting sequence if and only if $k \ge 2$. Thus if $k \ge 2$, the answer would always be "Yes". For cases where $k = 1$, we replace the only zero in sequence $a$ with the only element in $b$, and check the whole sequence. Hackable solutions include those only checking the replaced element and its neighbours, and those missing the replaced element.
[ "constructive algorithms", "greedy", "implementation", "sortings" ]
900
#include <cstdio> #include <algorithm> static const int MAXN = 102; int n, k; int a[MAXN], b[MAXN]; int p[MAXN], r[MAXN]; inline bool check() { for (int i = 1; i < n; ++i) if (r[i] <= r[i - 1]) return true; return false; } int main() { scanf("%d%d", &n, &k); int last_zero = -1; for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); if (a[i] == 0) last_zero = i; } for (int i = 0; i < k; ++i) scanf("%d", &b[i]); bool valid = false; for (int i = 0; i < k; ++i) p[i] = i; do { for (int i = 0, ptr = 0; i < n; ++i) { r[i] = (a[i] == 0) ? b[p[ptr++]] : a[i]; } if (check()) { valid = true; break; } } while (std::next_permutation(p, p + k)); puts(valid ? "Yes" : "No"); return 0; }
814
B
An express train to reveries
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized. On that night, Sengoku constructed a permutation $p_{1}, p_{2}, ..., p_{n}$ of integers from $1$ to $n$ inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with $n$ meteorids, colours of which being integer sequences $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{n}$ respectively. Meteoroids' colours were also between $1$ and $n$ inclusive, and the two sequences were not identical, that is, at least one $i$ ($1 ≤ i ≤ n$) exists, such that $a_{i} ≠ b_{i}$ holds. Well, she almost had it all — each of the sequences $a$ and $b$ matched exactly $n - 1$ elements in Sengoku's permutation. In other words, there is exactly one $i$ ($1 ≤ i ≤ n$) such that $a_{i} ≠ p_{i}$, and exactly one $j$ ($1 ≤ j ≤ n$) such that $b_{j} ≠ p_{j}$. For now, Sengoku is able to recover the actual colour sequences $a$ and $b$ through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.
Permutating directly no longer works here. Let's try to dig something out from the constraints. Imagine that we take a permutation $p_{1... n}$, and change one of its elements to a different integer in $[1, n]$, resulting in the sequence $p'_{1... n}$. There are exactly $2$ positions $i, j$ ($i \neq j$) such that $p'_{i} = p'_{j}$, while the other $n - 2$ elements are kept untouched. This is actually what $a$ and $b$ satisfy. Find out these two positions in $a$, and the two candidates for them - that is, the only two numbers not present in the remaining $n - 2$ elements. Iterate over their two possible orders, and check the validity against sequence $b$. Of course you can solve this with casework if you like.
[ "constructive algorithms" ]
1,300
#include <cstdio> #include <utility> static const int MAXN = 1e3 + 4; int n; int a[MAXN], b[MAXN]; std::pair<int, int> get_duplication(int *a) { static int occ[MAXN]; for (int i = 1; i <= n; ++i) occ[i] = -1; for (int i = 0; i < n; ++i) { if (occ[a[i]] != -1) return std::make_pair(occ[a[i]], i); else occ[a[i]] = i; } return std::make_pair(-1, -1); } inline void fix_permutation(int pos) { static bool occ[MAXN]; for (int i = 1; i <= n; ++i) occ[i] = false; for (int i = 0; i < n; ++i) if (i != pos) occ[a[i]] = true; for (int i = 1; i <= n; ++i) if (!occ[i]) { a[pos] = i; return; } } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n; ++i) scanf("%d", &b[i]); std::pair<int, int> dup_a, dup_b; dup_a = get_duplication(a); dup_b = get_duplication(b); if (dup_a == dup_b) { a[dup_a.first] = b[dup_b.first]; } else if (dup_a.first == dup_b.first || dup_a.first == dup_b.second) { a[dup_a.second] = b[dup_a.second]; fix_permutation(dup_a.first); } else if (dup_a.second == dup_b.first || dup_a.second == dup_b.second) { a[dup_a.first] = b[dup_a.first]; fix_permutation(dup_a.second); } else { a[dup_a.first] = b[dup_a.first]; a[dup_a.second] = b[dup_a.second]; } for (int i = 0; i < n; ++i) printf("%d%c", a[i], i == n - 1 ? '\n' : ' '); return 0; }
814
C
An impassioned circulation of affection
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it! Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has $n$ pieces numbered from $1$ to $n$ from left to right, and the $i$-th piece has a colour $s_{i}$, denoted by a lowercase English letter. Nadeko will repaint \textbf{at most} $m$ of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour $c$ — Brother Koyomi's favourite one, and takes the length of the longest among them to be the \underline{Koyomity} of the garland. For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of $3$. Thus the \underline{Koyomity} of this garland equals $3$. But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has $q$ plans on this, each of which can be expressed as a pair of an integer $m_{i}$ and a lowercase letter $c_{i}$, meanings of which are explained above. You are to find out the maximum \underline{Koyomity} achievable after repainting the garland according to each plan.
The first thing to notice is that we are only changing other colours to Koyomi's favourite one. Furthermore, we won't create disconnected segments of that colour, for that's no better than painting just around the longest among them. This leads us to a straightforward approach: when faced with a query $(m, c)$, we check each segment $[l, r]$ and determine whether it's possible to fill this segment with letter $c$, within at most $m$ replacements. This can be done by finding the number of times $c$ occurs in that segment (denote it by $t_{c}$), and checking whether $(r - l + 1) - t \le m$. But this $O(n^{2} \cdot q)$ solution would be too slow. Since the number of different queries is $26n$, we can calculate all answers beforehand. For each letter $c$ and a segment $[l, r]$, we'll be able to fill the whole segment with $c$ within $(r - l + 1) - t_{c}$ moves. Use this information to update the answers, and employing a "prefix max" method gives us a time complexity of $O(n^{2} \cdot | \Sigma | + q)$, where $| \Sigma |$ equals $26$. Refer to the code for a possible implementation.
[ "brute force", "dp", "strings", "two pointers" ]
1,600
#include <cstdio> #include <algorithm> static const int MAXN = 1502; static const int ALPHABET = 26; int n; char s[MAXN]; int ans[ALPHABET][MAXN] = {{ 0 }}; int q, m_i; char c_i; int main() { scanf("%d", &n); getchar(); for (int i = 0; i < n; ++i) s[i] = getchar() &mdash; 'a'; for (char c = 0; c < ALPHABET; ++c) { for (int i = 0; i < n; ++i) { int replace_ct = 0; for (int j = i; j < n; ++j) { if (s[j] != c) ++replace_ct; ans[c][replace_ct] = std::max(ans[c][replace_ct], j - i + 1); } } for (int i = 1; i < MAXN; ++i) ans[c][i] = std::max(ans[c][i], ans[c][i - 1]); } scanf("%d", &q); for (int i = 0; i < q; ++i) { scanf("%d %c", &m_i, &c_i); printf("%d\n", ans[c_i - 'a'][m_i]); } return 0; }
814
D
An overnight dance in discotheque
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it? The discotheque can be seen as an infinite $xy$-plane, in which there are a total of $n$ dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area $C_{i}$ described by a center $(x_{i}, y_{i})$ and a radius $r_{i}$. \textbf{No two ranges' borders have more than one common point}, that is for every pair $(i, j)$ ($1 ≤ i < j ≤ n$) either ranges $C_{i}$ and $C_{j}$ are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges. Tsukihi, being one of them, defines the \underline{spaciousness} to be \textbf{the area covered by an odd number of movement ranges of dancers who are moving}. An example is shown below, with shaded regions representing the \underline{spaciousness} if everyone moves at the same time. But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves — before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The \underline{spaciousness} of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. By different plans of who dances in the first half and who does in the other, different sums of \underline{spaciousness} over two halves are achieved. You are to find the largest achievable value of this sum.
Circles' borders do not intersect, that is, each circle is "directly" contained in another circle, or is among the outermost ones. Can you see a tree/forest structure out of this? We create a node for each of the circles $C_{i}$, with weight equal to its area $ \pi r_{i}^{2}$. Its parent is the circle which "directly" contains it, namely the one with smallest radius among those circles containing $C_{i}$. If a circle is an outermost one, then it's made a root. This tree structure can be found in $O(n^{2})$ time. Consider what happens if there's only one group: the spaciousness equals the sum of weights of all nodes whose depths are even, minus the sum of weights of all nodes whose depths are odd. Now we are to split the original tree/forest into two disjoint groups. This inspires us to think of a DP approach - consider a vertex $u$, and the parity (oddness/evenness) of number of nodes in its ancestors from the first and the second group. Under this state, let $f[u][0 / 1][0 / 1]$ be the largest achievable answer in $u$'s subtree. The recursion can be done from bottom to top in $O(1)$, and the answer we need is the sum of $f[u][0][0]$ for all $u$ being roots. Time complexity is $O(n^{2})$ for the tree part and $O(n)$ for the DP part. See the code for the complete recursion.
[ "dfs and similar", "dp", "geometry", "greedy", "trees" ]
2,000
#include <cstdio> #include <cmath> #include <algorithm> #include <vector> typedef long long int64; static const int MAXN = 1004; #ifndef M_PI static const double M_PI = acos(-1.0); #endif int n; int x[MAXN], y[MAXN], r[MAXN]; int par[MAXN]; std::vector<int> e[MAXN]; bool level[MAXN]; // Whether one of C[u] and C[v] is contained in another inline bool circle_contains(int u, int v) { return ((int64)(x[u] - x[v]) * (x[u] - x[v]) + (int64)(y[u] - y[v]) * (y[u] - y[v]) <= (int64)(r[u] - r[v]) * (r[u] - r[v])); } void dfs_colour(int u, bool c) { level[u] = c; for (int v : e[u]) dfs_colour(v, c ^ 1); } int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d%d%d", &x[i], &y[i], &r[i]); for (int i = 0; i < n; ++i) { par[i] = -1; for (int j = 0; j < n; ++j) if (r[j] > r[i] && circle_contains(i, j)) { if (par[i] == -1 || r[par[i]] > r[j]) par[i] = j; } e[par[i]].push_back(i); } for (int i = 0; i < n; ++i) if (par[i] == -1) dfs_colour(i, false); int64 ans = 0; for (int i = 0; i < n; ++i) ans += (int64)r[i] * r[i] * (par[i] == -1 || (level[i] == true) ? +1 : -1); printf("%.8lf\n", (double)ans * M_PI); return 0; }
814
E
An unavoidable detour for home
Those unwilling to return home from a long journey, will be affected by the oddity of the snail and lose their way. Mayoi, the oddity's carrier, wouldn't like this to happen, but there's nothing to do with this before a cure is figured out. For now, she would only like to know the enormous number of possibilities to be faced with if someone gets lost. There are $n$ towns in the region, numbered from $1$ to $n$. The town numbered $1$ is called the capital. The traffic network is formed by bidirectional roads connecting pairs of towns. No two roads connect the same pair of towns, and no road connects a town with itself. The time needed to travel through each of the roads is the same. Lost travelers will not be able to find out how the towns are connected, but the residents can help them by providing the following facts: - Starting from each town other than the capital, the shortest path (i.e. the path passing through the minimum number of roads) to the capital exists, and is unique; - Let $l_{i}$ be the number of roads on the shortest path from town $i$ to the capital, then $l_{i} ≥ l_{i - 1}$ holds for all $2 ≤ i ≤ n$; - For town $i$, the number of roads connected to it is denoted by $d_{i}$, which equals either $2$ or $3$. You are to count the number of different ways in which the towns are connected, and give the answer modulo $10^{9} + 7$. Two ways of connecting towns are considered different if a pair $(u, v)$ ($1 ≤ u, v ≤ n$) exists such there is a road between towns $u$ and $v$ in one of them but not in the other.
Let's make it intuitive: the graph looks like this. Formally, if we find out the BFS levels of the graph, it will look like a tree with extra edges among vertices of the same level, and indices of vertices in the same level form a consecutive interval. Therefore we can add vertices from number $1$ to number $n$ to the graph, without missing or violating anything. Consider the case when we want to add vertex $u$ to a graph formed by the first $u - 1$ vertices. The state only depend on the current and the previous level (We can't start level $l + 1$ without finishing level $l - 1$, thus there are only two unfinished levels). The whole thing is described by four parameters: the number of "1-plug" (having one outgoing edge that is not determined) and "2-plug" (similar definition) vertices in the previous and the current level. Let $f[u][p_{1}][p_{2}][c_{1}][c_{2}]$ be the number of ways to build the graph with the first $u$ vertices, with $p_{1}$ "1-plug" vertices and $p_{2}$ "2-plug" vertices in the previous level, and $c_{1}$ and $c_{2}$ in the current one respectively. For vertex $u$, we must choose one vertex $v$ in the previous layer and connect $u$ to it. For the remaining degree(s) of $u$, we can choose either to connect them to vertices in the same layer, or simply leave them for future. Also, we may start a new level if $p_{1} = p_{2} = 0$. This gives us an $O(1)$ recursion. There are $O(n^{5})$ states, giving us a time complexity of $O(n^{5})$ and a space complexity of $O(n^{4})$ if the first dimension is reused. The constant factor can be rather small (since $p_{1} + p_{2} + c_{1} + c_{2} \le n$). See solution 1 for detailed recursion. Let's try to improve this a bit. Instead of adding one vertex at a time, we consider the layer as a whole. Let $f[c_{0}][c_{1}][c_{2}]$ be the number of ways to build a single level with $c_{0}$ vertices (their "plugs" don't matter), and connect it to the previous layer which has $c_{1}$ "1-plug" vertices and $c_{2}$ "2-plug" ones. Recursion over $f$ can be done in $O(1)$. Then let $g[l][r]$ be the number of ways to build the graph with vertices from $l$ to $n$, while vertices from $l$ to $r$ form the first level - note that this level should be connected to another previous one. The recursion over $g$ can be done in $O(n)$. The final answer should be $g[2][d_{1}]$ since the capital must be directly connected to vertices from $2$ to $d_{1}$. The overall time complexity is $O(n^{3})$. Huge thanks to Nikolay Kalinin (KAN) for this!
[ "combinatorics", "dp", "graphs", "shortest paths" ]
2,600
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 55; const int MOD = 1000000007; int ways[maxn][maxn][maxn]; int answer[maxn][maxn]; int n; int d[maxn]; int sumd[maxn]; inline void add(int &a, ll b) { a = (a + b) % MOD; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &d[i]); ways[0][0][0] = 1; for (int c0 = 0; c0 <= n; c0++) { for (int c2 = 0; c2 <= n; c2++) { for (int c1 = 0; c1 <= n; c1++) if (c1 + c2 > 0) { if (c2 > 0) { if (c0 > 1) add(ways[c0][c1][c2], (ll)ways[c0 - 2][c1][c2 - 1] * (c0 * (c0 - 1) / 2)); // 2-0, 2-0 if (c2 > 1 && c0 > 0) add(ways[c0][c1][c2], (ll)ways[c0 - 1][c1 + 1][c2 - 2] * (c2 - 1) * c0); // 2-2, 2-0 if (c2 > 2) add(ways[c0][c1][c2], (ll)ways[c0][c1 + 2][c2 - 3] * ((c2 - 1) * (c2 - 2) / 2)); // 2-2, 2-2 if (c1 > 0 && c2 > 1) add(ways[c0][c1][c2], (ll)ways[c0][c1][c2 - 2] * c1 * (c2 - 1)); // 2-2, 2-1 if (c1 > 0 && c0 > 0) add(ways[c0][c1][c2], (ll)ways[c0 - 1][c1 - 1][c2 - 1] * c1 * c0); // 2-1, 2-0 if (c1 > 1) add(ways[c0][c1][c2], (ll)ways[c0][c1 - 2][c2 - 1] * (c1 * (c1 - 1) / 2)); // 2-1, 2-1 } else { if (c0 > 0) add(ways[c0][c1][c2], (ll)ways[c0 - 1][c1 - 1][c2] * c0); // 1-0 if (c1 > 1) add(ways[c0][c1][c2], (ll)ways[c0][c1 - 2][c2] * (c1 - 1)); // 1-1 } } } } for (int i = 0; i < n; i++) sumd[i + 1] = sumd[i] + d[i]; answer[n][n - 1] = 1; for (int l = n - 1; l > 0; l--) { for (int r = l; r < n; r++) { int cnt2 = sumd[r + 1] - sumd[l] - 2 * (r - l + 1); int cnt1 = r - l + 1 - cnt2; for (int nextlvl = 0; nextlvl <= 2 * cnt2 + cnt1 && nextlvl <= n; nextlvl++) { int curways = ways[nextlvl][cnt1][cnt2]; if (r + nextlvl < n) { add(answer[l][r], (ll)answer[r + 1][r + nextlvl] * curways); } } } } if (d[0] + 1 > n) cout << 0 << endl; else cout << answer[1][d[0]] << endl; return 0; }
815
A
Karen and Game
On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with $n$ rows and $m$ columns. Each cell originally contains the number $0$. One move consists of choosing one row or column, and adding $1$ to all of the cells in that row or column. To win the level, after all the moves, the number in the cell at the $i$-th row and $j$-th column should be equal to $g_{i, j}$. Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!
Fix the number of times we choose the first row. Say we choose the first row $k$ times. This actually uniquely determines the rest of the solution; consider the cells on the first row. There is no other way to increase these cells, except by choosing the columns they are on, and so we need to choose the $j$-th column $g_{1, j} - k$ times. Now, once we know the number of times we have to choose each column, we will also know how many times to choose the remaining rows. At this point, for any given row $i$, the remaining number of times we have to choose it is $g_{i, j} - (g_{1, j} - k)$, this should be the same for all $j$ in a given row (otherwise there is no solution). We can simply try all $k$, see if they can form a valid solution, and if so, calculate how many moves it will take. Find the smallest required number of moves, and then recover the solution. Implemented properly, it should run in $O(n)$ time, which should be fast enough. Note that there are $O(max g_{i, j})$ possible choices for $k$, and testing a certain $k$ can be done in $O(nm)$ time. A solution will have at most $O(max(n, m) \cdot max g_{i, j})$ moves, so printing them will take that much time. Overall, this solution hence runs in $O(nm \cdot max g_{i, j})$ time, which is acceptable. There is a faster solution to this, both in terms of runtime and implementation time, which we will describe below. Notice that, when there is a $0$ on the grid, all the moves are already fixed. If the $0$ is at $g_{i, j}$, then we need to choose row $i'$ exactly $g_{i', j}$ times, and column $j'$ exactly $g_{i, j'}$ times. What if there is no $0$ on the grid? Well, we intuitively want to reduce numbers as much as possible, and in fact the greedy algorithm works here. If there are not more rows $(n \le m)$, we should keep choosing rows, and if there are fewer columns $(n > m)$, we should keep choosing columns, until there is a $0$. It doesn't even matter which particular rows or columns we choose; for example, if $n \le m$, we could just keep choosing row $1$ until a $0$ appears, or we could choose all rows $1, 2, 3, ..., n$ in order and just keep cycling through them. The end result will be the same. We can just check that the grid is correct at the end and print $- 1$ otherwise. Implemented properly, this runs in $O(nm + max(n, m) \cdot max g_{i, j})$, which is asymptotically optimal; it takes at least $O(nm)$ time to read the input, and $O(max(n, m) \cdot max g_{i, j})$ to print the output.
[ "brute force", "greedy", "implementation" ]
1,700
null
815
B
Karen and Test
Karen has just arrived at school, and she has a math test today! The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. There are $n$ integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition. Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa. The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test. Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row? Since this number can be quite large, output only the non-negative remainder after dividing it by $10^{9} + 7$.
There are a couple of ways to solve this problem. The easiest way is to calculate the coefficients, or "contributions", of each number to the final sequence. In fact, the contribution of any number is determined by its position as well as the $n$. To do this, using brute force, we can compute the contribution of each element by just running a brute-force on $0, 0, 0, ..., 1, ..., 0, 0, 0$ for all positions $1$ and then trying to observe patterns. In any case, one should eventually realize that the pattern depends on $n{\mathrm{~mod~}}4$: When $n{\mathrm{~mod~}}4=0$, the pattern is: $\bigl(\stackrel{(n-2)/2}{0}\bigr),-\Bigl(\stackrel{(n-2)/2}{0}\bigr),\bigl(\stackrel{(n-2)/2}{1}\bigr),\bigl(\stackrel{(n-2)/2}{2}\bigr),-\bigl(\stackrel{(n-2)/2}{1}\bigr),-\bigl(\stackrel{(n-2)/2}\bigr),\nonumber\bigr(\stackrel{(n-2)/2}{2}\bigr),\ldots.$ When $n{\mathrm{~mod~}}4=1$, the pattern is: $\left(\begin{array}{l}{{(n-1)/2}}\\ {{0}}\end{array}\right),(\begin{array}{l}{{\left(n-1\right)/2}}\\ {{1}}\end{array}\right),(\begin{array}{l}{{\left(n-1\right)/2}}\\ {{2}}\end{array}\right),(\not=.$ When $n{\mathrm{~mod~}}4=2$, the pattern is: $\bigl(\stackrel{(n-2)/2}{0}\bigr),\bigl(\stackrel{(n-2)/2}{0}\bigr),\bigl(\stackrel{(n-2)/2}{1}\bigr),\bigl(\stackrel{(n-2)/2}{2}\bigr),\bigl(\stackrel{(n-2)/2}\bigr),\bigl(\stackrel{(n-2)/2}{2}\bigr),\nonumber\cdot\cdot\cdot.$ When $n{\mathrm{~mod~}}4=3$, the pattern is: $(^{(n-3)/2}),2{\binom{(n-3)/2}{0}},({^{(n-3)/2}}),({^{(n-3)/2}})-{\big(}^{(n-3)/2}{\big)},2{\binom{(n-3)/2}{1}},2{\binom{(n-3)/2}{2}}{\big)},2{\big(}{^{(n-3)/2}}{\big)},2{\big(}{^{(n-3)/2}}{\big)}...\cdots$ This is perhaps what most contestants did in the contest. We will not prove that this is correct; instead, a more elegant solution will be suggested. First, simplify the problem so that only addition ever happens. In fact, this version is much easier: the contribution of the $\textstyle\int_{\lambda}{\mathrm{th}}$ element when there are $n$ elements is precisely $\textstyle{\binom{n-1}{k-1}}$. Now, let's go back to the original task. We will repeatedly perform the operation until the number of elements $n$ is even, and the first operation is addition, to reduce the number of cases we have to handle. It can be observed that, regardless of our starting $n$, this will happen somewhere within the first two rows. We can therefore just brute force it. Observe the following picture: Consider the blue elements only. Am I the only one whose mind is on the verge of exploding? Notice that they are doing precisely the simpler version of the task! In other words, if we consider only $a_{1}, a_{3}, a_{5}, ...$, we are basically solving the simple version of the task! In fact, the same can be said of $a_{2}, a_{4}, a_{6}, ...$. Why is this true? Well, look at the picture. Notice that, if we have an even number of elements with the first element being addition, then, after $4$ rows, it will again be even and the first element will also be addition, so the pattern simply continues! We can hence compute the final two values on the second to last row, and then add or subtract them, depending on what the final operation should be. In fact, this also explains the patterns we observed for $n{\mathrm{~mod~}}4=0$ and $n{\mathrm{~mod~}}4=2$! To compute $\textstyle{\binom{n}{k}}$ quickly, we can use the formula ${\binom{n}{k}}={\frac{n!}{k!(n-k)!}}$. We can just preprocess all relevant factorials in $O(n)$, and also their modular multiplicative inverses modulo $10^{9} + 7$ in order to perform the division. This runs in $O(n\log(10^{9}+7))$ or just $O(n)$ if you are willing to consider the $\log(10^{9}+7)$ a constant.
[ "brute force", "combinatorics", "constructive algorithms", "math" ]
2,200
null
815
C
Karen and Supermarket
On the way home, Karen decided to stop by the supermarket to buy some groceries. She needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to $b$ dollars. The supermarket sells $n$ goods. The $i$-th good can be bought for $c_{i}$ dollars. Of course, each good can only be bought once. Lately, the supermarket has been trying to increase its business. Karen, being a loyal customer, was given $n$ coupons. If Karen purchases the $i$-th good, she can use the $i$-th coupon to decrease its price by $d_{i}$. Of course, a coupon cannot be used without buying the corresponding good. There is, however, a constraint with the coupons. For all $i ≥ 2$, in order to use the $i$-th coupon, Karen must also use the $x_{i}$-th coupon (which may mean using even more coupons to satisfy the requirement for that coupon). Karen wants to know the following. What is the maximum number of goods she can buy, without exceeding her budget $b$?
Instead of asking for the maximum number of items we can buy with $b$ dollars, let's ask instead for the minimum cost to buy $j$ items for all $j$. Afterwards, we can simply brute force all $j$ to find the largest $j$ that still fits within her budget $b$. Note this problem is actually on a rooted tree, with root at node $1$; the constraint $x_{i} < i$ guarantees there are no cycles in this problem. The coupon requirement essentially means that if we buy good $i$ at the discounted price, we also need to buy good $x_{i}$ at the discounted price, and so on. If we don't buy at discounted price there are no constraints (except that Karen can afford it. Unfortunately, she isn't a criminal.) There is a rather straightforward $O(n^{3})$ dynamic programming solution to this problem, as follows: Let $f_{i, j}$ be the minimum cost to buy $j$ items in the subtree of $i$ if we can still use coupons, and $g_{i, j}$ the minimum cost to buy $j$ items in the subtree of $i$ if we cannot use any more coupons. We know that for all leaves, $f_{i, j} = c_{i} - d_{i}$ and $g_{i, j} = c_{i}$. We can compute $g_{i, j}$ for all nodes as well; this is simply the sum of the $j$ smallest $c$'s in the subtree of $i$. This can be done straightforwardly in $O(n^{2})$ or $O(n^{2}\log{n})$. To compute this $f_{i, j}$ for some non-leaf node $i$, we should initialize $f_{i, 1} = c_{i} - d_{i}$. Now, we can add each of the children of $i$ one by one, and try each $j$. Suppose we take $k$ elements from one of the children. Then we have $f_{i, j} = min(f_{i, j}, f_{i, j - k} + f_{i, k})$. We just have to make sure to implement it in a way that we don't inadvertently take elements multiple times, usually by making an auxiliary array. Finally, we set $f_{i, j} = min(f_{i, j}, g_{i, j})$ to consider not using the coupons. Note that we can't do this at the start, because otherwise it could cause conflicts. This runs in $O(n^{3})$, which is too slow. This is because there are $n$ nodes, and to compute $f_{i, j}$ for all $j$ in that node, it takes $O(n\geq{}_{h\in p_{i}}\,s(h))$ where $p_{i}$ is the set of all of the children of $i$, and $s(h)$ is the subtree size of node $h$. This sum turns out to be $O(n^{2})$, and so the final runtime is $O(n^{3})$. How could we make it faster? Take the largest (in terms of nodes) child of subtree $i$. Can we avoid iterating through this? Yes, we can! Suppose our tree was binary. Now, we can compute $f_{i, j} = min_{0 \le k < j}(f_{a, j - k - 1} + f_{b, k} + c_{i} - d_{i})$, where $a$ and $b$ are the subtrees of $i$, with $s(a) \ge s(b)$. This skips iterating through the larger subtree $a$. We can extend this to non-binary trees, too; just do this to skip the largest subtree, and then add the rest like before. The runtime of the transition is now $O(n(\sum_{h\in p_{i}}s(h)-s(a)))$, which turns out to be just $O(n)$. The final runtime is hence $O(n^{2})$ (or $O(n^{2}\log{n})$, depending on the algorithm used for the greedy portion.) This is sufficient to solve this problem.
[ "brute force", "dp", "trees" ]
2,400
null
815
D
Karen and Cards
Karen just got home from the supermarket, and is getting ready to go to sleep. After taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection. She recalled that she used to play with those cards as a child, and, although she is now grown-up, she still wonders a few things about it. Each card has three characteristics: strength, defense and speed. The values of all characteristics of all cards are positive integers. The maximum possible strength any card can have is $p$, the maximum possible defense is $q$ and the maximum possible speed is $r$. There are $n$ cards in her collection. The $i$-th card has a strength $a_{i}$, defense $b_{i}$ and speed $c_{i}$, respectively. A card beats another card if at least two of its characteristics are strictly greater than the corresponding characteristics of the other card. She now wonders how many different cards can beat all the cards in her collection. Two cards are considered different if at least one of their characteristics have different values.
Let's say we have one card, with $a_{1} = 4$, $b_{1} = 2$ and $c_{1} = 3$. For simplicity, we have $p = q = r = 5$. Consider which cards will beat this one. Let's fix the $c$ of our card, and see what happens at all various $c$: Note that a green cell at $(a, b)$ in grid $c$ represents that the card $(a, b, c)$ can beat the card $(4, 2, 3)$. Hence, the total number of cards that can beat this card is simply the number of green cells across all $c$ grids. This representation is helpful, because we can easily account for more cards. For example, let's say we have another card $a_{2} = 2$, $b_{2} = 3$ and $c_{2} = 4$: Now, what happens when we want to consider the cards that beat both of these cards? Well, we simply have to consider the intersection of both sets of grids! Remember that we are simply trying to count the total number of green cells in all grids. It turns out that trying to count the number of green cells directly is quite difficult. Instead, it is more feasible to count the number of not green cells, and then simply subtract it from the number of cells $pqr$. How could we do this? We should exploit some properties of the grids. First, for any particular card $(a_{i}, b_{i}, c_{i})$, all the grids from $1$ to $c_{i}$ are the same, and all the grids from $c_{i} + 1$ to $r$ are the same. This means that we can avoid a lot of redundancy, and only perform some sort of update when we reach the change. Second, if some cell $(a, b)$ is not green for some fixed $c$, then neither are the cells $(a', b')$ for all $a' \le a$ and $b' \le b$ for the same $c$. This means that we can replace each grid with an array $u_{1}, u_{2}, u_{3}, ...$ where $u_{a}$ is the largest $b$ for which $(a, b)$ is not green. Additionally, $u_{1} \ge u_{2} \ge u_{3} \ge ... \ge u_{p}$. Third, for any card, there are only at most two distinct values in $u$ for any fixed $c$ in one card. Finally, for any card, no value $u_{i}$ in $c$ is less than $u_{i}$ in $c'$ if $c < c'$. These properties are all pretty easy to observe and prove, but they will form the bread and butter of our solution. Let's iterate cards from $c = r$ to $c = 1$. Suppose we maintain an array $s$ which will at first contain all $0$. This will be the number of cells that are not green. We will update it for all grids first. For each card, we are essentially setting, for all $i$, $s_{i}$ to $max(s_{i}, u_{i})$. Of course, doing this for each grid will take $O(np)$, which is too slow. To remedy this, initialize $s$ as a segment tree instead. Now, we are basically just setting $s_{1}, s_{2}, s_{3}, ..., s_{ai}$ to $max(s_{j}, b_{i})$ for all cards $i$. Because $s$ is essentially a maximum of a bunch of $u$'s, which are all nonincreasing by the second property, it follows that $s$ is also nonincreasing at all times. Therefore, these updates are easy to do; we are essentially setting $s_{k}, s_{k + 1}, s_{k + 2}, ..., s_{ai}$ to $b_{i}$ for the smallest $k$ where $b_{i} \ge s_{k}$. We can find $k$ using binary search. Binary searching the segment tree can be done in $O(\log p)$ time using an implicit binary search by going down the tree; an explicit $O(\log^{2}p)$ binary search might have trouble passing the time limit. Using the aforementioned procedure, we are able to generate $s$ corresponding to the layer $c = r$ in $O(n\log p)$ time. Using the segment tree, we should also be able to get the sum of all values in $s$ at all times. This will allow us to count the number of not green cells. Now, we will go backwards from $c = r$ to $c = 1$. We should decrement $c$, and then see which grids changed. (Just sort the cards by $c_{i}$ and do a two-pointers approach.) All the newly-changed grids can then be updated in a similar manner as before. When a grid changes, thanks to the fourth property, there is no worry of any $u_{i}$ getting smaller than it was before; they can only get bigger. So, we have to update two ranges $s_{1}, s_{2}, s_{3}, ..., s_{ai}$ to $r$ and $s_{ai + 1}, s_{a2 + 1}, s_{ai + 3}, ..., s_{p}$ to $max(s_{j}, b_{i})$. The former is a simple range update, the latter can be done using binary search like before. After we update all grids for a particular $c$, get the range sum, and decrement $c$ again, and so on until we reach $1$. We will have the found the total number of not green cells in all $c$, and from there we can recover all the green cells, and hence the final answer. Sorting the cards by $c_{i}$ takes $O(n\log n)$ time, constructing the segment tree $s$ takes $O(p)$ time, there are $O(n)$ updates each taking $O(\log p)$ time, and iterating takes $O(r)$ time. The final runtime is therefore $O(n(\log n+\log p)+p+r)$ time, which is sufficient to solve this problem. This solution can be modified to pass $p, q, r \le 10^{9}$, too; however, this was not done as it uses only standard ideas and just contains more tedious implementation. If you want, you can try to implement it.
[ "binary search", "combinatorics", "data structures", "geometry" ]
2,800
null
815
E
Karen and Neighborhood
It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood. The neighborhood consists of $n$ houses in a straight line, labelled $1$ to $n$ from left to right, all an equal distance apart. Everyone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one. Note that the first person to arrive always moves into house $1$. Karen is the $k$-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into?
Surprisingly, it is possible to solve this problem without knowledge of any sophisticated algorithms or data structures; this problem can be solved completely through observations, brutal case analysis and grunt work, which we will try to summarize here. The first and most obvious observation: the first person always goes to house $1$, and the second person always goes to house $n$. Consider these two guys as special cases; now, we're solving the problem on a segment of length $n - 2$. Note how we define segments here; a segment of length $l$ is a row of $l$ unoccupied houses, with the two houses just before and after both endpoints occupied. Notice that, for any segment, if a person moves into any house in this segment it will be the middle one; if there are two middles, it will be the left of the two middles. So, if we have a length $3$ segment, the person will move into the $2$-nd house in the segment. If we have a length $6$ segment, the person will move into the $3$-rd house in the segment, and so on. When a person moves into a house in a given segment of length $l$, if $l > 2$, it will also create two new segments; the left segment will be length $\left\lfloor{\frac{l-1}{2}}\right\rfloor$ and the right segment will be length $\textstyle{\left|{\frac{l}{2}}\right|}$. Let's write down the segments in a binary tree, where the $i$-th layer contains all segments spawned by the $(i - 1)$-th layer, and the first layer contains precisely the segment of length $n - 2$. For example, consider $n = 46$. The binary tree will look like this: From this, we can make a number of observations. We can see that there are at most $2$ different segment lengths in any layer. Additionally, these values are always $l$ and $l + 1$, where $l$ is the smaller one. Let the two lengths in a given layer be $l$ and $l + 1$ (if there is only one, it's just $l$). Now, consider the following: If $l$ is odd, the segments of length $l$ and $l + 1$ will be processed in order from left to right. If $l$ is even, all segments of length $l + 1$ will be processed first, from left to right, then all segments of length $l$ will be processed, also from left to right. This makes sense; the "minimum distance" is actually just the smaller of the two children, and you can observe that in the above first case, the smaller of the two children is equal, while in the second case, the smaller of the two children of $l$ is smaller than the smaller of the two children of $l + 1$. Additionally, all segments in any particular layer are always processed before the segments in the next layer (except in the case $l = 2$-we will discuss the special cases later.) We can therefore determine, rather straightforwardly, what layer the $k$-th segment is. Since all the layers above this layer are now irrelevant, we can just subtract all the taken layers from $k$. Now, the problem has been reduced to finding what house the $k$-th guy in a fixed layer moves into. How will we find this? Well, note that there is exactly one house separating any two segments in a given layer. If we go to the $k$-th segment, the label of the house we actually went into is $k$ (number of houses occupied on previous layers), plus the total length of segments $1, 2, 3, ..., k - 1$ (unoccupied houses before this one), plus $\left\lfloor{\frac{k+1}{2}}\right\rfloor$ (the middle house in the $k$-th segment). It is easy to determine $l$ and the number of length $l$ and length $l + 1$ segments for any particular layer. What's harder to compute are two crucial details: What's the relative position of the $k$-th processed segment in this layer? How many layers have length $l + 1$ before the segment at this relative position? If we can answer these two questions efficiently, we are basically done with the core of the solution, and just have to handle special cases. Let's answer the first question. If $l$ is odd, this is trivial; the $k$-th processed segment is precisely that at position $k$. If $l$ is even, things get a lot trickier. Luckily, we can perform more observations. Draw the tree with root segment $39$ $(n = 41)$, and observe the fourth row. Now, draw the trees with root segments $40, 41, 42, ..., 47$. Observe how the fourth row changes from root segment $39$ to $47$: Root segment is $39$: $4, 4, 4, 4, 4, 4, 4, 4$ Root segment is $40$: $4, 4, 4, 4, 4, 4, 4, 5$ Root segment is $41$: $4, 4, 4, 5, 4, 4, 4, 5$ Root segment is $42$: $4, 4, 4, 5, 4, 5, 4, 5$ Root segment is $43$: $4, 5, 4, 5, 4, 5, 4, 5$ Root segment is $44$: $4, 5, 4, 5, 4, 5, 5, 5$ Root segment is $45$: $4, 5, 5, 5, 4, 5, 5, 5$ Root segment is $46$: $4, 5, 5, 5, 5, 5, 5, 5$ Root segment is $47$: $5, 5, 5, 5, 5, 5, 5, 5$ In what order are the numbers increased? It's not immediately obvious, but we can try to write down the binary representations of the (zero-indexed) positions in the order they are increased: $7$: $111$ $3$: $011$ $5$: $101$ $1$: $001$ $6$: $110$ $2$: $010$ $4$: $100$ $0$: $000$ Actually, this is just the reversed binary numbers in reverse order! Remember that our goal is to find the relative position of the $k$-th processed element. Without loss of generality, suppose that the $k$-th processed element is of length $l + 1$ (the analysis when it is length $l$ is almost the same.) This is equivalent to asking for the $k$-th smallest element among the first $m$ numbers in that list ($m$ is the number of $l + 1$ segments in the given layer, which is easy to compute). Let's take root segment equal to $44$, as in the illustration earlier. Let's say we want the position of the $k = 4$-th occurrence of $5$. That's equivalent to finding the $4$-th smallest element in this list (obviously we never get to generate this list explicitly): $7$: $111$ $3$: $011$ $5$: $101$ $1$: $001$ $6$: $110$ Consider these binary numbers digit by digit starting from the largest. Notice that, at any point, the number of ones is always equal to or one more than the number of zeroes; above, there are $3$ ones and $2$ zeroes. We want the $4$-th smallest, and there are only $2$ zeroes, so we know it has to start with $1$. We throw out (again, not explicitly) all the numbers that start with zero, and we are now left with finding the $2$-nd smallest in this list: Our number so far: $1??$ $7$: $11$ $5$: $01$ $6$: $10$ Now, there are $2$ ones and $1$ zero. We want the $2$-nd smallest, and there is only $1$ zero, so we know the next digit is $1$. We throw out all the numbers that start with zero, and we are now left with finding the $1$-st smallest in this list: Our number so far: $11?$ $7$: $1$ $6$: $0$ Now, there is $1$ one and $1$ zero. We want the $1$-st smallest, and there is $1$ zero, which is enough. So, this is the next digit. The final number is $6$, which means that the position of the $4$-th $5$ is at $6$. ($7$ if one-indexed). This process works for any arbitrary numbers in $O(\log n)$, and now we are able to answer the first required question in just $O(\log n)$ time. Now, we need to answer the second question. How many layers have length $l + 1$ before the segment at this relative position? Actually, this question can be solved using almost the exact same binary digit analysis! The problem is equivalent to asking for how many numbers, among the first $m$ numbers in the earlier list, have a position less than $k$. We will omit the analysis here for brevity, but it uses virtually the same idea and also solves this question in $O(\log n)$. Now, we have solved both questions, and have essentially finished the core of the problem. But we're not yet done! We still have to handle the corner cases. There are actually only two corner cases: $l = 1$ and $l = 2$. When $l = 1$, note that every segment of length $2$ is basically treated as two segments of length $1$. When $l = 2$, segments of length $3$ are handled first, each creating segments of length $1$. Then, the segments of length $1$ and $2$ are treated like with $l = 1$, despite the segments of length $1$ technically being on the next layer. Both of these cases can be solved using the same binary digit analysis, with some grunt-work formulas that can be a bit hard to get precisely correct. These cases can also be solved in $O(\log n)$. Overall, the runtime of the solution is just $O(\log n)$.
[ "binary search", "constructive algorithms", "implementation" ]
2,900
null
816
A
Karen and Morning
Karen is getting ready for a new school day! It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome? Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
This is a rather straightforward implementation problem. The only observation here is that there are only $1440$ different possible times. It is enough to iterate through all of them until we encounter a palindromic time, and count the number of times we had to check before we reached a palindromic time. How do we iterate through them? The most straightforward way is to simply convert the given string into two integers $h$ and $m$. We can do this manually or maybe use some functions specific to your favorite language. It is good to be familiar with how your language deals with strings. It is also possible, though inadvisable, to try to work with the string directly. To go to the next time, we simply increment $m$. If $m$ becomes $60$, then make it $0$ and increment $h$. If $h$ becomes $24$, then make it $0$. To check whether a given time is palindromic, we simply need to check if the tens digit of $h$ is the same as the ones digit of $m$, and if the ones digit of $h$ is the same as the tens digit of $m$. This can be done like so: check if $|\underline{{{h}}}^{k}\rangle=m\ \mathrm{mod}\ 10$ and $h_{\mathrm{\scriptsize~IIDd}}\left|0\right|=\left|\frac{m}{10}\right|$. Another way is to simply cross-check against a list of palindromic times. Just be careful not to miss any of them, and not to add any extraneous values. There are $16$ palindromic times, namely: $00: 00$, $01: 10$, $02: 20$, $03: 30$, $04: 40$, $05: 50$, $10: 01$, $11: 11$, $12: 21$, $13: 31$, $14: 41$, $15: 51$, $20: 02$, $21: 12$, $22: 22$ and $23: 32$.
[ "brute force", "implementation" ]
1,000
null
816
B
Karen and Coffee
To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe". She knows $n$ coffee recipes. The $i$-th recipe suggests that coffee should be brewed between $l_{i}$ and $r_{i}$ degrees, inclusive, to achieve the optimal taste. Karen thinks that a temperature is admissible if at least $k$ recipes recommend it. Karen has a rather fickle mind, and so she asks $q$ questions. In each question, given that she only wants to prepare coffee with a temperature between $a$ and $b$, inclusive, can you tell her how many admissible integer temperatures fall within the range?
There are two separate tasks here: Efficiently generate an array $c$ where $c_{i}$ is the number of recipes that recommend temperature $i$. Efficiently answer queries "how many numbers $c_{a}, c_{a + 1}, c_{a + 2}, ..., c_{b}$" are at least $k$?" where $k$ is fixed across all queries. There are some solutions to this task using advanced data structures or algorithms. For example, a conceptually straightforward idea is the following: create a segment tree $c$. We can treat all recipes as range update queries which we can do efficiently in $O(n\log m)$ (where $m$ is the largest $a_{i}$ or $b_{i}$) time using lazy propagation. After all recipes, we replace all $c_{i}$ by $1$ if it's at least $k$, and $0$ otherwise. Afterwards, each of the next $q$ queries is a basic range sum query, which can be done simply in $O(q\log m)$ time. Other solutions exist, too: Fenwick trees with range updates, event sorting, sqrt-decomposition with binary search, Mo's algorithm, and so on. These solutions all pass, but they are all overkill for this task. A very simple solution is as follows. Initialize $c$ with all zeroes. For recipe that recommends temperatures between $l_{i}$ and $r_{i}$, we should increment $c_{li}$ and decrement $c_{ri + 1}$. Cumulate all values. That is, set $c_{i}$ to $c_{1} + c_{2} + c_{3} + ... + c_{i}$. This can be done with one pass through the array. Now, magically, $c_{i}$ is now the number of recipes that recommend temperature $i$. If $c_{i}$ is at least $k$, set it to $1$, otherwise, set it to $0$. Cumulate all values again. Now, every query that asks for the number of admissible temperatures between $a$ and $b$ can be answered simply as $c_{b} - c_{a - 1}$. This runs in $O(n + q + m)$, which is really fast. Note that if your solution does this and still runs quite slow, chances are your solution is using slower input methods. We raised the time limit to 2.5 seconds in this problem in order to avoid failing slow input solutions.
[ "binary search", "data structures", "implementation" ]
1,400
null
817
A
Treasure Hunt
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure. Bottle with potion has two values $x$ and $y$ written on it. These values define four moves which can be performed using the potion: - $(a,b)\rightarrow(a+x,b+y)$ - $(a,b)\to(a+x,b-y)$ - $(a,b)\rightarrow(a-x,b+y)$ - $(a,b)\to(a-x,b-y)$ Map shows that the position of Captain Bill the Hummingbird is $(x_{1}, y_{1})$ and the position of the treasure is $(x_{2}, y_{2})$. You task is to tell Captain Bill the Hummingbird whether he should accept this challenge or decline. If it is possible for Captain to reach the treasure using the potion then output "YES", otherwise "NO" (without quotes). \textbf{The potion can be used infinite amount of times.}
Firstly, let's approach this problem as if the steps were $(a,b)\to(a\pm x,0)$ and $(a,b)\rightarrow(0,b\pm y)$. Then the answer is "YES" if $|x_{1} - x_{2}|$ $mod$ $x = 0$ and $|y_{1} - y_{2}|$ $mod$ $y = 0$. It's easy to see that if the answer to this problem is "NO" then the answer to the original one is also "NO". Let's return to the original problem and take a look at some sequence of steps. It ends in some point $(x_{e}, y_{e})$. Define $cnt_{x}$ as $\textstyle{\frac{|x_{e}-x_{1}|}{x}}$ and $cnt_{y}$ as $\textstyle\frac{|j_{i}-y_{i}|}{y}$. The parity of $cnt_{x}$ is the same as the parity of $cnt_{y}$. It is like this because every type of move changes parity of both $cnt_{x}$ and $cnt_{y}$. So the answer is "YES" if $|x_{1} - x_{2}|$ $mod$ $x = 0$, $|y_{1} - y_{2}|$ $mod$ $y = 0$ and $\textstyle{\frac{|x_{1}-x_{2}|}{x}}$ $mod$ $2={\frac{\vert y_{1}-y_{2}\vert}{y}}$ $mod$ $2$. Overall complexity: $O(1)$.
[ "implementation", "math", "number theory" ]
1,200
null
817
B
Makes And The Product
After returning from the army Makes received a gift — an array $a$ consisting of $n$ positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices $(i,  j,  k)$ ($i < j < k$), such that $a_{i}·a_{j}·a_{k}$ is minimum possible, are there in the array? Help him with it!
Minimal product is obtained by multiplying three smallest elements of the array. Let's iterate over the middle element of these three and calc sum of all options. Firstly let's precalc two arrays of pairs - $mnl$ and $mnr$. $mnl[x]$ is minimum and number of its occurrences on the prefix of array $a$ up to index $x$ inclusive. $mnr[x]$ is minimum and number of its occurrences on the suffix of array $a$ up to index $x$ inclusive. It can be done with two traversals over the array. Let's also store set of three elements which give minimal product of the array. Consider every index $j$ from $1$ to $n - 2$ inclusive (0-indexed). If set ($a[j], mnl[j - 1].first, mnr[j + 1].first$) is equal to the stored set of three minimums then add to the answer number of ways to choose pair $(i, k)$, that is $mnl[j - 1].second \cdot mnr[j + 1].second$. Overall complexity: $O(n)$.
[ "combinatorics", "implementation", "math", "sortings" ]
1,500
null
817
C
Really Big Numbers
Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number $x$ is really big if the difference between $x$ and the sum of its digits (in decimal representation) is not less than $s$. To prove that these numbers may have different special properties, he wants to know how rare (or not rare) they are — in fact, he needs to calculate the quantity of really big numbers that are not greater than $n$. Ivan tried to do the calculations himself, but soon realized that it's too difficult for him. So he asked you to help him in calculations.
Let's prove that if $x$ is really big, then $x + 1$ is really big too. Since the sum of digits of $x + 1$ (let's call it $sumd(x + 1)$) is not greater than $sumd(x) + 1$, then $x + 1 - sumd(x + 1) \ge x - sumd(x)$, and if $x - sumd(x) \ge s$, then $x + 1 - sumd(x + 1) \ge s$. So if $x$ is really big, then $x + 1$ is really big. This observation allows us to use binary search to find the minimum really big number (let's call it $y$). And if $y \le n$, then all numbers in the segment $[y, n]$ are really big and not greater than $n$, so the quantity of these numbers is the answer to the problem.
[ "binary search", "brute force", "dp", "math" ]
1,600
null
817
D
Imbalanced Array
You are given an array $a$ consisting of $n$ elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array $[1, 4, 1]$ is $9$, because there are $6$ different subsegments of this array: - $[1]$ (from index $1$ to index $1$), imbalance value is $0$; - $[1, 4]$ (from index $1$ to index $2$), imbalance value is $3$; - $[1, 4, 1]$ (from index $1$ to index $3$), imbalance value is $3$; - $[4]$ (from index $2$ to index $2$), imbalance value is $0$; - $[4, 1]$ (from index $2$ to index $3$), imbalance value is $3$; - $[1]$ (from index $3$ to index $3$), imbalance value is $0$; You have to determine the imbalance value of the array $a$.
First of all, we will calculate the sum of maximum and minimum values on all segments separatedly. Then the answer is the difference between the sum of maximum values and minimum values. How can we calculate the sum of minimum values, for example? For each element we will try to find the number of segments where it is the leftmost minimum element. So, we will calculate two arrays $left$ ($left[i] = j$ means that $j$ is the maximum index such that $a_{i} \ge a_{j}$ and $j < i$) and $right$ ($right[i] = j$ means that $j$ is the minimum index such that $a_{i} > a_{j}$ and $j > i$). So actually, $left[i]$ and $right[i]$ represent the borders of the largest segment where $a_{i}$ is the leftmost minimum element (and we need to exclude those borders). While knowing these values, we can calculate the number of subsegments where $a_{i}$ is the leftmost minimum element. How can we calculate, for example, the array $left$? We will use a stack where we will store some indices in the array $a$ in such a way that, if we change all indices to the values in the array $a$, they will be in sorted order (the maximum element will be at the top of the stack, and the minimum - at the bottom). Let's calculate $left$ from the minimum index to the maximum. When we calculate $left[i]$, we remove all elements $j$ such that $a_{j} > a_{i}$ from the stack (since the stack is "sorted", all these elements will be at the top of the stack, and when we encounter the first element $j$ such that $a_{j} \le a_{i}$, it is guaranteed that all elements below it don't need to be deleted). Then, if there's any element on top of the stack, it becomes the value of $left[i]$, then we push $i$ into the stack. Since every element will be added (and deleted) not more than one time, the complexity of this algorithm is linear. We can apply the same technique to calculate the values of $right$ and the sum of maximums.
[ "data structures", "divide and conquer", "dsu", "sortings" ]
1,900
null
817
E
Choosing The Commander
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires. Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors. Each warrior is represented by his personality — an integer number $p_{i}$. Each commander has two characteristics — his personality $p_{j}$ and leadership $l_{j}$ (both are integer numbers). Warrior $i$ respects commander $j$ only if $p_{i}\oplus p_{j}<l_{j}$ ($x\oplus y$ is the bitwise excluding OR of $x$ and $y$). Initially Vova's army is empty. There are three different types of events that can happen with the army: - $1 p_{i}$ — one warrior with personality $p_{i}$ joins Vova's army; - $2 p_{i}$ — one warrior with personality $p_{i}$ leaves Vova's army; - $3 p_{i} l_{i}$ — Vova tries to hire a commander with personality $p_{i}$ and leadership $l_{i}$. For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.
Let's use binary trie to store all personalities of warriors (that is, just use the trie data structure on binary representations of all $p_{i}$). For each subtree of this trie you have to maintain the number of $p_{i}$'s currently present in this subtree - when inserting a value of $p_{i}$, we increase the sizes of subtrees on the path from the node with $p_{i}$ to the root by $1$, and when removing $p_{i}$, we decrease the sizes of subtrees on this path by $1$. How can it help us with answering the events of third type? We will descend the trie. When descending, we will try to find the number $p_{i}\oplus l_{i}$ in the structure. When we go to some subtree, we determine whether we add the quantity of numbers in the subtree we are not going into by checking if the current bit in $l_{i}$ is equal to $1$ (if so, then for all numbers from this subtree their bitwise xor with the current commander's personality is less than $l_{i}$). The answer to the event is the sum of sizes of all subtrees we "added" while descending into the trie.
[ "bitmasks", "data structures", "trees" ]
2,000
null
817
F
MEX Queries
You are given a set of integer numbers, initially it is empty. You should perform $n$ queries. There are three different types of queries: - 1 $l$ $r$ — Add all missing numbers from the interval $[l, r]$ - 2 $l$ $r$ — Remove all present numbers from the interval $[l, r]$ - 3 $l$ $r$ — Invert the interval $[l, r]$ — add all missing and remove all present numbers from the interval $[l, r]$ After each query you should output MEX of the set — the smallest positive (MEX $ ≥ 1$) integer number which is not presented in the set.
There are many ways to solve this problem, you can use cartesian tree, segment tree, sqrt decomposition, maybe something else. I personally see the solution with the segment tree the easiest one so let me describe it. Firstly, let's notice that the queries are offline. So we can compress the numbers by taking $L$ and $R + 1$ of each query. MEX will be either one of these numbers or 1. So now we have numbers up to $2 \cdot 10^{5}$ and pretty basic task on segment tree. The first two types of queries are translated to "assign value 1 or 0 on a segment" (set the number on some position is either present or not). The third is "for each $i$ in segment $[l, r]$ assign $x_{i}$ to $x_{i}\oplus1$" (this will inverse the segment as described in statement). Segment tree should keep sum of the segment in its nodes. XOR on segment will turn $val$ into $len - val$, $len$ is the length of the segment being covered by the node. The leftmost zero cell is MEX. While standing in some node $v$, check if its left son is full (has 1 in every cell of the segment, like $t[v * 2] = mid - left$ if you use 1-indexed tree and intervals for it). If it is full then go down to the right son, otherwise there exists some zero cell in a segment of the left child and you should go down to it. You should use lazy propagation to guarantee $\log n$ per query. Overall complexity: $O(q\cdot\log q)$.
[ "binary search", "data structures", "trees" ]
2,300
null
818
A
Diplomas and Certificates
There are $n$ students who have taken part in an olympiad. Now it's time to award the students. Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be \textbf{exactly} $k$ times greater than the number of diplomas. The number of winners must \textbf{not be greater than half of the number of all students} (i.e. not be greater than half of $n$). It's possible that there are no winners. You have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners.
Let $a$ be the number of students with diplomas and $b$ - students with certificates. $b$ is always $a \cdot k$. So the total number of winners is $a + a \cdot k = a \cdot (k + 1)$. It should not exceed $\textstyle{\left[{\frac{n}{2}}\right]}$, so the maximum value for $a$ will be hit in $(n$ $div$ $2)$ $div$ $(k + 1)$, where $a$ $div$ $b$ is $\left\lfloor{\frac{\Omega}{b}}\right\rfloor$. Overall complexity: $O(1)$.
[ "implementation", "math" ]
800
null
818
B
Permutation Game
$n$ children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation $a_{1}, a_{2}, ..., a_{n}$ of length $n$. It is an integer sequence such that each integer from $1$ to $n$ appears exactly once in it. The game consists of $m$ steps. On each step the current leader with index $i$ counts out $a_{i}$ people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader. You are given numbers $l_{1}, l_{2}, ..., l_{m}$ — indices of leaders in the beginning of each step. Child with number $l_{1}$ is the first leader in the game. Write a program which will restore a possible permutation $a_{1}, a_{2}, ..., a_{n}$. If there are multiple solutions then print any of them. If there is no solution then print -1.
Let's show by construction that there can be no ambiguity in values of $a_{j}$ of the children who were leaders at least once (except for probably the last leader). If $l_{i + 1} > l_{i}$ then on this step the value of $a_{l[i]}$ taken was exactly $l_{i + 1} - l_{i}$. Otherwise $l_{i} + a_{l[i]}$ went over $n$ and in circle ended up to the left or in the same position. So for this case $a_{l[i]}$ should be $(n - l_{i}) + l_{i + 1}$. Obviously counting cannot go over $n$ two or more times as this will result in $a_{l[i]} > n$. We only need to check if all the numbers are unique and fill the unvisited children with remaining values to form the permutation. Overall complexity: $O(n)$.
[ "implementation" ]
1,600
null
818
C
Sofa Thief
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss? Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same! The storehouse is represented as matrix $n × m$. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells. Sofa $A$ is standing to the left of sofa $B$ if there exist two such cells $a$ and $b$ that \textbf{$x_{a} < x_{b}$}, $a$ is covered by $A$ and $b$ is covered by $B$. Sofa $A$ is standing to the top of sofa $B$ if there exist two such cells $a$ and $b$ that \textbf{$y_{a} < y_{b}$}, $a$ is covered by $A$ and $b$ is covered by $B$. Right and bottom conditions are declared the same way. \textbf{Note that in all conditions $A ≠ B$.} Also some sofa $A$ can be both to the top of another sofa $B$ and to the bottom of it. The same is for left and right conditions. The note also stated that there are $cnt_{l}$ sofas to the left of Grandpa Maks's sofa, $cnt_{r}$ — to the right, $cnt_{t}$ — to the top and $cnt_{b}$ — to the bottom. Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions. Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.
Coordinates don't exceed $10^{5}$ so it's possible to use sweep line method to solve the problem. Let's calculate $cnt$ value separately for each side. I will show the algorithm for left side and all the others will be done similarly. Let $cnt_left[i]$ be the number of sofas which has smaller of their $x$ coordinates less than or equal to $i$. To count that let's firstly increment by one $cnt_left[min(x1_{i}, x2_{i})]$ for all sofas and then proceed from left to right and do $cnt_left[i] = cnt_left[i] + cnt_left[i - 1]$. Now $cnt_left[max(x1_{i}, x2_{i}) - 1]$ will represent number of sofas to the left of the current one but the sofa itself can also be counted. You need to decrement the result by one if $x1_{i} \neq x2_{i}$. The same is for top value but with $y$ coordinates insted of $x$. For the right and bottom values you should calculate $cnt_right[max(x1_{i}, x2_{i})]$ and $cnt_bottom[max(y1_{i}, y2_{i})]$. Then take $cnt_right[min(x1_{i}, x2_{i}) + 1]$ and $cnt_bottom[min(y1_{i}, y2_{i}) + 1]$. The only thing left is to compare values of each sofa with given ones and find the suitable sofa. Overall complexity: $O(n)$.
[ "brute force", "implementation" ]
2,000
null
818
D
Multicolored Cars
Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another. The game rules are like this. Firstly Alice chooses some color $A$, then Bob chooses some color $B$ ($A ≠ B$). After each car they update the number of cars of their chosen color that have run past them. Let's define this numbers after $i$-th car $cnt_{A}(i)$ and $cnt_{B}(i)$. - If $cnt_{A}(i) > cnt_{B}(i)$ for every $i$ then the winner is Alice. - If $cnt_{B}(i) ≥ cnt_{A}(i)$ for every $i$ then the winner is Bob. - Otherwise it's a draw. Bob knows all the colors of cars that they will encounter and order of their appearance. Alice have already chosen her color $A$ and Bob now wants to choose such color $B$ that he will win the game (draw is not a win). Help him find this color. If there are multiple solutions, print any of them. If there is no such color then print -1.
Let's maintain the current availability of colors and the amounts of cars of each color. Firstly color $A$ is never available. When car of some color $C$ ($C \neq A$) goes, you check if the number of cars of color $C$ past before this one isn't smaller than the number of cars of color $A$. Only after that increment the amount by one. If it was less then set its availability to false. If car of color $A$ goes then simply increment its amount. In the end iterate over all colors and check if it's both available and has higher or equal amount than the amount of cars of color $A$. Okay, why this works? As all the amounts cannot decrease, color $C$ will become not available at some moment when car of color $A$ goes. And this will be encountered either when the new car of color $C$ goes, or in the end of the sequence. Amount of cars of color $C$ doesn't update between this periods. And if there was point when there became more cars of color $A$ than of color $C$ then this inequality will hold until the next moment we will check. Overall complexity: $O(n)$.
[ "data structures", "implementation" ]
1,700
null
818
E
Card Game Again
Vova again tries to play some computer card game. The rules of deck creation in this game are simple. Vova is given an existing deck of $n$ cards and a magic number $k$. The order of the cards in the deck is fixed. Each card has a number written on it; number $a_{i}$ is written on the $i$-th card in the deck. After receiving the deck and the magic number, Vova removes $x$ (possibly $x = 0$) cards from the top of the deck, $y$ (possibly $y = 0$) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards $x + 1$, $x + 2$, ... $n - y - 1$, $n - y$ from the original deck. Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by $k$. So Vova received a deck (possibly not a valid one) and a number $k$, and now he wonders, how many ways are there to choose $x$ and $y$ so the deck he will get after removing $x$ cards from the top and $y$ cards from the bottom is valid?
Let's use two pointers. Firstly you need to learn to factorize any number in no more than $O(\log n)$. We don't actually need any of their prime divisors except for those that are presented in $k$. So let's factorize $k$ in $O({\sqrt{10^{9}}})$. After that check for the maximum power of each useful prime will work in $O(\log10^{9})$ for each number. Now notice that if some segment $[l, r]$ has its product divisible by $k$ then all segments $[l, i]$ for ($r \le i \le n$) will also have products divisible by $k$. Now we have to find the smallest $r$ for each $l$ out there. That's where two pointers kick in. Let's maintain the current product of the segment in factorized form (only useful primes), as in normal form its enormous. The power of some prime in this form is the sum of powers of this prime in all the numbers in the segment. We firstly move the left border of the segment one step to the right and then keep moving the right border to the right until power of at least one prime number in the product is smaller than in $k$. It means that it is not divisible by $k$. Moving the left border means subtracting all the powers of useful primes of number $a_{l}$ from the product and moving the right border is adding all the powers of useful primes of $a_{r}$. The first time we reach such a segment, we add ($n - r$) to answer (consider $r$ $0$-indexed). Overall complexity: $O(n\cdot\log M A X N+\sqrt{M A X M})$, where $MAXN$ is up to $10^{9}$.
[ "binary search", "data structures", "number theory", "two pointers" ]
1,900
null
818
F
Level Generation
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly $n_{i}$ vertices in the graph representing level $i$, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices $u$ and $v$ is called a bridge if this edge belongs to every path between $u$ and $v$ (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given $q$ numbers $n_{1}, n_{2}, ..., n_{q}$, for each $i$ tell the maximum number of edges in a graph with $n_{i}$ vertices, if at least half of the edges are bridges. \textbf{Note that the graphs cannot contain multiple edges or self-loops}.
The best way to build a graph is to make a $2$-edge-connected component with $k$ vertices and connect each of the remaining $n - k$ vertices to it with a single edge. Then we will have $n - k$ bridges outside the component and $m i n({\frac{k\cdot(k-1)}{2}},n-k)$ edges in the component. So the answer for some fixed $k$ and $n$ is $n-k+m i n({\frac{k\cdot(k-1)}{2}},n-k)$; let's denote is at $f(k)$. Now since $\textstyle{\frac{k(k-1)}{2}}$ is increasing, and $n - k$ is decreasing, there exists some $k_{0}$ such that if $k \le k_{0}$, then ${\frac{k\cdot(k-1)}{2}}\leq n-k$, and if $k > k_{0}$, then ${\frac{k(k-1)}{2}}>n-k$. Then $f(k)$ is strictly increasing on the segment $[1, k_{0}]$, and strictly decreasing on the segment $[k_{0} + 1, n]$; and this proves that we can use ternary search to find its maximum.
[ "binary search", "math", "ternary search" ]
2,100
null
818
G
Four Melodies
Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with $n$ notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.
Let's build a directed graph where vertices represent notes and a directed edge comes from vertex $i$ to vertex $j$ iff $i < j$ and $a_{i}$ and $a_{j}$ can be consecutive notes in a melody. Now we have to find four longest vertex-disjoint paths in this graph. This problem can be solved with mincost $k$-flow algorithms. We build a network where each vertex of the graph is split into two (let's denote the vertices that we obtain when we are splitting some vertex $i$ as $v_{i, 1}$ and $v_{i, 2}$). Then each directed edge $i\rightarrow j$ transforms into a directed edge from vertex $v_{i, 2}$ to vertex $v_{j, 1}$ in the network, the capacity of this edge is $1$, and the cost is $0$. Also we add directed edges from the source to every vertex $v_{i, 1}$ and from every vertex $v_{i, 2}$ to the sink (they have the same characteristics: capacity is $1$, cost is $0$). And for each $i$ we add a directed edge between $v_{i, 1}$ and $v_{i, 2}$; these edges actually represent that we are using some note in a melody, so their capacities are also equal to $1$, and their costs are $- 1$. The answer to the problem is equal to the absolute value of minimum cost of $4$-flow in this network. The bad thing is that the network is really large. So we have to use some advanced mincost algorithm here. Model solution uses Dijkstra's algorithm with Johnson's potentials to find augmenting paths of minimum cost. We set a number $p(v)$ for each vertex $v$ of the network (these numbers are called potentials). Then we modify costs of the edges: if some edge $i\rightarrow j$ had cost $c_{i, j}$, now it's cost is ${c'}_{i, j} = c_{i, j} + p(i) - p(j)$. It's easy to prove that if some path from vertex $v$ to vertex $u$ was the shortest one between these vertices without modifying the costs with potentinals, then after modifying it will also be the shortest between these vertices. So instead of looking for an augmenting path in the original network we can try looking for it in a network with modified edges. Why? Because it is always possible to set all potentials in such a way that all costs of edges will be non-negative (and we will be able to use Dijkstra to find the shortest path from the source to the sink). Before looking for the first augmenting path, we calculate potentials recursively: $p(source) = 0$, $p(v) = min{p(u) + c_{u, v}}$ (we check all $u$'s such that there is an edge $u\rightarrow v$ in the network). The network is acyclic before we push flow, so there is always a way to calculate these potentials with dynamic programming. Then each time we want to find an augmenting path, we run Dijkstra's algoritm on modified network, push flow through the path we found and modify the potentials: new potential of each vertex $v$ becomes $p'(v) = p(v) + d(v)$, where $d(v)$ is the distance between the source and vertex $v$ in the modified network (and we found this distance with Dijkstra). When we have found four augmenting paths, we are done and it's time to evaluate the cost of the flow.
[ "flows", "graphs" ]
2,600
null
819
A
Mister B and Boring Game
\textbf{Unfortunately, a mistake was found in the proof of the author's solution to this problem. Currently, we don't know the absolutely correct solution. However, you can solve this task, but if your solution passes all the tests, it is not guaranteed to be correct. If your solution has passed all the tests, and you are sure that it is correct, you can write to one of the contest authors about it.} Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens. All characters in this game are lowercase English letters. There are two players: Mister B and his competitor. Initially the players have a string $s$ consisting of the first $a$ English letters in alphabetical order (for example, if $a = 5$, then $s$ equals to "abcde"). The players take turns appending letters to string $s$. Mister B moves first. Mister B must append exactly $b$ letters on each his move. He can arbitrary choose these letters. His opponent adds exactly $a$ letters on each move. Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string $s$ of length $a$ and generates a string $t$ of length $a$ such that all letters in the string $t$ are distinct and don't appear in the considered suffix. From multiple variants of $t$ lexicographically minimal is chosen (if $a = 4$ and the suffix is "bfdd", the computer chooses string $t$ equal to "aceg"). After that the chosen string $t$ is appended to the end of $s$. Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string $s$ on the segment between positions $l$ and $r$, inclusive. Letters of string $s$ are numerated starting from $1$.
Tutorial is not available
[ "games", "greedy" ]
2,200
null
819
B
Mister B and PR Shifts
Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation $p$ of length $n$ or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation $p$ as $\textstyle\sum_{i=1}^{n-n}|p|i|-i|$. Find a cyclic shift of permutation $p$ with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id $k$ ($0 ≤ k < n$) of a cyclic shift of permutation $p$ as the number of right shifts needed to reach this shift, for example: - $k = 0$: shift $p_{1}, p_{2}, ... p_{n}$, - $k = 1$: shift $p_{n}, p_{1}, ... p_{n - 1}$, - ..., - $k = n - 1$: shift $p_{2}, p_{3}, ... p_{n}, p_{1}$.
Let's see, how $p_{k}$ $(1 \le k \le n)$ affects different shifts. Let's denote $d_{i}$ is deviation of the $i - th$ shift. At first all $d_{i} = 0$. Then $p_{k}$ affects it in following way: $d_{0} + = |p_{k} - k|$, $d_{1} + = |p_{k} - (k + 1)|$, $...$ $d_{n - k} + = |p_{k} - n|$, $d_{n - k + 1} + = |p_{k} - 1|$, $...$ $d_{n - 1} + = |p_{k} - (k - 1)|$. Then there are 2 cases: $p_{k} \ge k$ or not. If $p_{k} \ge k$ after removing modules we will get 3 query: to add $p_{k} - (k + i)$ to $d_{i}$ where $0 \le i \le p_{k} - k$, to add $(k + i) - p_{k}$ to $d_{i}$ where $p_{k} - k < i \le n - k$ and to add $p_{k} - i$ to $d_{n - k + i}$ where $0 < i < k$. Else if $p_{k} < k$ we need to perform next operation: to add $(k + i) - p_{k}$ to $d_{i}$ where $0 \le i \le n - k$, to add $p_{k} - i$ to $d_{n - k + i}$ where $1 \le i \le p_{k}$ and to add $i - p_{k}$ to $d_{n - k + i}$ where $p_{k} < i < k$. But in both cases we must add 3 arithmetic progression to the segment of array $d$. Or make operation of adding $k \cdot (x - l) + b$ to segment $[l, r]$. Its known task, which can be done by adding/subtracting values in start and end of segment offline. To make such operation we need to remember, how to add value $b$ to segment $[l, r]$ of array $d$ offline. We can just do next operations: $d[l] + = b$ and $d[r + 1] - = b$. Now value in position $i$ $a n s_{i}=\sum_{j=0}^{j=t}d[j]$. So what is adding progression with coef $k$? it's only adding to array $d$ value $k$ to all positions in segment $[l, r]$. That's why we need other array, for example $df$ and making $df[l] + = k$ and $df[r + 1] - = k$. In result, $d[i]=d[i]+\sum_{j=0}^{j=i-1}d f[j]$. So algorithm to add $k \cdot (x - l) + b$ to segment $[l, r]$ is next: $d[l] + = b$, $d[r + 1] - = k \cdot (r - l + 1)$, $df[l] + = k$, $df[r + 1] - = k$. After all queries we need recover array $d$ with formula $d[i]=d[i]+\sum_{j=0}^{j=i-1}d f[j]$. And after that get answer with formula $a n s_{i}=\sum_{j=0}^{j=t}d[j]$. So complexity is $O(n)$.
[ "data structures", "implementation", "math" ]
1,900
#define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) typedef long long li; const int N = 1000 * 1000 + 555; int n, p[N]; inline bool read() { if(!(cin >> n)) return false; forn(i, n) assert(scanf("%d", &p[i]) == 1); return true; } li sum[N], df[N], res[N]; inline void add(int lf, int rg, int k, int b) { if(lf > rg) return; sum[lf] += b; df[lf] += k; sum[rg + 1] -= b + k * 1ll * (rg - lf); df[rg] -= k; } inline void calc() { li curdf = 0; forn(i, n) { sum[i] += curdf; curdf += df[i]; } li cursm = 0; forn(i, n) { cursm += sum[i]; res[i] += cursm; } } inline void solve() { memset(sum, 0, sizeof sum); memset(df, 0, sizeof df); memset(res, 0, sizeof res); forn(i, n) { int c1 = i + 1, p1 = 0; int c2 = n, p2 = p1 + c2 - c1; int c3 = i, p3 = p2 + c3; if(p[i] <= c3) { add(p1, p2, 1, c1 - p[i]); add(p2 + 1, p2 + p[i], -1, p[i] - 1); add(p2 + p[i] + 1, p3, 1, 1); } else { add(p1, p1 + p[i] - c1, -1, p[i] - c1); add(p1 + p[i] - c1 + 1, p2, 1, 1); add(p2 + 1, p3, -1, p[i] - 1); } } calc(); int ans = 0; forn(i, n) if(res[ans] > res[i]) ans = i; cout << res[ans] << " " << ans << endl; }
819
C
Mister B and Beacons on Field
Mister B has a house in the middle of a giant plain field, which attracted aliens life. For convenience, aliens specified the Cartesian coordinate system on the field in such a way that Mister B's house has coordinates $(0, 0)$. After that they sent three beacons to the field, but something went wrong. One beacon was completely destroyed, while the other two landed in positions with coordinates $(m, 0)$ and $(0, n)$, respectively, but shut down. Mister B was interested in this devices, so he decided to take them home. He came to the first beacon, placed at $(m, 0)$, lifted it up and carried the beacon home choosing the shortest path. After that he came to the other beacon, placed at $(0, n)$, and also carried it home choosing the shortest path. When first beacon was lifted up, the navigation system of the beacons was activated. Partially destroyed navigation system started to work in following way. At time moments when both survived beacons are at points with integer coordinates the system tries to find a location for the third beacon. It succeeds if and only if there is a point with integer coordinates such that the area of the triangle formed by the two survived beacons and this point is equal to $s$. In this case the system sends a packet of information with beacon positions to aliens, otherwise it doesn't. Compute how many packets of information system sent while Mister B was moving the beacons.
There 2 stages in this task: moving of first beacon and moving of second. But at first we need factorization of $n$ and $s$. Since $n$ and $s$ are product of integers $ \le 10^{6}$, it can be done in $O(log(n) + log(s))$ time by "Sieve of Eratosthenes". Start from second stage, when second beacon is moving: Position of beacons will look like pair of points: $(0, 0)$, $(0, k)$, where $0 \le k \le n$. We need to check existing of point $(x, y)$ such, that area of triangle $(0, 0)$, $(0, k)$, $(x, y)$ equals to $s$. Using cross product $|((0, k) - (0, 0)) \cdot ((x, y) - (0, 0))| = 2 \cdot s$. After simplifying we get $|k \cdot x| = 2 \cdot s$ where $0 \le k \le n$. So we can iterate all divisors of $2 \cdot s$, using factorization of $s$ and recursive algorithm. Complexity of second stage is $O( \sigma (s))$, where $ \sigma (s)$ - number of divisors of $s$ and for $s \le 10^{18}$ $ \sigma (s) \le \approx 10^{5}$. In the first stage we have such points: $(k, 0)$, $(0, n)$, where $1 \le k \le m$. We need to check existing of point $(x, y)$ such, that area of triangle $(k, 0)$, $(0, n)$, $(x, y)$ equals to $s$. Using cross product $|((k, 0) - (0, n)) \cdot ((x, y) - (0, n))| = 2 \cdot s$ we can get next equation: $|k \cdot (y - n) + n \cdot x| = 2 \cdot s$. Then solution exists iff $gcd(k, n) | 2 \cdot s$ $(2s % gcd(k, n) = 0)$. And we need to calculate how many $1 \le k \le m$ such, that $gcd(k, n) | 2 \cdot s$. We will solve it in next way: let's $n = p_{1}^{n1}p_{2}^{n2}... p_{l}^{nl}$ and $2s = p_{1}^{s1}p_{2}^{s2}... p_{l}^{sl}$ $(n_{i}, s_{i} \ge 0)$. Look at all $p_{i}$, that $n_{i} > s_{i}$. It's obvious, that if $p_{i}^{si + 1}$ is divisor of $k$, then $2s$ doesn't divide at $gcd(k, n)$. In result, we have some constrains on $k$, like $k$ doesn't divide at $a_{j} = p_{ij}^{sij + 1}$. Finally, we have next task: calculate number of $k$ $(1 \le k \le n)$ such, that $k$ doesn't divide any of $a_{i}$. It can be done with inclusion-exclusion principle, where number of $k$ which divides $a_{i1}$, $a_{i2}$ ... $a_{ib}$ is $\frac{n}{a_{i_{1}a_{2}\cdots a_{i_{k}}}}$. Complexity of first stage is $O(2^{z(n)})$, where $z(x)$ - number of prime divisors of $x$, $z \le 15$ for integers up to $10^{18}$. Result complexity is $O( \sigma (s) + 2^{z(n)})$ per test.
[ "number theory" ]
2,900
#define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) #define all(a) (a).begin(), (a).end() #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define mp make_pair #define pb push_back typedef long long li; typedef pair<int, int> pt; typedef pair<li, li> ptl; const int INF = int(1e9); const li INF64 = li(INF) * INF; int n[3], m[3], s[3]; inline bool read() { if(scanf("%d %d %d", &n[0], &n[1], &n[2]) != 3) return false; forn(i, 3) assert(scanf("%d", &m[i]) == 1); forn(i, 3) assert(scanf("%d", &s[i]) == 1); return true; } const int N = 2 * 1000 * 1000 + 55; int ls[N]; inline void precalc() { memset(ls, -1, sizeof ls); ls[0] = ls[1] = 1; fore(i, 2, N) { if(ls[i] != -1) continue; ls[i] = i; for(li j = i * 1ll * i; j < N; j += i) if(ls[j] == -1) ls[j] = i; } } inline vector<pt> fact(int n[3]) { vector<int> divs; forn(i, 3) { int cur = n[i]; while(ls[cur] != cur) { divs.pb(ls[cur]); cur /= ls[cur]; } if(cur > 1) divs.pb(cur); } sort(all(divs)); vector<pt> ans; int u = 0; while(u < sz(divs)) { int v = u; while(v < sz(divs) && divs[v] == divs[u]) v++; ans.pb(mp(divs[u], v - u)); u = v; } return ans; } li ans; li nn, mm, ss; vector<pt> fs; vector<li> bad; void calcDivs(int pos, li val) { if(pos >= sz(fs)) { ans += (val <= nn); return; } li cv = 1; forn(i, fs[pos].y + 1) { calcDivs(pos + 1, val * cv); cv *= fs[pos].x; } } void calcInEx(int pos, li val, int cnt) { if(pos >= sz(bad)) { li k = cnt ? -1 : 1; ans += k * (mm / val); return; } calcInEx(pos + 1, val, cnt); calcInEx(pos + 1, val * bad[pos], cnt ^ 1); } inline void solve() { ans = 0; s[0] *= 2; nn = n[0] * 1ll * n[1] * 1ll * n[2]; mm = m[0] * 1ll * m[1] * 1ll * m[2]; ss = s[0] * 1ll * s[1] * 1ll * s[2]; fs = fact(s); calcDivs(0, 1); bad.clear(); vector<pt> fn = fact(n); forn(i, sz(fn)) { li cv = fn[i].x; forn(k, fn[i].y) { if(ss % cv != 0) { bad.pb(cv); break; } cv *= fn[i].x; } } calcInEx(0, 1, 0); printf("%I64d\n", ans); }
819
D
Mister B and Astronomers
After studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly $T$ seconds. The problem is that the star is yet to be discovered by scientists. There are $n$ astronomers numerated from $1$ to $n$ trying to detect the star. They try to detect the star by sending requests to record the sky for $1$ second. The astronomers send requests \textbf{in cycle}: the $i$-th astronomer sends a request exactly $a_{i}$ second after the $(i - 1)$-th (i.e. if the previous request was sent at moment $t$, then the next request is sent at moment $t + a_{i}$); the $1$-st astronomer sends requests $a_{1}$ seconds later than the $n$-th. The first astronomer sends his first request at moment $0$. Mister B doesn't know the first moment the star is going to shine, but it's obvious that all moments at which the star will shine are determined by the time of its shine moment in the interval $[0, T)$. Moreover, this interval can be split into $T$ parts of $1$ second length each of form $[t, t + 1)$, where $t = 0, 1, 2, ..., (T - 1)$. Mister B wants to know how lucky each astronomer can be in discovering the star first. For each astronomer compute how many segments of form $[t, t + 1)$ ($t = 0, 1, 2, ..., (T - 1)$) there are in the interval $[0, T)$ so that this astronomer is the first to discover the star if the first shine of the star happens in this time interval.
Let's construct slow but clear solution and then, speed it up. Let's denote $s=\sum_{i=1}^{i=n}a_{i}$. We can see, that, at first, all operation with time are modulo $T$ and the $i - th$ astronomer checks moments $st_{i}$, $(st_{i} + s)%T$, $(st_{i} + 2s)%T$ ..., where $s t_{i}=\sum_{j=2}^{j=i}a_{i}$. More over, every astronomer, who checks moment $t$ will check moment $(t + S)%T$ by next time. So we now constructed functional graph with $T$ vertices. But this graph has very special type, since it can be divided on some cycles. More specifically, This graph consists of $gcd(T, s)$ oriented cycles and each cycle has length exactly $\frac{T}{r e c(T,s)}$. Even more, vertices $u$ and $v$ belong to same cycle iff $u \equiv v (mod gcd(T, s))$. So we can work with cycles independently. Let's look closely on one cycle. It's obviously, that all astronomers will walk on their cycles from their starting positions $st_{i} % T$. But what the answer for them. Answer for the $i - th$ astronomer is number of vertices, including starting vertex, to the nearest starting vertex of any other astronomer if count along the orientation of cycle, because if two astronomers came to same vertex, lucky is one, who came first. Other astronomer has this vertex as start, his time is $st_{j}$, $i - th$ time is $st_{i} + k \cdot s$, $k \ge 1$ and $st_{i} + k \cdot s > st_{j}$. If $st_{i} \equiv st_{j} (mod T)$ and $st_{i} < st_{j}$ then answer for the $j - th$ astronomer is always $0$. So we must effectively calculate distance between two positions on cycle. For that, let's numerate vertices along the orientation of cycle using vertex with minimal label as $0$. If we will know position of $st_{i}% T$ for every astronomer calculation of distance between consecutive is trivial (sort, or set or other). For the $i - th$ astronomer let's denote vertex with label $0$ in his cycle as $z_{i}$. $z_{i} = st_{i} % gcd(T, s)$. But cycles very specific, because vertex with label $0$ is $z_{i}$, vertex with label $1$ is $(z_{i} + s) % T$, vertex with label $2$ is $(z_{i} + 2s) % T$. In other words, vertex with label $k$ is $(z_{i} + k \cdot s) % T$. If we want to know position $k$ of $st_{i}$, we need to find $v$ such, that $v \equiv (v% gcd(T, s)) + k \cdot s(mod T)$ which is diofant equation and can be calculated in $O(log(T))$ time. Result complexity is $O(n \cdot log(T))$.
[ "number theory" ]
2,900
#define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) #define all(a) (a).begin(), (a).end() #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define mp make_pair #define pb push_back #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(INF) * INF; int gcd(int a, int b) { if(a == 0) return b; return gcd(b % a, a); } int exgcd(int a, li &x, int b, li &y) { if(a == 0) { x = 0, y = 1; return b; } li xx, yy; int g = exgcd(b % a, xx, a, yy); x = yy - b / a * xx; y = xx; return g; } const int N = 200 * 1000 + 555; int t, n, a[N]; inline bool read() { if(!(cin >> t >> n)) return false; forn(i, n) assert(scanf("%d", &a[i]) == 1); return true; } int pf[N], s; inline li up(li a, li b) { return (a + b - 1) / b; } inline int findPos(int a, int b, int c) { li x, y; int g = exgcd(a, x, b, y); assert(c % g == 0); x *= +c / g; y *= -c / g; assert(a * 1ll * x - b * 1ll * y == c); int ag = a / g; int bg = b / g; li k = 0; if(x < 0) k = up(-x, bg); if(x >= bg) k = -up(x - bg, bg); x += bg * k; y += ag * k; assert(0 <= x && x < bg); k = 0; if(y < 0) k = up(-y, ag); x += bg * k; y += ag * k; return x; } map< int, set<pt> > cycle; int ans[N]; inline void solve() { cycle.clear(); pf[0] = 0; fore(i, 1, n) pf[i] = (pf[i - 1] + a[i]) % t; s = (a[0] + pf[n - 1]) % t; int g = gcd(s, t); forn(i, n) { int st = pf[i] % g; auto& cc = cycle[st]; int pos = findPos(s, t, pf[i] - st); if(cc.empty()) { ans[i] += t / g; cc.insert(pt(pos, -i)); } else { auto rg = cc.lower_bound(pt(pos, -i)); if(rg == cc.end()) { ans[i] += t / g - pos; rg = cc.begin(); ans[i] += rg->x; } else ans[i] += rg->x - pos; auto lf = cc.lower_bound(pt(pos, -i)); if(lf == cc.begin()) lf = --cc.end(); else lf--; ans[ -(lf->y) ] -= ans[i]; cc.insert(pt(pos, -i)); } } forn(i, n) printf("%d ", ans[i]); puts(""); }
819
E
Mister B and Flight to the Moon
In order to fly to the Moon Mister B just needs to solve the following problem. There is a complete indirected graph with $n$ vertices. You need to cover it with several simple cycles of length $3$ and $4$ so that each edge is in exactly $2$ cycles. We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?
There are different constructive solutions in this problem. Here is one of them. Consider odd and even $n$ separately. Let $n$ be even. Let's build for each even $n \ge 4$ a solution such that there are triangles 1-2-x, 3-4-y, 5-6-z and so on. For $n = 4$ it's easy to construct such a solution. Then let's add two vertices at a time: $a = n - 1$ and $b = n$. Instead of triangle 1-2-x let's add triangle 1-a-2-x, square 1-a-2-b and square 1-2-b. The same with 3-4-y, 5-6-z and so on. Only one edge a-b is remaining, we should add it twice. To do this let's replace the square 1-a-2-b with triangles a-b-1 and a-b-2. Easy to see that the condition on triangles is satisfied, so we can proceed to adding two more vertices and so on. To deal with odd $n$ let's keep triangles 2-3-x, 4-5-y and so on. To add two more vertices replace each of these triangles with two squares and one triangle in the same way as for even $n$, and also add two triangles 1-a-b.
[ "constructive algorithms", "graphs" ]
2,800
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 305; int pair3[maxn]; int n; vector<vector<int>> answer; void add3(int a, int b, int c) { answer.pb({a, b, c}); } void add4(int a, int b, int c, int d) { answer.pb({a, b, c, d}); } int main() { cin >> n; if (n % 2 == 0) { pair3[0] = 3; // 0 1 3 pair3[2] = 1; // 2 3 1 add3(0, 1, 2); add3(2, 3, 0); for (int i = 4; i < n; i += 2) { add4(0, pair3[0], 1, i); add3(i, i + 1, 0); pair3[i] = 1; pair3[0] = i + 1; for (int j = 2; j < i; j += 2) { add4(j, pair3[j], j + 1, i); add4(j, i, j + 1, i + 1); pair3[j] = i + 1; } } for (int i = 0; i < n; i += 2) { add3(i, i + 1, pair3[i]); } } else { pair3[1] = 0; // 1 2 0 add3(0, 1, 2); for (int i = 3; i < n; i += 2) { add3(i, i + 1, 0); pair3[i] = 0; for (int j = 1; j < i; j += 2) { add4(j, pair3[j], j + 1, i); add4(j, i, j + 1, i + 1); pair3[j] = i + 1; } } for (int i = 1; i < n; i += 2) { add3(i, i + 1, pair3[i]); } } printf("%d\n", (int)answer.size()); for (auto &t : answer) { printf("%d", (int)t.size()); for (auto t2 : t) printf(" %d", t2 + 1); printf("\n"); } return 0; }
820
A
Mister B and Book Reading
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had $c$ pages. At first day Mister B read $v_{0}$ pages, but after that he started to speed up. Every day, starting from the second, he read $a$ pages more than on the previous day (at first day he read $v_{0}$ pages, at second — $v_{0} + a$ pages, at third — $v_{0} + 2a$ pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than $v_{1}$ pages per day. Also, to refresh his memory, every day, starting from the second, Mister B had to reread last $l$ pages he read on the previous day. Mister B finished the book when he read the last page for the first time. Help Mister B to calculate how many days he needed to finish the book.
All that needed - is to accurately simulate process. Create variable, which will contain count of read pages, subtract $l$, add $v_{0}$, check, what you still have unread pages, make $v_{0} = min(v_{1}, v_{0} + a)$ and again. Complexity is $O(c)$.
[ "implementation" ]
900
#define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) int c, l, v0, v1, a; inline bool read() { if(!(cin >> c >> v0 >> v1 >> a >> l)) return false; return true; } inline void solve() { int pos = v0; int t = 1; int add = v0; while(pos < c) { add = min(v1, add + a); pos += add - l; t++; } cout << t << endl; }
820
B
Mister B and Angle in Polygon
On one quiet day all of sudden Mister B decided to draw angle $a$ on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is \textbf{regular convex $n$-gon} (regular convex polygon with $n$ sides). That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices $v_{1}$, $v_{2}$, $v_{3}$ such that the angle $\angle v_{1}v_{2}v_{3}$ (where $v_{2}$ is the vertex of the angle, and $v_{1}$ and $v_{3}$ lie on its sides) is as close as possible to $a$. In other words, the value $|Z v_{1}v_{2}v_{3}-a|$ should be minimum possible. If there are many optimal solutions, Mister B should be satisfied with any of them.
Since polygon is regular, all vertices of a regular polygon lie on a common circle (the circumscribed circle), so all possible angles are inscribed angles. And all inscribed angles subtending the same arc have same measure. More over, minor and major arcs between vertices $v_{i}$ and $v_{k}$ equals to minor and major arcs between vertices $v_{i + 1}$ and $v_{k + 1}$. And finally, length of arc can be calculated with formula as sum of minor arcs between consecutive vertices. Length of minor arcs between consecutive vertices equals to $360 / n$. Length of inscribed angle is half of arc it based on. In other words $\displaystyle\angle v_{1}v_{2}v_{3}={\frac{190\,(n-(v_{3}-v_{1}))}{n}}$ if $v_{1} < v_{2} < v_{3}$ or $\textstyle{\frac{|\mathbf{x}|_{1}(x_{1})_{n}|}{n}}$ in other case. In the end, this task can be solved by checking all different $(v_{3} - v_{1})$ ($v_{1}$ can be fixed as $1$), or by formula, if we put in $|Z v_{1}v_{2}v_{3}-a|$ formula above. In result finding closest angle can be done in $O(n)$ or even $O(1)$ time.
[ "constructive algorithms", "geometry", "math" ]
1,300
int n, a; inline bool read() { if(!(cin >> n >> a)) return false; return true; } inline void solve() { int base = n * a / 180; base = max(1, min(n - 2, base)); int bk = base; for(int ck = max(1, base - 2); ck <= min(n - 2, base + 2); ck++) { if(abs(180 * ck - n * a) < abs(180 * bk - n * a)) bk = ck; } cout << 2 << " " << 1 << " " << bk + 2 << endl; }
821
A
Okabe and Future Gadget Laboratory
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an $n$ by $n$ square grid of integers. A good lab is defined as a lab in which every number not equal to $1$ can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every $x, y$ such that $1 ≤ x, y ≤ n$ and $a_{x, y} ≠ 1$, there should exist two indices $s$ and $t$ so that $a_{x, y} = a_{x, s} + a_{t, y}$, where $a_{i, j}$ denotes the integer in $i$-th row and $j$-th column. Help Okabe determine whether a given lab is good!
We can simulate exactly what's described in the statement: loop over all cells not equal to 1 and check if it doesn't break the city property. To check if a cell breaks the property, just loop over an element in the same row, and an element in the same column, and see if they can add to give the cell's number. The complexity is O($n^{4}$).
[ "implementation" ]
800
#include <queue> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <complex> #include <fstream> #include <cstring> #include <string> #include <climits> using namespace std; //macros typedef long long ll; typedef complex<double> point; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector< vector<int> > vvi; #define FOR(k,a,b) for(int k=(a); k<=(b); ++k) #define REP(k,a) for(int k=0; k<(a);++k) #define SZ(a) int((a).size()) #define ALL(c) (c).begin(),(c).end() #define PB push_back #define MP make_pair #define INF 999999999 #define INFLONG 1000000000000000000LL #define MOD 1000000007 #define MAX 100 #define ITERS 100 #define pi 3.1415926 #define MAXN 100000 #define _gcd __gcd int main() { int n; cin >> n; int grid[50][50]; REP(i,n){ REP(j,n){ cin >> grid[i][j]; } } REP(i,n){ REP(j,n){ if(grid[i][j]==1) continue; bool pass = false; for(int r = 0;r<n;r++){ if(r==i) continue; for(int c = 0; c < n; c++){ if(c==j) continue; int sum = grid[r][j]+grid[i][c]; if(sum==grid[i][j]){ pass=true; break; } } if(pass)break; } if(!pass){ cout << "No"<<endl; return 0; } } } cout << "Yes"<<endl; }
821
B
Okabe and Banana Trees
Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees. Consider the point $(x, y)$ in the 2D plane such that $x$ and $y$ are integers and $0 ≤ x, y$. There is a tree in such a point, and it has $x + y$ bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation $y=-{\frac{x}{m}}+b$. Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point. Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely. Okabe is sure that the answer does not exceed $10^{18}$. You can trust him.
The critical observation to make is that the optimal rectangle should always have a lower-left vertex at the origin. This is due to the fact that the line has positive y-intercept and negative slope: any rectangle which doesn't have a vertex at the origin could easily be extended to have a vertex at the origin and even more bananas. Then, we just need to try every x-coordinate for the upper-right corner of the box and pick the maximum y-coordinate without going over the line. We can compute the sum of any rectangle in $O(1)$ using arithmetic series sums, so this becomes $O(bm)$ because the x-intercept can be up to $bm$. You can make it faster by trying every y-coordinate; this makes the complexity $O(b)$, but this was unnecessary to solve the problem.
[ "brute force", "math" ]
1,300
#include <queue> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <complex> #include <fstream> #include <cstring> #include <string> #include <climits> using namespace std; //macros typedef long long ll; typedef complex<double> point; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector< vector<int> > vvi; #define FOR(k,a,b) for(int k=(a); k<=(b); ++k) #define REP(k,a) for(int k=0; k<(a);++k) #define SZ(a) int((a).size()) #define ALL(c) (c).begin(),(c).end() #define PB push_back #define MP make_pair #define INF 999999999 #define INFLONG 1000000000000000000 #define MOD 1000000007 #define MAX 100 #define ITERS 100 #define MAXM 200000 #define MAXN 1000000 #define _gcd __gcd #define eps 1e-9 ll series(ll x){ return x*(x+1)/2; } int main() { int m,b; cin >> m >> b; ll best = 0; for(int y = b; y >=0; y--){ //y = -x/m + b ll x = m*(b-y); ll t = 0; t+=(x+1)*series(y)+(y+1)*series(x); best = max(best,t); } cout << best << endl; }