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
769
A
Year of University Entrance
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than $x$ from the year of university entrance of this student, where $x$ — some non-negative integer. A value $x$ is not given, but it can be uniquely determined from the available data. Note that students don't join other groups. You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.
This task can be solved in several ways. The simplest of them is - to put all given integers to an array, sort out it and print the median of the resulting array (it means that the element which is in the middle of it).
[ "*special", "implementation", "sortings" ]
800
null
769
B
News About Credit
Polycarp studies at the university in the group which consists of $n$ students (including himself). All they are registrated in the social net "TheContacnt!". Not all students are equally sociable. About each student you know the value $a_{i}$ — the maximum number of messages which the $i$-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that: - the student $i$ sends no more than $a_{i}$ messages (for all $i$ from $1$ to $n$); - all students knew the news about the credit (initially only Polycarp knew it); - the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from $1$ to $n$, and Polycarp \textbf{always} has the number $1$. In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.
For solving this task you need to consider the following. Let it be that not all students knew news for that moment. If there are not students which knew this news and still can send messages, the answer for the task is -1. Otherwise, it is necessary to send the message to the student $x$, which still doesn't know news, wherein the number of messages which then can be sent by the student $x$ was maximum among students which still don't know the news. It does not matter which one of the students will send the message to the student number $x$. It is necessary to repeat the descriped process until not all students knew the news. For example, for realization it was possible firstly to sort out all students in descending number of messages which each of them can send. Then you can use the queue and put other students who learn the news to the end of it. At the same time, students should learn the news according to the sorted order. It is necessary to send messages starting from Polycarp (student number $1$), because initially only he knews the news.
[ "*special", "greedy", "two pointers" ]
1,200
null
769
C
Cycle In Maze
The Robot is in a rectangular maze of size $n × m$. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell. Your task is to find \textbf{lexicographically minimal} Robot's cycle with length \textbf{exactly} $k$, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting). Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU". In this task you \textbf{don't need} to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Initially check $k$ on parity. If $k$ is odd, there is no the answer, because the cycle in the task should always have an even length. Otherwise, we will act as follows. With the help of the search algorithm of the width to find the shortest distance from the starting cell to the rest free cells. After that we will move on the field. Before each moving it is necessary to understand to which cell to go. We will sort out directions in the order "D", "L", "R", "U". The current direction equals $c$. So if the cell $x$, which corresponding to the moving in direction $c$, is empty, and the distance from it to the starting cell doesn't exceed the remaining number of steps, then move to the direction $c$, add the appropriate letter to the answer and move on to the new step. If on some step it is impossible to move the Robot, the cycle with the lenght $k$ doesn't exist. Otherwise, when the Robot will do $k$ steps, we have only to print the answer.
[ "*special", "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,700
null
769
D
k-Interesting Pairs Of Integers
Vasya has the sequence consisting of $n$ integers. Vasya consider the pair of integers $x$ and $y$ k-interesting, if their binary representation differs from each other exactly in $k$ bits. For example, if $k = 2$, the pair of integers $x = 5$ and $y = 3$ is k-interesting, because their binary representation $x$=101 and $y$=011 differs exactly in two bits. Vasya wants to know how many pairs of indexes ($i$, $j$) are in his sequence so that $i < j$ and the pair of integers $a_{i}$ and $a_{j}$ is k-interesting. Your task is to help Vasya and determine this number.
To solve this problem you need to each value from $1$ to $10^{4}$ calculate the number of numbers in the sequence which equal to this value. Let $cnts[x]$ is a number of elements which equal to $x$. After that with two nested loops from $1$ to $10^{4}$ we can brute all pairs and for each pair ($i$, $j$) check that the number of ones in bits in $i$ ^ $j$ equals to $k$ (here we mean operation xor - bitwise exclusive or). To make this check faster we can use standard functions for some compilers (for example, __builtin_popcount for g++) or precalculate such array. If the number of ones in bits in $i$ ^ $j$ equals to $k$ we need to add to the answer $cnts[i] \cdot cnts[j]$.
[ "*special", "bitmasks", "brute force", "meet-in-the-middle" ]
1,700
null
770
A
New Password
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: - the length of the password must be equal to $n$, - the password should consist only of lowercase Latin letters, - the number of distinct symbols in the password must be equal to $k$, - any two consecutive symbols in the password must be distinct. Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.
To solve this problem, consider the first $k$ Latin letters. We will add them to the answer in the order, firstly, we add a, then b and so on. If letters are finished but the length of the answer is still less than the required one, then we start again adding letters from the beginning of the alphabet. We will repeat this algorithm until the length of the answer becomes $n$.
[ "*special", "implementation" ]
800
null
770
B
Maximize Sum of Digits
Anton has the integer $x$. He is interested what positive integer, which doesn't exceed $x$, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.
Initially, we put the integer $x$ to the answer. Then look at the integer from right to left. Do the following for each digit: if the digit is not zero, reduce it by one and change all other digits to nine. If the sum of digits in the resulting integer is strictly greater than the sum of the digits of the current answer, then update the answer with the resulting integer.
[ "*special", "implementation", "math" ]
1,300
null
770
C
Online Courses In BSU
Now you can take online courses in the Berland State University! Polycarp needs to pass $k$ \textbf{main} online courses of his specialty to get a diploma. In total $n$ courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all \textbf{main} and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.
Initially, we construct an oriented graph. If it is necessary firstly to take the course $j$ to pass the course $i$, add the edge from $i$ to $j$ to the graph. Then run the search in depth from all vertices, which correspond to main courses. In the depth search, we will simultaneously check the existence of oriented cycles (we need the array of colors marked with white-gray-black) and to build a topological sorting, simply adding vertices in response at the moment when they become black. Here is the code for such a search in depth: The variable $cycle$ will be equal to true only when there is the cycle on the main courses or those on which they depend. So if $cycle$=true, print -1. Otherwise ord (the array with the result of a topological sorting) will contain the answer of the problem. This follows directly from its definition.
[ "*special", "dfs and similar", "graphs", "implementation" ]
1,500
null
770
D
Draw Brackets!
A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as: \begin{verbatim} +- -++- -+ |+- -++- -+|| | || || ||| | |+- -++- -+|| | +- -++- -+ \end{verbatim} Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above. Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image. Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.
It is necessary to draw brackets carefully according to the condition to solve this problem. Draw brackets in a two-dimensional array. Firstly, you need to determine the size of the array and then start to draw. To determine the height of the image, you need to find the maximum nesting of the brackets $x$. Then the height of the image (it means the number of necessary strings) is equal to $2 * x + 1$. The width of the image (it means the number of necessary columns) will be counted in the process of drawing. Also initially you need to fill the entire resulting array with spaces. To simplify the solution, it is possible to implement a function that draws the next bracket in two parameters. Here are parameters: the cell which should contain the left upper bracket and the type of it - opening or closing. Thus, to solve this problem, you need to iterate among all brackets from left to right while mantaining the balance of brackets and draw the next bracket using the described auxiliary function. Also check the situation when the current bracket is closing and the previous bracket is opening. In this case it is necessary to leave an empty column according to the condition.
[ "*special", "implementation" ]
1,400
null
771
A
Bear and Friendship Condition
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are $n$ members, numbered $1$ through $n$. $m$ pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three \textbf{distinct} members (X, Y, Z), if X-Y and Y-Z then also X-Z. For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well. Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
The main observation is that you should print "YES" if the graph is a set of disjoint cliques (in each connected non-clique there is a triple of vertices X,Y,Z that X-Y and Y-Z but not X-Z). To check if each connected component is a clique, you can run dfs and count vertices and edges in the connected component - it's a clique if and only if $e d g e s={\frac{v e r t e e s(v e c t a c e s-1)}{2}}$.
[ "dfs and similar", "dsu", "graphs" ]
1,500
#include <bits/stdc++.h> using namespace std; const int nax = 150123; vector<int> edges[nax]; bool vis[nax]; void dfs(int a, int & cnt_vertices, int & cnt_edges) { assert(!vis[a]); vis[a] = true; ++cnt_vertices; cnt_edges += edges[a].size(); for(int b : edges[a]) if(!vis[b]) dfs(b, cnt_vertices, cnt_edges); } int main() { int n, m; scanf("%d%d", &n, &m); while(m--) { int a, b; scanf("%d%d", &a, &b); edges[a].push_back(b); edges[b].push_back(a); } for(int i = 1; i <= n; ++i) if(!vis[i]) { int cnt_vertices = 0, cnt_edges = 0; dfs(i, cnt_vertices, cnt_edges); if(cnt_edges != (long long) cnt_vertices * (cnt_vertices - 1)) { puts("NO"); return 0; } } puts("YES"); }
771
B
Bear and Different Names
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?). A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't. You are a spy in the enemy's camp. You noticed $n$ soldiers standing in a row, numbered $1$ through $n$. The general wants to choose a group of $k$ consecutive soldiers. For every $k$ consecutive soldiers, the general wrote down whether they would be an effective group or not. You managed to steal the general's notes, with $n - k + 1$ strings $s_{1}, s_{2}, ..., s_{n - k + 1}$, each either "YES" or "NO". - The string $s_{1}$ describes a group of soldiers $1$ through $k$ ("YES" if the group is effective, and "NO" otherwise). - The string $s_{2}$ describes a group of soldiers $2$ through $k + 1$. - And so on, till the string $s_{n - k + 1}$ that describes a group of soldiers $n - k + 1$ through $n$. Your task is to find possible names of $n$ soldiers. Names should match the stolen notes. Each name should be a string that consists of between $1$ and $10$ English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print "Xyzzzdj" or "T" for example. Find and print any solution. It can be proved that there always exists at least one solution.
First generate $n$ different names. If the $i$-th given string is "NO", make names $i$ and $i + k - 1$ equal. Note that it doesn't affect other groups of $k$ consecutive names.
[ "constructive algorithms", "greedy" ]
1,500
#include <bits/stdc++.h> using namespace std; string s[105]; int main() { int n, k; cin >> n >> k; // generate n different names for(int i = 1; i <= n; ++i) { s[i] = "Aa"; s[i][0] += i / 26; s[i][1] += i % 26; } for(int start = 1; start <= n - k + 1; ++start) { string should; cin >> should; if(should[0] == 'N') // not effective group s[start+k-1] = s[start]; // make two names equal } for(int i = 1; i <= n; ++i) cout << s[i] << " "; cout << "\n"; }
771
C
Bear and Tree Jumps
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of $n$ vertices, numbered $1$ through $n$. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most $k$. For a pair of vertices $(s, t)$ we define $f(s, t)$ as the minimum number of jumps Limak needs to get from $s$ to $t$. Your task is to find the sum of $f(s, t)$ over all pairs of vertices $(s, t)$ such that $s < t$.
It's a known problem to count the sum of distances for all pairs of vertices. For each edge, we should add to the answer the number of times this edge appears in a path between some two vertices. If $s_{v}$ denotes the size of the subtree of the vertex $v$ (we can first root the tree in $1$), we should add $s_{v} \cdot (n - s_{v})$ to the sum. In this problem, the answer is around $\mathbf{\Sigma}_{k}^{\infty}$, where $S$ is the answer for the known problem described above. But for each path with length $L$, we should add $\left[{\frac{L}{k}}\right]={\frac{L+f(L,k)}{k}}$ to the answer, where $f(L, k)$ says how much we must add to $L$ to get a number divisible by $k$ ($f(10, 3) = 2, f(11, 3) = 1, f(12, 3) = 0$). We know the sum of $\begin{array}{l}{{\frac{L}{k}}}\end{array}$ because it's $\mathbf{\Sigma}_{k}^{\infty}$ in total. What remains is to compute the sum of $f(L, k)$. To achieve that, for each remainder modulo $k$, we want to know the number of paths with length that has this remainder. For example, if $k = 3$ and there are $200$ paths with remainder $1$, they all have $f(L, k) = 2$, so we should add $200 \cdot 2$ to the answer. Let's root the tree in any vertex and do bottom-up dp. For each subtree we compute the $k$ values: for each remainder modulo $k$ how many paths (starting from the root of this subtree) have this remainder. We can merge two subtrees in $O(k^{2})$, so the total complexity is $O(n \cdot k^{2})$. See my code for details.
[ "dfs and similar", "dp", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; const int nax = 2e5 + 5; vector<int> edges[nax]; int count_subtree[nax][5]; int total_subtree[nax]; long long answer; int n, k; int subtract(int a, int b) { return ((a - b) % k + k) % k; } void dfs(int a, int par, int depth) { count_subtree[a][depth % k] = total_subtree[a] = 1; for(int b : edges[a]) if(b != par) { dfs(b, a, depth + 1); for(int i = 0; i < k; ++i) for(int j = 0; j < k; ++j) { // compute distance modulo k int remainder = subtract(i + j, 2 * depth); // compute x such that (distance + x) is divisible by k int needs = subtract(k, remainder); answer += (long long) needs * count_subtree[a][i] * count_subtree[b][j]; } for(int i = 0; i < k; ++i) count_subtree[a][i] += count_subtree[b][i]; total_subtree[a] += total_subtree[b]; } // in how many pairs we will count the edge from 'a' to its parent? answer += (long long) total_subtree[a] * (n - total_subtree[a]); } int main() { scanf("%d%d", &n, &k); for(int i = 0; i < n - 1; ++i) { int a, b; scanf("%d%d", &a, &b); edges[a].push_back(b); edges[b].push_back(a); } dfs(1, -1, 0); assert(answer % k == 0); printf("%lld\n", answer / k); }
771
D
Bear and Company
Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible. Limak has a string $s$ that consists of uppercase English letters. In one move he can swap two \textbf{adjacent} letters of the string. For example, he can transform a string "ABBC" into "BABC" or "ABCB" in one move. Limak wants to obtain a string without a substring "VK" (i.e. there should be no letter 'V' immediately followed by letter 'K'). It can be easily proved that it's possible for any initial string $s$. What is the minimum possible number of moves Limak can do?
Letters different than 'V' and 'K' are indistinguishable, so we can treat all of them as the same letter 'X'. We will try to build the final string from left to right Let $dp[v][k][x]$ denote the number of moves needed to move first $v$ letters 'V', first $k$ letters 'K' and first $x$ letters 'X' to the beginning of the string (those letters should become first $v + k + x$ letters of the string). We should also remember the last used letter (to ensure that there is no 'K' just after 'V') so let's extend the state to $dp[v][k][x][lastLetter]$ (or it can be $dp[v][k][x][is_the_last_letter_V]$). To move from a state, we should consider taking the next 'K' (i.e. the $k + 1$-th letter 'K' in the initial string), the next 'V' or the next 'X'. Of course, we can't take 'K' if the last used letter was 'V'. The last step is to see how we should add to the score when we add a new letter. It turns out that it isn't enough to just add the difference between indices (where the letter was and where it will be) and the third sample test ("VVKEVKK") showed that. Instead, we should notice that we know which letters are already moved to the beginning (first $k$ letters 'K' and so on) so we know how exactly the string looks like currently. For example, let's consider the string "VVKXXVKVV" and moving from the state $v = 4, k = 1, x = 1$ by taking a new letter 'K'. We know that first $4$ letters 'V', $1$ letter 'K' and $1$ letter 'X' are already moved to the beginning. To move the next letter 'K' (underlined in blue on the drawing below) to the left, we must swap it with all not-used letters that were initially on the left from this 'K'. Counting them in linear time gives the total complexity $O(n^{4})$ but you can also think a bit and get $O(n^{3})$ - it's quite easy but it wasn't required to get AC. On the drawing below, used letters are crossed out. There is only $1$ not-crossed-out letter on the left from 'K' so we should increase the score by $1$ (because we need $1$ swap to move this 'K' to the $x + k + v + 1$-th position).
[ "dp" ]
2,500
#include <bits/stdc++.h> using namespace std; int n; vector<int> V, K, X; // lists of indices with 'V', 'K' and other letters void read() { cin >> n; string s; cin >> s; for(int i = 0; i < n; ++i) { if(s[i] == 'V') V.push_back(i); else if(s[i] == 'K') K.push_back(i); else X.push_back(i); } } const int nax = 77; const int INF = 1e9 + 5; int dp[nax][nax][nax][2]; void mini(int & a, int b) { a = min(a, b); } int count_remaining(const vector<int> & list, int from, int limit_val) { int cnt = 0; for(int i = from; i < (int) list.size() && list[i] < limit_val; ++i) ++cnt; return cnt; } int main() { read(); for(int a = 0; a <= n; ++a) for(int b = 0; b <= n; ++b) for(int c = 0; c <= n; ++c) for(int d = 0; d < 2; ++d) dp[a][b][c][d] = INF; dp[0][0][0][0] = 0; for(int v = 0; v <= (int) V.size(); ++v) for(int k = 0; k <= (int) K.size(); ++k) for(int x = 0; x <= (int) X.size(); ++x) for(int type = 0; type < 2; ++type) { auto moving_cost = [&] (int where) { return count_remaining(V, v, where) + count_remaining(K, k, where) + count_remaining(X, x, where); }; int already = dp[v][k][x][type]; if(v < (int) V.size()) mini(dp[v+1][k][x][1], already + moving_cost(V[v])); if(k < (int) K.size() && type == 0) mini(dp[v][k+1][x][0], already + moving_cost(K[k])); if(x < (int) X.size()) mini(dp[v][k][x+1][0], already + moving_cost(X[x])); } int answer = INF; for(int i = 0; i < 2; ++i) mini(answer, dp[V.size()][K.size()][X.size()][i]); printf("%d\n", answer); }
771
E
Bear and Rectangle Strips
Limak has a grid that consists of $2$ rows and $n$ columns. The $j$-th cell in the $i$-th row contains an integer $t_{i, j}$ which can be positive, negative or zero. A non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to $0$. Limak wants to choose some nice rectangles and give them to his friends, as gifts. No two chosen rectangles should share a cell. What is the maximum possible number of nice rectangles Limak can choose?
There are three types of rectangles: in the top row, in the bottom row, and in both rows (with height 2). For each type, and for each starting index $i$ we can quite easily find the first possible ending index - it's the first index on the right with the same prefix sum of numbers (it means that the difference of prefix sums is $0$). We can iterate from right to left for each of three types, use store prefix sums in the set and for each type and each starting index we can remember the first possible ending index (or we will know that there is no such index). The complexity of this part is $O(n\cdot\log n)$. Now, the naive square solution would be to create an array $dp[n][n]$ and compute $dp[i][j]$ as the maximum possible score, if we are allowed to use only first $i$ cells in the first row and first $j$ cells in the second row. Thanks to the precomputing above, we can move from a state in $O(1)$, considering the following options: increase $i$ by $1$ (without taking any rectangle) increase $j$ by $1$ take the first possible rectangle in the first row (check what is the first possible ending index of a rectangle in the first row, starting at index $i + 1$) take the first possible rectangle in the second row if $i = j$, also consider taking first possible rectangle of height $2$ (in both rows) Now let's improve this part to $O(n)$. Let $C_{i}$ denote the best score if we were allowed to use only first $i$ cells in each row ($C_{i} = dp[i][i]$). It turns out that the following values for each $i$ are enough to solve the problem: $C_{i}$ If we were allowed to use only first $i$ cells in the first row, how far we must go in the second row, in order to get the score $C_{i} + 1$. In other words, what is the smallest $j$ such that $dp[i][j] = C_{i} + 1$ Similarly, the smallest $j$ such that $dp[j][i] = C_{i} + 1$ Take a look at the drawings below. The value $C_{i}$ is the maximum possible score for light-blue cells on the left drawing. The right drawing shows the third of situation listed above - we want to know what prefix of cells in the first row is needed, if we want to get the score $C_{i} + 1$. To see that it works, we must prove that we don't have to care how far we must go in one row to get the score $C_{i} + 2$ or higher. The crucial observation that getting score at least $C_{i} + 2$ means that we took at least two rectangles that are at least partially on the right from index $i$ (i.e. each of them contains at least one cell with index greater than $i$) - see the drawing below. So, instead of considering this situation now, we can first take some rectangle in the second row (or skip a few cells) because we can take that last rectangle in the first row later. In other words, when we are in the state $dp[i][j]$ where $i < j$, it's enough to consider taking a rectangle in the first row or just increasing $i$ without taking anything.
[ "dp", "greedy" ]
3,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; void maxi(int & a, int b) { a = max(a, b); } vector<ll> candidate[2][2]; int n; vector<int> answer; vector<vector<vector<int>>> extensions; void consider(int one, int two, int score) { maxi(answer[max(one, two)], score); extensions[min(one, two)].push_back(vector<int>{one, two, score}); } void go_from(int one, int two, int so_far) { // extend the first row if(one < n) { consider(one + 1, two, so_far); int i = candidate[0][0][one]; if(i != -1) consider(i + 1, two, so_far + 1); } // extend the second row if(two < n) { consider(one, two + 1, so_far); int i = candidate[1][1][two]; if(i != -1) consider(one, i + 1, so_far + 1); } // extend both rows (with a rectangle of height 2) if(one == two && one < n) { int i = candidate[0][1][one]; if(i != -1) consider(i + 1, i + 1, so_far + 1); } } int main() { scanf("%d", &n); answer.resize(n + 1, 0); extensions.resize(n + 1); vector<vector<ll>> in(2, vector<ll>(n)); for(vector<ll> & row : in) for(int i = 0; i < n; ++i) { scanf("%lld", &row[i]); if(i) row[i] += row[i-1]; // prefix sums } for(int i0 = 0; i0 <= 1; ++i0) for(int i1 = i0; i1 <= 1; ++i1) { candidate[i0][i1].resize(n, -1); map<ll, int> next_occurrence; for(int where = n - 1; where >= 0; --where) { ll new_value = 0; for(int i = i0; i <= i1; ++i) new_value += in[i][where]; next_occurrence[new_value] = where; ll need = 0; if(where != 0) for(int i = i0; i <= i1; ++i) need += in[i][where-1]; if(next_occurrence.count(need)) candidate[i0][i1][where] = next_occurrence[need]; } } for(int where = 0; where < n; ++where) { int so_far = answer[where]; go_from(where, where, so_far); auto mini = [&] (int & a, int b) { if(a == -1 || b < a) a = b; }; int how_far_up = -1, how_far_down = -1; for(const vector<int> & ext : extensions[where]) { if(ext[1] == where && ext[2] == so_far + 1) mini(how_far_up, ext[0]); if(ext[0] == where && ext[2] == so_far + 1) mini(how_far_down, ext[1]); } if(how_far_up != -1) go_from(how_far_up, where, so_far + 1); if(how_far_down != -1) go_from(where, how_far_down, so_far + 1); } printf("%d\n", answer[n]); }
771
F
Bear and Isomorphic Points
Bearland is a big square on the plane. It contains all points with coordinates not exceeding $10^{6}$ by the absolute value. There are $n$ houses in Bearland. The $i$-th of them is located at the point $(x_{i}, y_{i})$. The $n$ points are distinct, but some subsets of them may be collinear. Bear Limak lives in the first house. He wants to destroy his house and build a new one somewhere in Bearland. Bears don't like big changes. For every three points (houses) $p_{i}$, $p_{j}$ and $p_{k}$, the sign of their cross product $(p_{j} - p_{i}) × (p_{k} - p_{i})$ should be the same before and after the relocation. If it was negative/positive/zero, it should still be negative/positive/zero respectively. This condition should be satisfied for all triples of indices $(i, j, k)$, possibly equal to each other or different than $1$. Additionally, Limak isn't allowed to build the house at the point where some other house already exists (but it can be the point where his old house was). In the formula above, we define the difference and the cross product of points $(a_{x}, a_{y})$ and $(b_{x}, b_{y})$ as: \[ (a_{x}, a_{y}) - (b_{x}, b_{y}) = (a_{x} - b_{x}, a_{y} - b_{y}), \] \[ (a_{x}, a_{y}) × (b_{x}, b_{y}) = a_{x}·b_{y} - a_{y}·b_{x}. \] Consider a set of possible new placements of Limak's house. Your task is to find the area of that set of points. Formally, let's say that Limak chooses the new placement randomly (each coordinate is chosen independently uniformly at random from the interval $[ - 10^{6}, 10^{6}]$). Let $p$ denote the probability of getting the allowed placement of new house. Let $S$ denote the area of Bearland ($S = 4·10^{12}$). Your task is to find $p·S$.
If $p_{1}$ is collinear with some two other points, we should print $0$. Now let's assume that no two points are collinear with $p_{1}$. The naive solution is to iterate over $O(n^{2})$ pairs of points. For each pair of points there is a line going through them both, and we know that the new placement of $p_{1}$ should be on the same side (e.g. on the left) from the line - otherwise the sign of the cross product will change. In other words, the new placement must belong to some halfplane. What we're looking for is the intersection of those $O(n^{2})$ halfplanes, what can be found in $O(n^{2}\log{n})$. We should also remember that the new placement must be inside the big square, what can be achieved by adding four halfplanes (each for one side of the square). It turns out that it's quite easy to improve the complexity of the naive solution. Let's first sort other $n - 1$ points by angle. One way to approach the problem is to think "we are interested in those new placements that don't affect the sorting of those $n - 1$ points" - this is almost enough to get the intended solution. If sorted (in the clockwise order) points are $p_{2}, p_{3}, ..., p_{n}$, taking into account a halfplane that goes through points $p_{i}$ and $p_{i + 1}$ ensures that $p_{i + 1}$ is further in the clockwise order than $p_{i}$ (i.e. it is more "on the right" if we look from $p_{1}$). Usually, $p_{i + 2}$ is also more "on the right" than $p_{i}$, and so on, till some point $p_{j}$ that is no longer "on the left" from $p_{i}$ (if we look from $p_{1}$). For each $i$, let's find the first $j$ that $p_{j}$ is "on the left" from $p_{i}$ (move indices $i$ and $j$ with two pointers) and then consider a halfplane that goes through $p_{i}$ and $p_{j}$. To sum up, we consider $n$ halfplanes determined by pairs $(p_{i}, p_{i + 1})$ and $n$ halfplanes determined by pairs $(p_{i}, p_{j})$ where $p_{i}$ and $p_{j}$ are almost opposite to each other, with respect to $p_{1}$. It turns out that this is already a working solution - no other halfplanes are needed. The answer is the intersection of found $O(n)$ halfplanes. Let's prove the correctness. Let's assume that one of halfplanes (going through some $p_{a}$ and $p_{b}$) wasn't considered, while it should be because it would affect the answer. And let's say that $p_{b}$ is more "on the right" than $p_{a}$, and $a < b$. If $|a - b| = 1$, we surely considered that halfplane. Otherwise, if there is some other point with index $m\in[a+1,b-1]$ such that it is on the proper side of the line $(p_{a}, p_{b})$, i.e. on the same side as $p_{1}$, halfplanes determined by pairs $(a, m)$ and $(m, b)$ completely cover that $(a, b)$ halfplane. Here we must use induction: if each halfplane determined by a pair $(a, b)$ for smaller value of $b - a$ is either taken or covered by some other taken halfplanes, then also halfplanes with greater differences $b - a$ will be considered (remember that we assumed that there is some other points with index $m\in[a+1,b-1]$ such that ...). The case analysed above is shown on the drawing below. Let R denote the red point. If halfplanes $(pa, R)$ and $(R, pb)$ are considered (or from induction they are covered by something else), we don't need considering $(pa, pb)$. What remains is the case when $a + 1 \neq b$ and each point with index in $[a + 1, b - 1]$ is on the line $(p_{a}, p_{b})$ or on the wrong side (not the same as $p_{1}$). It quite easily implies that our line is already covered everywhere except for the segment $(p_{a}, p_{b})$, see the drawing: Now we should take a look at points $p_{b + 1}, p_{b + 2}, ...$. If one of them $p_{k}$ is on the wrong side of the line $(p_{a}, p_{b})$ (i.e. on the side different than $p_{1}$), the halfplane $(p_{k - 1}, p_{k})$ covers our segment $(p_{a}, p_{b})$ and we are done. Otherwise, all those points are on the proper side (the same as $p_{1}$). Eventually one of them will be the last one that is "on the right" from $p_{a}$ and let's remember that we consider halfplanes determined by such pairs (earlier denoted as $p_{i}$ and $p_{j}$). Since that point is on the proper side of the line $(p_{a}, p_{b})$, the segment is covered:
[ "geometry", "two pointers" ]
3,300
#include <bits/stdc++.h> using namespace std; #include <bits/stdc++.h> using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge {c b, e; }; sim > rge<c> range(c i, c j) { return rge<c>{i, j}; } sim > auto dud(c* x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } eni(!=) cerr << boolalpha << i; ris; } eni(==) ris << range(begin(i), end(i)); } sim, class b dor(pair < b, c > d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c&) { ris; } #endif }; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " typedef long long ll; struct P { ll x, y; void read() { scanf("%lld%lld", &x, &y); } P operator - (const P & b) const { return P{x - b.x, y - b.y}; } void operator += (const P & b) { x += b.x, y += b.y; } ll operator * (const P & b) const { return x * b.y - y * b.x; } ll cross(const P & b, const P & c) const { return (b - *this) * (c - *this); } bool isRight() const { return x > 0 || (x == 0 && y > 0); } bool operator < (const P & b) const { if(isRight() != b.isRight()) return isRight(); return *this * b < 0; } }; debug & operator << (debug & dd, P p) { dd << make_pair(p.x, p.y); return dd; } struct L2 { P one, two; P dir() const { return two - one; } bool operator < (const L2 & b) const { return dir() < b.dir(); } long double get_coeff(const L2 & b) const { long double r = (b.dir() * (one - b.one)) / (long double) (dir() * b.dir()); return r; } bool isParallel(const L2 & b) const { return dir() * b.dir() == 0; } // checks if this line is more important than the other parallel line bool isBetter(const L2 & b) const { assert(isParallel(b)); return (b.one - one) * (two - one) < 0; } // checks if this line is less important than two neighbouring lines bool isBelow(const L2 & a, const L2 & c) const { return get_coeff(a) >= get_coeff(c); } pair<long double, long double> intersect(const L2 & b) const { long double r = get_coeff(b); return make_pair(one.x + r * (two - one).x, one.y + r * (two - one).y); } }; debug & operator << (debug & dd, L2 line) { dd << make_pair(line.one, line.two); return dd; } deque<L2> getHull(vector<L2> halfplanes) { sort(halfplanes.begin(), halfplanes.end()); debug() << imie(halfplanes); deque<L2> hull; #define sec_back(vect) vect[(int) vect.size() - 2] for(L2 line : halfplanes) { if(!hull.empty() && line.isParallel(hull.back())) { if(hull.back().isBetter(line)) line = hull.back(); hull.pop_back(); } while((int) hull.size() >= 2 && hull.back().isBelow(sec_back(hull), line)) hull.pop_back(); hull.push_back(line); } while((int) hull.size() >= 3) { if(hull.back().isBelow(sec_back(hull), hull[0])) hull.pop_back(); else if(hull[0].isBelow(hull.back(), hull[1])) hull.pop_front(); else break; } #undef sec_back debug() << imie(hull); return hull; } long double test_case() { int n; scanf("%d", &n); P origin; origin.read(); vector<P> points(n - 1); for(P & p : points) { p.read(); p = p - origin; } sort(points.begin(), points.end()); debug() << imie(points); vector<L2> halfplanes; for(int i = 0; i < (int) points.size(); ++i) { int j = (i + 1) % points.size(); halfplanes.push_back(L2{points[i], points[j]}); } int pointer = 0; for(int i = 0; i < (int) points.size(); ++i) { pointer = max(pointer, i + 1); while(points[i] * points[pointer % points.size()] < 0) ++pointer; if(i != pointer % (int) points.size()) halfplanes.push_back(L2{points[i], points[pointer % points.size()]}); } debug() << imie(halfplanes); for(L2 & line : halfplanes) { if(line.one * line.two == 0) return 0; if(line.one * line.two > 0) swap(line.one, line.two); line.one += origin; line.two += origin; } const int MAX = 1e6; vector<P> corners{P{-MAX, MAX}, P{MAX, MAX}, P{MAX, -MAX}, P{-MAX, -MAX}}; for(int i = 0; i < (int) corners.size(); ++i) { int j = (i + 1) % corners.size(); halfplanes.push_back(L2{corners[i], corners[j]}); } deque<L2> hull = getHull(halfplanes); vector<pair<long double, long double>> polygon; long double area = 0; for(int i = 0; i < (int) hull.size(); ++i) { int j = (i + 1) % hull.size(); polygon.push_back(hull[i].intersect(hull[j])); } debug() << imie(polygon); for(int i = 0; i < (int) polygon.size(); ++i) { int j = (i + 1) % polygon.size(); area += polygon[i].first * polygon[j].second - polygon[i].second * polygon[j].first; } return abs(area) / 2; } int main() { int T; scanf("%d", &T); while(T--) printf("%.12lf\n", (double) test_case()); }
772
A
Voltage Keepsake
You have $n$ devices that you want to use simultaneously. The $i$-th device uses $a_{i}$ units of power per second. This usage is continuous. That is, in $λ$ seconds, the device will use $λ·a_{i}$ units of power. The $i$-th device currently has $b_{i}$ units of power stored. All devices can store an arbitrary amount of power. You have a single charger that can plug to any single device. The charger will add $p$ units of power per second to a device. This charging is continuous. That is, if you plug in a device for $λ$ seconds, it will gain $λ·p$ units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible. You are wondering, what is the maximum amount of time you can use the devices until one of them hits $0$ units of power. If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits $0$ power.
First, let's deal with the infinite case. If the supply of power is at least as big as the sum of demands, we can keep all devices alive indefinitely. Otherwise, let's binary search for the result. We can do binary search since if we can keep all devices alive for $E$ seconds, we can keep it alive for any time less than $E$ seconds. Since all usage/charging is continuous, we can think about it as "splitting" up the charge amount. For each device and a fixed time $T$, we can compute the rate that we need to charge it so that the device always has positive power. Well, it uses $a_{i}$ power per second, so it uses a total of $T * a_{i}$ power. It currently has $b_{i}$ power, so we need $X_{i} = max(0, T * a_{i} - b_{i})$ units of power. This means we need $X_{i} / T$ units of power per second to this device. So, we just need to check that $\textstyle\sum_{i}X_{i}/T\leq P$. If so, then it is possible to keep the devices alive for $T$ seconds, and we can use this to continue our binary search. Since we are binary searching on doubles, it is useful to just do it for a fixed number of steps. We can approximate the max answer is somewhere around $10^{14}$ and we need a precision of $10^{ - 4}$, so we need approximately $\log_{2}(10^{18})\approx60$ iterations.
[ "binary search", "math" ]
1,800
#include <stdio.h> #include <algorithm> #include <assert.h> using namespace std; typedef long long ll; typedef long double ld; // Adjust MAXN for bounds const ll MAXN=1e5+4; // MAXV is the max amount of time we can take const ld MAXV=1e18; ll a[MAXN],b[MAXN]; ld exhaust[MAXN]; int n; ll P; bool f(ld imid) { ld needsum=0; for (int i=0;i<n;i++) { ld need=max(0.0L, (imid-exhaust[i])*a[i]); needsum+=need; } ld supply=imid*P; return supply>=needsum; } int main() { scanf("%d%lld",&n,&P); for (int i=0;i<n;i++) { scanf("%lld%lld",&a[i],&b[i]); } ll suma=0; for (int i=0;i<n;i++) { suma+=a[i]; } if (P>=suma) { printf("-1\n"); return 0; } for (int i=0;i<n;i++) { exhaust[i]=((ld)b[i])/((ld)a[i]); } ld imin=0,imax=MAXV; for (ll iter=0;iter<220;iter++) { ld imid=(imin+imax)/2; if (f(imid)) imin=imid; else imax=imid; } if (imax>MAXV-100) printf("-1\n"); else printf("%.9f\n",(double)imin); }
772
B
Volatile Kite
You are given a convex polygon $P$ with $n$ distinct vertices $p_{1}, p_{2}, ..., p_{n}$. Vertex $p_{i}$ has coordinates $(x_{i}, y_{i})$ in the 2D plane. These vertices are listed in clockwise order. You can choose a real number $D$ and move each vertex of the polygon a distance of at most $D$ from their original positions. Find the maximum value of $D$ such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
First, let's restate the problem as the minimum distance D needed to make the polygon nonconvex. We can notice we can achieve this by by changing one angle of the polygon nonconvex. So, that involves moving at most 3 points. Let's take a look at the following picture: Here, A,B,C denote consecutive vertices on our polygon. The circle represents the area that each point can be moved to (once we fix our distance), and we want to choose red points that lie in or on the circle such that they form an obtuse angle. We can see that this is possible as long as the radius exceeds half the distance between segment AC and point B. Thus, we just need to compute the minimum such distance for all such consecutive three points on our polygon. To compute the distance between a segment and a point, consider this link: https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points In particular, it is the cross product between (B-A) and (C-A) divided by the length of segment AC.
[ "geometry" ]
1,800
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); NonConvexPolygon solver = new NonConvexPolygon(); solver.solve(1, in, out); out.close(); } static class NonConvexPolygon { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); long[][] p = new long[n][2]; for (int i = 0; i < n; i++) { p[i][0] = in.nextInt(); p[i][1] = in.nextInt(); } double ans = 1L << 60; for (int i = 0; i < n; i++) { int prev = (i + n - 1) % n, next = (i + 1) % n; ans = Math.min(ans, PointToSegmentDistance.pointToLineThroughTwoPointsDistance( p[i][0], p[i][1], p[prev][0], p[prev][1], p[next][0], p[next][1] ) / 2.0); } out.printf("%.10f\n", ans); } } static class Utils { public static double cross(Point a, Point b, Point c) { Point ab = new Point(b.x - a.x, b.y - a.y); Point ac = new Point(c.x - a.x, c.y - a.y); return ab.x * ac.y - ab.y * ac.x; } } static class PointToSegmentDistance { static double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } public static double pointToLineThroughTwoPointsDistance(long x, long y, long ax, long ay, long bx, long by) { double t = Utils.cross(new Point(ax, ay), new Point(bx, by), new Point(x, y)); return Math.abs(t / fastHypot(ax - bx, ay - by)); } } static class Point implements Comparable<Point> { public double x; public double y; public double angle; public int idx; public Point(double x, double y) { this.x = x; this.y = y; angle = 0; } public Point(double x, double y, int idx) { this.x = x; this.y = y; this.idx = idx; } public int compareTo(Point other) { return x == other.x ? (int) Math.signum(y - other.y) : (int) Math.signum(x - other.x); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void printf(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } }
772
C
Vulnerable Kerbals
You are given an integer $m$, and a list of $n$ distinct integers between $0$ and $m - 1$. You would like to construct a sequence satisfying the properties: - Each element is an integer between $0$ and $m - 1$, inclusive. - All prefix products of the sequence modulo $m$ are distinct. - No prefix product modulo $m$ appears as an element of the input list. - The length of the sequence is maximized. Construct any sequence satisfying the properties above.
Let's consider a directed graph with $m$ nodes, labeled from $1$ to $m$, where there is an edge between nodes $i$ and node $j$ if there exists a number $x$ such that $i x\equiv j{\mathrm{~mod~}}m$. Now, we can notice there is an edge between node $i$ and node $j$ if and only if $gcd(n, i)$ divides $gcd(n, j)$. So, there are two directed edges between two nodes $i$ and $j$ if and only if $gcd(n, i) = gcd(n, j)$. So, these form some directed cliques in our graphs. We can also notice that this happens to form the SCC decomposition of our graph (i.e. condensation). So this problem reduces to finding the heaviest path in a DAG with weights on nodes. The nodes in this dag correspond to divisors of $n$, and the weight corresponds to the number of allowed numbers with that gcd.
[ "constructive algorithms", "dp", "graphs", "math", "number theory" ]
2,300
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); PrefixProductSequence solver = new PrefixProductSequence(); solver.solve(1, in, out); out.close(); } static class PrefixProductSequence { public int[] div; public boolean[] forbidden; public ArrayList<Long> ans; public int n; public int m; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); m = in.nextInt(); forbidden = new boolean[m + 1]; for (int i = 0; i < n; i++) { forbidden[in.nextInt()] = true; } int[] add = new int[m + 1]; for (int i = 0; i < m; i++) { if (!forbidden[i]) { int g = Utils.gcd(i, m); add[m / g]++; } } int[] arr = new int[m + 1]; div = new int[m + 1]; Arrays.fill(arr, 1); Arrays.setAll(div, x -> x); for (int i = 2; i <= m; i++) { arr[i] += add[i]; for (int j = i + i; j <= m; j += i) { if (arr[i] > arr[j]) { arr[j] = arr[i]; div[j] = j / i; } } } ans = new ArrayList<>(); solve(1, 1); out.println(ans.size()); boolean first = true; for (long x : ans) { if (!first) out.print(" "); out.print(x); first = false; } out.println(); } public void solve(int cmult, long mm) { if (cmult == m) { if (!forbidden[0]) { ans.add(0L); } return; } int prev = 1; boolean has = false; for (int i = 1; i < m / cmult; i++) { if (!forbidden[i * cmult] && Utils.gcd(m / cmult, i) == 1) { long x = Utils.inv(prev, m / cmult) * i % m; if (!has) { has = true; x = x * mm % m; } ans.add(x); prev = i; } } long nmm = Utils.inv(prev, m / cmult) * div[m / cmult] % m; if (!has) nmm = nmm * mm % m; solve(cmult * div[m / cmult], nmm); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println() { writer.println(); } public void close() { writer.close(); } public void print(long i) { writer.print(i); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class Utils { public static long inv(long N, long M) { long x = 0, lastx = 1, y = 1, lasty = 0, q, t, a = N, b = M; while (b != 0) { q = a / b; t = a % b; a = b; b = t; t = x; x = lastx - q * x; lastx = t; t = y; y = lasty - q * y; lasty = t; } return (lastx + M) % M; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } } }
772
D
Varying Kibibits
You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Denote this list of integers as $T$. Let $f(L)$ be a function that takes in a non-empty list of integers $L$. The function will output another integer as follows: - First, all integers in $L$ are padded with leading zeros so they are all the same length as the maximum length number in $L$. - We will construct a string where the $i$-th character is the minimum of the $i$-th character in padded input numbers. - The output is the number representing the string interpreted in base 10. For example $f(10, 9) = 0$, $f(123, 321) = 121$, $f(530, 932, 81) = 30$. Define the function \[ G(x)=x\cdot\left(\left(\sum_{s\in Z,s\neq o,f(S)=x}\left(\sum_{y\in S}y\right)^{2}\right){\mathrm{~mod~}}1{\mathrm{~ooo~}}000{\mathrm{00}}\bar{v}\right) \] Here, $\subseteq$ denotes a subsequence.In other words, $G(x)$ is the sum of squares of sum of elements of nonempty subsequences of $T$ that evaluate to $x$ when plugged into $f$ modulo $1 000 000 007$, then multiplied by $x$. The last multiplication is not modded. You would like to compute $G(0), G(1), ..., G(999 999)$. To reduce the output size, print the value $G(0)\oplus G(1)\oplus G(2)\oplus.\cdot\Leftrightarrow G(999999)$, where $\mathbb{C}$ denotes the bitwise XOR operator.
There are two approaches. One is inclusion exclusion. The other is a modification of the fast walsh hadamard transform. Inclusion Exclusion: Let's change definition of G(x) so that f(S) >= x rather than f(S) = x. Here "y >= x" means that if y and x are considered as strings, then each digit in a particular position in y is greater than its corresponding digit in x. This is then easy to compute, since the numbers we can use must satisfy the constraint that each digit is larger than the corresponding position in x. So, we can go from $999, 999$ to $0$ and do inclusion/exclusion to change the >= condition to =, by fixing which digits are fixed and which ones are strictly greater, so it takes $2^{6}$ time per value of $x$ to compute. Fast Walsh Hadamard transform: Let's consider the simplified problem where we just want to know the number of subsets that evaluate to $x$ for all values of $x$. Let f(freq) taken in a frequency array of length 10^k, and returns a list of length 10^k, where the i-th element represents the result. When $k = 0$, this is easy to compute, it is just $2^{freq[0]}$. Let's fix the value of the topmost digit. We can split our frequency array into 10 parts, representing which one is the top digt. Let's label these freq_0, freq_1, ..., freq_9 (these have length 10^(k-1)). Then, we can compute g_9 = f(freq_9) g_8 = f(freq_9+freq_8) g_7 = f(freq_9+freq_8+freq_7) ... g_0 = f(freq_9+freq_8+...+freq_0) (The plus signs here are element by element addition, so [0,3] + [5,4] = [5,7] for example). Then, we can combine these to get the answer to our original problem. Namely, our final answer will be (g_0 - g_1), (g_1 - g_2), ... , g_9 (i.e. concatenate the element by element subtraction of g_1 from g_0 to g_1-g_2 and so on). Of course, we don't need to do this recursively, we can do it in a loop (see my java code for example). Back to the original problem, we need to keep track of three values when doing the first pass of our algorithm, the number of elements, sum of elements, and sum of squares of elements. Then, in our base case, we can use these three numbers to compute the desired sum. The runtime of this is T(n) = 10 * T(n/10) + O(n) = O(n log_10(n)).
[ "bitmasks", "dp" ]
2,700
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); MinAddition solver = new MinAddition(); solver.solve(1, in, out); out.close(); } static class MinAddition { public int[] pow10 = {1, 10, 100, 1000, 10000, 100000, 1000000}; public int MAXN = 1000000; public int LOG = 6; public int mod = 1000000007; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] freq = new int[MAXN]; int[] sum = new int[MAXN]; int[] sum2 = new int[MAXN]; int[] pow2 = new int[n + 1]; pow2[0] = 1; for (int i = 1; i <= n; i++) pow2[i] = (pow2[i - 1] << 1) % mod; for (int i = 0; i < n; i++) { int a = in.nextInt(); freq[a]++; sum[a] += a; if (sum[a] >= mod) sum[a] -= mod; int x = (int) (1L * a * a % mod); sum2[a] += x; if (sum2[a] >= mod) sum2[a] -= mod; } int[] mod10 = new int[MAXN]; for (int i = 0; i < 10; i++) mod10[i] = i; for (int i = 10; i < MAXN; i++) mod10[i] = mod10[i - 10]; for (int level = LOG - 1; level >= 0; level--) { for (int i = MAXN - 1; i >= 0; i--) { int d = mod10[i / pow10[level]]; if (d > 0) { int p = i - pow10[level]; freq[p] += freq[i]; sum[p] += sum[i]; if (sum[p] >= mod) sum[p] -= mod; sum2[p] += sum2[i]; if (sum2[p] >= mod) sum2[p] -= mod; } } } for (int i = 0; i < MAXN; i++) { int sdiff = (int) ((1L * sum[i] * sum[i] + mod - sum2[i]) % mod); int ssame = sum2[i]; int g = 0; if (freq[i] >= 1) g += (int) (1L * ssame * pow2[freq[i] - 1] % mod); if (freq[i] >= 2) g += (int) (1L * sdiff * pow2[freq[i] - 2] % mod); while (g >= mod) g -= mod; freq[i] = g; } for (int level = 0; level < LOG; level++) { for (int i = 0; i < MAXN; i++) { int d = mod10[i / pow10[level]]; if (d + 1 < 10) { int p = i + pow10[level]; freq[i] -= freq[p]; if (freq[i] < 0) freq[i] += mod; } } } long s = 0; for (int i = 0; i < MAXN; i++) { s ^= 1L * i * freq[i]; } out.println(s); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } }
772
E
Verifying Kingdom
\textbf{This is an interactive problem.} The judge has a hidden rooted full binary tree with $n$ leaves. A full binary tree is one where every node has either $0$ or $2$ children. The nodes with $0$ children are called the leaves of the tree. Since this is a full binary tree, there are exactly $2n - 1$ nodes in the tree. The leaves of the judge's tree has labels from $1$ to $n$. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions. A question consists of printing the label of three distinct leaves $a_{1}, a_{2}, a_{3}$. Let the depth of a node be the shortest distance from the node to the root of the tree. Let $LCA(a, b)$ denote the node with maximum depth that is a common ancestor of the nodes $a$ and $b$. Consider $X = LCA(a_{1}, a_{2}), Y = LCA(a_{2}, a_{3}), Z = LCA(a_{3}, a_{1})$. The judge will tell you which one of $X, Y, Z$ has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties. More specifically, if $X$ (or $Y$, $Z$ respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively). You may only ask at most $10·n$ questions.
Consider building the tree leaf by leaf. The base case of two leaves is trivial. Now, suppose want to add another leaf $w_{i}$. We can define the "centroid" as a tree such that after removing the centroid, all remaining connected components has at most half the number of leaves (note this is different from the standard definition of centroid). Notice, each internal node can be represented as a pair of leaves (x,y), where x comes from the left child, and y comes from the right child. Ask the judge (x,y,w_i). Depending on the response, we can remove the centroid, and know which subtree that w_i lies in (i.e. either the left child, right child, or upper child). So, we can recurse on that tree. So, inserting a node takes log_2 i questions and O(i) time, so overall we ask n log n questions and take n^2 time.
[ "binary search", "divide and conquer", "interactive", "trees" ]
3,200
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ForgottenTree solver = new ForgottenTree(); solver.solve(1, in, out); out.close(); } static class ForgottenTree { public InputReader in; public OutputWriter out; public int nidx; public int n; public int[] par; public void solve(int testNumber, InputReader in, OutputWriter out) { this.in = in; this.out = out; n = in.nextInt(); nidx = n; ForgottenTree.Node root = new ForgottenTree.Node(0); ForgottenTree.Node.cgen = 0; for (int i = 1; i < n; i++) { ForgottenTree.Node.cgen++; root.getLeaves(); root = insert(root, i); } out.println(-1); par = new int[2 * n - 1]; dfs(root, -2); out.println(par); } public String ask(int a, int b, int c) { out.println((a + 1) + " " + (b + 1) + " " + (c + 1)); out.flush(); String ret = in.next(); if (ret.equals("-1")) System.exit(0); return ret; } public void dfs(ForgottenTree.Node root, int p) { par[root.label] = p + 1; if (root.lchild != null) { dfs(root.lchild, root.label); dfs(root.rchild, root.label); } } public ForgottenTree.Node insert(ForgottenTree.Node root, int label) { if (!root.active()) { return add(root, label); } root.dfs(); if (root.lchild == null) { return add(root, label); } int curleaves = root.nleaves; if (curleaves <= 1) { int nnodes = 0; ForgottenTree.Node cur = root; while (!cur.isLeaf()) { nnodes++; if (cur.lchild.active()) cur = cur.lchild; else cur = cur.rchild; } cur = root; int depth = 0; while (2 * (depth + 1) < nnodes) { if (cur.lchild.active()) cur = cur.lchild; else cur = cur.rchild; depth++; } return process(root, cur, label); } ForgottenTree.Node cur = root; while (true) { if (cur.lchild == null) { if (cur.par == null) { return add(cur, label); } if (cur.which == 0) { cur.par.setChild(0, add(cur, label)); return root; } else { cur.par.setChild(1, add(cur, label)); return root; } } int x1 = cur.lchild.active() ? cur.lchild.nleaves : 0; int x2 = cur.rchild.active() ? cur.rchild.nleaves : 0; if (x1 * 2 > curleaves) { cur = cur.lchild; continue; } if (x2 * 2 > curleaves) { cur = cur.rchild; continue; } return process(root, cur, label); } } public ForgottenTree.Node process(ForgottenTree.Node root, ForgottenTree.Node cur, int label) { String s = ask(cur.x, cur.y, label); switch (s) { case "X": if (cur.par == null) { return add(cur, label); } cur.disable(); return insert(root, label); case "Y": cur.setChild(1, insert(cur.rchild, label)); return root; case "Z": cur.setChild(0, insert(cur.lchild, label)); return root; default: throw new RuntimeException(); } } public ForgottenTree.Node add(ForgottenTree.Node cnode, int label) { ForgottenTree.Node add = new ForgottenTree.Node(nidx++); add.setChild(0, cnode); add.setChild(1, new ForgottenTree.Node(label)); return add; } static class Node { public static int cgen; public int x; public int y; public int label; public int gen; public int nleaves; public int which; public ForgottenTree.Node lchild; public ForgottenTree.Node rchild; public ForgottenTree.Node par; public Node(int label) { this.lchild = null; this.rchild = null; this.par = null; this.which = 0; this.label = label; this.gen = 0; this.nleaves = 1; } public boolean active() { return gen < cgen; } public void disable() { this.gen = cgen; } public boolean isLeaf() { return lchild == null || (!lchild.active() && !rchild.active()); } public void setChild(int which, ForgottenTree.Node x) { if (which == 0) { this.lchild = x; } else { this.rchild = x; } x.par = this; x.which = which; } public void dfs() { if (isLeaf()) { this.nleaves = 1; return; } this.nleaves = 0; if (lchild.active()) { lchild.dfs(); this.nleaves += lchild.nleaves; } if (rchild.active()) { rchild.dfs(); this.nleaves += rchild.nleaves; } } public void getLeaves() { if (lchild == null) { this.x = this.y = label; return; } lchild.getLeaves(); rchild.getLeaves(); this.x = lchild.x; this.y = rchild.x; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public String next() { int c; while (isSpaceChar(c = this.read())) { ; } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } public void println(int i) { writer.println(i); } } }
773
A
Success Rate
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made $y$ submissions, out of which $x$ have been successful. Thus, your current success rate on Codeforces is equal to $x / y$. Your favorite rational number in the $[0;1]$ range is $p / q$. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be $p / q$?
This problem can be solved using binary search without any special cases. You can also solve it using a formula, handling a couple of special cases separately. If our success rate is $p / q$, it means we have $pt$ successful submissions out of $qt$ for some $t$. Since $p / q$ is already irreducible, $t$ has to be a positive integer. Let's reformulate things a bit. Initially we have $x$ successful submissions and $y - x$ unsuccessful ones. Suppose we fix $t$, and in the end we want to have $pt$ successful submissions and $qt - pt$ unsuccessful ones. It's clear we can achieve that if $pt \ge x$ and $qt - pt \ge y - x$, since we can only increase both the number of successful and unsuccessful submissions. Note that both inequalities have constant right hand side, and their left hand side doesn't decrease as $t$ increases. Therefore, if the inequalities are satisfied for some $t$, they will definitely be satisfied for larger $t$ as well. It means we can apply binary search to find the lowest value of $t$ satisfying the inequality. Then, the answer to the problem is $qt - y$. If even for very large $t$ the inequalities are not satisfied, the answer is -1. It can be proved that one "very large" value of $t$ is $t = y$ - that is, if the inequalities are not satisfied for $t = y$, then they cannot be satisfied for any value of $t$. Alternatively, picking $t = 10^{9}$ works too, since $y \le 10^{9}$. Actually, inequalities $pt \ge x$ and $qt - pt \ge y - x$ are easy to solve by hand. From $pt \ge x$ it follows that $t\geq{\frac{\alpha}{p}}$. From $qt - pt \ge y - x$ it follows that $t\geq{\frac{y-x}{q-p}}$. In order to satisfy both inequalities, $t$ has to satisfy $t\geq\operatorname*{max}(\frac{x}{p},\frac{y-x}{q-p})$. Don't forget that $t$ has to be integer, so the division results have to be rounded up to the nearest integer. In general, if we want to find $\overset{\stackrel{\wedge}{a}}{b}$ rounded up where both $a$ and $b$ are positive integers, the usual way to do that is to calculate $(a + b - 1) / b$, where "$/$" is the standard integer division (rounded down). In this solution, cases when $p / q = 0 / 1$ or $p / q = 1 / 1$ have to be handled separately.
[ "binary search", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int x, y, p, q; cin >> x >> y >> p >> q; if (p == 0) { cout << (x == 0 ? 0 : -1) << endl; continue; } if (p == q) { cout << (x == y ? 0 : -1) << endl; continue; } int t1 = (x + p - 1) / p; int t2 = ((y - x) + (q - p) - 1) / (q - p); cout << (q * 1LL * max(t1, t2) - y) << endl; } return 0; }
773
B
Dynamic Problem Scoring
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round. $\frac{\left|\frac{\mathrm{Solvers~fraction~}}\mathrm{Maxim~point~value}}{\left|\begin{array}{l}{\mathrm{Soln}\mathrm{xin}\left|\mathrm{pari\value}}\\ {\left(1/2,1/2\right|}\\ {\left[\left.\left.\left(1/3,1/32\right|\right)}\\ {\left(1/4,1/2\right|}\\ {\left[\left.\left[0,1/32\right]}\end{array}\right|}}{\left|\begin{array}{l}{\mathrm{Soln}\right|}\\ {\left|\left.\left.\left.\left.\left|\left.\left.\left.\left|\left.\left|1/3,1/32\right|\right|}\right|}}\\ {\left|\left[\left|\left[\left|\left|\left|\left|\left(1/4,1/2\right|\right)\right|\right|\begin{array}{l}{\mathrm{Jo0}}\\ {\left|\left|\left|\left|\left|\right)}}\\ {\right|\right|\right|}_{\left|\left|\begin{array}{\begin{array}{\begin{array}\right|\right|\right|}}}\\ {{\right|\right|\right|\right|}_{\right|\right|}$ Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to $1 / 4$, and the problem's maximum point value is equal to 1500. If the problem's maximum point value is equal to $x$, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses $x / 250$ points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with $2000·(1 - 40 / 250) = 1680$ points for this problem. There are $n$ participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem. With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing. Unfortunately, Vasya is a cheater. He has registered $10^{9} + 7$ new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved. Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts. Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.
Dynamic problem scoring used to be used more often in Codeforces rounds, including some tournament rounds like VK Cup 2015 Finals. Once you read the problem statement carefully, the problem itself isn't overly difficult. Consider new accounts Vasya puts into play. Correct solutions to which problems does he submit from these new accounts? If Vasya hasn't solved a problem, he can't submit correct solutions to it. If Vasya has solved a problem which Petya hasn't solved, then clearly Vasya wants the maximum point value of this problem to be as high as possible, thus it doesn't make sense to submit its solution from the new accounts. Suppose Vasya solved the problem at minute $v$, Petya solved it at minute $p$ and the problem's maximum point value is $m$, then Vasya's and Petya's scores for this problem are $m \cdot (1 - v / 250)$ and $m \cdot (1 - p / 250)$, respectively. Let's denote the difference between these values by $d = m \cdot (p - v) / 250$. Vasya wants to maximize this value. If $p - v$ is positive (that is, Vasya solved the problem faster than Petya), then $d$ is maximized when $m$ is maximized. To maximize $m$, Vasya shouldn't submit correct solutions to this problem from the new accounts. On the other hand, if $p - v$ is negative (that is, Petya solved the problem faster than Vasya), then $d$ is maximized when $m$ is minimized. To minimize $m$, Vasya should submit correct solutions to this problem from the new accounts. Finally, if $p - v$ is zero (that is, Petya and Vasya solved the problem at the same moment), then $d = 0$ for any value of $m$, so it doesn't matter if Vasya submits correct solutions to this problem or not. It follows from the above that Vasya should always do the same for all new accounts he puts into play. Let's iterate over $x$ - the number of new accounts Vasya puts into play, starting from 0. Then we can determine what solutions Vasya should submit from these accounts using the reasoning above. Then we can calculate the maximum point values of the problems, and then the number of points Vasya and Petya will score. If Vasya's score is higher than Petya's score, then the answer is $x$, otherwise we increase $x$ by one and continue. When do we stop? If Vasya submits solutions to a problem from the new accounts, then after putting at least $n$ accounts into play the maximum point value of this problem will reach 500 and won't change anymore. If Vasya doesn't, then after putting at least $31n$ accounts into play the maximum point value of this problem will reach 3000 and won't change anymore. Therefore, if $x$ exceeds $31n$, we can stop and output -1. Note that we can't find the value of $x$ using binary search due to the fact that Vasya can't submit solutions to the problems he hasn't solved. That is, more accounts do not mean more profit. For example, consider the following test case: If Vasya doesn't use any new accounts, his score will be 1000, while Petya's score will be 500. If Vasya uses at least 61 accounts, both his and Petya's score will be 3000.
[ "brute force", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 123456; const int m = 5; const int k = 6; int a[N][m]; int score[N]; int cost[m]; int solved[m]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", a[i] + j); if (a[i][j] != -1) { solved[j]++; } } } for (int bots = 0; bots <= ((1 << (k - 1)) - 1) * n; bots++) { for (int j = 0; j < m; j++) { int total = n + bots; int cur = solved[j]; if (a[0][j] != -1 && a[1][j] != -1 && a[0][j] > a[1][j]) { cur += bots; } cost[j] = 500; while (cost[j] < 500 * k && 2 * cur <= total) { cur *= 2; cost[j] += 500; } } for (int i = 0; i < 2; i++) { score[i] = 0; for (int j = 0; j < m; j++) { if (a[i][j] != -1) { score[i] += cost[j] / 250 * (250 - a[i][j]); } } } if (score[0] > score[1]) { printf("%d\n", bots); return 0; } } printf("%d\n", -1); return 0; }
773
C
Prairie Partition
It can be shown that any positive integer $x$ can be uniquely represented as $x = 1 + 2 + 4 + ... + 2^{k - 1} + r$, where $k$ and $r$ are integers, $k ≥ 0$, $0 < r ≤ 2^{k}$. Let's call that representation \underline{prairie partition} of $x$. For example, the prairie partitions of $12$, $17$, $7$ and $1$ are: \begin{center} $12 = 1 + 2 + 4 + 5$,$17 = 1 + 2 + 4 + 8 + 2$, $7 = 1 + 2 + 4$, $1 = 1$. \end{center} Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!
This kind of partition sometimes shows up in solutions to knapsack problems with multiple items of the same type. Let's say we want to check if the answer can be $m$. That means we have to construct $m$ chains of powers of 2 like $1, 2, 4, ..., 2^{k - 1}$ (possibly with different values of $k$), and then assign at most one of the remaining elements to each chain so that the element doesn't exceed double the largest power of 2 in its assigned chain. If we can assign all the elements successfully, $m$ is one possible answer. It can be proved that the chains can be constructed greedily one by one, with each chain as long as possible. Let's denote the number of occurrences of integer $x$ in the input by $c(x)$. Then, the number of chains where integer $2^{k}$ can be used is restricted by $bound(2^{k}) = min(c(2^{0}), c(2^{1}), ..., c(2^{k}))$. If we construct the chains greedily, then it's easy to see that the first $bound(2^{k})$ chains will use $2^{k}$. And if we use as many occurrences of powers of 2 as possible, that's better both because we are left with less elements to be assigned to the chains and because the largest powers of 2 in the chains are higher, thus more elements can be assigned to the chains. Having $m$ chains constructed, how do we quickly check if we can assign the remaining elements to these chains? This can also be done greedily. If we can't assign the largest of the remaining elements to the longest chain, then we can't assign this element to any chain, so there's no possible assignment. Otherwise, remove the largest element and the longest chain from consideration, and repeat the process until we either assign all the elements or run into a failure situation described above. Why is greedy correct? Consider a valid assignment where the largest element $E$ is assigned to some chain $c$, and some element $e$ is assigned to the longest chain $C$. If $E \neq e$ and $C \neq c$, it can be seen that we can as well reassign $E$ to $C$ and $e$ to $c$ to get another valid assignment. Thus, if there exists a valid assignment, there also exists one with $E$ assigned to $C$. Implemented straightforwardly, this solution works in $O(n^{2})$. In fact, both factors of $n$ can be optimized. First, it can be seen that if $m$ is one possible answer but there is at least element equal to 1 not yet involved in any chains, then $m + 1$ is another possible answer, since when we construct the $m + 1$-th chain we only make the situation better - we won't have to assigned the elements of this chain to other chains, and we'll have another chain which can be used for assignment too. Therefore, we can perform a binary search on the smallest possible value of $m$, thus having to do $O(\log n)$ assignments instead of $O(n)$. Second, let $a$ be the largest of the input integers. All elements of the input sequence can be distributed into $2\log a$ groups: powers of 2, and integers between consecutive powers of 2. The integers in the groups are effectively indistinguishable from our point of view, which allows us to do the assignment part in $O(\log{a})$. Applying any of these two optimizations was enough to solve the problem.
[ "binary search", "constructive algorithms", "greedy", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; const int MAX = 66; int power[MAX + 10]; int between[MAX + 10]; int extra[MAX + 10]; int ende[MAX + 10]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { long long foo; cin >> foo; int cc = 0; bool good = true; while (foo > 1) { if (foo & 1) { good = false; } cc++; foo >>= 1; } if (good) { power[cc]++; } else { between[cc]++; } } int low = 1, high = power[0] + 1; while (low < high) { int mid = (low + high) >> 1; int cur = mid; for (int i = 0; i < MAX; i++) { extra[i] = power[i] - cur; int new_cur = min(cur, power[i + 1]); ende[i] = cur - new_cur; cur = new_cur; } bool fail = false; int open = 0; for (int i = MAX - 1; i >= 0; i--) { open += ende[i]; open -= between[i]; open -= extra[i + 1]; if (open < 0) { fail = true; break; } } open -= extra[0]; if (open < 0) { fail = true; } if (fail) { low = mid + 1; } else { high = mid; } } if (low > power[0]) { cout << -1 << endl; return 0; } for (int i = low; i <= power[0]; i++) { cout << i << " "; } cout << endl; return 0; }
773
D
Perishable Roads
In the country of Never, there are $n$ cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as $\textstyle{\frac{n(n-1)}{2}}$ roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians. An independent committee has evaluated each road of Never with a positive integer called the \underline{perishability} of the road. The lower the road's perishability is, the more pleasant it is to drive through this road. It's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum. Neverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the \underline{perishability of the route} to be equal to the smallest perishability of all the roads in this route. The government of Never has not yet decided where to build the museum, so they consider all $n$ possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all $n$ possible options of the city where the museum can be built.
This is my favorite problem in this contest. Several clever observations make its solution really simple. First important observation helps understand the optimal structure of the signpost directions. Suppose there are two cities A and B with the signposts directed to the same city C. Without loss of generality, suppose that the road A-C has smaller or equal perishability than the road B-C. Then, if the signpost in city B is redirected to city A instead, perishability of the route from B (as well as from other cities with routes passing through B) to the museum city won't increase. It follows that there exists an optimal solution with at most one signpost directing to each city, so the directions of the signposts form a path ending in the museum city. Second important observation is that there exists a road with the smallest perishability $p$. Let's subtract $p$ from all road perishabilities, and increase the answer by $p \cdot (n - 1)$ in the end. Now, all roads have non-negative perishabilities, and there exists a road with perishability 0. Once our path contains such a road, perishabilities of all routes from cities after this road up the path is equal to 0. More formally, let's denote perishabilities of the roads in the path starting from the museum city as $w_{1}, w_{2}, ..., w_{n - 1}$. The sought sum is then equal to $\sum_{i=1}^{n-1}\operatorname*{min}_{j=1}w_{j}$. It's easy to prove that there exists some $k$ such that $w_{k} = 0$. Indeed, as we go up the path from the museum city, then once we visit an endpoint of any 0-perishability road it's good to follow this 0-perishability road so that route perishabilities of all the remaining cities become 0. Consider an optimal solution, and let $k$ be the smallest index with $w_{k} = 0$. Let's prove that for all $i \le k - 3$ we have $w_{i} > w_{i + 1}$. Indeed, assume that for some $i \le k - 3$ we have $w_{i} \le w_{i + 1}$. Then, since the graph is complete, we can replace the $i + 1$-th edge with an edge directing to an endpoint of any 0-perishability road, and the $i + 2$-th edge with this 0-perishability road. In this case, the minimized sum will become smaller, which is a contradiction to our solution being optimal. Then, we have two options: either $w_{k - 2} > w_{k - 1}$ or $w_{k - 2} \le w_{k - 1}$. If some path of the first type is optimal, then it always coincides with the minimum weight path from the museum city to some city adjacent to a 0-perishability road, and the weight of this path will be the answer. If some path of the second type is optimal, then in this path we first move to some city X, and then use two roads to move to a city adjacent to a 0-perishability road, and we increase the answer by double the weight of the first of these roads as the result of this movement - therefore, first we find the minimum weight path from the museum city to each city X, increase the weight of this path by double the smallest perishability of the roads adjacent to X, and find the answer as the smallest of these values. This gives us an $O(n^{3})$ solution if we run Dijkstra's algorithm from every vertex of the graph to find the answer for it. It can be optimized to $O(n^{2})$ if instead of running Dijkstra's algorithm from every vertex, we run just one instance of Dijkstra's algorithm, initializing the answer for each vertex with double the smallest perishability of an adjacent edge.
[ "dp", "graphs", "shortest paths" ]
2,700
#include <bits/stdc++.h> using namespace std; const long long inf = (long long) 1e18; const int N = 2010; int a[N][N]; long long d[N]; bool used[N]; int main() { // reading input data int n; scanf("%d", &n); for (int i = 0; i < n; i++) { a[i][i] = 0; for (int j = i + 1; j < n; j++) { scanf("%d", a[i] + j); a[j][i] = a[i][j]; } } // finding minimum edge weight int min_edge = a[0][1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { min_edge = min(min_edge, a[i][j]); } } } // subtracting minimum edge weight from all edge weights for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { a[i][j] -= min_edge; } } } // initializing distance array for (int i = 0; i < n; i++) { d[i] = inf; for (int j = 0; j < n; j++) { if (i != j) { d[i] = min(d[i], 2LL * a[i][j]); } } used[i] = false; } // running Dijkstra for (int it = 0; it < n; it++) { long long min_d = inf; int ver = -1; for (int i = 0; i < n; i++) { if (!used[i] && d[i] < min_d) { min_d = d[i]; ver = i; } } used[ver] = true; for (int i = 0; i < n; i++) { d[i] = min(d[i], d[ver] + a[ver][i]); } } // printing result for (int i = 0; i < n; i++) { cout << (d[i] + (long long) min_edge * (n - 1)) << endl; } return 0; }
773
E
Blog Post Rating
It's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over time — its \underline{community rating}. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by +1 or -1. Consider the following model of Codeforces users' behavior. The $i$-th user has his own \underline{estimated blog post rating} denoted by an integer $a_{i}$. When a user visits a blog post page, he compares his estimated blog post rating to its community rating. If his estimated rating is higher, he rates the blog post with +1 (thus, the blog post's community rating increases by 1). If his estimated rating is lower, he rates the blog post with -1 (decreasing its community rating by 1). If the estimated rating and the community rating are equal, user doesn't rate the blog post at all (in this case we'll say that user rates the blog post for 0). In any case, after this procedure user closes the blog post page and never opens it again. Consider a newly created blog post with the initial community rating of 0. For each of $n$ Codeforces users, numbered from 1 to $n$, his estimated blog post rating $a_{i}$ is known. For each $k$ from 1 to $n$, inclusive, the following question is asked. Let users with indices from 1 to $k$, \textbf{in some order}, visit the blog post page, rate the blog post and close the page. Each user opens the blog post only after the previous user closes it. What could be the maximum possible community rating of the blog post after these $k$ visits?
There are several different solutions to this problem, I'll describe one of them. First, we have to determine the optimal rating order for a set of users. Using an exchange argument, it can be shown that to maximize the final community rating the users should rate the blog post in non-decreasing order of their estimated ratings. Indeed, consider an optimal rating order, consider two users with estimated ratings $x$ and $y$ next to each other in this order, and assume that $x > y$. Let's denote the community rating before these two users rate the blog post by $a$. Then here is what happens if these two users rate this blog post in the current and the reverse order: $\left[\begin{array}{l}{\overbrace{\mathrm{Gondition~}}\!\!\!\!\!\!\left[\begin{array}{l l l}{\scriptstyle\mathrm{Order}\;\mathrm{X,\;y}\!\!\!}&{\mathrm{Order\;\;y,\;\;x}}\\ {\mid\mathrm{a<y}<1\!\!\!}&{\displaystyle\mathrm{a+2}\;}\\ {\mid\begin{array}{c}{{\scriptstyle\mathrm{a=x}}}\\ {{\mid\begin{array}{c}{{\mathrm{a=2}}}\\ {{\scriptstyle\mathrm{a}=\mathrm{X}}}\\ {{\mid\begin{array}{c}{{\mathrm{a}}}\\ {{\scriptstyle\mathrm{a}=\mathrm{X}}}\end{array}\right)}}\\ {{\qquad\qquad\qquad\qquad\qquad\mathrm{a+2}}}\\ {{\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\quad\qquad\qquad\quad\qquad\qquad\quad\qquad\qquad\quad\quad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\quad\qquad\qquad\qquad\qquad\qquad\right]}}\\ {\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad}}}}}&{\qquad\qquad\end{array}{\qquad}\qquad}}}\qquad\end{array}\leftend{array}\qquad$ We can see that the $x$, $y$ order is never better than $y$, $x$. That means we can swap these two users in the order and the result won't become worse. We can continue swapping all such pairs of users until we obtain a non-decreasing order. Now, suppose users with estimated ratings $b_{1} \le b_{2} \le ... \le b_{m}$ rate a newly created blog post. For some $x$, the first $x$ users will rate it with -1. It can be seen that the following property will hold for the rest of the users - their estimated ratings will not be lower than the community rating of the blog post at the moment of viewing the page. Thus, all remaining users will rate the blog post with +1 or 0. Let's sort all users according to their estimated rating, and maintain a segment tree which contains, for each user in this order, the difference between his estimated rating and the community rating after his view. Initially, all users are inactive and it looks like they rate the blog post with 0. Then, we'll make users active one by one in order of input. We'll also maintain three sets of active users - those who rate the blog post with +1, 0 and -1, respectively. To make a user active, first we find how he rates the blog post. Then, there are three cases: If he rates the blog post for 0, there is no need to do anything else. If he rates the blog post for -1, the rightmost -1 might change to 0. If it does, we are done. Otherwise, the community rating before users in the "+1 and 0" group has decreased by 1. Thus, the leftmost 0 (if it exists) changes to +1, and we're done. If he rates the blog post for +1, then either there's a user to the right of him whose value in the segment tree becomes negative, in which case the leftmost of these users now rates the blog post for 0 instead of +1, or there's no such user, in which case nothing else changes. All operations above can be performed using queries to our sets of users and segment tree. For example, when a user appears who rated the blog post with +1, we have to insert him into the +1 set and make a query to the segment tree to decrease the value by 1 in the range from this user to the last user. The answer - that is, the maximum possible community rating after the first $k$ users - is the size of the +1 set minus the size of the -1 set.
[ "data structures", "sortings" ]
3,000
#include <bits/stdc++.h> using namespace std; inline int signum(int x) { return (x < 0 ? -1 : (x > 0 ? 1 : 0)); } const int inf = (int) 1e9; const int N = 500010; pair <int, int> a[N]; int pos[N]; pair <int, int> mn[4 * N]; int add[4 * N]; void push(int x) { add[x + x] += add[x]; mn[x + x].first += add[x]; add[x + x + 1] += add[x]; mn[x + x + 1].first += add[x]; add[x] = 0; } void pull(int x) { mn[x] = min(mn[x + x], mn[x + x + 1]); } void build(int x, int l, int r) { add[x] = 0; if (l == r) { mn[x] = make_pair(a[l].first, l); return; } int y = (l + r) >> 1; build(x + x, l, y); build(x + x + 1, y + 1, r); pull(x); } void modify(int x, int l, int r, int ll, int rr, int v) { if (ll <= l && r <= rr) { add[x] -= v; mn[x].first -= v; return; } push(x); int y = (l + r) >> 1; if (ll <= y) { modify(x + x, l, y, ll, rr, v); } if (rr > y) { modify(x + x + 1, y + 1, r, ll, rr, v); } pull(x); } pair <int, int> find_min(int x, int l, int r, int ll, int rr) { if (ll <= l && r <= rr) { return mn[x]; } push(x); int y = (l + r) >> 1; pair <int, int> res = make_pair(inf, -1); if (ll <= y) { res = min(res, find_min(x + x, l, y, ll, rr)); } if (rr > y) { res = min(res, find_min(x + x + 1, y + 1, r, ll, rr)); } pull(x); return res; } int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i].first); a[i].second = i; } sort(a, a + n); for (int i = 0; i < n; i++) { pos[a[i].second] = i; } build(1, 0, n - 1); set <int> minus, zero, plus; for (int id = 0; id < n; id++) { int i = pos[id]; auto p = find_min(1, 0, n - 1, i, i); int vote = signum(p.first); if (vote == 0) { zero.insert(i); } else { if (vote == -1) { minus.insert(i); modify(1, 0, n - 1, i, n - 1, -1); int last_minus = *(--minus.end()); if (a[last_minus].first == 1 - (int) minus.size()) { minus.erase(last_minus); modify(1, 0, n - 1, last_minus, n - 1, 1); zero.insert(last_minus); } else { if (!zero.empty()) { int first_zero = *(zero.begin()); zero.erase(first_zero); plus.insert(first_zero); modify(1, 0, n - 1, first_zero, n - 1, 1); } } } else { plus.insert(i); modify(1, 0, n - 1, i, n - 1, 1); auto q = find_min(1, 0, n - 1, i, n - 1); if (q.first == -1) { int pos = q.second; plus.erase(pos); modify(1, 0, n - 1, pos, n - 1, -1); zero.insert(pos); } } } printf("%d\n", (int) plus.size() - (int) minus.size()); } return 0; }
773
F
Test Data Generation
Test data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness. For example, consider a problem from an old Codeforces round. Its input format looks roughly as follows: {The first line contains a single integer $n$ ($1 ≤ n ≤ max_{n}$) — the size of the set. The second line contains $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i} ≤ max_{a}$) — the elements of the set \textbf{in increasing order}.} If you don't pay attention to the problem solution, it looks fairly easy to generate a good test case for this problem. Let $n = max_{n}$, take random distinct $a_{i}$ from 1 to $max_{a}$, sort them... Soon you understand that it's not that easy. Here is the actual problem solution. Let $g$ be the greatest common divisor of $a_{1}, a_{2}, ..., a_{n}$. Let $x = a_{n} / g - n$. Then the correct solution outputs "Alice" if $x$ is odd, and "Bob" if $x$ is even. Consider two wrong solutions to this problem which differ from the correct one only in the formula for calculating $x$. The first wrong solution calculates $x$ as $x = a_{n} / g$ (without subtracting $n$). The second wrong solution calculates $x$ as $x = a_{n} - n$ (without dividing by $g$). A test case is interesting if it makes \textbf{both} wrong solutions output an incorrect answer. Given $max_{n}$, $max_{a}$ and $q$, find the number of interesting test cases satisfying the constraints, and output it modulo $q$.
This problem was inspired by division 1 problem A from Codeforces Round #201, which I tested: http://codeforces.com/contest/346/problem/A. Several hours before the round, I noticed that all test cases except for the examples were generated randomly. Moreover, there were three cases with $max_{n} = 10$ and $max_{a} = 100$, twenty cases with $max_{n} = 100$ and $max_{a} = 10^{9}$, and that's all. Not surprisingly, all test cases had even $n$ and greatest common divisor equal to 1. The problem statement tells us that interesting test cases have odd $n$, even $a_{n}$, and odd $a_{n} / g$. Suppose that $g$ is divisible by $2^{k}$ and not divisible by $2^{k + 1}$ for some $k \ge 1$. Let's focus on interesting test cases with some fixed value of $k$. We choose integers $a_{1} < a_{2} < ... < a_{n}$ from 1 to $max_{a}$, all divisible by $2^{k}$, with $a_{n}$ not divisible by $2^{k + 1}$. This is equivalent to choosing integers $a_{1} < a_{2} < ... < a_{n}$ from 1 to $b=\lfloor{\frac{m a x_{a}}{2^{k}}}\rfloor$ with $a_{n}$ being odd. Thus, for fixed $k$, the problem asks us to calculate the number of ways to choose at most $max_{n}$, but an odd number, of integers from 1 to $b$ so that the largest chosen number is odd. Let $f(b, n, p)$ be the number of ways to choose exactly $n$ integers from 1 to $b$ so that the largest chosen number has parity $p$ (we define $f(b, 0, 0) = 1$ and $f(b, 0, 1) = 0$). Suppose that for fixed $b$ we have calculated the values of $f(b, n, p)$ for all $n \le max_{n}$ and $p\in\{0,1\}$. Can we calculate all the values of $f(2b, n, p)$ quickly? Yes, we can! Here is a formula which allows us to do that: $f(2b,n,p)=f(b,n,p)+\sum_{i=0}^{n-1}(f(b,i,0)+f(b,i,1))\cdot f(b,n-i,p\oplus(b\mathrm{~mod~2)})$ The first summand corresponds to the case when out of integers from 1 to $2b$, we only choose those from 1 to $b$. In the other case, we iterate over $i$ - the number of integers chosen from 1 to $b$. It follows that we don't care about the parity of the largest of these $i$ integers, but we have $n - i$ integers chosen from $b + 1$ to $2b$, and we know the number of ways to choose those with the largest integer of the required parity (which might change if $b$ is odd). This formula allows us to calculate all the values of $f(2b, n, p)$ in $O(max_{n}^{2})$, but we can still do better. Let $x_{i} = f(b, i, 0) + f(b, i, 1)$ and $y_{i}=f(b,j,p\oplus(b\mathrm{~\mod~}2))$. Then, $f(2b,n,p)-f(b,n,p)+x_{n}\cdot y_{0}=\sum_{i=0}^{n}x_{i}\cdot y_{n-i}$ The right hand side is nothing else but the convolution of sequences $x$ and $y$, so all these values can be calculated in $O(m a x_{n}\log m a x_{n})$ using Fast Fourier Transform. The modulo $q$ given in the input was set to a low enough value so that doing FFT in doubles and rounding the result to the nearest integer gave enough precision. Discrete Fourier Transform with two different modulos can also be used, though it's several times slower. It's also important that, given all the values of $f(b, n, p)$, it's easy to calculate all the values of $f(b + 1, n, p)$ in $O(max_{n})$ time. This means we can calculate the values of $f(b, n, p)$ for any $b$ in $O(m a x_{n}\log m a x_{n}\log b)$ using an idea similar to exponentiation by squaring. Finally, recall that we need to find the values of $f(b, n, p)$ for all $b=\lfloor{\frac{m a x_{a}}{2^{k}}}\rfloor$, that is, for $\log m a x_{a}$ different values of $b$. Doing calculations separately for all $b$ gives a solution which works in $O(m a x_{n}\log m a x_{n}\log^{2}m a x_{a})$. We can do better if we notice that while doing calculations for $b=\lfloor{\frac{m a x_{a}}{2}}\rfloor$, we also do the calculations for all $b=\lfloor{\frac{m a x_{a}}{2^{k}}}\rfloor$ naturally. Thus, we only need $\log m a x_{a}$ convolutions. The final complexity of the solution is $O(r m a x_{n}\log r n a x_{n}\log r m a x_{a})$.
[ "combinatorics", "divide and conquer", "dp", "fft", "math", "number theory" ]
3,400
#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 long double pi = acos((ld)-1.0); const int maxn = 1 << 16; typedef complex<double> comp; comp oddc[maxn], evenc[maxn], tmp[maxn]; comp w[maxn], invw[maxn]; ll odd[maxn], even[maxn]; int oldodd[maxn], oldeven[maxn]; int btr[maxn]; int n, A, mod; int st2; int answer; inline int bitrev(int x) { return btr[x]; } void fft(comp *a, int n, comp *w, comp *res) { for (int i = 0; i < n; i++) res[bitrev(i)] = a[i]; for (int len = 2; len <= n; len *= 2) { int step = n / len; for (int i = 0; i < n; i += len) { int curw = 0; for (int j = 0; j < len / 2; j++) { comp x = res[i + j]; comp y = res[i + len / 2 + j] * w[curw]; res[i + j] = x + y; res[i + len / 2 + j] = x - y; curw += step; } } } } void preparefft(int n) { for (int i = 0; i < n; i++) { int cur = i; for (int j = 0; (1 << j) < n; j++) { btr[i] = (btr[i] << 1) | (cur & 1); cur >>= 1; } } for (int i = 0; i < n; i++) { w[i] = comp(cos(2 * pi / n * i), sin(2 * pi / n * i)); invw[i] = w[i]; } reverse(invw + 1, invw + n); } void conv(ll *from, comp *to) { for (int i = n + 1; i < st2; i++) tmp[i] = 0; for (int i = 0; i <= n; i++) tmp[i] = from[i]; fft(tmp, st2, w, to); } void convback(comp *from, ll *to) { fft(from, st2, invw, tmp); for (int i = 0; i < st2; i++) tmp[i] /= st2; for (int i = 0; i <= n; i++) { to[i] = (ll)(tmp[i].real() + 0.5); assert(abs(tmp[i].imag()) < 0.1); } } void addans() { for (int i = 1; i <= n; i += 2) answer = (answer + odd[i]) % mod; } void go(int A) { if (A == 1) { even[0] = 1; odd[0] = 0; odd[1] = 1; addans(); return; } go(A / 2); for (int i = 0; i <= n; i++) oldodd[i] = odd[i]; for (int i = 0; i <= n; i++) oldeven[i] = even[i]; conv(even, evenc); conv(odd, oddc); for (int i = 0; i < st2; i++) { if ((A / 2) % 2 == 0) { tie(oddc[i], evenc[i]) = make_pair((oddc[i] + evenc[i]) * oddc[i], (oddc[i] + evenc[i]) * (evenc[i] - (comp)1)); } else { tie(evenc[i], oddc[i]) = make_pair((oddc[i] + evenc[i]) * oddc[i], (oddc[i] + evenc[i]) * (evenc[i] - (comp)1)); } } convback(oddc, odd); convback(evenc, even); for (int i = n + 1; i <= 2 * n; i++) { odd[i] = 0; even[i] = 0; } for (int i = 0; i <= n; i++) { odd[i] = (odd[i] + oldodd[i]) % mod; even[i] = (even[i] + oldeven[i]) % mod; } if (A % 2 == 1) { for (int i = n; i >= 1; i--) { odd[i] = (odd[i] + odd[i - 1] + even[i - 1]) % mod; } } addans(); } int main() { cin >> n >> A >> mod; if (A == 1) { cout << 0 << endl; return 0; } st2 = 0; while ((1 << st2) <= n) st2++; st2++; st2 = 1 << st2; preparefft(st2); go(A / 2); cout << answer << endl; return 0; }
776
A
A Serial Killer
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim. You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.
You just have to store the current two strings. This can simply be done by replacing the string to be deleted with the new string. This can be done in O(n)
[ "brute force", "implementation", "strings" ]
900
#include <algorithm> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #ifdef PRINTERS #include "printers.hpp" using namespace printers; #define tr(a) cerr<<#a<<": "<<a<<endl; #else #define tr(a) #endif #define ll long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define sz(x) (int)x.size() #define hell 1000000007 #define endl '\n' #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; void solve(){ string a,b; cin>>a>>b; vector<string>taken; int n; cin>>n; rep(i,0,n){ cout<<a<<" "<<b<<endl; string c,d; cin>>c>>d; if(c==a)a=d; else b=d; } cout<<a<<" "<<b<<endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t=1; while(t--){ solve(); } return 0; }
776
B
Sherlock and his girlfriend
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought $n$ pieces of jewelry. The $i$-th piece has price equal to $i + 1$, that is, the prices of the jewelry are $2, 3, 4, ... n + 1$. Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used. Help Sherlock complete this trivial task.
Hint: Observe that if $i + 1$ is prime, then only would the pieces having their prices as the multiples of $i + 1$ would have to be of a different color. Editorial: We are required to color the jewelry pieces such that for every jewelry piece $i$ having a price $i + 1$, all the pieces whose prices are prime divisors of $i + 1$ should have colors different from that of the $i$th piece. This can be achieved by simply coloring all the pieces with their prices as primes in one color, and all the other pieces in a second color. We calculate the Sieve of Eratosthenes upto the range of $n( \le 10^{5})$ and thus, obtain the list of primes as well as non-primes.
[ "constructive algorithms", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; int sieve[100005]; int main() { int i, n, j; cin>>n; for(i=2; i<=n+1; i++) { if(!sieve[i]) for(j=2*i; j<=n+1; j+=i) sieve[j]=1; } if(n>2) cout<<"2\n"; else cout<<"1\n"; for(i=2; i<=n+1; i++) { if(!sieve[i]) cout<<"1 "; else cout<<"2 "; } return 0; }
776
C
Molly's Chemicals
Molly Hooper has $n$ different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The $i$-th of them has affection value $a_{i}$. Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative \textbf{integer} power of $k$. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment. Help her to do so in finding the total number of such segments.
Hint: The number of possible powers will be less than 50 for any $k$. Editorial: We are going to loop over all possible non-negative powers of $k$. Since the maximum possible value of subarray sum can be $10^{5} \times 10^{9} = 10^{14}$, there can be at most $\lfloor\log_{2}10^{14}\rfloor+1$ possible powers that can be the sum of subarrays. Let $p[i]$ be the sum of elements from index $1$ to index $i$. We can precalculate $p[i]$ in $O(n)$ time complexity. (Prefix sum) We will try to find the count of subarrays starting from index $l$. The sum of any such subarray ending at index $r$ can be written as $p[r] - p[l - 1]$. Now, $p[r]-p[l-1]=w\implies p[r]=w+p[l-1]$ where $w$ is a power of $k$. We have to count the values of $r \ge l$ such that $p[r] = w + p[l - 1]$. For this part, we can store the count of $p[r]$ in a dictionary as we move from right of the array and use the dictionary to find count of $p[r]$ for corresponding $p[l]$ and $w$. PS: Do take care of a corner case for $k = \pm 1$ while calculating powers of $k$.
[ "binary search", "brute force", "data structures", "implementation", "math" ]
1,800
#include <algorithm> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #ifdef PRINTERS #include "printers.hpp" using namespace printers; #define tr(a) cerr<<#a<<": "<<a<<endl; #else #define tr(a) #endif #define ll long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define sz(x) (int)x.size() #define hell 1000000007 #define endl '\n' #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; void solve(){ int N,k; scanf("%d%d",&N,&k); ll x[N+1]; x[0]=0; rep(i,0,N)scanf("%lld",&x[i+1]); partial_sum(x,x+N+1,x); if(k==1){ ll ans=0; map<ll,int>m; for(int i=N;i>=0;i--){ if(m.find(x[i]+1)!=m.end()) ans+=m[x[i]+1]; m[x[i]]++; } printf("%lld\n",ans); } else if(k==-1){ ll ans=0; map<ll,int>m; for(int i=N;i>=0;i--){ if(m.find(x[i]+1)!=m.end()) ans+=m[x[i]+1]; if(m.find(x[i]-1)!=m.end()) ans+=m[x[i]-1]; m[x[i]]++; } printf("%lld\n",ans); } else{ ll ans=0; map<ll,int>m; for(int i=N;i>=0;i--){ ll cur=1; while(true){ if(abs(cur)>=1e15)break; if(m.find(x[i]+cur)!=m.end()) ans+=m[x[i]+cur]; cur*=k; } m[x[i]]++; } printf("%lld\n",ans); } } signed main(){ int t=1; while(t--){ solve(); } return 0; }
776
D
The Door Problem
Moriarty has trapped $n$ people in $n$ distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are $m$ switches. Each switch control doors of some rooms, but each door is controlled by \textbf{exactly two} switches. You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch $1$, which was connected to room $1$, $2$ and $3$ which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked. You need to tell Sherlock, if there exists a way to unlock all doors at the same time.
Hint : Try to model the situation as a graph with rooms as edges and switches as nodes. Editorial : All rooms are represented as edges. Mark the edges as $1$ if the room is open else mark the edge as closed. The answer will be "YES" if you can color the graph in such a manner that the edges having value $0$ have both nodes under different color (if the door is locked then one of the switches should be selected) and the edges having $1$ have both nodes under same color (if the door is unlocked you should either select both switches or neither of them). For checking the same start a bfs from switch $1$ and toggle it and proceed, if you are able to color all of the switches then the answer is "YES" else it is not possible. Complexity: $O(N + M)$ See the setter's solution for implementation details.
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
2,000
#include <bits/stdc++.h> using namespace std; #define mem(x,y) memset(x,y,sizeof(x)) #define bitcount __builtin_popcountll #define mod 1000000007 #define N 1000009 #define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ss(s) cin>>s; #define si(x) scanf("%d",&x); #define sl(x) cin>>x; #define pb push_back #define mp make_pair #define all(v) v.begin(),v.end() #define S second #define F first #define ll long long int n,m; vector<int> arr[N]; int arr1[N]; vector<pair<int,int > > adj[100008]; //max-size void graph(int n){for(int i=1;i<=n;i++){ int x = arr[i][0]; int y = arr[i][1]; adj[x].push_back(mp(y,arr1[i] )); //arr1[i] stores th color of the edge adj[y].push_back(mp(x,arr1[i]) );} } int col[N]; bool vis[N]; int main(){ //fast //uncomment on submission cin>>n>>m; assert(n>=2 && n<=100000); assert(m>=2 && m<=100000); for(int i =1;i<=n;i++)cin >> arr1[i]; for(int i = 1;i<=m;i++){ int sz; cin >> sz; for(int j =0;j<sz;j++){ int y ; cin >> y; arr[y].push_back(i); } } graph(n); mem(col,-1); mem(vis,false); bool p = true; for(int i = 1;i<=m;i++){ if(!vis[i] && adj[i].size()){ col[i] = 0; vis[i] = true; queue <int > q; q.push(i); while(q.size()){ int node = q.front(); q.pop(); for(auto pi:adj[node]){ int co = col[node]; if(pi.S == 0){ //if the edge is 0 then give the opposite color. co = 1 - co; } if(vis[pi.F] && col[pi.F] != co){ p = false; } if(!vis[pi.F]){ col[pi.F] = co; vis[pi.F] = true; q.push(pi.F); } } } } } if(!p)cout<<"NO"; else cout<<"YES"; }
776
E
The Holmes Children
The Holmes children are fighting over who amongst them is the cleverest. Mycroft asked Sherlock and Eurus to find value of $f(n)$, where $f(1) = 1$ and for $n ≥ 2$, $f(n)$ is the number of distinct ordered positive integer pairs $(x, y)$ that satisfy $x + y = n$ and $gcd(x, y) = 1$. The integer $gcd(a, b)$ is the greatest common divisor of $a$ and $b$. Sherlock said that solving this was child's play and asked Mycroft to instead get the value of $g(n)=\sum_{d\mid n}f(n/d)$. Summation is done over all positive integers $d$ that divide $n$. Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft. She defined a $k$-composite function $F_{k}(n)$ recursively as follows: \[ F_{k}(n)=\left\{\begin{array}{l}{{f(g(n)),}}\\ {{g(F_{k-1}(n)),~~\mathrm{for}~k>1~\mathrm{and}~k~\mathrm{mod}~2=0,}}\\ {{f(F_{k-1}(n)),~~\mathrm{for}~k>1~\mathrm{and}~k~\mathrm{mod}~2=1.}}\end{array}\right. \] She wants them to tell the value of $F_{k}(n)$ modulo $1000000007$.
Hint: For $n = 10$, the pairs satisfying the conditions are $(1, 9), (3, 7), (7, 3), (9, 1)$. The first members of each pair form the set ${1, 3, 7, 9}$. Similarly, for $n = 12$, the corresponding set is ${1, 5, 7, 11}$. Also, observe that $f(n) = n - 1$ whenever $n$ is a prime. Editorial: Given, $x+y=N{\mathrm{~and~}}g c d(x,y)=1$ $\Rightarrow g c d(x,n-x)=1$ $\Rightarrow g c d(x,n)=1$ $\Rightarrow{\textbf{x i s c o p r i m e t o n}}$ Now,let's prove the converse. Let $x$ be coprime to $n$ and $y = n - x$. Let $gcd(x, y) = k \neq 1$ $\Rightarrow{\mathrm{k~divides~both~x~and~n}}$ $\Rightarrow{\mathrm{k~divides~n}}$ $\Rightarrow{\mathrm{k~divides~both~x~and~n~which~is~a~contradiction}}$ $\Rightarrow g c d(x,y)=1$ Thus, number of distinct ordered pairs (x,y) satisfying the conditions= $ \phi (n)$ where $ \phi $() denotes Euler totient function. Now,$g(n)=\sum_{d\mid n}\phi(n/d)$. Let $S$ denote the set ${1, 2, ..., n}$. We distribute the integers of $S$ into disjoint sets as follows. For each divisor d of n, let $A(d) = {k \in S: gcd(k, n) = d}$.The sets $A(d)$ form a disjoint collection whose union is $S$. Let $n(A(d))$ denote the number of integers in $A(d)$. If $k$ is a number in $A(d)$, then $k = d * m$ for some $m$ coprime to $n / d$. There are $ \phi (n / d)$ such $m$ in the interval $[1, n]$. Hence, $n(A(d)) = \phi (n / d)$. Since the sets $A(d)$ are disjoint, $\textstyle\sum_{d\mid n}n(A(d))=n$ $\Rightarrow\sum_{d|n}\phi(n/d)=n$ $\Rightarrow g(n)=n$ So, we only need to consider the number of times we apply $f()$ in $F_{k}$ which is $(k + 1) / 2$ for a given $k$. Now, let us consider the numbers in the set ${1, 2, ..., 2n}$. There are exactly $n$ even and $n$ odd numbers in the set. The $n$ even numbers can never be coprime to $2n$. So, $ \phi (2n) \le n$. Thus, we need to calculate $ \phi ()$ at most $log(n)$ times. Complexity: $O({\sqrt{n}}*l o g(n))$
[ "math", "number theory" ]
2,100
#include <bits/stdc++.h> using namespace std; #define ll long long #define MOD 1000000007 #define ll long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define endl '\n' #define PI 3.14159265359d #define sz(x) (int)x.size() ll phi(ll n) { ll i,res=n; for(i=2;i*i<=n;i++) if(n%i==0) { while(n%i==0) n/=i; res-=res/i; } if(n>1) res-=res/n; return res; } int main() { ll n,k,res; cin>>n>>k; res=n; k=(k+1)/2; while(k--) { res=phi(res); if(res==1) break; } cout<<res%MOD; return 0; }
776
F
Sherlock's bet to Moriarty
Sherlock met Moriarty for a final battle of wits. He gave him a regular $n$ sided convex polygon. In addition to it, he gave him certain diagonals to form regions on the polygon. It was guaranteed that the diagonals did not intersect in interior points. He took each of the region and calculated its importance value. Importance value for a region formed by vertices $a_{1}, a_{2}, ... , a_{x}$ of the polygon will be given by $2^{a1} + 2^{a2} + ... + 2^{ax}$. Then, he sorted these regions on the basis of their importance value in ascending order. After that he assigned each region an index from $1$ to $k$, where $k$ is the number of regions, and index of region is its position in the sorted array calculated above. He wants Moriarty to color the regions using not more than $20$ colors, such that two regions have same color only if all the simple paths between these two regions have at least one region with color value less than the color value assigned to these regions. Simple path between two regions $f$ and $h$ is a sequence of regions $r_{1}, r_{2}, ... r_{t}$ such that $r_{1} = f$, $r_{t} = h$, for each $1 ≤ i < t$ regions $r_{i}$ and $r_{i + 1}$ share an edge, and $r_{i} = r_{j}$ if and only if $i = j$. Moriarty couldn't answer and asks Sherlock to solve it himself. Help Sherlock in doing so.
Hint: Observe that if we consider all regions as nodes for a graph and connect two regions if they share an edge (in the form of sharing a diagonal), we will get a tree. Editorial: Use a greedy approach to form a tree from the given polygon. Let us take one diagonal between vertex $a$ and $b$ $(b > a)$. Let us define a value $x$ as minimum of two values $b - a - 1$ and $n - 2 - (b - a - 1)$. Sort all the diagonals on the basis of this value $x$. This value is the minimum number of nodes between $a$ and $b$. Remove the diagonals one by one. We can see that a new region will be formed each time which cannot be divided further, and this region will be formed on the side from where we got the value of $x$. Thus we can get the nodes in each region and form a tree. Then, this problem reduces to coloring the tree such that two regions have same color only if atleast one node between the two nodes with same color has a color with lesser value. This can be done by using the divide and conquer technique of centroid decomposition. Give each height in centroid tree a different color in increasing order. Complexity: $O(n * log(n))$
[ "constructive algorithms", "data structures", "divide and conquer", "geometry", "graphs", "implementation", "trees" ]
2,800
#include<bits/stdc++.h> using namespace std; #define sd(x) scanf("%d",&x) #define slld(x) scanf("%lld",&x) #define ss(x) scanf("%s",x) #define ll long long #define mod 1000000007 #define bitcount __builtin_popcountll #define pb push_back #define fi first #define se second #define mp make_pair #define pi pair<int,int> pi arr[100005]; int n,m; bool cmp(pi x, pi y) { int a=min(x.se-x.fi-1,n-2-(x.se-x.fi-1)); int b=min(y.se-y.fi-1,n-2-(y.se-y.fi-1)); return a<b; } vector<int>nodes[100005]; vector<int>v[100005],v2[100005]; int de[100005],siz[100005]; void dfs1(int node, int par) { siz[node]=1; for(int i=0;i<v[node].size();i++) { if(de[v[node][i]]==0&&v[node][i]!=par) { dfs1(v[node][i],node); siz[node]+=siz[v[node][i]]; } } } int dfs2(int node, int par,int s) { int maxi=0,maxinode; for(int i=0;i<v[node].size();i++) { if(de[v[node][i]]==0&&v[node][i]!=par&&siz[v[node][i]]>s/2) { return dfs2(v[node][i],node,s); } } //printf("%d\n",node ); return node; } int decompose(int node) { dfs1(node,-1); int cen=dfs2(node,-1,siz[node]); // printf("%d\n",cen ); de[cen]=1; for(int i=0;i<v[cen].size();i++) { if(de[v[cen][i]]==0) { int x=decompose(v[cen][i]); //printf("%d\n", x); v2[cen].pb(x); v2[x].pb(cen); } } return cen; } int level[100005]; int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int i,j,k; sd(n); sd(m); for(i=1;i<=m;i++) { sd(arr[i].fi); sd(arr[i].se); if(arr[i].fi>arr[i].se) { swap(arr[i].fi,arr[i].se); } } sort(arr+1,arr+m+1,cmp); set<int>s; for(i=1;i<=n;i++) s.insert(i); k=0; for(i=1;i<=m;i++) { if(arr[i].se-arr[i].fi-1<=n-2-(arr[i].se-arr[i].fi-1)) { nodes[k].pb(arr[i].fi); set<int>::iterator it=s.upper_bound(arr[i].fi); while((*it)!=arr[i].se) { nodes[k].pb(*it); it++; } nodes[k].pb(arr[i].se); for(j=1;j<nodes[k].size()-1;j++) s.erase(nodes[k][j]); } else { while(*s.begin()!=arr[i].fi) { nodes[k].pb(*s.begin()); s.erase(s.begin()); } nodes[k].pb(arr[i].fi); nodes[k].pb(arr[i].se); int l=nodes[k].size(); set<int>::iterator it=s.upper_bound(arr[i].se); while(it!=s.end()) { nodes[k].pb(*it); it++; } for(;l<nodes[k].size();l++) s.erase(nodes[k][l]); } reverse(nodes[k].begin(), nodes[k].end()); k++; } while(s.size()!=0) { nodes[k].pb(*s.begin()); s.erase(s.begin()); } reverse(nodes[k].begin(), nodes[k].end()); k++; sort(nodes,nodes+k); map<pi,int>m1; for(i=0;i<k;i++) { for(j=0;j<nodes[i].size()-1;j++) { if(nodes[i][j]==nodes[i][j+1]+1) continue; else if(m1.find(mp(nodes[i][j],nodes[i][j+1]))!=m1.end()) { v[m1[mp(nodes[i][j],nodes[i][j+1])]].pb(i+1); v[i+1].pb(m1[mp(nodes[i][j],nodes[i][j+1])]); m1.erase(mp(nodes[i][j],nodes[i][j+1])); } else { m1[mp(nodes[i][j],nodes[i][j+1])]=i+1; } } j=nodes[i].size()-1; if(nodes[i][0]!=n||nodes[i][j]!=1) { if(m1.find(mp(nodes[i][0],nodes[i][j]))!=m1.end()) { v[m1[mp(nodes[i][0],nodes[i][j])]].pb(i+1); v[i+1].pb(m1[mp(nodes[i][0],nodes[i][j])]); m1.erase(mp(nodes[i][0],nodes[i][j])); } else { m1[mp(nodes[i][0],nodes[i][j])]=i+1; } } } for(i=1;i<=n;i++) level[i]=1e6; int cen=decompose(1); //printf("%d\n",cen ); queue<int>q; i=0; q.push(cen); while(!q.empty()) { j=q.size(); while(j--) { int z=q.front(); q.pop(); level[z]=i; for(int l=0;l<v2[z].size();l++) { if(level[v2[z][l]]==1e6) { q.push(v2[z][l]); } } } i++; } for(i=1;i<=k;i++){ //printf("%d %d\n",v2[i].size(),level[i] ); printf("%d",level[i]+1 ); if(i!=k) printf(" "); } printf("\n"); return 0; }
776
G
Sherlock and the Encrypted Data
Sherlock found a piece of encrypted data which he thinks will be useful to catch Moriarty. The encrypted data consists of two integer $l$ and $r$. He noticed that these integers were in hexadecimal form. He takes each of the integers from $l$ to $r$, and performs the following operations: - He lists the distinct digits present in the given number. For example: for $1014_{16}$, he lists the digits as $1, 0, 4$. - Then he sums respective powers of two for each digit listed in the step above. Like in the above example $sum = 2^{1} + 2^{0} + 2^{4} = 19_{10}$. - He changes the initial number by applying bitwise xor of the initial number and the sum. Example: $1014_{16}\oplus19_{10}=4116_{10}\oplus19_{10}=4103_{10}$. Note that xor is done in binary notation. One more example: for integer 1e the sum is $sum = 2^{1} + 2^{14}$. Letters a, b, c, d, e, f denote hexadecimal digits $10$, $11$, $12$, $13$, $14$, $15$, respertively. Sherlock wants to count the numbers in the range from $l$ to $r$ (both inclusive) which decrease on application of the above four steps. He wants you to answer his $q$ queries for different $l$ and $r$.
Hint: This problem can be solved using dynamic programming approach by maintain dp for mask of digits appearing in the number($mask1$) along with position in the number($l$) and mask of last $16$ bits($mask2$) of the number formed upto $l$. Editorial: Observe that only the most significant bit of the $mask1$ is required to check if the number will decrease or not. So, form a $dp[most: significant: bit: of: mask1][mask2][len]$. Complexity: $O(16 * 2^{16} * 16 * 16)$
[ "bitmasks", "combinatorics", "dp" ]
2,900
#include<bits/stdc++.h> using namespace std; #define sd(x) scanf("%lld",&x) #define slld(x) scanf("%lld",&x) #define ss(x) scanf("%s",x) #define ll long long #define mod 65536 #define bitcount __builtin_popcountll #define pb push_back #define fi first #define se second #define mp make_pair #define pi pair<int,int> ll dp[17][65538][17]; char a[20]; ll b[20]; ll mo[1100005]; ll f(ll m,ll p,ll pos) { if(dp[m][p][pos]!=-1) return dp[m][p][pos]; if(pos==0) { if(((1<<m)&p)) dp[m][p][pos]=1; else dp[m][p][pos]=0; return dp[m][p][pos]; } ll j=0; for(ll i=0;i<=15;i++) { j+=f(max(m,i),mo[p*16+i],pos-1); } return dp[m][p][pos]=j; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); ll t,n,i,j,k,l,r,m,p,ans1; mo[0]=0; for(i=1;i<=1100000;i++) { mo[i]=mo[i-1]+1; if(mo[i]==mod) mo[i]=0; } memset(dp,-1,sizeof dp); f(0,0,16); sd(t); while(t--) { ss(a); n=strlen(a); l=0; for(i=0;i<n;i++) { l=l*16; if(a[i]>='0'&&a[i]<='9') l+=a[i]-'0'; else l+=a[i]-'a'+10; } ans1=0; if(l>0) { l--; j=l; for(i=0;i<n;i++) { b[i]=j%16; j/=16; } m=p=0; for(j=n-1;j>=0;j--) { for(k=0;k<b[j];k++) ans1-=dp[max(m,k)][mo[p*16+k]][j]; m=max(m,b[j]); p=mo[p*16+b[j]]; } ans1-=dp[m][p][0]; } ss(a); n=strlen(a); r=0; for(i=0;i<n;i++) { r=r*16; if(a[i]>='0'&&a[i]<='9') r+=a[i]-'0'; else r+=a[i]-'a'+10; } j=r; for(i=0;i<n;i++) { b[i]=j%16; j/=16; } m=p=0; for(j=n-1;j>=0;j--) { for(k=0;k<b[j];k++) ans1+=dp[max(m,k)][mo[p*16+k]][j]; m=max(m,b[j]); p=mo[p*16+b[j]]; } ans1+=dp[m][p][0]; printf("%lld\n",ans1); } return 0; }
777
A
Shell Game
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball. Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.). Let's number shells from $0$ to $2$ from left to right. Thus the left shell is assigned number $0$, the middle shell is $1$ and the right shell is $2$. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly $n$ movements were made by the operator and the ball was under shell $x$ at the end. Now he wonders, what was the initial position of the ball?
Fix the initial numeration of shells. Consider function $p(i, j)$ to be the index of the shell located at position $j$ after $i$ moves. $p(0) = {0, 1, 2}$ $p(1) = {1, 0, 2}$ $p(2) = {1, 2, 0}$ $p(3) = {2, 1, 0}$ $p(4) = {2, 0, 1}$ $p(5) = {0, 2, 1}$ $p(6) = {0, 1, 2}$ Thus, after $6$ movements all shells will get back to initial positions. To solve the problem we need to take $n$ modulo $6$ and simulate that number of moves.
[ "constructive algorithms", "implementation", "math" ]
1,000
null
777
B
Game of Credit Cards
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite $n$-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if $n = 3$, Sherlock's card is $123$ and Moriarty's card has number $321$, first Sherlock names $1$ and Moriarty names $3$ so Sherlock gets a flick. Then they both digit $2$ so no one gets a flick. Finally, Sherlock names $3$, while Moriarty names $1$ and gets a flick. Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name $1$, $2$, $3$ and get no flicks at all, or he can name $2$, $3$ and $1$ to give Sherlock two flicks. Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
First we want to consider a strategy that minimizes the amount of flicks Moriarty will receive from Sherlock. This is similar to loosing as few rounds as possible. He can use digit 0 can be used to not loose against digit 0, digit 1 to not loose against digits 0 and 1 and so on. Thus, Moriarty should try all digits from 0 to 9 and greedily apply them to Sherlock's digits they can beat. If the maximum number of rounds Moriarty can not loose is $a$ the answer for the first question is $n - a$. For the second question we need to count the maximum number of rounds Moriarty can win. Now digit 0 is useless, digit 1 wins against digit 0, digit 2 wins against digits 0 and 1, and so on. Thus, Moriarty should consider his digits from 0 to 9 and greedily use them to digits they can beat.
[ "data structures", "dp", "greedy", "sortings" ]
1,300
null
777
C
Alyona and Spreadsheet
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. Now she has a table filled with integers. The table consists of $n$ rows and $m$ columns. By $a_{i, j}$ we will denote the integer located at the $i$-th row and the $j$-th column. We say that the table is sorted in non-decreasing order in the column $j$ if $a_{i, j} ≤ a_{i + 1, j}$ for all $i$ from $1$ to $n - 1$. Teacher gave Alyona $k$ tasks. For each of the tasks two integers $l$ and $r$ are given and Alyona has to answer the following question: if one keeps the rows from $l$ to $r$ inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such $j$ that $a_{i, j} ≤ a_{i + 1, j}$ for all $i$ from $l$ to $r - 1$ inclusive. Alyona is too small to deal with this task and asks you to help!
For each cell $(i, j)$ compute value $up(i, j)$ equal to maximum $r$, such that table is non-decreasing in row $j$ if we keep only rows from $i$ to $r$ inclusive. This values can be computed in $O(nm)$ time using the following formulas: $up(i, j) = up(i + 1, j) + 1$, if $i < n$ and $a_{i, j} < a_{i + 1, j}$; $up(i, j) = 1$ otherwise. To process the query $(l_{i}, r_{i})$ we have to check whether there exists $k$ such that $up(l_{i}, k) \ge r_{i}$. We will answer this questions using by precomputing maximum values in each row $b e s t(i)=\operatorname*{max}_{j=1}u p(i,j)$.
[ "binary search", "data structures", "dp", "greedy", "implementation", "two pointers" ]
1,600
null
777
D
Cloud of Hashtags
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it \textbf{without} the symbol '#'. The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition). Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is \textbf{minimum} possible. If there are several optimal solutions, he is fine with any of them.
It is possible to solve this problem in many ways. One of them was to iterate over all strings in reversed order and to try to leave the longest possible prefix of each string greedily without breaking the statement. Let's prove this solution formally. Note that the set of possible lengths of some string $s_{i}$ in a correct answer forms a segment between $1$ and some critical length $l_{i}$. Indeed, if there exists a correct answer with $i$-string having a length of $x \ge 2$, then there also exists an answer with $i$-th string having a length of $x - 1$, since it is possible to leave only the first symbol of all previous strings and make the answer correct. Let's express $l_{i}$ through $l_{i + 1}$. Reduce the length of $(i + 1)$-st string to $l_{i + 1}$ and consider two options. First, $s_{i}$ may be lexicographically not greater than $s_{i + 1}$, and in this case we may obviously let $l_{i}$ be equal to $|s_{i}|$. Otherwise, $l_{i}$ can't be larger than $lcp(s_{i}, s_{i + 1})$ where $lcp$ deontes the length of the longest common prefix of two strings (if we keep $s_{i}$ longer, it will be larger than any possible prefix of $s_{i + 1}$). At the same time, if we reduce $s_{i}$ up to $lcp(s_{i}, s_{i + 1})$, it will be correct. So, we may let $l_{i}$ be equal to $lcp(s_{i}, s_{i + 1})$. Note that due to the way we defined $l_{i}$, if we just reduce any string up to its maximum possible length, it will also be a correct answer. So, it is also a correct answer to the original problem.
[ "binary search", "greedy", "implementation", "strings" ]
1,800
null
777
E
Hanoi Factory
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings. There are $n$ rings in factory's stock. The $i$-th ring has inner radius $a_{i}$, outer radius $b_{i}$ and height $h_{i}$. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied: - Outer radiuses form a non-increasing sequence, i.e. one can put the $j$-th ring on the $i$-th ring only if $b_{j} ≤ b_{i}$. - Rings should not fall one into the the other. That means one can place ring $j$ on the ring $i$ only if $b_{j} > a_{i}$. - The total height of all rings used should be maximum possible.
To start with make the following observation: if two rings $i$ and $j$ have equal outer radiuses $b_{i} = b_{j}$ they can be merged in one ring of the same outer radius, inner radius equal to $min(a_{i}, a_{j})$ and height equal to $h_{i} + h_{j}$. Using the observation we transform our problem to the one with distinct outer radiuses. Sort ring by this radius in descending order. From this point we consider $b_{i} < b_{j}$ for all $i > j$. For each ring we want to compute value $ans(i)$ - maximum height of the tower that ends with the ring $i$. This dynamic programming can be computed in $O(n^{2})$ time using the following formula: $a n s(i)=\operatorname*{max}_{j<i,a_{i}<b_{i}}a n s(j)+h_{i}$. There are two different ways to speed up the calculation of this dp: Keep rings sorted by inner radius in a separate array. For each ring $j < i$ store its value of $ans(j)$ there and $0$ for others. To get $max ans(j)$ we have to query maximum on some suffix of this array: from the one hand only rings with original index $j < i$ will be non-zero, from the other hand this will suffice the condition $b_{i} > a_{j}$. This can be done using segment tree or binary indexed tree. Note that if $i < j < k$ and it's possible to place ring $k$ on ring $j$ and ring $k$ on ring $i$, then it's possible to place ring $j$ on ring $i$. Indeed, from $a_{i} < b_{k}$ and $b_{k} < b_{j}$ follows $a_{i} < b_{j}$. That means we only need to compute for each $i$ maximum value $j$ such that $a_{j} < b_{i}$. This can be done using data structures listed above or just with a single pass over array with a stack. Go from left to right and keep indexes of all valid positions in increasing order. Pop elements while they do not suffice condition $a_{j} < a_{i}$ and then put $i$ on the top. For clarifications, check the following code: stack <int> opt; for (int i = 0; i < n; i++) { while (!opt.empty() && r[opt.back()].inner >= r[i].outer) opt.pop(); if (!opt.empty()) ans[i] = ans[opt.back()]; ans[i] += r[i].height; opt.push(i); }
[ "brute force", "data structures", "dp", "greedy", "sortings" ]
2,000
null
778
A
String Game
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word $t$ and wants to get the word $p$ out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word $t$: $a_{1}... a_{|t|}$. We denote the length of word $x$ as $|x|$. Note that after removing one letter, the indices of other letters don't change. For example, if $t = $"nastya" and $a = [4, 1, 5, 3, 2, 6]$ then removals make the following sequence of words "nastya" $\to$ "{nas\sout{t}ya}" $\to$ "{\sout{n}as\sout{t}ya}" $\to$ "{\sout{n}as\sout{t}\sout{y}a}" $\to$ "{\sout{n}a\sout{s}\sout{t}\sout{y}a}" $\to$ "{\sout{n}\sout{a}\sout{s}\sout{t}\sout{y}a}" $\to$ "{\sout{n}\sout{a}\sout{s}\sout{t}\sout{y}\sout{a}}". Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word $p$. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey. It is guaranteed that the word $p$ can be obtained by removing the letters from word $t$.
In this problem we have to find the last moment of time, when $t$ has $p$ as a subsequence. If at some moment of time $p$ is a subsequence of $t$ then at any moment before, $p$ is also its subsequence. That's why the solution is binary search for the number of moves, Nastya makes. For binary search for a moment of time $m$ we need to check, if $p$ is a subsequence of $t$. We remove $a_{1}, a_{2}, ... a_{m}$ and check if $p$ is a subsequence greedily.
[ "binary search", "greedy", "strings" ]
1,700
null
778
B
Bitwise Formula
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer $m$, bit depth of the game, which means that all numbers in the game will consist of $m$ bits. Then he asks Peter to choose some $m$-bit number. After that, Bob computes the values of $n$ variables. Each variable is assigned either a constant $m$-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.
Note that changing $i$-th bit of chosen number doesn't change any bits of any of the variables other than $i$-th one. Also note that the total number of values is greater, as more variables have 1 at $i$-th position. Let's solve for every bit independently: learn, what is the value of $i$-th bit of chosen number. We can try both values and simulate the given program. Choose one of the values that makes more variables to have 1 at $i$-th position. If both 0 and 1 give equal number of variables to have 1 at $i$-th position, choose 0.
[ "bitmasks", "brute force", "dfs and similar", "expression parsing", "implementation" ]
1,800
null
778
C
Peterson Polyglot
Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters. Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his languages which is called \underline{broom}. Broom is rooted tree with edges marked with letters. Initially broom is represented by the only vertex — the root of the broom. When Peterson wants to add new word to the language he stands at the root and processes the letters of new word one by one. Consider that Peterson stands at the vertex $u$. If there is an edge from $u$ marked with current letter, Peterson goes through this edge. Otherwise Peterson adds new edge from $u$ to the new vertex $v$, marks it with the current letter and goes through the new edge. Size of broom is the number of vertices in it. In the evening after working day Peterson can't understand the language he made this morning. It is too difficult for bored Peterson and he tries to make it simpler. Simplification of the language is the process of erasing some letters from some words of this language. Formally, Peterson takes some positive integer $p$ and erases $p$-th letter from all the words of this language having length at least $p$. Letters in words are indexed starting by 1. Peterson considers that simplification should change at least one word, i.e. there has to be at least one word of length at least $p$. Peterson tries to make his language as simple as possible, so he wants to choose $p$ such that the size of the broom for his simplified language is as small as possible. Peterson is pretty annoyed with this task so he asks you for help. Write a program to find the smallest possible size of the broom and integer $p$.
While erasing letters on position $p$, trie changes like the following: all the edges from one fixed vertex of depth $p$ are merging into one. You can see it on the picture in the sample explanation. After merging of the subtrees we have the only tree - union of subtrees as the result. Consider the following algorithm. For every vertex $v$ iterate over all the subtrees of $v$'s children except for the children having largest subtree. There is an interesting fact: this algorithm works in $O(n\log n)$ in total. Denote as $s_{x}$ the size of the subtree rooted at vertex $x$. Let $h_{v}$ be the $v$'s child with the largest subtree, i.e. $s_{u} \le s_{hv}$ for every $u$ - children of $v$. If $u$ is a child of $v$ and $u \neq h_{v}$ then $s_{u}<{\frac{\sin}{2}}$. Let's prove that. Let $s_{h_{\mathrm{U}}}<\frac{s_{\mathrm{H}}}{2}$. Then $s_{u}\leq s_{h v}<{\frac{s_{v}}{2}}$ and $s_{u}<{\frac{\sin}{2}}$. Otherwise, if $s_{h_{v}}\geq{\frac{s_{w}}{2}}$, then we know that $s_{u} + s_{hv} < s_{v}$. Therefore, $s_{u}<s_{v}-s_{h v}\Rightarrow s_{u}<s_{v}-{\textstyle\frac{s_{\mathrm{n}}}{2}}\implies s_{u}<{\textstyle\frac{s_{\mathrm{n}}}{2}}$. Consider vertex $w$ and look at the moments of time when we have iterated over it. Let's go up through the ancestors of $w$. Every time we iterate over $w$ the size of the current subtree becomes twice greater. Therefore we could't iterate over $w$ more than $\lceil\log_{2}n\rceil$ times in total. It proves that time complexity of this algorithm is $O(n\log n)$. Solution: Iterate over all integers $p$ up to the depth of the trie For every vertex $v$ of depth $p$ Unite all the subtrees of $v$ with running over all of them except for the largest one. How to unite subtrees? First method. Find the largest subtree: it has been already built. Try to add another subtree in the following way. Let's run over smaller subtree's vertices and add new vertices into respective places of larger subtree. As the result we will have the union of the subtrees of $v$'s children. All we need from this union is it's size. After that we need to roll it back. Let's remember all the memory cells, which were changed while merging trees, and their old values. After merging we can restore it's old values in reverse order. Is it possible to implement merging without rolling back? Second method. Let's take all the subtrees except for the largest one and build their union using new memory. After that we should have two subtrees: the largest one and the union of the rest. We can find size of their union without any changes. Everything we need is to run over one of these trees examining another tree for the existence of respective vertices. After this we can reuse the memory we have used for building new tree.
[ "brute force", "dfs and similar", "dsu", "hashing", "strings", "trees" ]
2,500
null
778
D
Parquet Re-laying
Peter decided to lay a parquet in the room of size $n × m$, the parquet consists of tiles of size $1 × 2$. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it. The workers decided that removing entire parquet and then laying it again is very difficult task, so they decided to make such an operation every hour: remove two tiles, which form a $2 × 2$ square, rotate them 90 degrees and put them back on the same place. They have no idea how to obtain the desired configuration using these operations, and whether it is possible at all. Help Peter to make a plan for the workers or tell that it is impossible. The plan should contain at most $100 000$ commands.
Let's assume that the width of the rectangle is even (if not, flip the rectangle). Convert both start and final configurations into the configuration where all tiles lie horizontally. After that, since all the moves are reversible, simply reverse the sequence of moves for the final configuration. How to obtain a configuration in which all tiles lie horizontally. Let's go from top to bottom, left to right, and put all the tiles in the correct position. If the tile lie vertically, then try to turn it into the correct position. If it cannot be rotated, because the neighboring tile is oriented differently, proceed recursively to it. Thus, you get a "ladder", which can not go further than $n$ tiles down. At the end of the ladder there will be two tiles, oriented the same way. Making operations from the bottom up, we'll put the top tile in a horizontal position.
[ "constructive algorithms" ]
2,700
null
778
E
Selling Numbers
Boris really likes numbers and even owns a small shop selling interesting numbers. He has $n$ decimal numbers $B_{i}$. Cost of the number in his shop is equal to the sum of costs of its digits. You are given the values $c_{d}$, where $c_{d}$ is the cost of the digit $d$. Of course, Boris is interested in that numbers he owns have the maximum cost possible. Recently Boris got hold of the magical artifact $A$, which can allow him to increase the cost of his collection. Artifact is a string, consisting of digits and '?' symbols. To use the artifact, Boris must replace all '?' with digits to get a decimal number without leading zeros (it is also not allowed to get number 0). After that, the resulting number is added to all numbers $B_{i}$ in Boris' collection. He uses the artifact exactly once. What is the maximum cost of the collection Boris can achieve after using the artifact?
Because the target value for this problem is calculated independently for all digits, we'll use the dynamic programming approach. Define $dp_{k, C}$ as the maximum possible cost of digits after we processed $k$ least significant digits in $A$ and $C$ is the set of numbers having the carry in current digit. This information is sufficient to choose the digit in the current position in $A$ and recalculate the $C$ set and DP value for the next digit. The key observation is that there are only $n + 1$ possible sets instead of $2^{n}$. Consider last $k$ digits of $A$ and $B_{i}$. Sort all the length-$k$ suffixes of $B_{i}$ in descending lexicographical order. Because all these suffixes will be increased by the same value, the property of having the carry is monotone. That means that all possible sets $C$ are the prefixes of length $m$ ($0 \le m \le n$) of this sorted list of suffixes. This fact allows us to reduce the number of DP states to $O(n \cdot |A|)$. Sorting all suffixes of $B_{i}$ can be accomplished using the radix sort, appending the digits to the left and recalculating the order. The only thing that's left is to make all DP transitions in $O(1)$ time. To do that, maintain the total cost of all digits and the amount of numbers that have the carry. After adding one more number with carry in current digit, these two values can be easily recalculated. After processing all digits in $A$, we have to handle the remaining digits in $B_{i}$ (if there are any) and take the best answer. Total running time is $O(n\cdot\operatorname*{max}(|A|,|B_{i}|))$.
[ "dp", "sortings" ]
3,000
null
779
A
Pupils Redistribution
In Berland each high school student is characterized by academic performance — integer value between $1$ and $5$. In high school 0xFF there are two groups of pupils: the group $A$ and the group $B$. Each group consists of exactly $n$ students. An academic performance of each student is known — integer value between $1$ and $5$. The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to $1$, the same number of students whose academic performance is $2$ and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal. To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class $A$ and one student of class $B$. After that, they both change their groups. Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.
To solve this problem let's use array $cnt[]$. We need to iterate through first array with academic performances and for current performance $x$ let's increase $cnt[x]$ on one. In the same way we need to iterate through the second array and decrease $cnt[x]$ on one. If after that at least one element of array $cnt[]$ is odd the answer is $- 1$ (it means that there are odd number of student with such performance and it is impossible to divide them in two. If all elements are even the answer is the sum of absolute values of array $cnt$ divided by 2. In the end we need to divide the answer on 2 because each change will be counted twice with this way of finding the answer.
[ "constructive algorithms", "math" ]
1,000
null
779
B
Weird Rounding
Polycarp is crazy about round numbers. He especially likes the numbers divisible by $10^{k}$. In the given number of $n$ Polycarp wants to remove the least number of digits to get a number that is divisible by $10^{k}$. For example, if $k = 3$, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by $10^{3} = 1000$. Write a program that prints the minimum number of digits to be deleted from the given integer number $n$, so that the result is divisible by $10^{k}$. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists.
To solve this problem we need to make $k$ zeroes in the end of number $n$. Let's look on the given number as on the string and iterate through it beginning from the end (i.e. from the low order digit). Let $cnt$ equals to the number of digits which we reviewed. If the current digit does not equal to zero we need to increase the answer on one. If $cnt$ became equal to $k$ and we reviewed not all digits we need to print the answer. In the other case we need to remove from the string all digits except one, which equals to zero (if there are more than one such digit we left only one of them). Such digit always exists because the problem statement guaranteed that the answer exists.
[ "brute force", "greedy" ]
1,100
null
779
C
Dishonest Sellers
Igor found out discounts in a shop and decided to buy $n$ items. Discounts at the store will last for a week and Igor knows about each item that its price now is $a_{i}$, and after a week of discounts its price will be $b_{i}$. Not all of sellers are honest, so now some products could be more expensive than after a week of discounts. Igor decided that buy \textbf{at least} $k$ of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all $n$ items.
To solve this problem we need at first to sort all items in increasing order of values $a_{i} - b_{i}$. Then let's iterate through sorted array. If for the current item $x$ we did not buy $k$ items now and if after discounts it will cost not more than now, we need to buy it now and pay $a_{x}$, in the other case we need to buy item $x$ after discounts and pay $b_{x}$.
[ "constructive algorithms", "greedy", "sortings" ]
1,200
null
780
A
Andryusha and Socks
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has $n$ distinct pairs of socks which are initially in a bag. The pairs are numbered from $1$ to $n$. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe. Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?
This is a simple implementation problem. Store an array for whether a sock of each type is currently on the table, along with the total number of socks, and the largest number encountered. It is now easy to process socks one by one and maintain everything. Complexity: $O(n)$ time and memory.
[ "implementation" ]
800
null
780
B
The Meeting Place Cannot Be Changed
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are $n$ friends, and $i$-th of them is standing at the point $x_{i}$ meters and can move with any speed no greater than $v_{i}$ meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the $n$ friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.
We will apply binary search to solve this problem. Inside the binary search we have to check if it is possible to meet within $t$ seconds. In this time, $i$-th friend can get anywhere within the segment $[x_{i} - tv_{i}, x_{i} + tv_{i}]$. For the meeting to be possible, there must be a point common to all these segments, that is, their intersection must be non-empty. An easy way to intersect a number of segments $[l_{1}, r_{1}]$, ..., $[l_{n}, r_{n}]$ is to compute $L = max l_{i}$ and $R = min r_{i}$. If $L \le R$, then $[L, R]$ is the intersection, otherwise, the intersection is empty. Complexity: $O(n\log(\varepsilon^{-1}))$ time and $O(n)$ memory. Here $ \epsilon $ is the required relative precision.
[ "binary search" ]
1,600
null
780
C
Andryusha and Colored Balloons
Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them. The park consists of $n$ squares connected with $(n - 1)$ bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from $1$. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if $a$, $b$ and $c$ are distinct squares that $a$ and $b$ have a direct path between them, and $b$ and $c$ have a direct path between them, then balloon colors on these three squares are distinct. Andryusha wants to use as little different colors as possible. Help him to choose the colors!
If $v$ is a vertex of degree $d$, then the answer is at least $d + 1$. Indeed, any two neighbours of $v$ can be connected by a path of length three via vertex $v$. Also, $v$ lies on a common three-vertex path with any of its neighbours (possibly using a non-neighbour vertex). It follows that $v$ and all of its neighbours must have pairwise distinct colors. Let us show that the strongest of these estimates is best possible, that is, construct a coloring with $D + 1$ colors, where $D$ is the maximal degree. Root the tree at arbitrary vertex, and color the root with color 1, also color its children with subsequent colors. All the rest vertices will be colored as follows: if a vertex $v$ is colored $x$, and its parent is colored $y$, then for the children of $v$ we will use numbers starting from 1 skipping $x$ and $y$. One can check that no color with number larger than $D + 1$ shall be used. Implementation-wise, this is a simple DFS procedure. Complexity: $O(n)$ time and memory.
[ "dfs and similar", "graphs", "greedy", "trees" ]
1,600
null
780
D
Innokenty and a Football League
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of \textbf{three letters}. Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: - the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", - or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club $x$ the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club $x$. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name. Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.
Let us write $a_{i}$ and $b_{i}$ for first and second options for $i$-th club name. If all $a_{i}$ are distinct, we can assign all of them to be club names without conflict. Otherwise, suppose that for clubs $i$, $j$ we have $a_{i} = a_{j}$, hence we can't use them simultaneously. Note that, say, choosing $a_{i}$ and $b_{j}$ is also forbidden by the statement. It follows that we must use $b_{i}$ and $b_{j}$ as $i$-th and $j$-th club names respectively. If for some other club $k$ we now have $a_{k} = b_{i}$, then we are forced to use $b_{k}$ as its name as well. We can process this kind of chain conflicts with a BFS-like procedure. If at any point we are forced to use the same name for two different clubs, then the answer is NO. Otherwise, resolving all conflicts will yield a correct assignment. Complexity: $O(n)$ memory and time if implemented carefully (not necessary though).
[ "2-sat", "graphs", "greedy", "implementation", "shortest paths", "strings" ]
1,900
null
780
E
Underground Lab
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex. The lab can be pictured as a connected graph with $n$ vertices and $m$ edges. $k$ clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone. Each clone can visit at most $\left\lceil{\frac{2m}{k}}\right\rceil$ vertices before the lab explodes. Your task is to choose starting vertices and searching routes for the clones. Each route can have at most $\left\lceil{\frac{2m}{k}}\right\rceil$ vertices.
Let's start a DFS at any vertex of the graph, and produce an Euler tour - the order of vertices visited by a DFS, where each vertex $v$ is written down every time DFS visits it (in particular, when a recursive call made from $v$ terminates). Note that the Euler tour has exactly $2n - 1$ entries in it, hence it would be a correct answer for $k = 1$. For a general $k$, cut the Euler tour into $k$ consecutive pieces of size at most $ \lceil 2n / k \rceil $, and yield it as an answer. Note that each path of the answer has to contain at least one vertex. Complexity: $O(n + m)$ time and memory.
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,100
null
780
F
Axel and Marston in Bitland
A couple of friends, Axel and Marston are travelling across the country of Bitland. There are $n$ towns in Bitland, with some pairs of towns connected by one-directional roads. Each road in Bitland is either a pedestrian road or a bike road. There can be multiple roads between any pair of towns, and may even be a road from a town to itself. However, no pair of roads shares the starting and the destination towns along with their types simultaneously. The friends are now located in the town 1 and are planning the travel route. Axel enjoys walking, while Marston prefers biking. In order to choose a route diverse and equally interesting for both friends, they have agreed upon the following procedure for choosing the road types during the travel: - The route starts with a pedestrian route. - Suppose that a beginning of the route is written in a string $s$ of letters P (pedestrain road) and B (biking road). Then, the string $\overline{{\mathbf{X}}}$ is appended to $s$, where $\overline{{\mathbf{X}}}$ stands for the string $s$ with each character changed to opposite (that is, all pedestrian roads changed to bike roads, and vice versa). In the first few steps the route will look as follows: P, PB, PBBP, PBBPBPPB, PBBPBPPBBPPBPBBP, and so on. After that the friends start travelling from the town 1 via Bitlandian roads, choosing the next road according to the next character of their route type each time. If it is impossible to choose the next road, the friends terminate their travel and fly home instead. Help the friends to find the longest possible route that can be travelled along roads of Bitland according to the road types choosing procedure described above. If there is such a route with more than $10^{18}$ roads in it, print -1 instead.
Let us write $A_{i}$ for the binary string obtained after $i$ inverse-append steps, for example, $A_{0} = 0$, $A_{1} = 01$, and so on. Let us also write $B_{i}={\overline{{A_{i}}}}$. By definition we must have $A_{i+1}=A_{i}B_{i}$, and $B_{i+1}=B_{i}A_{i}$. Let us store matrices $P_{k}$ and $Q_{k}$, with entries $P_{k} / Q_{k}(v, u)$ equal to 1 for pairs of vertices $v, u$ such that there is a $A_{k}$/$B_{k}$-path from $v$ to $u$. Note that $P_{0}$ and $Q_{0}$ are exactly the adjacency matrices with 0- and 1-arcs respectively. Next, note that $P_{k + 1}(v, u) = 1$ if and only if there is a vertex $w$ such that $P_{k}(v, w) = Q_{k}(w, u) = 1$, and a similar condition can be written for $Q_{k + 1}(v, u)$. It follows that $P_{k + 1}$ and $Q_{k + 1}$ can be computed using $P_{k}$ and $Q_{k}$ in $O(n^{3})$ time (the method is basically boolean matrix multiplication: $P_{k+1}=P_{k}Q_{k}$, $Q_{k+1}=Q_{k}P_{k}$). To use the matrices $P_{k}$ and $Q_{k}$ to find the answer, let us store $L$ - the largest answer found, and $S$ - the set of vertices reachable from the vertex 1 in exactly $L$ steps. Let's process $k$ by decreasing from a certain value $k_{0}$, and see if $L$ can be increased by $2^{k}$. The next $2^{k}$ characters after $L$-th position will form the string $A_{k}$ or $B_{k}$ depending on the popcount parity of $L$. Let's denote $S'$ the set of vertices reachable from $S$ following $A_{k} / B_{k}$. If $S'$ is non-empty, we can increase $L$ by $2^{k}$, and assign $S = S'$, otherwise, we don't change anything. In the end, $L$ will be the maximal path length as long as it at less than $2^{k0}$. Note that we can take $k_{0} = 60$ since we don't care about exact value of answer if it is greater than $2^{60}$. This results in an $O(k_{0n}^{3})$ solution, which is too slow. However, optimizing boolean multiplication with bitsets cuts the working time $\sim64$ times, and the solution is now fast enough. Complexity: $O(k_{0}n^{3}/w)$ time, and $O(k_{0}n^{2})$ memory. Here $k_{0}=\log_{2}10^{18}$, and $w = 64$ is the word length in bits.
[ "bitmasks", "dp", "graphs", "matrices" ]
2,400
null
780
G
Andryusha and Nervous Barriers
Andryusha has found a perplexing arcade machine. The machine is a vertically adjusted board divided into square cells. The board has $w$ columns numbered from $1$ to $w$ from left to right, and $h$ rows numbered from $1$ to $h$ from the bottom to the top. Further, there are barriers in some of board rows. There are $n$ barriers in total, and $i$-th of them occupied the cells $l_{i}$ through $r_{i}$ of the row $u_{i}$. Andryusha recollects well that no two barriers share the same row. Furthermore, no row is completely occupied with a barrier, that is, at least one cell in each row is free. The player can throw a marble to any column of the machine from above. A marble falls downwards until it encounters a barrier, or falls through the bottom of the board. A marble disappears once it encounters a barrier but is replaced by two more marbles immediately to the left and to the right of the same barrier. In a situation when the barrier is at an edge of the board, both marbles appear next to the barrier at the side opposite to the edge. More than one marble can occupy the same place of the board, without obstructing each other's movement. Ultimately, all marbles are bound to fall from the bottom of the machine. \begin{center} {\small Examples of marble-barrier interaction.} \end{center} Peculiarly, sometimes marbles can go through barriers as if they were free cells. That is so because the barriers are in fact alive, and frightened when a marble was coming at them from a very high altitude. More specifically, if a marble falls towards the barrier $i$ from relative height more than $s_{i}$ (that is, it started its fall strictly higher than $u_{i} + s_{i}$), then the barrier evades the marble. If a marble is thrown from the top of the board, it is considered to appear at height $(h + 1)$. Andryusha remembers to have thrown a marble once in each of the columns. Help him find the total number of marbles that came down at the bottom of the machine. Since the answer may be large, print it modulo $10^{9} + 7$.
Solution 1: Let us move a sweep-line from the bottom to the top, and say that $i$-th barrier is active if the current $y$-coordinate satisfies $u_{i} \le y \le u_{i} + s_{i}$. If we want to find the result of dropping a ball in column $x$ at a certain moment, we have to find the highest active barrier that covers $x$ at the moment. Let us store a segment tree, with a set of active segments in each tree node. When introducing a new active segment, we represent it as a union of $O(\log w)$ tree nodes, and add this segment in each of these nodes' set; when a segment becomes non-active, we delete these entries. If at any point we are interested in finding the highest active barrier for a column $x$, we consider all $O(\log w)$ tree nodes covering $x$ and look at their highest entries only. Also, for each segment we store the number of resulting balls after hitting this segment; this number can be found by making two queries to the tree (for the two balls resulting from the collision) at the same time we activate the barrier. To find the final answer, for each column drop a ball in it from height $h + 1$ and sum the results. Thus, the answer can be found in $O((n+w)\log^{2}w)$ time (with the second logarithm for std::set working time). Solution 2: Let us go from the top to the bottom instead, and maintain positions of all balls to be dropped. If any of these balls occupy the same position, we group them together and store the size of the group. Each column will have a separate stack of groups, with lower groups on top of the stack. Let's see how a new barrier $[l, r]$ changes our configuration. For each column $[l, r]$ we want to drop several lowest groups on the barrier, which will result in creating at most two new groups next to the barrier. Let us store a segment tree of size $w$, with $x$-th entry equal to the height of the lowest group in column $x$. While $[l, r]$ range minimum in the segment tree is low enough, we pop the lowest group from the corresponding stack (and update the segment tree accordingly). Finally, we create the new groups, and push them to their respective stacks. After processing all barriers, the rest groups will fall straight to the bottom. A standard amortized estimate shows that $O(n + w)$ operations will be performed, for $O((n+w)\log w)$ time complexity.
[ "data structures", "dp" ]
2,700
null
780
H
Intranet of Buses
A new bus route is opened in the city $\mathbb{N}$. The route is a closed polygon line in the place, with all segments parallel to one of the axes. $m$ buses will operate on the route. All buses move in a loop along the route in the same direction with equal constant velocities (stopping times are negligible in this problem). Buses start their movement in the first vertex of the route with equal interval. Suppose that $T$ is the total time for a single bus to travel the whole loop of the route. Then, the bus 1 starts moving at time 0, the bus 2 starts at time $T / m$, the bus 3 starts at time $2T / m$, and so on; finally, the bus $m$ starts moving at time $(m - 1)T / m$. Thus, all intervals between pairs of consecutive buses (including the interval between the last and the first bus) are equal. Buses can communicate with each other via wireless transmitters of equal power. If the transmitters have power $D$, then only buses within distance $D$ of each other can communicate. The buses are also equipped with a distributed system of schedule tracking. For all buses to stick to the schedule, the system has to synchronize the necessary data between all buses from time to time. At the moment of synchronization, the bus 1 communicates with the bus 2, the bus 2 — with bus 3, and so on; also, the bus $m$ communicates with the bus 1. As a research employee, you are tasked with finding the smallest value of $D$ such that it is possible to find a time moment to perform synchronization once all buses have started moving.
Let us do a binary search on the answer. Inside it, we have to check if at any time moment bus pairs 1 and 2, 2 and 3, ..., $n$ and 1 are within distance $x$ of each other simultaneously. Let $p(t)$ be the location of the bus 1 (that departed at time 0) at time $t$. Let us call a time moment $t$ good, if we have $||p(t + T / m) - p(t)|| \le x$, with $||a - b||$ equal to the distance between points $a$ and $b$. If there is a moment $t$ such that $t$, $t + T / m$, ..., $t + (m - 1)T / m$ are all good, then the answer is at least $x$. We can build the two-dimensional graph (as in "function graph", not "graph with vertices and edges") of $p(t + T / m) - p(t)$ over time by keeping track of segments where points $p(t)$ and $p(t + T / m)$ are. When the points are bounded to a pair of sides, the vector $p(t + T / m) - p(t)$ changes linearly in time. There are $O(n)$ time moments when either point switches from side to side, hence the difference graph can be constructed in $O(n)$ time with the two pointers approach. Now, for a certain $x$ let's find the set of good moments $t$. We will do this separately for each segment of the difference graph, and then paste the answers. We have the condition $||q|| \le x$, where $q$ ranges over a segment. This is the segment-circle intersection problem, which is a standard geometrical primitive, with various approaches from solving quadratic equations to rotating a certain vector by an angle. In any case, the result will be a time range or an empty set. Note that $q$ may stay still for a certain time range of the graph, which should be treated separately. To ensure that $p(t)$, $p(t + T / m)$, and so on are all good for certain $t$, let us "cut" the segment $[0, T]$ into $m$ equal parts and superimpose them, with "good" segments possibly being cut into parts, now overlapping each other. A suitable moment $t$ is now a point that is covered $m$ times. Finding such point is a simple scan-line application. Complexity: $O(n\log\varepsilon^{-1})$, where $ \epsilon $ is the required relative precision.
[ "binary search", "geometry", "implementation", "two pointers" ]
3,100
null
785
A
Anton and Polyhedrons
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: - Tetrahedron. Tetrahedron has $4$ triangular faces. - Cube. Cube has $6$ square faces. - Octahedron. Octahedron has $8$ triangular faces. - Dodecahedron. Dodecahedron has $12$ pentagonal faces. - Icosahedron. Icosahedron has $20$ triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of $n$ polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
I think there's nothing to explain in this problem. Just check the polyhedron type, determine its number of faces and sum these numbers. Time complexity is $O(n)$.
[ "implementation", "strings" ]
800
vals = { 'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20 } n = int(input()) ans = 0 for i in range(0, n): ans += vals[input()] print(ans)
785
B
Anton and Classes
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes. Anton has $n$ variants when he will attend chess classes, $i$-th variant is given by a period of time $(l_{1, i}, r_{1, i})$. Also he has $m$ variants when he will attend programming classes, $i$-th variant is given by a period of time $(l_{2, i}, r_{2, i})$. Anton needs to choose \textbf{exactly one} of $n$ possible periods of time when he will attend chess classes and \textbf{exactly one} of $m$ possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal. The distance between periods $(l_{1}, r_{1})$ and $(l_{2}, r_{2})$ is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible $|i - j|$, where $l_{1} ≤ i ≤ r_{1}$ and $l_{2} ≤ j ≤ r_{2}$. In particular, when the periods intersect, the distance between them is $0$. Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!
At first, let's determine what classes Anton will attend first - chess classes or programming classes. Consider the case when Anton attends chess classes first and then attends programming classes. It's not hard to observe that in this case it's better to take the chess classes variant in which the right range is as more to the left as possible. Also, we take the programming classes variant in which the left range is as more to the right as possible. Because chess classes must be earlier than programming classes, the distance between them can be calculated as the distance between these two points (the right range of chess classes and the left range of programming classes). But if the right chess classes point will be later than the left programming classes point, it means that our condition (chess is earlier than programming) is false or the periods intersect. So in this case we take $0$ instead of the distance. The second case is considered in the same way. It's obvious that the answer will be the maximum of these two cases. Time complexity is $O(n+m)$.
[ "greedy", "sortings" ]
1,100
infinity = 1234567890 minR1 = minR2 = infinity maxL1 = maxL2 = -infinity n = int(input()) for i in range(0, n): (l, r) = map(int, input().split()) maxL1 = max(maxL1, l) minR1 = min(minR1, r) m = int(input()) for i in range(0, m): (l, r) = map(int, input().split()) maxL2 = max(maxL2, l) minR2 = min(minR2, r) res = max(maxL2 - minR1, maxL1 - minR2); print(max(res, 0))
785
C
Anton and Fairy Tale
Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale: "Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that barn for three days and three nights. But they overlooked and there remained a little hole in the barn, from which every day sparrows came through. Here flew a sparrow, took a grain and flew away..." More formally, the following takes place in the fairy tale. At the beginning of the first day the barn with the capacity of $n$ grains was full. Then, every day (starting with the first day) the following happens: - $m$ grains are brought to the barn. If $m$ grains doesn't fit to the barn, the barn becomes full and the grains that doesn't fit are brought back (in this problem we can assume that the grains that doesn't fit to the barn are not taken into account). - Sparrows come and eat grain. In the $i$-th day $i$ sparrows come, that is on the first day one sparrow come, on the second day two sparrows come and so on. Every sparrow eats one grain. If the barn is empty, a sparrow eats nothing. Anton is tired of listening how Danik describes every sparrow that eats grain from the barn. Anton doesn't know when the fairy tale ends, so he asked you to determine, by the end of which day the barn will become empty for the first time. Help Anton and write a program that will determine the number of that day!
At first, let's make the following assumption: if a sparrow cannot eat a grain because the barn is empty, the number of grains in the barn becomes negative. It's easy to see that the answer doesn't change because of this. Now, let's observe the number of grains before sparrows come. At first, the barn remains full for $m + 1$ days (because sparrows eat less grains than it's added to the barn). Then the number of grains is decreased by one, by two and so on. So, on the $m + 1 + i$-th day there are $n-{\frac{\iota_{-}\iota_{+1}}{2}}$ grains in the barn before sparrows come (remember that for any positive integer $x$ the equality $1+2+3+\cdot\cdot\cdot+x={\frac{x\cdot(x+1)}{2}}$ is always true). How can we determine if the barn is empty? It's reasonable that if there are $q$ grains on the $k$-th day after grain is brought, then at the end of the $k - 1$-th day there are $q - m$ grains in the barn. So, if on the $k - 1$-th day the barn becomes empty ($q - m \le 0$), then there must be $q \le m$ grains on the $k$-th day after grain is brought. So, we must find such minimal day $m + 1 + k$, in which there are $m$ or less grains after grain is brought. That is, using the formula above, we must find such minimal $k$ that $n-{\frac{k\cdot(k{+}1)}{2}}\leq m$ It can be easily done using binary search. It's not hard to observe that the answer in this case is $m + k$ (if in the $m + 1 + k$-th day before sparrows come there are less or equal than $m$ grains, then in the $m + 1 + k - 1 = m + k$-th day the barn is empty). The corner case in this problem is $m \ge n$. In this case the barn becomes full every day and it becomes empty only in the $n$-th day when sparrows eat all the grain. Also notice that $k$ can be found using a formula, but such solutions could fail by accuracy, because the formula is using the square root function. Time complexity is $O(\log n)$.
[ "binary search", "math" ]
1,600
(n, m) = map(int, input().split()) if n <= m: print(n) else: aM = m n -= m (l, r) = (0, int(2e9)) while l < r: m = (l + r) // 2; val = m * (m+1) // 2; if val >= n: r = m else: l = m+1 print(l + aM)
785
D
Anton and School - 2
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)). On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence $s$ of length $n$ is an RSBS if the following conditions are met: - It is not empty (that is $n ≠ 0$). - The length of the sequence is even. - First $\frac{n t}{2}$ charactes of the sequence are equal to "(". - Last $\frac{n t}{2}$ charactes of the sequence are equal to ")". For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS. Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence $s$. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of $s$ is a string that can be obtained from $s$ by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted. Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo $10^{9} + 7$. Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
At first, let's simplify the problem: let our string consists of $x + y$ characters, begins with $x$ characters "(" and ends with $y$ characters ")". How to find the number of RSBS in such string? Let's prove that this number is equal to $\textstyle(x+y)={\frac{(x+y)!}{x!.y!}}$. It's easy to observe that this formula also means the number of ways to match the string with the sequence of zeros and ones of the same length, which contains exactly $x$ ones. Now prove that for every such sequence of zeros and ones we can find an RSBS subsequence. How can we do it? Let's consider it on the example of the following string: Let's include to our subsequence all the opening brackets that match zeros and all the closing brackets that match ones. In our example, we include brackets number $1$, $3$, $5$ and $6$, so we get the subsequence "(())", which is an RSBS. Why every sequence we got in this way is an RSBS? Let the number of ones that match closing brackets is equal to $z$. So $x - z$ ones match opening brackets (because we have $x$ ones, as we remember) and, therefore, $z$ zeros match opening brackets. So the number of opening brackets is equal to the number of closing brackets in our subsequence. Also opening brackets appear earlier than closing brackers. So such subsequence is always an RSBS, and the statement above is proved. Now we must understand how to solve the entire problem. Let's iterate over an opening bracket that is the last opening bracket in our subsequence. Now observe that only opening brackets may come before this bracket, and only closing brackets may come after this bracket. The rest of the brackets will definitely not appear in the subsequence. Let's count the number of opening brackets before the iterated one, incluing the iterated one (let this number is equal to $x$), and also the number of closing brackets after the iterated one (let this number is equal to $y$). To calculate these numbers, we can precalc them for all the positions in $O(n)$ using prefix sums. Now, we have reduced our problem to the already solved, because we have $x$ opening brackets and then $y$ closing brackets. But we also have an additional condition: we must necessarily take the last opening bracket. So the answer is equal to $\textstyle(x+y-1)$, not $\textstyle{\left(x+y\right)}$, because on the position with the last opening bracket we must put a zero. So we must put $x$ ones on $x + y - 1$ positions instead of $x + y$ positions. Time complexity is $O(n\cdot\log(10^{9}+7))$ (logarithm is to divide by modulo, that is necessary to calculate the number of combinations).
[ "combinatorics", "dp", "math", "number theory" ]
2,300
import java.io.*; import java.util.*; public class BracketsJava { public static int mod = (int)1e9 + 7; public static class ExtGcdResult { long x; long y; } public static long extGcd(long a, long b, ExtGcdResult res) { if (a == 0) { res.x = 0L; res.y = 1L; return b; } ExtGcdResult newRes = new ExtGcdResult(); long d = extGcd(b % a, a, newRes); res.x = newRes.y - (b / a) * newRes.x; res.y = newRes.x; return d; } public static final int addMod(int a, int b) { return (int)(((long)a + b) % mod); } public static final int mulMod(int a, int b) { return (int)(((long)a * b) % mod); } public static final int divMod(int a, int b) { ExtGcdResult res = new ExtGcdResult(); long g = extGcd(b, mod, res); if (g != 1) { System.out.println("Bad gcd!"); for (;;); } int q = (int)((res.x % mod + mod) % mod); return mulMod(a, q); } public static final int[] precalcFactorials() { int[] fact = new int[factRange]; fact[0] = 1; for (int i = 1; i < factRange; i++) { fact[i] = mulMod(fact[i-1], i); } return fact; } public static final int factRange = 1000000; public static final int[] fact = precalcFactorials(); public static final int F(int n) { return (n < 0) ? 0 : fact[n]; } public static final int C(int k, int n) { int res = divMod(F(n), mulMod(F(n-k), F(k))); return divMod(F(n), mulMod(F(n-k), F(k))); } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); String s = reader.readLine(); int len = s.length(); int[] opnLeft = new int[len], clsRight = new int[len]; opnLeft[0] = (s.charAt(0) == '(') ? 1 : 0; for (int i = 1; i < len; i++) { opnLeft[i] = opnLeft[i-1] + ((s.charAt(i) == '(') ? 1 : 0); } clsRight[len-1] = (s.charAt(len-1) == ')') ? 1 : 0; for (int i = len-2; i >= 0; i--) { clsRight[i] = clsRight[i+1] + ((s.charAt(i) == ')') ? 1 : 0); } int res = 0; for (int i = 0; i < len; i++) { if (s.charAt(i) != '(' || clsRight[i] == 0) { continue; } int add = C(opnLeft[i], opnLeft[i] + clsRight[i] - 1); res = addMod(res, add); } writer.write(Integer.toString(res)); reader.close(); writer.close(); } }
785
E
Anton and Permutation
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of $n$ elements is a sequence of numbers ${a_{1}, a_{2}, ..., a_{n}}$, in which every number from $1$ to $n$ appears exactly once. One day Anton got a new permutation and started to play with it. He does the following operation $q$ times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs $(i, j)$ such that $1 ≤ i < j ≤ n$ and $a_{i} > a_{j}$. Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him. Initially Anton's permutation was ${1, 2, ..., n}$, that is $a_{i} = i$ for all $i$ such that $1 ≤ i ≤ n$.
At first observe that there is $0$ inversions in the initial permutation. Let's divide our queries in ${\sqrt{q}}$ blocks. Now learn how to answer all the queries in one block in $O(n+q+\sqrt{n q})$. At first, let's divide our positions in the permutation in fixed and mobile positions. Mobile positions are all the positions that are changed in the current block. Fixed positions are the rest of the positions. Observe that the number of mobile positions is not more than $2\cdot{\sqrt{q}}$. Now all the inversions are divided into three types: Inversions only between fixed positions; Inversions only between mobile positions; Inversions between fixed and mobile positions. To keep inversions of the first type is the easiest of all: their number doesn't change. So we can precalcualte them in the beginning of the block. How can we do it? Let's remember the answer for the query that was directly before the beginning of the block (if the block starts with the first query, this number is equal to $0$). This number is equal to the total number of inversions in the beginning of the block. To get the number of fixed inversions, we can just subtract from this number the number of inversions of the second and the third types. It's also easy to calculate the number of inversions of the second type. In the beginning their number can be counted even using a naive algorithm in $O(\sqrt{q}^{2})=O(q)$. How to keep this number? We can recalculate each time not all the inversions but only these ones that contain changed elements. Totally we can count them in $O(\sqrt{q}\cdot\sqrt{q})=O(q)$ for a block. It's a little bit harder to keep inversions of the third type. To count them we'll use the similar approach as with inversions of the second type. We'll also recount the number of inversions only for changed elements. So, we must learn how to count the number of inversions between fixed elements and some mobile element on the position $x$. What fixed elements make an inversion with it? It's obvious that these are the elements which are earlier than the $x$-th and wherein bigger than it (denote this query $countLower(x, p_{x})$) or elements which are later than the $x$-th and wherein smaller than it (denote this query $countUpper(x, p_{x})$). Here $p_{x}$ denotes the $x$-th element of permutation. Observe that there are $O({\sqrt{q}})$ such queries. How can we calculate the answers for these queries quickly? At first note that we can count them offline, because fixed elements doesn't change and mobile elements are not counted in these queries. Consider how we can count answers for $countLower(x, y)$ (for $countUpper(x, y)$ we can use the same approach). Let's sort all the $countLower$ queries by non-decreasing $x$. Now if we have some structure that can add a value to an element and count a sum on a segment, we can easily do it. Let we added the fixed elements that stay earlier than $x$ (it can be easily done because all the queries are sorted by non-decreasing $x$). So the answer is the sum on the segment $(y + 1, n)$. What data structure can we use? We can use sqrt-decomposition, because it takes $O(1)$ for adding and $O({\sqrt{n}})$ for sum query. Totally all the $O({\sqrt{q}})$ $countLower$ and $countUpper$ queries in a block are processed in $O(n+{\sqrt{n q}})$. Time complexity is $O(\sqrt{q}\cdot(n+q+\sqrt{n q}))=O(n\sqrt{q}+q\sqrt{q}+q\sqrt{n})$. There also exists an $O((n+q)\cdot\log^{2}n)$ solution. You can find it by yourself as an exercise. Such solution should be written carefully, otherwise it doesn't fit to the time limit or memory limit.
[ "brute force", "data structures" ]
2,200
import java.io.*; import java.util.*; public class NsqrtNlogNnetman implements Runnable { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static class Fenwick { int[] ft; Fenwick(int n) { ft = new int[n]; } void add(int r, int val) { while (r < ft.length) { ft[r] += val; r |= r + 1; } } int sum(int r) { int res = 0; while (r >= 0) { res += ft[r]; r = (r & (r + 1)) - 1; } return res; } void clear() { Arrays.fill(ft, 0); } } static class Query { int x, bound, sign, id; Query(int x, int bound, int sign, int id) { this.x = x; this.bound = bound; this.sign = sign; this.id = id; } } static void getOnPrefSmaller(List<Query> qrs, int r, int y, int id, int sign) { qrs.add(new Query(r, y, sign, id)); } static void getOnPrefBetween(List<Query> qrs, int r, int x, int y, int id, int sign) { getOnPrefSmaller(qrs, r, y, id, sign); getOnPrefSmaller(qrs, r, x, id, -sign); } static void getOnSegmentBetween(List<Query> qrs, int l, int r, int x, int y, int id, int sign) { if (x > y) return; getOnPrefBetween(qrs, r, x, y, id, sign); getOnPrefBetween(qrs, l, x, y, id, -sign); } @Override public void run() { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int q = in.nextInt(); int[] l = new int[q]; int[] r = new int[q]; for (int i = 0; i < q; i++) { l[i] = in.nextInt() - 1; r[i] = in.nextInt() - 1; } int[] perm = new int[n]; for (int i = 0; i < n; i++) { perm[i] = n - i - 1; } final int BLOCK = 300; long inv = 0L; boolean[] isInteresting = new boolean[n]; long[] add = new long[q]; Fenwick f = new Fenwick(n); for (int i = 0; i < q; i += BLOCK) { int from = i, to = Math.min(i + BLOCK, q) - 1; List<Integer> lst = new ArrayList<>(); for (int j = from; j <= to; j++) { lst.add(l[j]); lst.add(r[j]); } lst.sort(Integer::compareTo); lst = new ArrayList<>(new HashSet<>(lst)); int[] interestingPositions = lst.stream().mapToInt(x -> x).toArray(); for (int pos : interestingPositions) { isInteresting[pos] = true; } List<Query> qrs = new ArrayList<>(); for (int j = from; j <= to; j++) { if (l[j] == r[j]) continue; if (l[j] > r[j]) { int tmp = l[j]; l[j] = r[j]; r[j] = tmp; } if (perm[l[j]] < perm[r[j]]) { getOnSegmentBetween(qrs, l[j], r[j], perm[l[j]], perm[r[j]], j,-1); int leftValue = perm[l[j]]; int rightValue = perm[r[j]]; for (int pos : interestingPositions) { if (pos > l[j] && pos < r[j] && perm[pos] > leftValue && perm[pos] < rightValue) { add[j] -= 2; } } add[j]--; } else { getOnSegmentBetween(qrs, l[j], r[j], perm[r[j]], perm[l[j]], j,1); int leftValue = perm[l[j]]; int rightValue = perm[r[j]]; for (int pos : interestingPositions) { if (pos > l[j] && pos < r[j] && perm[pos] > rightValue && perm[pos] < leftValue) { add[j] += 2; } } add[j]++; } int tmp = perm[l[j]]; perm[l[j]] = perm[r[j]]; perm[r[j]] = tmp; } qrs.sort(Comparator.comparingInt(a -> -a.x)); f.clear(); for (int pos = 0; pos < n; pos++) { if (!isInteresting[pos]) { f.add(perm[pos], 1); } while (!qrs.isEmpty() && qrs.get(qrs.size() - 1).x == pos) { Query t = qrs.get(qrs.size() - 1); qrs.remove(qrs.size() - 1); add[t.id] += 2 * t.sign * f.sum(t.bound); } } for (int j = from; j <= to; j++) { inv += add[j]; out.println(inv); } for (int pos : interestingPositions) { isInteresting[pos] = false; } } out.close(); } public static void main(String[] args) { new Thread(null, new NsqrtNlogNnetman(), "1", 1L << 28).run(); } }
786
A
Berzerk
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are $n$ objects numbered from $1$ to $n$ arranged in a circle (in clockwise order). Object number $1$ is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. Each one of them has a set of numbers between $1$ and $n - 1$ (inclusive). Rick's set is $s_{1}$ with $k_{1}$ elements and Morty's is $s_{2}$ with $k_{2}$ elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like $x$ from his set and the monster will move to his $x$-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins. Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.
For each state of monster ($2n$ possible states, the position and whose turn it is) we will determine if it will be won, lost, or stuck in loop (the player whose turn it is, will win, lose, or the game will never end if this state happens). For this purpose, first each state with monster on $1$ is lost. Then if we consider a graph that its vertices are our $2n$ states, we will recursively determine the answer for each vertex. If a state has an edge to a lost state, it's won, and if all its edges are to won states, it's lost. The vertices that are neither lost or won at the end have answer "loop". You can implement this using a simple memoize. Time complexity: $O(n^{2})\,$
[ "dfs and similar", "dp", "games" ]
2,000
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 7000 + 10; int n; int mod(int x){ while(x >= n) x -= n; return x; } vi v[2]; int dp[maxn][2], deg[maxn][2]; // 1 for WIN and 2 for LOSE void go(int i, int j){ int op = !j; rep(x, v[op]){ int p = mod(i + n - x); if(dp[p][op]) continue ; if(dp[i][j] == 1){ -- deg[p][op]; if(!deg[p][op]){ dp[p][op] = 2; go(p, op); } } else{ dp[p][op] = 1; go(p, op); } } } int main(){ iOS; cin >> n; For(i,0,2){ int k; cin >> k; while(k--){ int a; cin >> a; v[i].pb(a); } } For(i,0,n) For(j,0,2) deg[i][j] = (int)v[j].size(); dp[0][0] = dp[0][1] = 2; go(0, 0); go(0, 1); For(j,0,2) For(i,1,n) cout << (dp[i][j]? dp[i][j] == 1? "Win": "Lose": "Loop") << " "[i + 1 == n]; return 0; }
786
B
Legacy
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them. There are $n$ planets in their universe numbered from $1$ to $n$. Rick is in planet number $s$ (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial. By default he can not open any portal by this gun. There are $q$ plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more. Plans on the website have three types: - With a plan of this type you can open a portal from planet $v$ to planet $u$. - With a plan of this type you can open a portal from planet $v$ to any planet with index in range $[l, r]$. - With a plan of this type you can open a portal from any planet with index in range $[l, r]$ to planet $v$. Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.
Consider a weighted directed graph (initially it has $n$ vertices and no edges). We will construct a segment tree to handle queries of second type (and one for the third type but with similar approach). Build a segment tree on number $1, ..., n$. For each node of segment tree consider a vertex in the graph. For each leaf in this tree (like one with interval $[l, l + 1)$), add an edge with weight equal to $0$ from vertex corresponding to this node to vertex $l$ in the original graph. And for each non-leaf node, add an edge with weight equal to $0$ from vertex corresponding to this node to the vertex corresponding to node of each of its children. So we're adding about $4n$ vertices and edges to the graph. For each query of second type, we will add an edge from $v$ to each maximal node of segment tree that $[l, r)$ contains ($lg(n)$ nodes for each query) with weight equal to $w$. And construct a segment tree in the same way for queries of third type. Finally run Dijkstra's algorithm on this graph. Time complexity: $O(n l g^{2}(n))$
[ "data structures", "graphs", "shortest paths" ]
2,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, int> pli; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e5 + 100; const ll inf = 1LL << 60; int ver[2][4 * maxn]; // 0: to [l, r], 1: from [l, r] vector<pii> adj[9 * maxn]; ll dis[9 * maxn]; bool mark[9 * maxn]; int n, q, s, nx; priority_queue <pli, vector<pli>, greater<pli>> pq; void build(int t, int id = 1, int l = 0, int r = n){ ver[t][id] = nx ++; if(r - l < 2){ if(!t) adj[ver[t][id]].pb({l, 0}); else adj[l].pb({ver[t][id], 0}); return ; } int mid = (l + r) >> 1; build(t, L(id), l, mid); build(t, R(id), mid, r); if(!t) adj[ver[t][id]].pb({ver[t][L(id)], 0}), adj[ver[t][id]].pb({ver[t][R(id)], 0}); else adj[ver[t][L(id)]].pb({ver[t][id], 0}), adj[ver[t][R(id)]].pb({ver[t][id], 0}); } void add(int v, int w, int x, int y, int t, int id = 1, int l = 0, int r = n){ if(x >= r or l >= y) return ; if(x <= l && r <= y){ if(!t) adj[v].pb({ver[t][id], w}); else adj[ver[t][id]].pb({v, w}); return ; } int mid = (l + r) >> 1; add(v, w, x, y, t, L(id), l, mid); add(v, w, x, y, t, R(id), mid, r); } int main(){ scanf("%d %d %d", &n, &q, &s); -- s; nx = n; build(0), build(1); while(q--){ int type; scanf("%d", &type); if(type == 1){ int v, u, w; scanf("%d %d %d", &v, &u, &w); -- v, -- u; adj[v].pb({u, w}); } else{ int v, l, r, w; scanf("%d %d %d %d", &v, &l, &r, &w); -- v, -- l; add(v, w, l, r, type-2); } } fill(dis, dis + 9 * maxn, inf); dis[s] = 0; pq.push({0LL, s}); while(!pq.empty()){ int v = pq.top().y; pq.pop(); if(mark[v]) continue ; mark[v] = true; rep(p, adj[v]){ int u = p.x, w = p.y; if(dis[u] > dis[v] + w){ dis[u] = dis[v] + w; pq.push({dis[u], u}); } } } For(i,0,n) printf("%lld ", (dis[i] == inf? -1: dis[i])); puts(""); return 0; }
786
C
Till I Collapse
Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated $n$ Mr. Meeseeks, standing in a line numbered from $1$ to $n$. Each of them has his own color. $i$-th Mr. Meeseeks' color is $a_{i}$. Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most $k$ different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each $1 ≤ i ≤ e ≤ j ≤ n$, if Mr. Meeseeks number $i$ and Mr. Meeseeks number $j$ are in the same squad then Mr. Meeseeks number $e$ should be in that same squad. Also, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized. Rick and Morty haven't finalized the exact value of $k$, so in order to choose it, for each $k$ between $1$ and $n$ (inclusive) need to know the minimum number of presidios needed.
Your task is to find the minimum number of parts needed to partition this such that each part contains no more than $k$ different numbers. For a fixed $k$, we can greedily find the answer. First, fix a maximal partition with at most $k$ different numbers in it, then a maximal after that and so on. If answer for $k$ is $ans(k)$, we can find this number in $O(a n s(k)l g(n))$. The only thing we want is to find maximum $r$ for a fixed $l$ so that $[l, r]$ has at most $k$ distinct numbers. This can be done with binary search + segment tree, but it's too slow. We can do this using a persistent segment tree in $O(l g(n))$: for a fixed $l$, we define $f_{l}(i)$ to be $1$ if $l \le i$ and there's no such $j$ that $l \le j < i$ and $a_{i} = a_{j}$ otherwise $0$. So, if we have a segment tree on every $f_{l}$, we can use this segment tree to find the first $r$ for an arbitrary $k$ (it's like finding $k - th$ one in this array). So we find the answer in $O(a n s(k)l g(n))$, so the total complexity is $O(\sum_{k=1}^{n}a n s(k)l g(n))$, and because $a n s(k)\leq{\frac{n}{k}}$, $\sum_{k=1}^{n}a n s(k)=O(n l g(n))$, so: Total time complexity: $O(n l g^{2}(n))$.
[ "data structures", "divide and conquer" ]
2,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) //#define L(x) ((x)<<1) //#define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e5 + 100, maxl = 40; int a[maxn], nx[maxn], pr[maxn], nxt = 1, root[maxn], n; vi v[maxn]; int s[maxn * maxl], L[maxn * maxl], R[maxn * maxl]; inline void build(int id = 0, int l = 0, int r = n){ if(r - l < 2){ s[id] = pr[l] == -1; return ; } L[id] = nxt ++; R[id] = nxt ++; int mid = (l + r) >> 1; build(L[id], l, mid); build(R[id], mid, r); s[id] = s[L[id]] + s[R[id]]; } inline int upd(int p, int val, int id, int l = 0, int r = n){ int ID = nxt ++; s[ID] = s[id] + val; L[ID] = L[id]; R[ID] = R[id]; if(r - l < 2) return ID; int mid = (l + r) >> 1; if(p < mid) L[ID] = upd(p, val, L[id], l, mid); else R[ID] = upd(p, val, R[id], mid, r); return ID; } inline int kth(int k, int id, int l = 0, int r = n){ if(s[id] < k) return n; if(r - l < 2) return l; int mid = (l + r) >> 1; if(s[L[id]] >= k) return kth(k, L[id], l, mid); else return kth(k - s[L[id]], R[id], mid, r); } int main(){ memset(nx, -1, sizeof nx); memset(pr, -1, sizeof pr); scanf("%d", &n); For(i,0,n){ scanf("%d", a+i); -- a[i]; v[a[i]].pb(i); } For(i,0,n) For(j,1,(int)v[i].size()) nx[v[i][j-1]] = v[i][j], pr[v[i][j]] = v[i][j-1]; build(); root[0] = 0; For(i,1,n){ int cur = root[i-1]; cur = upd(i-1, -1, cur); if(~nx[i-1]) cur = upd(nx[i-1], 1, cur); root[i] = cur; } For(k,1,n+1){ int ans = 0; if(k == n) ans = 1; else{ int cur = 0; while(cur < n){ ++ ans; cur = kth(k+1, root[cur]); } } printf("%d ", ans); } puts(""); return 0; }
786
D
Rap God
Rick is in love with Unity. But Mr. Meeseeks also love Unity, so Rick and Mr. Meeseeks are "love rivals". Unity loves rap, so it decided that they have to compete in a rap game (battle) in order to choose the best. Rick is too nerds, so instead he's gonna make his verse with running his original algorithm on lyrics "Rap God" song. His algorithm is a little bit complicated. He's made a tree with $n$ vertices numbered from $1$ to $n$ and there's a lowercase english letter written on each edge. He denotes $str(a, b)$ to be the string made by writing characters on edges on the shortest path from $a$ to $b$ one by one (a string of length equal to distance of $a$ to $b$). Note that $str(a, b)$ is reverse of $str(b, a)$ and $str(a, a)$ is empty. In order to make the best verse he can, he needs to answer some queries, but he's not a computer scientist and is not able to answer those queries, so he asked you to help him. Each query is characterized by two vertices $x$ and $y$ ($x ≠ y$). Answer to this query is the number of vertices like $z$ such that $z ≠ x, z ≠ y$ and $str(x, y)$ is lexicographically larger than $str(x, z)$. String $x = x_{1}x_{2}...x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}...y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ..., x_{|y|} = y_{|y|}$, or exists such number $r (r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ..., x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters are compared like their ASCII codes (or alphabetic order). Help Rick get the girl (or whatever gender Unity has).
Use centroid-decomposition. In each decomposition: Assume $c$ is centroid of current subtree. Then for each vertex $v$ in current subtree, we want to find some part of answer for each query with $x = v$. More precisely, for each query $(x, y)$ that $x$ is in the current subtree (in the decomposition), we want to find the number of vertices like $z$ such that $z$ is also in the subtree, if we remove the centroid from the tree $z$ and $x$ will be disconnected (centroid itself satisfies this condition) and $str(x, z) < str(x, y)$. $str(x, z) = str(x, c) + str(c, z)$. So for each query first compare $str(x, y)$ with $str(x, c)$. Comparing two paths ($str(x, y)$ and $str(v, u)$) can be done using hash (for each $v$ and $k$, keep hash of $str(v, 2^{i} - th parent of v)$ and its reverse) and using binary search for finding LCP of two strings. Based on result of comparison: If $str(x, y) < str(x, c)$, then there's no such $z$ in current subtree. If $str(x, y) > str(x, c)$ and $str(x, c)$ is not a prefix of $str(x, y)$, then all vertices like $z$ that satisfy the first two conditions (from the three conditions above) are counted. Otherwise there's a vertex $e$ on path from $x$ to $y$ such that $str(x, w) = str(x, c)$. Because $str(x, z) = str(x, c) + str(c, z)$ and $str(x, y) = str(x, w) + str(w, y) = str(x, c) + str(w, y)$, then you have to count such $z$ that satisfy the first two conditions and $str(c, z) < str(w, y)$. For the third case, you need to count vertices like $z$ that $str(c, z) < str(w, y)$. For this purpose, using a single DFS construct trie of all $str(c, z)$ and then for each query find the position of $str(w, y)$ in the trie (using hashes and binary search). More precisely, you need to find LCP of $str(w, y)$ and strings in the trie to determine how many strings in the trie are less than $str(w, y)$. All of this can be done in $O((n+q)l g^{2}(n))$ And there's an additional $log$ for centroid-decomposition, so: Total time complexity: $O((n+q)l g^{3}(n))$
[ "data structures", "dfs and similar", "hashing", "strings", "trees" ]
3,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 2e4 + 100, maxl = 15; int mod[2] = {(int)1e9 + 7, (int)1e9 + 9}, base[2] = {717, 749}; int pw[2][maxn], centroid; int par[maxn][maxl], up[maxn][maxl][2], dw[maxn][maxl][2], h[maxn], p2[maxl]; typedef pair<int, char> edge; int n, q; pii query[maxn]; vi queries[maxn]; int ANS[maxn]; vector<edge> adj[maxn]; char c2p[maxn]; bool block[maxn]; int sz[maxn]; inline void dfs(int v = 0, int p = -1, char ch = -1){ if(~p){ h[v] = h[p] + 1; c2p[v] = ch; For(e,0,2) up[v][0][e] = dw[v][0][e] = c2p[v] - 'a'; par[v][0] = p; } For(i,1,maxl){ if(~par[v][i-1]) par[v][i] = par[par[v][i-1]][i-1]; if(~par[v][i]) For(e,0,2){ up[v][i][e] = (1LL * up[v][i-1][e] * pw[e][p2[i-1]] + up[par[v][i-1]][i-1][e]) % mod[e]; dw[v][i][e] = (1LL * dw[par[v][i-1]][i-1][e] * pw[e][p2[i-1]] + dw[v][i-1][e]) % mod[e]; } } rep(e, adj[v]){ int u = e.x; if(u - p) dfs(u, v, e.y); } } inline int lca(int v, int u){ if(h[v] < h[u]) swap(v, u); rof(i,maxl-1,-1) if(~par[v][i] && h[par[v][i]] >= h[u]) v = par[v][i]; if(v == u) return v; rof(i,maxl-1,-1) if(par[v][i] - par[u][i]) v = par[v][i], u = par[u][i]; return par[v][0]; } inline int dist(int v, int u){ return h[v] + h[u] - 2 * h[lca(v, u)]; } inline int kth_anc(int v, int k){ rof(i,maxl-1,-1) if(k >= p2[i]){ k -= p2[i]; v = par[v][i]; assert(~v); } return v; } inline int kth_on_path(int v, int u, int k){ int x = lca(v, u); int a = h[v] - h[x], b = h[u] - h[x]; assert(a + b >= k); if(a >= k) return kth_anc(v, k); return kth_anc(u, a + b - k); } inline char kth_edge_on_path(int v, int u, int k){ int x = lca(v, u); int a = h[v] - h[x], b = h[u] - h[x]; assert(a + b >= k); if(a >= k) return c2p[kth_anc(v, k-1)]; return c2p[kth_anc(u, a + b - k)]; } inline pii hash_up(int v, int u){ int ans[2] = {}; rof(i,maxl-1,-1) if(~par[v][i] && h[par[v][i]] >= h[u]){ For(e,0,2) ans[e] = (1LL * ans[e] * pw[e][p2[i]] + up[v][i][e]) % mod[e]; v = par[v][i]; } return {ans[0], ans[1]}; } inline pii hash_dw(int v, int u){ int ans[2] = {}; int cur = 0; rof(i,maxl-1,-1) if(~par[v][i] && h[par[v][i]] >= h[u]){ For(e,0,2) ans[e] = (ans[e] + 1LL * pw[e][cur] * dw[v][i][e]) % mod[e]; cur += p2[i]; v = par[v][i]; } return {ans[0], ans[1]}; } inline pii hash_path(int v, int u){ int x = lca(v, u); int a = h[v] - h[x], b = h[u] - h[x]; pii U = hash_up(v, x), D = hash_dw(u, x); return {(1LL * U.x * pw[0][b] + D.x) % mod[0], (1LL * U.y * pw[1][b] + D.y) % mod[1]}; } bool olcp; inline int lcp(int v, int u, int x, int y){ int d1 = dist(v, u), d2 = dist(x, y); int r = 1 + min(d1, d2), l = 0; while(l + 1 < r){ int mid = (l + r) >> 1; int w = kth_on_path(v, u, mid), z = kth_on_path(x, y, mid); if(hash_path(v, w) == hash_path(x, z)) l = mid; else r = mid; } return l; } inline int cmp(int v, int u, int x, int y){ // first: neg, second: pos olcp = true; if(v == u && x == y) return 0; if(x == y) return 1; if(v == u) return -1; olcp = false; int d1 = dist(v, u), d2 = dist(x, y); int l = lcp(v, u, x, y); if(l == d1 || l == d2) olcp = true; if(d1 == d2 && l == d1) return 0; if(l == d1) return -1; if(l == d2) return 1; int c1 = kth_edge_on_path(v, u, l+1) - 'a', c2 = kth_edge_on_path(x, y, l+1) - 'a'; assert(c1 != c2); return c1 - c2; } int thash[maxn * 2][2], tri[maxn * 2][27], nx = 1; typedef pair<pii, int> piii; vector<piii > mp; vi weight[maxn * 2]; vector<pii> qth[maxn * 2]; int sig[maxn], tot; inline void clean(){ For(i,0,nx){ thash[i][0] = thash[i][1] = 0; For(j,0,27) tri[i][j] = 0; rep(w, weight[i]) if(~w) sig[w] = 0; weight[i].clear(); qth[i].clear(); } tot = 0; nx = 1; mp.clear(); } inline void dfs_on_trie(int v = 0){ rep(qt, qth[v]){ int q = qt.x, afc = qt.y; int ans = tot; if(~afc) ans -= sig[afc]; ANS[q] += ans; } rep(w, weight[v]){ ++ tot; if(~w) ++ sig[w]; } For(i,0,27) if(tri[v][i]) dfs_on_trie(tri[v][i]); } inline int MP(pii p){ pair<pii, int> P = make_pair(p, -1); lower_bound(all(mp), P); int x = lower_bound(all(mp), make_pair(p, -1)) - mp.begin(); if(x == (int)mp.size()) return -1; if(mp[x].x != p) return -1; return mp[x].y; } inline void insert(int q, int afc){ int ov = query[q].x, u = query[q].y; int v = kth_on_path(ov, u, dist(ov, centroid)); int d = dist(v, u); int l = 0, r = d + 1; while(l + 1 < r){ int mid = (l + r) >> 1; int w = kth_on_path(v, u, mid); if(~MP(hash_path(v, w))) l = mid; else r = mid; } int w = kth_on_path(v, u, l); if(u == w) qth[MP(hash_path(v, w))].pb({q, afc}); else{ int cur = MP(hash_path(v, w)); assert(~cur); int c = kth_edge_on_path(v, u, l+1) - 'a'; if(!tri[cur][c]) tri[cur][c] = nx ++; cur = tri[cur][c]; qth[cur].pb({q, afc}); } } inline void add_to_trie(int v, int c){ tri[v][c] = nx ++; int u = tri[v][c]; For(e,0,2) thash[u][e] = (1LL * thash[v][e] * base[e] + c) % mod[e]; pii p = {thash[u][0], thash[u][1]}; mp.pb(piii(p, u)); piii ww = mp[0]; } inline void dfs_add(int v, int p = -1, int cur = 0, int afc = -1){ weight[cur].pb(afc); rep(e, adj[v]){ int u = e.x, c = e.y - 'a'; if(block[u] or u == p) continue; if(!tri[cur][c]) add_to_trie(cur, c); dfs_add(u, v, tri[cur][c], (v == centroid? u: afc)); } } inline void dfs_insert(int v, int p = -1, int afc = -1){ rep(q, queries[v]){ int u = query[q].y; int res = cmp(v, u, v, centroid); if(res < 0) continue ; if(res && !olcp) ANS[q] += sz[centroid] - (~afc? sz[afc]: 1); else insert(q, afc); } rep(e, adj[v]){ int u = e.x; if(block[u] or u == p) continue; dfs_insert(u, v, (v == centroid? u: afc)); } } inline int DFS(int v, int p = -1){ sz[v] = 1; rep(e, adj[v]){ int u = e.x; if(u - p && !block[u]) sz[v] += DFS(u, v); } return sz[v]; } inline void centroid_decomposition(int v = 0){ int N = DFS(v), prv = -1; bool fnd = true; while(fnd){ fnd = false; rep(e, adj[v]){ int u = e.x; if(!block[u] && u != prv && sz[u] * 2 >= N){ prv = v; v = u; fnd = true; break ; } } } block[v] = true; rep(e, adj[v]){ int u = e.x; if(!block[u]) centroid_decomposition(u); } centroid = v; DFS(v); dfs_add(v); mp.pb({{0, 0}, 0}); sort(all(mp)); mp.resize(unique(all(mp)) - mp.begin()); dfs_insert(v); dfs_on_trie(); clean(); block[v] = false; } int main(){ memset(par, -1, sizeof par); For(i,0,maxl) p2[i] = 1 << i; For(e,0,2){ pw[e][0] = 1; For(i,1,maxn) pw[e][i] = (1LL * pw[e][i-1] * base[e]) % mod[e]; } iOS; cin >> n >> q; For(i,1,n){ int v, u; char c; cin >> v >> u >> c; ++ c; -- v, -- u; adj[v].pb({u, c}); adj[u].pb({v, c}); } For(i,0,q){ int v, u; cin >> v >> u; -- v, -- u; query[i] = {v, u}; queries[v].pb(i); } dfs(); centroid_decomposition(); For(i,0,q) cout << -- ANS[i] << ' '; return 0; }
786
E
ALT
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy. ALT has $n$ cities numbered from $1$ to $n$ and $n - 1$ bidirectional roads numbered from $1$ to $n - 1$. One can go from any city to any other city using these roads. There are two types of people in ALT: - Guardians. A guardian lives in a house alongside a road and guards the road. - Citizens. A citizen lives in a house inside a city and works in an office in another city. Every person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road. Rick and Morty talked to all the people in ALT, and here's what they got: - There are $m$ citizens living in ALT. - Citizen number $i$ lives in city number $x_{i}$ and works in city number $y_{i}$. - Every day each citizen will go through all roads along the shortest path from his home to his work. - A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy). - A guardian is always happy. You need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.
If $n$ and $m$ were smaller: We construct a bipartite graph. For each citizen we consider a vertex in the first part, and for each guardian in the tree we consider a vertex in the second part. We put an edge between vertex $i$ from first part and $j$ from second part if and only if path $x_{i}$ to $y_{i}$ contains edge $j$. Answer to the problem is vertex cover of this graph. Time complexity: $O(n^{2}m)$ But now that $n$ and $m$ are great, we can't use this approach. We will instead build a DAG. Like above, For each citizen we consider a vertex in the first part, and for each guardian in the tree we consider a vertex in the second part. Consider the data structure that is used to find LCA of two vertices in the tree (keeping $2^{i}$-th ancestor of each vertex for each $i$). We will use that to build the graph. For each vertex $v$ in the tree and $i$ ($0 \le i \le lg(n)$), we consider a vertex in the tree, this vertex is $pr(v, i)$. We'll build a flow network. For each $v$, we put an edge from $pr(v, 0)$ to the vertex corresponding to edge (guardian) connecting $v$ and its parent (with capacity = $ \infty $). For each $i > 0$, we put an edge from $pr(v, i)$ to $pr(v, i - 1)$ with capacity = $ \infty $ and one to $pr(2^{i - 1} - th parent of v, i - 1)$ with capacity = $ \infty $. Then for each citizen, like the algorithm we used to find the LCA of $x_{i}$ and $y_{i}$, when we're going up from a vertex $v$ to its $i$-th parent, we put an edge from vertex corresponding to citizen $i$ to $pr(v, i)$ with capacity = $1$. Finally we consider a vertex $S$ as source and $T$ and sink. For each citizen $i$, we put an edge from $S$ to vertex corresponding to him/her with capacity = $1$. And for each guardian put an edge from vertex corresponding to this edge to $T$ with capacity = $1$. It can be shown that the answer to the original problem is maximum flow of this network. Also certificate can be found using a DFS (it's exactly like finding a certificate(vertex cover) in maximum-matching approach). Since the network contains levels(cuts) from $S$ to $T$ with all edges with capacity equal to $1$, the total time complexity is $O(E{\sqrt{E}})$ where $E$ is the number of edges in the network which is $O(n\lg(n))$, so: Time complexity: $O(n{\sqrt{n}}l g(n))$
[ "data structures", "flows", "graphs", "trees" ]
3,200
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef pair<vi, vi> pvv; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 2e4 + 100, maxl = 15; template <class FlowT> class MaxFlow{ public: static const int maxn = 4e5+100, maxm = 1e6+100; static const FlowT FlowEPS = FlowT(1e-8), FlowINF = FlowT(1 << 29); int to[maxm * 2], prv[maxm * 2], hed[maxn], dis[maxn], pos[maxn]; int mat[maxn][2], stat[maxn], assignee[maxn]; bool mark[maxn]; FlowT cap[maxm * 2]; int n, m; inline void init(int N){ n = N, m = 0; memset(hed, -1, n * sizeof hed[0]); memset(stat, -1, sizeof mat); memset(mat, -1, sizeof mat); memset(assignee, -1, sizeof assignee); } private: inline void add_single_edge(int v, int u, FlowT c){ assert(m < 2*maxm); to[m] = u, prv[m] = hed[v], cap[m] = c, hed[v] = m ++; } public: void set_ver(int v, int s, int a){ stat[v] = s, assignee[v] = a; } inline void add_edge(int v, int u, FlowT c){ add_single_edge(v, u, c); add_single_edge(u, v, 0); } inline bool bfs(int source, int sink){ static int qu[maxn], head, tail; head = tail = 0; memset(dis, -1, n * sizeof dis[0]); dis[source] = 0; qu[tail ++] = source; while(head < tail){ int v = qu[head ++]; for(int e = hed[v]; e + 1; e = prv[e]) if(cap[e] > FlowEPS && dis[to[e]] == -1) dis[to[e]] = dis[v] + 1, qu[tail ++] = to[e]; if(dis[sink] + 1) break ; } return dis[sink] + 1; } inline FlowT dfs(int v, int sink, FlowT cur = FlowINF){ if(v == sink) return cur; FlowT ans = 0; for(int &e = pos[v]; e + 1; e = prv[e]) if(cap[e] > FlowEPS && dis[to[e]] == dis[v] + 1){ FlowT tmp = dfs(to[e], sink, min(cur, cap[e])); cur -= tmp; ans += tmp; cap[e] -= tmp; cap[e ^ 1] += tmp; if(cur <= FlowEPS/2) break ; } return ans; } inline FlowT flow(int source, int sink){ FlowT ans = 0; while(bfs(source, sink)){ memcpy(pos, hed, n * sizeof hed[0]); ans += dfs(source, sink); } return ans; } inline int dfs(int v){ if(stat[v] == 1) return v; for(int &e = pos[v]; e + 1; e = prv[e]){ if((e & 1) or !cap[e ^ 1]) continue ; -- cap[e ^ 1]; ++ cap[e]; return dfs(to[e]); } return -1; } inline void find_matches(){ memcpy(pos, hed, n * sizeof hed[0]); For(v,0,n) if(!stat[v]){ int u = dfs(v); if(~u) mat[v][0] = u, mat[u][1] = v; } } inline void DFS(int v){ mark[v] = true; if(stat[v] == 1){ if(~mat[v][1]) DFS(mat[v][1]); return ; } for(int e = hed[v]; e + 1; e = prv[e]) if(!(e & 1)){ int u = to[e]; if(!mark[u]) DFS(u); } } inline pvv vertex_cover(){ // (top, bottom) = (queries, edges) find_matches(); fill(mark, mark + maxn, false); For(v,0,n) if(!stat[v] && mat[v][0] == -1) DFS(v); vi q, e; For(v,0,n){ if(!stat[v] && ~mat[v][0] && !mark[mat[v][0]]) q.pb(assignee[v]); else if(stat[v] == 1 && mark[v]){ assert(~mat[v][1]); e.pb(assignee[v]); } } return pvv(q, e); } }; MaxFlow<int> F; const int N = 4e5; const int S = 0, T = 1; int nx = 2; vector<pii> adj[maxn]; int par[maxn][maxl], inp[maxn][maxl]; int h[maxn]; inline void dfs(int v = 0, int p = -1, int ep = -1){ par[v][0] = p; if(~p){ h[v] = h[p] + 1; inp[v][0] = nx; F.set_ver(nx, 1, ep); F.add_edge(nx ++, T, 1); } For(i,1,maxl) if(~par[v][i-1]){ par[v][i] = par[par[v][i-1]][i-1]; if(~par[v][i]){ inp[v][i] = nx; F.add_edge(nx, inp[v][i-1], N); F.add_edge(nx ++, inp[par[v][i-1]][i-1], N); } } rep(ue, adj[v]){ int u = ue.x, e = ue.y; if(u - p) dfs(u, v, e); } } inline int lca(int v, int u, int ver){ if(h[v] < h[u]) swap(v, u); rof(i,maxl-1,-1) if(~par[v][i] && h[par[v][i]] >= h[u]){ F.add_edge(ver, inp[v][i], N); v = par[v][i]; } if(v == u) return v; rof(i,maxl-1,-1) if(par[v][i] != par[u][i]){ F.add_edge(ver, inp[v][i], N); F.add_edge(ver, inp[u][i], N); v = par[v][i], u = par[u][i]; } F.add_edge(ver, inp[v][0], N); F.add_edge(ver, inp[u][0], N); return par[v][0]; } int main(){ iOS; memset(par, -1, sizeof par); int n, m; cin >> n >> m; F.init(N); For(i,1,n){ int v, u; cin >> v >> u; -- v, -- u; adj[v].pb({u, i}); adj[u].pb({v, i}); } dfs(); For(i,0,m){ int v, u; cin >> v >> u; -- v, -- u; int ver = nx; F.set_ver(nx, 0, i + 1); F.add_edge(S, nx++, 1); lca(v, u, ver); } assert(nx < N); cout << F.flow(S, T) << ' '; pvv pv = F.vertex_cover(); vi vc[2] = {pv.x, pv.y}; For(i,0,2){ cout << vc[i].size() << ' '; rep(v, vc[i]) cout << v << ' '; cout << ' '; } return 0; }
787
A
The Monster
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times $b, b + a, b + 2a, b + 3a, ...$ and Morty screams at times $d, d + c, d + 2c, d + 3c, ...$. The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
You need to find out if there are non-negative integers like $i$ and $j$ such $ai + b = cj + d$ and $i$ or $j$ (or both) is minimized. It's easy to show that if $a, b, c, d \le N$, and such $i$ and $j$ exist, then $i, j \le N$, so you can iterate over $i$ and check if such $j$ exists. Time complexity: ${\mathcal{O}}(n)$
[ "brute force", "math", "number theory" ]
1,200
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxi = 1e5; int main(){ iOS; int a, b, c, d; cin >> a >> b >> c >> d; For(i,0,maxi){ int v = a*i + b; if(v < d) continue ; int u = v - d; if(u % c == 0){ cout << v << endl; return 0; } } cout << -1 << endl; return 0; }
787
B
Not Afraid
Since the giant heads have appeared in the sky all humanity is in danger, so \textbf{all} Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are $n$ parallel universes participating in this event ($n$ Ricks and $n$ Mortys). I. e. each of $n$ universes has one Rick and one Morty. They're gathering in $m$ groups. Each person can be in many groups and a group can contain an arbitrary number of members. Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility). Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all $2^{n}$ possible scenarios, $2$ possible scenarios for who a traitor in each universe) such that in that scenario the world will end.
The problem says given a CNF formula, check if we can set value of literals such that the formula isn't satisfied. Answer is yes if and only if you can set values so that at least one clause isn't satisfied. It's easy to show that answer is yes if and only if there's at least one clause that for that clause there's no $i$ such that $x_{i}$ and $\overline{{x_{i}}}$ are both in it. This can be easily implemented. Time complexity: $O(n+m)$
[ "greedy", "implementation", "math" ]
1,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" ) "; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" ) "; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T> inline void smax(T &x,T y){ x = max((x), (y));} template <class T> inline void smin(T &x,T y){ x = min((x), (y));} const int maxn = 1e6 + 100; int lst[maxn * 2]; int main(){ int n, m; scanf("%d %d", &n, &m); For(i,1,m+1){ vi v; int k; scanf("%d", &k); bool ok = false; while(k--){ int x; scanf("%d", &x); if(lst[maxn-x] == i) ok = true; lst[maxn+x] = i; } if(!ok){ puts("YES"); return 0; } } puts("NO"); return 0; }
788
A
Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function $f$, which is defined as follows: \[ f(l,r)=\sum_{i=l}^{r-1}|a[i]-a[i+1]|\cdot(-1)^{i-l} \] In the above formula, $1 ≤ l < r ≤ n$ must hold, where $n$ is the size of the Main Uzhlyandian Array $a$, and $|x|$ means absolute value of $x$. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of $f$ among all possible values of $l$ and $r$ for the given array $a$.
We can solve the problem for segments with odd and even $l$ separately. Let's build arrays $b$ ($b_{i} = |a_{i + 1} - a_{i}| \cdot ( - 1)^{i}$) and $c$ ($c_{i} = |a_{i + 1} - a_{i}| \cdot ( - 1)^{i + 1}$). Obviously, that segment with the greatest sum in array $b$ starts in some even index. In every segment starting in odd index we can move $l$ one position right and make answer not-worse, because every element of odd index in $b$ is non-positive. Also, sum of segment starting in even index of $b$ equals to value of $f$ on the same segment. Analogically for array $c$ and odd starting indexes. So the answer equals to maximal of maximal sums of arrays $b$ and $c$. The segment with the greatest sum can be found with the two pointers method or using prefix sums. Such solution works with $O(N)$ complexity.
[ "dp", "two pointers" ]
1,600
null
788
B
Weird journey
Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia. It is widely known that Uzhlyandia has $n$ cities connected with $m$ bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over $m - 2$ roads twice, and over the other $2$ exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths.
We can consider the system of towns and roads as a graph, where edges correspond to roads and vertexes to cities. Now, let's fix two edges, that will be visited once. All other edges we can split into two. Then, the good way in the old graph equivalents to any Euler path in the computed one. Widely known that Euler path exists in graph when and only when there are 0 or 2 vertexes with odd degree. Consider following cases of mutual placement of edges that will be visited once: Regular(not loops) edges that are not adjacent - graph has four vertexes with odd degree, so Euler path doesn't exist. Regular edges that are adjacent - graph has exactly two vertexes with odd degree, so Euler path exists. So, any pair of adjacent regular edges satisfies Igor. One of the edges is a loop - graph hasn't any vertex with the odd degree(if another chosen edge is a loop too) or has two of them(if another chosen edge is regular). So, any pair in which at least one edge is a loop satisfies Igor. So, we have to calculate the number of pairs of adjacent regular edges and add the answer for loops. For every vertex $i$ we can calculate $cnt_{i}$ - the number of regular edges incoming in it. General number of adjacent regular edges is $\sum_{i=1}^{n}C_{c n t}^{2},$. Also, we need to add the number of pairs with loops. Let's count $loop$ - general number of loops in the graph. So we can add $loop \cdot (m - 1)$ to the answer. Now, we included pairs with two loops twice. That's why we need to subtract $C_{loop}^{2}$ - the number of pairs with two loops. Also, we need to check the graph to be connected by edges. If the graph is not connected then the answer is 0. We can do it using algorithms of DFS or BFS. Complexity of the given solution if $O(N + M)$.
[ "combinatorics", "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,100
null
788
C
The Great Mixing
Sasha and Kolya decided to get drunk with Coke, again. This time they have $k$ types of Coke. $i$-th type is characterised by its carbon dioxide concentration $\frac{d i_{i}}{1000}$. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration $\frac{p_{L}}{1000}$. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration $\frac{p_{L}}{1000}$. Assume that the friends have unlimited amount of each Coke type.
Let $\frac{p_{L}}{1000}$ - needed concentration and $s_{1}, s_{2}, ..., s_{m}$ - concentration of types we'll use. ${\frac{s_{1}+s_{2}+\cdot\cdot\cdot\cdot+s_{m}}{1000\cdot m}}={\frac{n}{1000}}$${\frac{s_{1}+s_{2}+\cdot\cdot\cdot+s_{m}}{m}}=n$ $s_{1}+s_{2}+\cdot\cdot\cdot+s_{m}=n\cdot m$ $s_{1}+s_{2}+\cdot\cdot\cdot\cdot+s_{m}=n+n+\cdot\cdot\cdot+n$ $(s_{1}-n)+(s_{2}-n)+\cdot\cdot\cdot+(s_{m}-n)=0$ ${\frac{s_{1}+s_{2}+\cdot\cdot\cdot+s_{m}}{m}}=n$ $s_{1}+s_{2}+\cdot\cdot\cdot+s_{m}=n\cdot m$ $s_{1}+s_{2}+\cdot\cdot\cdot\cdot+s_{m}=n+n+\cdot\cdot\cdot+n$ $(s_{1}-n)+(s_{2}-n)+\cdot\cdot\cdot+(s_{m}-n)=0$ Then, we can decrease every $s_{i}$ by $n$. So, we reduced the problem to finding a set of numbers with zero sum. Now we can build a graph, where vertexes are our sum. There will be $m$ edges from each vertex, where $m$ - the number of different concentrations. Obviously, we'll have at most 1001 different concentrations, so there are at most 1001 edges from each vertex. Now, we need to find a cycle of smallest length. We can do this using BFS starting from vertex 0. With BFS we can find the first vertex with the existing edge to vertex 0. We need at most 1000 vertexes to each side (from -1000 to 1000), so the solution complexity is $O(2001 \cdot min(k, 1001))$.
[ "dfs and similar", "graphs", "shortest paths" ]
2,300
null
788
D
Finding lines
After some programming contest Roma decided to try himself in tourism. His home country Uzhlyandia is a Cartesian plane. He wants to walk along each of the Main Straight Lines in Uzhlyandia. It is known that each of these lines is a straight line parallel to one of the axes (i.e. it is described with the equation $x = a$ or $y = a$, where $a$ is integer called the coordinate of this line). Roma lost his own map, so he should find out the coordinates of all lines at first. Uncle Anton agreed to help him, using the following rules: - Initially Roma doesn't know the number of vertical and horizontal lines and their coordinates; - Roma can announce integer coordinates of some point in Uzhlandia, and Anton then will tell him the minimum among the distances from the chosen point to each of the lines. However, since the coordinates of the lines don't exceed $10^{8}$ by absolute value, Roma can't choose a point with coordinates exceeding $10^{8}$ by absolute value. Uncle Anton is in a hurry to the UOI (Uzhlandian Olympiad in Informatics), so he can only answer no more than $3·10^{5}$ questions. The problem is that Roma doesn't know how to find out the coordinates of the lines. Write a program that plays Roma's role and finds the coordinates.
First we solve another problem. Let we have points not straight lines, but points on one axis. Let $MAX = 10^{8}$, that is, the maximum coordinate. First, we find the left and right points. The left is ($- MAX + get( - MAX)$), and the right one ($MAX - get(MAX)$). Then we solve the problem recursively. There will be a function $f(l, r)$ that finds all points on the segment $(l, r)$ if $l$ and $r$ - are points. We have already found the extreme points, so we can call this function. The function $f(l, r)$ makes a query at the center point between $l$ and $r$, that is, $\frac{l\pm r}{2}$. If the answer is equal to the distance to the extreme points, then there are no more points between $l$ and $r$. If the distance is less, then for one more query we can find out the point on the left or right. Let this point $x$, then we start $f(l, x)$ and $f(x, r)$. We introduce a function that checks if there is a vertical line $x$. We can select a random point in the range $[ - MAX, MAX]$ and make a query, if the answer $0$ - is a straight line. If $MAX = 10^{8}$, and the maximum $n = 10^{4}$, then the error probability is $10^{ - 4}$, if you querys twice, then $10^{ - 8}$. Now we will solve the main task. We make a query at the point $( - MAX, - MAX)$, we can find out whether the minimum distance to the vertical or horizontal line. We introduce the function $G(x, y)$, which will find the nearest straight line whose coordinates are greater than $x$ or $y$, and $get(x, y) = 0$. How is this solved? If there are no more lines, then for non-negative $t$, $get(x + t, y + t) = t$. Then we can find a minimal power such that $get(x + t, y + t) \neq t$. Then we know that this applies to either the vertical line $(x + t + get(x + t, y + t))$, or the horizontal $(y + t + get(x + t, y + t))$ . We can find out which one. If, for example, to the vertical one, then we solve the problem for $G(x + t + get(x + t, y + t), y)$. Then we find either all horizontal lines, or all vertical lines. To find out which straight lines we found, we need to look at the last function $G(x, y)$, namely our "ray". If it rests on the vertical straight $MAX$, then we find all the vertical ones. And vice versa. Now how to find other lines. Let's say we found all the vertical ones. Then we will find the maximum distance between the neighbors, between the first line and $( - MAX)$, between the last line and $(MAX)$, this distance will be at least $\textstyle{\frac{M A X}{M A X N}}$. That is, we search in what position the maximum will be reached, if there are no horizontal lines, let it be $val$. Let this be the coordinate $x$, we will make queries on the line $x$, starting with - $- MAX$, ending with $MAX$, with the step $\frac{v a l}{4}$. We find all the points whose answer is not equal to $val$. Then we can divide all these points into "segments", that is, a set of points that go successively. For each "segment", the minimum distance will only apply to horizontal lines, that is, vertical ones will not affect in any way. Therefore, each "segment" can be solved independently, by the method already known to us (assume that there are no vertical lines).
[ "constructive algorithms", "divide and conquer", "interactive" ]
3,000
null
788
E
New task
On the 228-th international Uzhlyandian Wars strategic game tournament teams from each country are called. The teams should consist of $5$ participants. The team of Uzhlyandia will consist of soldiers, because there are no gamers. Masha is a new minister of defense and gaming. The prime duty of the minister is to calculate the efficiency of the Uzhlandian army. The army consists of $n$ soldiers standing in a row, enumerated from $1$ to $n$. For each soldier we know his skill in Uzhlyandian Wars: the $i$-th soldier's skill is $a_{i}$. It was decided that the team will consist of three players and two assistants. The skills of players should be same, and the assistants' skills should not be greater than the players' skill. Moreover, it is important for Masha that one of the assistants should stand in the row to the left of the players, and the other one should stand in the row to the right of the players. Formally, a team is five soldiers with indexes $i$, $j$, $k$, $l$, $p$, such that $1 ≤ i < j < k < l < p ≤ n$ and $a_{i} ≤ a_{j} = a_{k} = a_{l} ≥ a_{p}$. The efficiency of the army is the number of different teams Masha can choose. Two teams are considered different if there is such $i$ such that the $i$-th soldier is a member of one team, but not a member of the other team. Initially, all players are able to be players. For some reasons, sometimes some soldiers become unable to be players. Sometimes some soldiers, that were unable to be players, become able to be players. At any time any soldier is able to be an assistant. Masha wants to control the efficiency of the army, so she asked you to tell her the number of different possible teams modulo $1000000007$ ($10^{9} + 7$) after each change.
To begin with, we apply scaling to all numbers and replace each element of the array with its position in the sorted array. Count the answer for the original array. For each $i$, calculate smaller_pref$_{i}$ as the quantity of such $j$ that $j < i$, $a_{j} \le a_{i}$ and smaller_suf$_{i}$ - the number of such $j$ that $j > i$, $a_{j} \le a_{i}$. This can be done with a segment tree or a Fenwick tree. If we consider each element as $k$ from the command $[i, j, k, l, p]$, then the answer for fives with this $k$ is $(\sum_{j=1}^{k-1}$smaller_pref$_{j}$$, a_{j} = a_{k})$$ \cdot $$({{\sum}_{j=k+1}^{n}})$smaller_suf$_{j}$$, a_{j} = a_{k})$. The common answer is the sum of the answers for each possible $k$. Now after each request we will update the answer. We will support for each type of number for the prefix and suffix for 2 segment tree. Since when, an element turns on/off it is important to know only information about elements with the same value, then you can update the answer using only it. Consider array b as a number vector of occurrences of the form $a_{u}$. In the first "suffix tree" in the sheet we store smaller_suf$_{bi}$, if the element with the number $b_{i}$ is included, otherwise 0, and in the remaining vertices the sum in the sons. In the second suffix tree we store in the sheet smaller_suf$_{bi}$$ \cdot $((the number $j$, such that $a_{j} = a_{bi}$, $< b[i]$, element with the number $j$ - is included) + 1), if the element with the number $b_{i}$ is included, otherwise 0, and in the remaining vertices the sum in the sons. For the prefix, you need to do exactly the same thing. Let $cnt_{au}$ be the number of numbers of the form $a_{u}$. Now when the request for turning off/on the element with number $u$ came, we need to subtract/add to the answer the number of such pentads [$i$, $j$, $k$, $l$, $p$] where $u = k$, $u = j$, $u = l$. Further $c_{u} =$ ((the quantity $j$, $j < u$, $a_{j} = a_{u}$) + 1). In other words, $c_{u}$ - is the number in the occurrence vector of numbers of the form $a_{u}$). First, consider the number of fives where $u = k$. Them is (the sum on the interval [1;$c_{u}$-1] in the first prefix tree) $ \cdot $ (the sum on the segment [$c_{u}$+1;$cnt_{au}$] in the first "suffix tree"). The number of fives where $u = j$ is ((the sum on the segment [$c_{u}$+2;$cnt_{au}$] in the second "suffix tree" segments) - ((the number of elements j, $j \le u$, $a_{j} = a_{u}$, the element with the number $j$ is included) +1)$ \cdot $ (the sum on the segment [$c_{u}$+2;$cnt_{au}$] in the first "suffix tree" segments ))$ \cdot $smaller_pref$_{u}$. The number of fives where $u = l$ must be calculated in the same way as for $u = j$, only in the other direction. Updating the values of the suffix tree elements: When the item is turned off, you need: Take the sum on the segment [$c_{u}$+1;$cnt_{au}$] in the second segment tree in the same segment in the first tree. Assign the element with the number $c_{u}$ to the element in the second segments tree 0. Assign the element with the number $c_{u}$ in the first tree 0. When you enable an item, you need: Add on the segment [$c_{u}$+1;$cnt_{au}$] in the second segment tree the sum on the same line in the first tree. Assign the element with the number $c_{u}$ in the second tree (the number of such $j$, $j \le u$, $a_{j} = a_{u}$, the element j is included) + 1)$ \cdot $smaller_suff$_{u}$. Assign the element with the number $c_{u}$ in the first tree smaller_suf$_{u}$. The update in the tree with the prefix is the same. Adding on the segment will be done by a kind of lazy pushing - in the second segment tree you need to have access to the corresponding vertex of the first tree, when changing the vertex, add/subtract the sum at the top of the first segment tree. The complexity of the solution is $O(N \cdot logN + M \cdot logN))$ by time, $O(N)$ by memory.
[ "data structures" ]
2,900
null
789
A
Anastasia and pebbles
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only \textbf{two pockets}. She can put at most $k$ pebbles in each pocket at the same time. There are $n$ different pebble types in the park, and there are $w_{i}$ pebbles of the $i$-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day. Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
For every pebble type we can count the minimal number of pockets Anastasia need to collect all pebbles of this type. That's easy to notice that this number equals $\textstyle\left[{\frac{\boldsymbol{w_{j}}}{k}}\right]$. So the answer for the problem is $\textstyle\left[\frac{\sum_{i=1}^{n}|\frac{-i}{k}\vert}{2}\right]$. Solution complexity is $O(N)$.
[ "implementation", "math" ]
1,100
null
789
B
Masha and geometric depression
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression $b$ defined by two integers $b_{1}$ and $q$. Remind that a geometric progression is a sequence of integers $b_{1}, b_{2}, b_{3}, ...$, where for each $i > 1$ the respective term satisfies the condition $b_{i} = b_{i - 1}·q$, where $q$ is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both $b_{1}$ and $q$ \textbf{can equal $0$}. Also, Dvastan gave Masha $m$ "bad" integers $a_{1}, a_{2}, ..., a_{m}$, and an integer $l$. Masha writes all progression terms one by one onto the board (including repetitive) while condition $|b_{i}| ≤ l$ is satisfied ($|x|$ means absolute value of $x$). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term. But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
We need to handle following cases in the solution: $|b_{1}| > l$ - answer is 0. $b_{1} = 0$ - if 0 is present in array $a$ than answer is 0, else $inf$. $q = 1$ - if $b_{1}$ is present in array $a$ than answer is 0, else $inf$. $q = - 1$ - if both $b_{1}$ and $- b_{1}$ are present in array $a$ than answer is 0, otherwise $inf$. $q = 0$ - if 0 isn't present in array $a$ than answer is $inf$, else if $b_{1}$ is present in $a$ than answer is 0, else answer is 1. In all other cases we can simply iterate over all terms of progression $b$ while their absolute value doesn't exceed $l$. For every term that is not present in $a$ we simply increasing answer by 1. Obviously, the absolute value of every next element is bigger in at least 2 times than the absolute value of previous. That's why we'll need to check at most $log$ $l$ progression terms. Solution complexity is $O(M \cdot log$$L)$ or $O(M \cdot log$$M + log$$L \cdot log$$M)$.
[ "brute force", "implementation", "math" ]
1,700
null
791
A
Bear and Big Brother
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh $a$ and $b$ respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year. After how many full years will Limak become strictly larger (strictly heavier) than Bob?
This problem is simple: just multiply $a$ by $3$ and $b$ by $2$ until $a > b$. Output the number of operations. You will not need more than $6$ iterations.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int a, b; cin >> a >> b; int answer = 0; while(a <= b) { a *= 3; b *= 2; ++answer; } printf("%d\n", answer); }
792
A
New Bus Route
There are $n$ cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers $a_{1}, a_{2}, ..., a_{n}$. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
At first let's notice that if there exists such triple $a_{i}$, $a_{j}$ and $a_{k}$ that $a_{i} < a_{j} < a_{k}$, then $|a_{k} - a_{i}| > |a_{j} - a_{i}|$ and $|a_{k} - a_{i}| > |a_{k} - a_{j}|$. Thus we can sort all numbers and check only adjacent ones. There are exactly $n - 1$ of such pairs. The only thing left is to find minimal distance of all pairs and count pairs with that distance. Overall complexity: $O(n\log n)$
[ "implementation", "sortings" ]
1,100
null
792
B
Counting-out Rhyme
$n$ children are standing in a circle and playing the counting-out game. Children are numbered clockwise from $1$ to $n$. In the beginning, the first child is considered the leader. The game is played in $k$ steps. In the $i$-th step the leader counts out $a_{i}$ people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader. For example, if there are children with numbers $[8, 10, 13, 14, 16]$ currently in the circle, the leader is child $13$ and $a_{i} = 12$, then counting-out rhyme ends on child $16$, who is eliminated. Child $8$ becomes the leader. You have to write a program which prints the number of the child to be eliminated on every step.
The task was just about implementing algorithm described in statement. This is one of many possible ways of doing this. Firstly you should notice that doing $a_{i}$ iterations in $i$-th step is equal to doing $a_{i}$ $mod$ $(n - i)$ iterations ($0$-based numbering). That is less than $n$. Now fill array of length $n$ with ones and create pointer to current leader. Then on $i$-th step move pointer to the right (from cell $n - 1$ proceed to $0$) till you encounter $a_{i}$ $mod$ $(n - i)$ ones. When finished, write $0$ to this cell and move pointer to next cell which contains $1$. Overall complexity: $O(n^{2})$.
[ "implementation" ]
1,300
null
792
C
Divide by Three
A positive integer number $n$ is written on a blackboard. It consists of not more than $10^{5}$ digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible. The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of $3$. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not. Write a program which for the given $n$ will find a beautiful number such that $n$ can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number $n$. If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Let's declare a function which takes number as a string and erases minimal number of digits in substring from $2$-nd to last character to obtain beautiful number. Note that if the answer for given string exists, then this function will erase no more than $2$ digits. If the number is divisible by $3$ then sum of its digits is also divisible by $3$. So here are the only options for the function: Sum of digits is already equal to $0$ modulo $3$. Thus you don't have to erase any digits. There exists such a digit that equals sum modulo $3$. Then you just have to erase this digit. All of the digits are neither divisible by $3$, nor equal to sum modulo $3$. So two of such digits will sum up to number, which equals sum modulo $3$ ($(2 + 2)$ $mod$ $3 = 1$, $(1 + 1)$ $mod$ $3 = 2$). Let positions of non-zero numbers be $a_{1}, a_{2}, ..., a_{k}$. Then you can easily see that its enough to check only three function outputs: on substrings $[a_{1}..n]$, $[a_{2}..n]$ and $[a_{3}..n]$. We imply that all digits to the left of the taken non-zero digit are erased. As we can erase no more than $2$ digits, these options will cover all the cases. If there exists no answer for any of substrings, than you need to check if the number contains $0$ - it will be answer in that case. If there is no $0$, then answer is $- 1$. Otherwise the answer is the function output of maximal length. Overall complexity: $O(n)$.
[ "dp", "greedy", "math", "number theory" ]
2,000
null
792
D
Paths in a Complete Binary Tree
$T$ is a complete binary tree consisting of $n$ vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So $n$ is a number such that $n + 1$ is a power of $2$. In the picture you can see a complete binary tree with $n = 15$. Vertices are numbered from $1$ to $n$ in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given $n$ answers $q$ queries to the tree. Each query consists of an integer number $u_{i}$ ($1 ≤ u_{i} ≤ n$) and a string $s_{i}$, where $u_{i}$ is the number of vertex, and $s_{i}$ represents the path starting from this vertex. String $s_{i}$ doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from $s_{i}$ have to be processed from left to right, considering that $u_{i}$ is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by $s_{i}$ ends. For example, if $u_{i} = 4$ and $s_{i} = $«UURL», then the answer is $10$.
In this editorial $x$ represents the number of vertex we are currently in. Let $k$ be the maximum integer number such that $x$ is divisible by $2^{k}$ (or the number of zeroes at the end of the binary representation of $x$). It is easy to prove that if $k = 0$, then $x$ is a leaf; if $k = 1$, then both children of $x$ are leaves, and so on. Even more, the difference between $x$ and any of his children is exactly $2^{k - 1}$. So to traverse to the left child, we have to subtract $2^{k - 1}$ from $x$ (if $x$ is not a leaf), and to traverse to the right child, we add $2^{k - 1}$ to $x$. How can we process traversions up? Let $y$ be the number of the parent node. $y$ has exactly $k + 1$ zeroes at the end of its binary representation, so to traverse from $y$ to $x$, we need to either add or subtract $2^{k}$ from $y$. And to traverse from $x$ to $y$ we also have to either subtract or add $2^{k}$ to $x$. One of these operations will lead us to the number divisible by $2^{k + 1}$ and not divisible by $2^{k + 2}$, and we need to choose this operation. Time complexity is $O(\sum_{i=1}^{q}|s_{i}|)$.
[ "bitmasks", "trees" ]
1,900
null
792
E
Colored Balls
There are $n$ boxes with colored balls on the table. Colors are numbered from $1$ to $n$. $i$-th box contains $a_{i}$ balls, all of which have color $i$. You have to write a program that will divide all balls into sets such that: - each ball belongs to exactly one of the sets, - there are no empty sets, - there is no set containing two (or more) balls of different colors (each set contains only balls of one color), - there are no two sets such that the difference between their sizes is greater than $1$. Print the minimum possible number of sets.
If we want to divide all balls from some box into $k$ sets with sizes $x$ and $x + 1$ (and there are $a_{i}$ balls in this box), then either $k\leq{\sqrt{a_{i}}}$ or $x\leq{\sqrt{a_{i}}}$. So the solution will be like that: Iterate over the possible sizes of sets $x$ (from $1$ to $|{\sqrt{a_{1}}}|$, or to some constant - in our solution it's $40000$) and check if we can divide all balls into sets with sizes $x$ and $x + 1$, Then iterate over the number of sets $k$, calculate the sizes of sets if we want to divide the first box exactly into $k$ sets and try to divide balls from all other boxes into sets of these sizes. If we want to divide $a_{i}$ balls from the same box into $k$ sets, then the sizes will be $\left\lfloor{\frac{a_{k}}{k}}\right\rfloor$ and $\lfloor{\frac{a_{i}}{k}}\rfloor+1$; but if $a_{i}{\dot{z}}{\dot{k}}$, then we also have to check if sizes can be $\left\vert{\frac{a_{i}}{k}}\right\vert-1$ and $\left\lfloor{\frac{a_{k}}{k}}\right\rfloor$. If we fix sizes $x$ and $x + 1$ and we want to check whether we can divide a box with $a_{i}$ balls into sets with these sizes (and to get the minimum possible number of such sets), then the best option will be to take $\textstyle{\left[{\frac{a_{i}}{x+1}}\right]}$ sets. If $x\cdot\lceil{\frac{a_{i}}{x+1}}\rceil\leq a_{i}$, then such division is possible. If not, then it's impossible to divide $a_{i}$ balls into sets of $x$ and $x + 1$ balls. Time complexity of this solution is $O(n\cdot{\sqrt{a_{1}}})$.
[ "greedy", "math", "number theory" ]
2,500
null
792
F
Mages and Monsters
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is characterized by two values $x_{i}$ and $y_{i}$ — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage $x$ and mana cost $y$ for $z$ seconds, then he will deal $x·z$ damage and spend $y·z$ mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously. Also Vova can fight monsters. Every monster is characterized by two values $t_{j}$ and $h_{j}$ — monster kills Vova's character in $t_{j}$ seconds and has $h_{j}$ health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones. Vova's character kills a monster, if he deals $h_{j}$ damage to it in no more than $t_{j}$ seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. \textbf{If monster's health becomes zero exactly in $t_{j}$ seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight}. You have to write a program which can answer two types of queries: - $1$ $x$ $y$ — Vova's character learns new spell which deals $x$ damage per second and costs $y$ mana per second. - $2$ $t$ $h$ — Vova fights the monster which kills his character in $t$ seconds and has $h$ health points. \textbf{Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.} For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
Let's represent spells as points on cartesian plane. If we consider three spells $A$, $B$ and $C$ such that $A_{x} \le B_{x} \le C_{x}$ and $B$ is above $AC$ on the cartesian plane or belongs to it, then we don't need to use spell $B$ because we can replace it with a linear combination of spells $A$ and $C$ without any additional mana cost. We can maintain the lower boundary of the convex hull of all points from $1$-type queries and the point $(0, 0)$. Then to process $2$-type query we have to find the intersection of aforementioned lower boundary and the line $x={\frac{h_{i}}{t_{j}}}$ (our average damage in this fight has to be at least this value). If there is no intersection, then the answer is NO because even with infinite mana Vova's character can't deal that much damage before dying. If there is an intersection, we have to check that it is not higher than the line $y={\frac{m}{t_{j}}}$ to ensure that we have enough mana to kill the monster in given time. Model solution uses only integral calculations, but it seems that long double precision is enough. Time complexity: $O(q \cdot log$ $q)$.
[ "data structures", "geometry" ]
3,100
null
793
A
Oleg and shares
Oleg the bank client checks share prices every day. There are $n$ share prices he is interested in. Today he observed that each second exactly one of these prices decreases by $k$ rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all $n$ prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
Let's notice that as prices can only decrease and answer should be minimum possible, all prices should become equal to minimum among given prices. Formally, answer is $\sum_{i=1}^{n}{\frac{a_{i}-\operatorname*{min}a_{1},......a_{r}}{k}}$, if exists no such $i$ that $(a_{i}-\operatorname*{min}a_{1},\ldots,a_{n}){\mathrm{~mod~}}k\neq0$, otherwise answer is <<$- 1$>>.
[ "implementation", "math" ]
900
null
793
B
Igor and his way to work
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make \textbf{no more than two turns} on his way to his office in bank. Bankopolis looks like a grid of $n$ rows and $m$ columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
This problem has many solutions. The simplest of them is the following. Let's go over all cells where we can get before or after the first turn using simple recursive brute force. For every cell we should check if there exists a path from current cell to Igor's office. We can do it using prefix sums or even naively. Other solutions are dfs over graph of states ${\mathrm{[row.~column.~current~direction.~number~of~turns~made}}\,$ or $0$-$1$ bfs over graph of states $(\mathrm{row},\;\mathrm{column},\;\mathrm{current}\;\;\mathrm{direction})$.
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
1,600
"#include <bits/stdc++.h>\n#define left lolkek\n \nusing namespace std;\n \nint n, m;\nvector<int> dx = {-1, 1, 0, 0};\nvector<int> dy = {0, 0, -1, 1};\nvector<char> dir = {'L', 'R', 'U', 'D'};\nvector<vector<int>> grid;\nvector<vector<int>> left;\nvector<vector<int>> up;\nint si = 0;\nint sj = 0;\nint ti = 0;\nint tj = 0;\n \nstring path;\n \nvoid dfs(int i, int j, int d, int t) {\n path += dir[d];\n if (t > 1 || i < 1 || i > n || j < 1 || j > m || grid[i][j] == 1) {\n path.pop_back();\n return;\n }\n if (j == tj) {\n int occ = up[max(ti, i)][j] - up[min(ti, i) - 1][j];\n if (occ == 0) {\n cout << \"YES\";\n exit(0);\n }\n } else if (i == ti) {\n int occ = left[i][max(tj, j)] - left[i][min(tj, j) - 1];\n if (occ == 0) {\n cout << \"YES\";\n exit(0);\n }\n }\n for (int d1 = 0; d1 < 4; d1++) {\n if (d1 == d || d1 == (d ^ 1)) continue;\n dfs(i + dy[d1], j + dx[d1], d1, t + 1);\n }\n dfs(i + dy[d], j + dx[d], d, t);\n path.pop_back();\n}\n \nint main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n cin >> n >> m;\n grid.assign(n + 1, vector<int>(m + 1, 0));\n string inp;\n for (int i = 0; i < n; i++) {\n cin >> inp;\n for (int j = 0; j < m; j++) {\n if (inp[j] == '*') {\n grid[i + 1][j + 1] = 1;\n }\n if (inp[j] == 'S') {\n si = i + 1;\n sj = j + 1;\n } else if (inp[j] == 'T') {\n ti = i + 1;\n tj = j + 1;\n }\n }\n }\n left.assign(n + 1, vector<int>(m + 1, 0));\n up.assign(n + 1, vector<int>(m + 1, 0));\n for (int i = 1; i <= n; i++) {\n for (int j = 1; j <= m; j++) {\n left[i][j] = left[i][j - 1] + grid[i][j];\n up[i][j] = up[i - 1][j] + grid[i][j];\n }\n }\n for (int d = 0; d < 4; d++) {\n dfs(si + dy[d], sj + dx[d], d, 0);\n }\n cout << \"NO\";\n}\n "
793
C
Mice problem
Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them. The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$. Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the $i$-th mouse is equal to $(v_{i}^{x}, v_{i}^{y})$, that means that the $x$ coordinate of the mouse increases by $v_{i}^{x}$ units per second, while the $y$ coordinates increases by $v_{i}^{y}$ units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are \textbf{strictly} inside the mousetrap. Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.
If at least one point will go on the border of rectangle then answer is <<$- 1$>>. For every point there exists (or doesn't exist) some segment of time when it's inside the rectangle. Then let's seperatly find segment when $x$ belongs to $(x_{1};x_{2})$ and $y$ inside $(y_{1};y_{2})$. Then we can intersect them and get time segment when point is inside the rectangle. To find answer for 1D task we can just check some cases and solve linear equations. There are two ways to do it, we can just do $x_{1}$ += $eps$, $x_{2}$ -= $eps$, $y_{1}$ += $eps$, $y_{2}$ -= $eps$ and then solve task not strictly, or solve strictly using fractions as pairs of integers to maintain good accuracy and using intervals instead of segments. Then let's find intersection of all segments/intervals and if it is not empty print it's left border.
[ "geometry", "implementation", "math", "sortings" ]
2,300
null
793
D
Presents in Bankopolis
Bankopolis is an incredible city in which all the $n$ crossroads are located on a straight line and numbered from $1$ to $n$ along it. On each crossroad there is a bank office. The crossroads are connected with $m$ oriented bicycle lanes (the $i$-th lane goes from crossroad $u_{i}$ to crossroad $v_{i}$), the difficulty of each of the lanes is known. Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly $k$ offices, in each of them he wants to gift presents to the employees. The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the $i$-th lane passes near the office on the $x$-th crossroad if and only if $min(u_{i}, v_{i}) < x < max(u_{i}, v_{i})))$. Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly $k - 1$ bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office. Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
At any time Oleg can make correct move to crossroad from two segments: from crossroad $v$ he can go to crossroads from segment $[a;v - 1]$ or from segment $[v + 1;b]$. After we go from crossroad v to some crossroad u from segment $[a;v - 1]$ there appear two new segments: $[a;u - 1]$ and $[u + 1;v - 1]$. If we go from crossroad v to some crossroad u from segment $[v + 1;b]$, then two new segments will be $[v + 1;u - 1]$ and $[u + 1;b]$. Then you can think about dp solution like $dp[v][a][b][cnt]$, and try each $to$, so $a \le to \le b$ and recalc $dp[to][a][v - 1][cnt + 1]$, $dp[to][v + 1][b][cnt + 1]$. Time complexity: $O((n + m) * n^{2} * k)$. But we can optimize this solution: Notice that we don't need to know $b$ if we want to go to the left and we don't need to know $a$ if we want to go to the right. Then we can make $dp[v][go][cnt]$. If $v < go$ then we have a segment $[v + 1;go]$, else $[go;v - 1]$. Then if $v < go$ we need to recalc $dp[to][v + 1][cnt + 1]$ and $dp[to][go][cnt + 1]$, otherwise $dp[to][go][cnt + 1]$ and $dp[to][v - 1][cnt + 1]$. Time complexity: $O((n + m) * n * k)$.
[ "dp", "graphs", "shortest paths" ]
2,100
null
793
E
Problem of offices
Earlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices. Once Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offices of the bank following the same route every day. The collectors started from the central department and moved between some departments or between some department and some office using special roads. Finally, they returned to the central department. The total number of departments and offices was $n$, the total number of roads was $n - 1$. In other words, the special roads system was a rooted tree in which the root was the central department, the leaves were offices, the internal vertices were departments. The collectors always followed the same route in which the number of roads was minimum possible, that is $2n - 2$. One of the collectors said that the number of offices they visited between their visits to offices $a$ and then $b$ (in the given order) is equal to the number of offices they visited between their visits to offices $b$ and then $a$ (in this order). The other collector said that the number of offices they visited between their visits to offices $c$ and then $d$ (in this order) is equal to the number of offices they visited between their visits to offices $d$ and then $c$ (in this order). The interesting part in this talk was that the shortest path (using special roads only) between any pair of offices among $a$, $b$, $c$ and $d$ \textbf{passed through the central department}. Given the special roads map and the indexes of offices $a$, $b$, $c$ and $d$, determine if the situation described by the collectors was possible, or not.
Formal statement: we have a rooted tree, let it contain $m$ leaves. We can reorder sons of any vertex. We have to reorder tree in such way that while doing Eulerian tour (from vertex we go to it's first son, then to it's second son etc.) between visiting $a$ and $b$ we will visit exactly ${\frac{m}{2}}-1$ leaves, and same for $c$ and $d$. Let's separately consider case when tree has odd number of leaves - then answer is <<NO>>. Otherwise let's start visiting given leaves from $a$. Then we will visit $c$, then $b$ and then $d$. Amount of visited leaves between visiting $a$ and $b$ depends on how we will order subtrees on path from root to $a$, same for $b$, and also which sons of root we will place between $a$ and $b$ (subtree with $c$ will always be there). $\operatorname{Let~a~size~of~subtree~be~amount~of~leaves~in~it.}$ After this we can notice that the set of possible distances between $a$ and $b$ is the set of knapsack solutions on following items: sizes of root sons except those that contain $a$, $b$, $c$, $d$, sizes of branching subtrees on path to $a$ and sizes of branching subtrees on path to $b$. With these items we should get knapsack of weight equal to ${\operatorname*{m}_{2}}-1-\mathrm{{size~of~root~son,~containing~c}}.$ Same holds for $c$ and $d$, but now items are sizes of root sons except those that contain $a$, $b$, $c$, $d$, sizes of branching subtrees on path to $c$ and sizes of branching subtrees on path to $d$. With these items we should get knapsack of weight equal to $\textstyle{\frac{m}{2}}-1-\mathrm{size\of\root\son,\,containing\b}.$ If solution of both knapsacks exists, then answer is <<YES>>, otherwise <<NO>>. We can always order items from both knapsacks in needed way. Exactly, all subtrees that are present only in solution of $a$-$b$ knapsack we place on path between $a$ and $c$, subtrees that are present in solutions of both knapsacks we place between $c$ and $b$, subtrees that are present only in solution of $c$-$d$ knapsack we place between $b$ and $d$, and subtrees that aren't present in any solutions we place between $d$ and $a$.
[ "constructive algorithms", "dfs and similar", "dp", "trees" ]
2,900
null
793
F
Julia the snail
After hard work Igor decided to have some rest. He decided to have a snail. He bought an aquarium with a slippery tree trunk in the center, and put a snail named Julia into the aquarium. Igor noticed that sometimes Julia wants to climb onto the trunk, but can't do it because the trunk is too slippery. To help the snail Igor put some ropes on the tree, fixing the lower end of the $i$-th rope on the trunk on the height $l_{i}$ above the ground, and the higher end on the height $r_{i}$ above the ground. For some reason no two ropes share the same position of the higher end, i.e. all $r_{i}$ are distinct. Now Julia can move down at any place of the trunk, and also move up from the lower end of some rope to its higher end. Igor is proud of his work, and sometimes think about possible movements of the snail. Namely, he is interested in the following questions: «Suppose the snail is on the trunk at height $x$ now. What is the highest position on the trunk the snail can get on if it would never be lower than $x$ or higher than $y$?» Please note that Julia can't move from a rope to the trunk before it reaches the higher end of the rope, and Igor is interested in the highest position \textbf{on the tree trunk}. Igor is interested in many questions, and not always can answer them. Help him, write a program that answers these questions.
At first, let's solve this task with $O(r - l)$ time complexity for each query. For each $i$, let's store $back_{i}$ if there is exists a segment [$back_{i}$; $i$] (there's at most one such segment for every $i$). For query [$l$, $r$], let's go from $l$ to $r$, storing rightmost $x$, that is reachable from $l$ (at start it is $l$), then if $(l \le back_{i} \le x)$, then we can add segment [$back_{i}$, $i$] to answer, and say that $x = i$. Now let's apply the following idea. If we found answer for some $p$ $(l \le p \le r)$ answer for query [$l$, $p$], we can find can find answer in $O(r - p)$ time complexity for the whole query [$l$, $r$]. Let's find answers for all $p$ that are divisable by $k$ (for some $k$). For this we have to to calculate additional array $go[i][j]$ that stores answer for segment [$i$, $j * k$]. For this we need to calculate additional array $to[i][j]$ - maximal right border, with left border equal to $i$, that $ \le $ $k * j$ (we can calc this with two pointers method). To find array $go$, run from right to left, and for each $j$ find answer: $go[i][j] = max(go[k][j]), (i \le k \le to[i][j])$ Now we can notice that because we go from right to left that if element should be relaxed with some element $i$, it will be relaxed also with all elements $p$, so $to[p][j] \ge i$. We can store stack for each $j$, pop from them all elements so their index $ \le to[i][j]$, relax with them current value, and then add to stack current value with current index. So we have found array $go$. Then for answering query, if $r - l \le k$ solve naive in $O(r - l)$ else let $p$ be the closest to $r$ number that divides k. $x\to g o[i][{\frac{r}{k}}]$, then for $O(r - x)$ solve other query part. Now time complexity is: $O(q*k+n\ *{\frac{n}{k}})$ Optimal choice of $k$ is $k\approx{\sqrt{n}}$.
[ "data structures", "divide and conquer", "dp" ]
3,000
null
793
G
Oleg and chess
Oleg the bank client solves an interesting chess problem: place on $n × n$ chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell. Remind that a rook standing in the cell $(a, b)$ beats a rook standing in the cell $(x, y)$ if and only if $a = x$ or $b = y$. Unfortunately (of fortunately?) for Oleg the answer in this problem was always $n$, so the task bored Oleg soon. He decided to make it more difficult by removing some cells from the board. If a cell is deleted, Oleg can't put a rook there, but rooks do beat each other "through" deleted cells. Oleg deletes the cells in groups, namely, he repeatedly choose a rectangle with sides parallel to the board sides and deletes all the cells inside the rectangle. Formally, if he chooses a rectangle, lower left cell of which has coordinates $(x_{1}, y_{1})$, and upper right cell of which has coordinates $(x_{2}, y_{2})$, then he deletes all such cells with coordinates $(x, y)$ that $x_{1} ≤ x ≤ x_{2}$ and $y_{1} ≤ y ≤ y_{2}$. It is guaranteed that no cell is deleted twice, i.e. the chosen rectangles do not intersect. This version of the problem Oleg can't solve, and his friend Igor is busy at a conference, so he can't help Oleg. You are the last hope for Oleg! Help him: given the size of the board and the deleted rectangles find the maximum possible number of rooks that could be placed on the board so that no two rooks beat each other.
Naive solution: Make bipartite graph, there is edge $i \rightarrow j$ only if cell $(i, j)$ is free. Then answer is maximum matching. But this solution time complexity is $O(n^{3})$ To get faster solution, let's cut our field into rectangles that are free of occupied cells. We will go from left to right wth line sweep and store all vertical free spaces to the left of the line in the set. Triples $(y1, y2, x)$ - from $y1$ to $y2$ border of free space is $x$. When we meet rectangle $(x1, y1, x2, y2)$, we should take everything that lies between $y1$ and $y2$ in the set, seperate boundary segments, throw out everything that lies inside, construct new rectangles, and add $(y1, y2, x2 + 1)$ to the set. We will have $O(n)$ rectangles. Then for each rectangle $(x1, y1, x2, y2)$ we need to add for all vertices from left part from $x1$ to $x2$ edges to all verticles of right part from $y1$ to $y2$. Let's build segment tree for all verticles of left part, and another segment tree for all vertices from right part. Then to add rectangle of free cells to our graph, lets split segment $[x1;x2]$ into $log$ vertices in segment tree of left part, and segment $[y1;y2]$ into $log$ in segment tree of right part. Then for all pairs of these vertixes add edge with capacity $ \infty $. For all vertices of left segment tree add edges from them to their parents with capacity $ \infty $. For all vertices of right segment tree add edges from their parents to them with capacity $ \infty $. For all leafs of the left segment tree add edge from source to them with capacity 1. For all leafs of the right segment tree add edge from them to sink with capacity 1. Then max flow in this graph is the answer. Why does this work fast? At first let's try the Edmonds-Karp algorithm. It works in $O(nE)$ in this task, where $E$ - is the number of edges, $E=O(n\log^{2}n)$. In the given constraints $E$ is bounded by value about several million, because the rectangles do not intersect. This gives complexity about $10^{10}$, and indeed, this algorithm passes, but very close to the time limit. Let's not try Dinic algorithm. We can prove (using a theorem that is known as Karsanov theorem in Russian) that, similar to matching search, the Dinic algorithm has no more than $O({\sqrt{n\log n}})$ phases. With the use of the same bound on the edges number, we can get around $10^{9}$ operations that is ok. Also there are alternative solution with sparse table.
[ "data structures", "divide and conquer", "flows", "graph matchings" ]
3,400
null
794
A
Bank Robbery
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the $i$-th safe from the left is called safe $i$. There are $n$ banknotes left in all the safes in total. The $i$-th banknote is in safe $x_{i}$. Oleg is now at safe $a$. There are two security guards, one of which guards the safe $b$ such that $b < a$, i.e. the first guard is to the left of Oleg. The other guard guards the safe $c$ so that $c > a$, i.e. he is to the right of Oleg. The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.
This is a simple implementation problem. We iterate through all banknotes one by one and check if Oleg can take each of them. If a banknote is at position $x$, then Oleg can take it if and only if $b < x < c$. This can be checked in $O(1)$ time. Thus, the total complexity is $O(n)$. Note that the information on the starting position of Oleg is useless here.
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int a, b, c; cin>>a>>b>>c; int n; cin>>n; int ans=0; for(int i=0;i<n;i++) { int x; cin>>x; if(x>b&&x<c) ans++; } cout<<ans<<' '; }
794
B
Cutting Carrot
Igor the analyst has adopted $n$ little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into $n$ pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to $1$ and height equal to $h$. Igor wants to make $n - 1$ cuts \textbf{parallel to the base} to cut the carrot into $n$ pieces. He wants to make sure that all $n$ pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area? \begin{center} {\small Illustration to the first example.} \end{center}
Let's find the value of $x_{i}$ explicitly. Suppose we make the $i$-th cut and distance $x_{i}$ from the apex. Then, the ratio of similitude of the isosceles triangle with apex equal to the apex of the carrot and the base equal to the $i$-th cut and the whole carrot is $\scriptstyle{\frac{\pi_{h}}{h}}$. Since the area of this smaller isosceles triangle is the sum of areas of the first $i$ pieces, which is $\textstyle{\frac{L}{n}}$ of the whole carrot. Thus, $({\frac{x_{i}}{h}})^{2}={\frac{i}{n}}$, which is equivalent to $h{\sqrt{\frac{i}{n}}}$. Thus, $x_{i}=h{\sqrt{\frac{i}{n}}}$ and we can find each $x_{i}$ in $O(1)$ time. The total complexity is $O(n)$.
[ "geometry", "math" ]
1,200
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll n, h; cin>>n>>h; for(int i=1;i<=n-1;i++) { cout<<fixed<<setprecision(12)<<sqrt(ld(i)/ld(n))*ld(h); if(i<n-1) cout<<' '; } cout<<' '; }
794
C
Naming Company
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of $n$ letters. Oleg and Igor each have a set of $n$ letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by $n$ question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters $c$ in his set and replace any of the question marks with $c$. Then, a copy of the letter $c$ is removed from his set. The game ends when all the question marks has been replaced by some letter. For example, suppose Oleg has the set of letters ${i, o, i}$ and Igor has the set of letters ${i, m, o}$. One possible game is as follows : Initially, the company name is ???. Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is ${i, o}$. Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is ${i, m}$. Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is ${i}$. In the end, the company name is oio. Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally? A string $s = s_{1}s_{2}...s_{m}$ is called lexicographically smaller than a string $t = t_{1}t_{2}...t_{m}$ (where $s ≠ t$) if $s_{i} < t_{i}$ where $i$ is the smallest index such that $s_{i} ≠ t_{i}$. (so $s_{j} = t_{j}$ for all $j < i$)
First, it is clear that Oleg will place $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$ letters and Igor will place $\textstyle{\left[{\frac{n}{2}}\right]}$ letters. Next, it is clear that Oleg and Igor will both choose their smallest and biggest letters respectively to place in the final string. Thus, we now consider that Oleg places his smallest $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$ letters and Igor places his largest $\textstyle{\left|{\frac{n}{2}}\right|}$ letters. Consider the following greedy strategy. When it's Oleg's turn, he will replace the frontmost question mark with his smallest letter. When it's Igor's turn, he will replace the frontmost question mark with his largest letter. At first glance, you might think that this works. However, there's another case that we haven't considered. Suppose Oleg has the letters ${x, y, z}$ and Igor has the letters ${a, b, c}$. According to our previous strategy, Oleg will place x as the first letter. However, that's not optimal. He can place his letters at the back and force Igor to place the first letter. The reason is because the largest letter of Igor is not larger than the smallest letter of Oleg. Thus, it is beneficial for Oleg to place his letters at the back and force Igor to place his letters in front. So, what exactly will the final string look like? We'll look at the moves one by one. If at some point Oleg's smallest letter is still strictly smaller than Igor's largest letter, then both player must put their smallest (largest if it's Igor) letter as the frontmost letter. Why? Suppose not, then on the next turn the other player will occupy that spot with their best (smallest if Oleg, largest if Igor) letter, and the resulting string will be worse for the current player. This proves that greedy is correct in this case. Now, what if Oleg's smallest letter is not smaller than Igor's largest letter. In this case, both players will want to force the other player to place their own letter at the beginning of the string. It can be proven that in this case, each person will place their current worst (largest if Oleg, smallest if Igor) letter at the back of the string in the optimal strategy. Thus, we can calculate the final string starting from this point and after that reverse this part and combine it with the first part of the string where both players greedily place their best letters in the beginning. Time Complexity : $O(n)$ Many people failed on pretest 6 initially because they didn't consider the second case.
[ "games", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; int main() { ios_base::sync_with_stdio(0); cin.tie(0); string ansl; string ansr; string s,t; cin>>s>>t; sort(s.begin(),s.end()); sort(t.begin(),t.end()); reverse(t.begin(),t.end()); int n = s.length(); deque<char> a,b; for(int i=0;i<(n+1)/2;i++) { a.pb(s[i]); } for(int i=0;i<n/2;i++) { b.pb(t[i]); } bool mode=0; for(int i=0;i<n;i++) { if(i&1) { if(!a.empty()&&a[0]>=b[0]) { mode=1; } if(mode) { ansr+=b.back(); b.pop_back(); } else { ansl+=b[0]; b.pop_front(); } } else //P1's turn { if(!b.empty()&&a[0]>=b[0]) { mode=1; } if(mode) { ansr+=a.back(); a.pop_back(); } else { ansl+=a[0]; a.pop_front(); } } } reverse(ansr.begin(),ansr.end()); ansl+=ansr; cout<<ansl<<' '; }
794
D
Labelling Cities
Oleg the bank client lives in Bankopolia. There are $n$ cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from $1$ to $n$. There are a total of $m$ roads in Bankopolia, the $i$-th road connects cities $u_{i}$ and $v_{i}$. It is guaranteed that from each city it is possible to travel to any other city using some of the roads. Oleg wants to give a label to each city. Suppose the label of city $i$ is equal to $x_{i}$. Then, it must hold that for all pairs of cities $(u, v)$ the condition $|x_{u} - x_{v}| ≤ 1$ holds if and only if there is a road connecting $u$ and $v$. Oleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.
Add each vertex to its own adjacency list. Now, we claim that if it is possible to label the cities to satisfy the problem conditions, then it is possible to do so so that for every two cities with the same adjacency list, they're labelled with the same number. Indeed, if they have the same adjacency list, they must be neighbours. Thus, the difference between their labels is at most $1$. Suppose we label the first vertex $u$ with number $i$ and the second vertex $v$ with the number $i + 1$. Note that since their adjacency lists are equal, a vertex $x$ is a neighbour of $u$ iff it's a neighbour of $v$. Thus, $u$ and $v$ can't have neighbours with labels $i - 1$ or $i + 2$, or else it will contradict the condition. Thus, all neighbours of $u$ and $v$ have labels $i$ or $i + 1$. Thus, we can safely change the label of the second vertex $v$ to $i$ and the conditions will still hold. Thus, we can sort the set of adjacency lists of each vertex, and then group the vertices with the same adjacency list together. Suppose there are $k$ such groups. For simplicity, we can create a new graph where each group represent a vertex of the new graph. Connect two groups $i$ and $j$ if and only if there exist some vertex in group $i$ that connects to a vertex in group $j$. Note that the graph will have at most $O(m)$ edges. Now, if a vertex has degree $ \ge 3$, we can't assign a number to that vertex properly, as one of its neighbours will not have a label which have a difference $ \le 1$ from it. Thus, all vertices in the new graph must have degree $ \le 2$. Since it's connected, it must be either a cycle or a path. However, it can be easily seen that there is no labelling if it's a cycle. Thus, it must be a path. Now, we can just assign the labels to the graph from one end of the path to the other end by the numbers $1$ to $k$. Finally, the label of a vertex is simply the label of its group. This solution can be implemented in $O(m\log m+n)$ time.
[ "dfs and similar", "graphs", "hashing" ]
2,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 300000; pair<vi,int> adj[N+2]; int ans[N+2]; int lab[N+2]; int lab2[N+2]; set<int> adj2[N+2]; vector<ii> edges; struct DSU { int S; struct node { int p; ll sum; }; vector<node> dsu; DSU(int n) { S = n; for(int i = 0; i < n; i++) { node tmp; tmp.p = i; tmp.sum = 0; dsu.pb(tmp); } } void reset(int n) { dsu.clear(); S = n; for(int i = 0; i < n; i++) { node tmp; tmp.p = i; tmp.sum = 0; dsu.pb(tmp); } } int rt(int u) { if(dsu[u].p == u) return u; dsu[u].p = rt(dsu[u].p); return dsu[u].p; } void merge(int u, int v) { u = rt(u); v = rt(v); if(u == v) return ; if(rand()&1) swap(u, v); dsu[v].p = u; dsu[u].sum += dsu[v].sum; } bool sameset(int u, int v) { if(rt(u) == rt(v)) return true; return false; } ll getstat(int u) { return dsu[rt(u)].sum; } }; deque<int> chain; void dfs(int u, int p, bool type) { if(type) chain.pb(u); else chain.push_front(u); int c=0; for(sit it = adj2[u].begin(); it != adj2[u].end(); it++) { int v = (*it); if(v==p) continue; if(p!=-1) { dfs(v,u,type); } else { dfs(v,u,c); c++; } } } int main() { //ios_base::sync_with_stdio(0); cin.tie(0); int n, m; scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { int u, v; scanf("%d %d", &u, &v); u--; v--; adj[u].fi.pb(v); adj[v].fi.pb(u); edges.pb(mp(u,v)); } for(int i = 0; i < n; i++) { adj[i].fi.pb(i); adj[i].se = i; sort(adj[i].fi.begin(),adj[i].fi.end()); } sort(adj,adj+n); int cnt = 1; for(int i = 0; i < n; i++) { if(i==0) { lab[adj[i].se] = cnt; } else { if(adj[i].fi==adj[i-1].fi) { lab[adj[i].se]=cnt; } else { lab[adj[i].se]=++cnt; } } } if(cnt==1) { printf("YES "); for(int i = 0; i < n; i++) { printf("%d ",lab[i]); } printf(" "); return 0; } DSU dsu(cnt+1); for(int i = 0; i < m; i++) { int u = edges[i].fi; int v = edges[i].se; if(lab[u]!=lab[v]) { adj2[lab[u]].insert(lab[v]); adj2[lab[v]].insert(lab[u]); dsu.merge(lab[u],lab[v]); } } bool pos = 1; for(int i = 1; i <= cnt; i++) { if(dsu.rt(i)!=dsu.rt(1)) { pos=0; break; } } if(!pos) { printf("NO "); return 0; } int d1 = 0; for(int i = 1; i <= cnt; i++) { if(adj2[i].size()>2) { printf("NO "); return 0; } if(adj2[i].size()==1) d1++; else assert(adj2[i].size()==2); } if(d1==2) { printf("YES "); dfs(1,-1,0); for(int i = 0; i < chain.size(); i++) { lab2[chain[i]] = i+1; } for(int i = 0; i < n; i++) { printf("%d ",lab2[lab[i]]); } printf(" "); } else { printf("NO "); return 0; } }
794
E
Choosing Carrot
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present. There are $n$ carrots arranged in a line. The $i$-th carrot from the left has juiciness $a_{i}$. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose. To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS. Oleg is a sneaky bank client. When Igor goes to a restroom, he performs $k$ moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first. Oleg wonders: for each $k$ such that $0 ≤ k ≤ n - 1$, what is the juiciness of the carrot they will give to ZS if he makes $k$ extra moves beforehand and both players play optimally?
First, we solve the problem when no one has any extra turns. Suppose we're binary searching the answer. Let all the numbers $ \ge x$ be equal to $1$ and all the numbers $< x$ be equal to $0$. Both players can remove one number from one end of the row. The goal of the first player is to let the remaining number be $1$ and the goal of the second player is to leave $0$ in the end. If the first player can win, this means that the answer is at least $x$. Thus, we first try to solve this simpler problem. We claim that the first player wins if and only if : $n$ is even and one of the two middle numbers is $1$. $n$ is odd, the middle digit is $1$ and at least one of the digits beside the middle digit is $1$ (unless $n = 1$, for which first players wins when the only carrot is labelled $1$) Indeed, once we deduce this, we can easily prove this by induction on $n$. The proof is just doing casework and considering all possible moves. Once we have this fact, we realize we don't actually have to binary search the answer. If $n$ is even, the answer is $\operatorname*{max}(a_{\frac{n}{2}},a_{\frac{n}{2}+1})$ while if $n \ge 3$ is odd, the answer is $\operatorname*{min}(a_{{\frac{n+1}{2}}},\operatorname*{max}(a_{{\frac{n-1}{2}}},a_{{\frac{n+3}{2}}}))$. (If $n = 1$ then the answer is obviously $a_{1}$.) Now, we have to take extra moves into account. Fortunately, it's not very difficult. Having $k$ extra moves just means that Player $1$ can choose to start the game in any subsegment of length $n - k$. Thus, we just have to compute the maximum answer for all subsegments of length $n - k$ for all $0 \le k \le n - 1$. With the formula above, you can find all the answers in $O(n)$ time or even $O(n\log n)$ time if you use sparse table for range maximum query.
[ "games", "math" ]
2,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; int a[300001]; int ans[300001]; int b[300001]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin>>n; int mx=0; for(int i=0;i<n;i++) { cin>>a[i]; mx=max(mx,a[i]); } for(int i=0;i<n-2;i++) { b[i]=min(a[i+1],max(a[i],a[i+2])); } ans[n-1]=mx; int odd=n;int even=n; if(n&1) even=n-1; else odd=n-1; mx=0; for(int i=even;i>=2;i-=2) { int l = (i-1)/2; int r=n-i/2; assert(l<=r); mx=max(mx,max(a[l],a[r])); if(i==even) { assert(r-l<=2); if(r-l==2) { mx=max(mx,a[l+1]); } } ans[n-i]=mx; } mx=0; for(int i=odd;i>=3;i-=2) { int l = i/2-1; int r=n-2-i/2; assert(l<=r); if(i==odd) assert(r-l<=1); mx=max(mx,max(b[l],b[r])); ans[n-i]=mx; } for(int i=0;i<n;i++) { cout<<ans[i]; if(i<n-1) cout<<' '; } cout<<' '; }
794
F
Leha and security system
Bankopolis, the city you already know, finally got a new bank opened! Unfortunately, its security system is not yet working fine... Meanwhile hacker Leha arrived in Bankopolis and decided to test the system! Bank has $n$ cells for clients' money. A sequence from $n$ numbers $a_{1}, a_{2}, ..., a_{n}$ describes the amount of money each client has. Leha wants to make requests to the database of the bank, finding out the total amount of money on some subsegments of the sequence and changing values of the sequence on some subsegments. Using a bug in the system, Leha can requests two types of queries to the database: - 1 l r x y denoting that Leha changes each digit $x$ to digit $y$ in each element of sequence $a_{i}$, for which $l ≤ i ≤ r$ is holds. For example, if we change in number $11984381$ digit $8$ to $4$, we get $11944341$. It's worth noting that Leha, in order to stay in the shadow, never changes digits in the database to $0$, i.e. $y ≠ 0$. - 2 l r denoting that Leha asks to calculate and print the sum of such elements of sequence $a_{i}$, for which $l ≤ i ≤ r$ holds. As Leha is a white-hat hacker, he don't want to test this vulnerability on a real database. You are to write a similar database for Leha to test.
We use a segment tree to solve this problem. For each node, it is sufficient to store two arrays : $sum[i]$, denoting the total contribution of the digit $i$ in the current segment (if a digit is in the tens digit then it contributes $10$ to the sum and etc...), and also $nxt[i]$, what all the digits $i$ in the current segment are changed to. Maintaining these arrays is quite straightforward with lazy propogation. When we push an update down a node, we need to update the nxt array of the children. First, we change $st[id].nxt[u]$ to $v$, where the current update is to change all digits $u$ to $v$. Then, we change $st[id * 2].nxt[i]$ to $st[id].nxt[st[id * 2].nxt[i]]$, where $st[id]$ is the current node and $st[id * 2]$ is one of the children nodes. (Do the same for the right children). You can see the code if you need more details. Finally, update the sum array of the current segment. The total complexity of the code is $O(q*10*\log n)$, which is fast enough.
[ "data structures" ]
2,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<int> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int N = 100000; int a[N+1][10]; struct node { int nxt[10]; ll sum[10]; }; node st[N*4+1]; void combine(int id) { for(int i = 0; i < 10; i++) { st[id].sum[i]=st[id*2].sum[i]+st[id*2+1].sum[i]; } } void build(int id, int l, int r) { if(r-l<2) { for(int i = 0; i < 10; i++) st[id].sum[i]=a[l][i]; for(int i = 0; i < 10; i++) { st[id].nxt[i] = i; } return ; } for(int i = 0; i < 10; i++) { st[id].nxt[i] = i; } int mid=(l+r)>>1; build(id*2,l,mid); build(id*2+1,mid,r); combine(id); } int nxt1[10]; int nxt2[10]; ll sum[10]; void push(int id, int l, int r) { memset(sum,0,sizeof(sum)); if(r-l>=2) { for(int i = 0; i < 10; i++) { nxt1[i] = st[id].nxt[st[id*2].nxt[i]]; nxt2[i] = st[id].nxt[st[id*2+1].nxt[i]]; } for(int i=0;i<10;i++) { st[id*2].nxt[i]=nxt1[i]; st[id*2+1].nxt[i]=nxt2[i]; } } for(int i=0;i<10;i++) { sum[st[id].nxt[i]]+=st[id].sum[i]; } for(int i=0;i<10;i++) { st[id].sum[i]=sum[i]; st[id].nxt[i]=i; } } void update(int id, int l, int r, int ql, int qr, int u, int v) { push(id,l,r); if(ql>=r||l>=qr) return ; if(ql<=l&&r<=qr) { st[id].nxt[u]=v; push(id,l,r); return ; } int mid=(l+r)>>1; update(id*2,l,mid,ql,qr,u,v); update(id*2+1,mid,r,ql,qr,u,v); combine(id); } ll query(int id, int l, int r, int ql, int qr) { push(id,l,r); if(ql>=r||l>=qr) return 0; if(ql<=l&&r<=qr) { ll sum=0; for(int i=1;i<10;i++) { sum+=ll(i)*st[id].sum[i]; } return sum; } int mid=(l+r)>>1; return (query(id*2,l,mid,ql,qr)+query(id*2+1,mid,r,ql,qr)); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, q; cin>>n>>q; for(int i = 0; i < n; i++) { int x; cin>>x; int cur=1; for(int j = 0; j < 9; j++) { a[i][x%10] += cur; x/=10; cur*=10; if(x==0) break; } } build(1,0,n); for(int i = 0; i < q; i++) { int type; cin>>type; if(type==1) { int l,r,u,v; cin>>l>>r>>u>>v; l--; r--; update(1,0,n,l,r+1,u,v); } else { int l,r; cin>>l>>r; l--; r--; ll sum = query(1,0,n,l,r+1); cout<<sum<<' '; } } }
794
G
Replace All
Igor the analyst is at work. He learned about a feature in his text editor called "Replace All". Igor is too bored at work and thus he came up with the following problem: Given two strings $x$ and $y$ which consist of the English letters 'A' and 'B' only, a pair of strings $(s, t)$ is called \underline{good} if: - $s$ and $t$ consist of the characters '0' and '1' only. - $1 ≤ |s|, |t| ≤ n$, where $|z|$ denotes the length of string $z$, and $n$ is a fixed positive integer. - If we replace all occurrences of 'A' in $x$ and $y$ with the string $s$, and replace all occurrences of 'B' in $x$ and $y$ with the string $t$, then the two obtained from $x$ and $y$ strings are equal. For example, if $x = $AAB, $y = $BB and $n = 4$, then (01, 0101) is one of good pairs of strings, because both obtained after replacing strings are "01010101". The \underline{flexibility} of a pair of strings $x$ and $y$ is the number of pairs of good strings $(s, t)$. The pairs are ordered, for example the pairs $($0, 1$)$ and $($1, 0$)$ are different. You're given two strings $c$ and $d$. They consist of characters 'A', 'B' and '?' only. Find the sum of flexibilities of all possible pairs of strings $(c', d')$ such that $c'$ and $d'$ can be obtained from $c$ and $d$ respectively by replacing the question marks with either 'A' or 'B', modulo $10^{9} + 7$.
First, we solve the problem when there're no question marks, i.e. we find a way to calculate the number of good pairs of strings fast for a constant pair of strings $A$ and $B$. Call a pair of strings $(S, T)$ where $|S| \le |T|$ coprime if $S = T$ or $S$ is a prefix of $T$, and if $T = S + X$, then $(X, S)$ is also coprime. $(S, T)$ where $|S| > |T|$ is coprime iff $(T, S)$ is coprime. If $A = B$, then all possible strings work. Thus, we assume $A \neq B$ from now on. We remove the longest common prefix of $A$ and $B$. Thus, we can assume $A[0] \neq B[0]$. Thus, either $S$ is a prefix of $T$ or $T$ is a prefix of $S$. WLOG, $S$ is a prefix of $T$. Let $T = S + X$. Now, $A$ and $B$ consists of only $S$ and $X$. Using this, we can prove by induction on $|S| + |T|$ that $S$ and $T$ must be coprime. One important property of coprime strings is that $S + T = T + S$ holds. (again induction works here) Now, since the strings $S$ and $T$ needs to be coprime, we have $S + T = T + S$. This allows us to swap any neighbouring Ss and Ts (or 'A's and 'B's) in $A$ and $B$, as the resulting strings will still be equal. Thus, swapping repeatedly allows us to sort the strings A and B. (the 'A's appear in front and 'B's appear at the back) Let $x_{A}, x_{B}, y_{A}, y_{B}$ denote the number of As and Bs in the first string and second string respectively. If $(x_{A}, x_{B}) > (y_{A}, y_{B})$, then the answer is $0$. We'll handle the case $(x_{A}, x_{B}) = (y_{A}, y_{B})$ later. Now, assume $x_{A} > y_{A}, x_{B} < y_{B}$. Thus, we have to solve the equation $(x_{A} - y_{A})$ copies of $S$ = $(y_{B} - x_{B})$ copies of $T$. Now, let $x = x_{A} - y_{A}, y = y_{B} - x_{B}$. If $x = y$, then the solution is $S = T$. Otherwise, assume $x > y$. Then, $|S| < |T|$. So, by comparing, we again have $T = S + X$, for some nonempty binary string $X$. Note that $S$ and $X$ must be coprime too, so we can sort the second string as well. We cancel off the Ss on both sides to get $(x - y)S = yX$. Thus, this means that if $(S, T)$ is a solution for $(x, y)$, then $(S, X)$ is a solution for $(x - y, y)$. Note that repeating this process will eventually lead us to $(1, 1)$. (this process is similar to Euclidean Algorithm) The answer for $(1, 1)$ is the number of solutions to $S = T$. Let's denote the solution here as $X$. Doing some backtracking, we realize that the answer for $(x, y)$ is equal to (X....X ($y$ times), X...X ($x$ times)). Note that we still have the condition $|S|, |T| \le N$, so we can translate this to an appropriate condition on the length of $X$ and the answer is simply the number of binary strings of length not exceeding the maximum possible length of $X$. The only case that remains is that $(x_{A}, x_{B}) = (y_{A}, y_{B})$. In this case, any pair of coprime strings $S$ and $T$ will work. Thus, our task reduces to calculating the number of coprime pair of strings with length not exceeding $N$. We claim that the number of coprime pair of strings $(S, T)$ with $|S| = p, |T| = q$ is $2^{\mathrm{Ned}(p,q)}$. If $p = q$ the claim is obviously true. Otherwise, we can induct on $p + q$ agin. If $q > p$, we can write $T = S + X$ and then the number of coprime pairs of $(S, T)$ is equal to the number of coprime pairs of $(S, X)$, which by induction is equal to $2^{\mathrm{gcd}(p,q-p)}=2^{\mathrm{gcd}(p,q)}$. This proves the claim. Thus, we just need to compute the sum of $2^{\mathrm{Ned}(p,q)}$ for all $1 \le p, q \le N$. Indeed, since $N \le 3 \cdot 10^{5}$, it is enough to count the number of pairs $(p, q)$ with $gcd = g$ for all $g$. However, this is quite easy. Let $cnt[i]$ denote the number of pairs $(p, q)$ such that $p$ and $q$ are both divisible by $i$. Let $ans[i]$ denote the number of pairs $(p, q)$ with $gcd = i$. Then, $a n s[i]=c n t[i]+\sum_{i=2}^{\frac{N}{i}}\bigl(\mu(j)\cdot c n t[i\cdot j]\bigr)$. Thus, this can be computed in $O(n\log n)$. Now, we need to find out how to calculate the sum of all these values on two strings $X$ and $Y$ with question marks. Handle the case when the two strings become equal separately. Let's first make a summary of the number of good pairs of strings for constant strings $A$ and $B$. In fact, note that the formulaes above only depends on $(d_{A}, d_{B})$, the difference between the number of As in $A$ and $B$, and the difference between the number of Bs in $A$ and $B$ (note that $d_{A}, d_{B}$ can be negative) If $d_{A} = d_{B} = 0$, then the answer is the sum of $2^{\mathrm{Ned}(p,q)}$ for all $1 \le p, q \le N$, which as we have just saw can be precomputed in time. Otherwise, if $d_{A}, d_{B} \ge 0$ or $d_{A}, d_{B} \le 0$, then there are no good pair of strings. Finally, in other cases, let $p = |d_{A}|, q = |d_{B}|$. Then, the answer is $2^{\frac{N}{m a x(p,q)}}+1\leq2$. This also means that we can compute the answer if we know $d_{A}$ and $d_{B}$ very fast. (worst case is $O(\log N)$) Now, suppose in the strings $X$ and $Y$, we have $a$ and $b$ question marks respectively. Additionally, suppose the current difference between the number of As and Bs of these strings is $(p, q)$. If we choose $x$ and $y$ of the question marks from $X$ and $Y$ to be replaced with As, then the difference between As and Bs in the strings become $(p + x - y, q + (a - b) - (x - y))$. Let's denote $q$ as $q + a - b$ for simplicity. Thus, the difference is now written as $(p + (x - y), q - (x - y))$. The values of $x$ and $y$ can be any integer in the range $[0, a]$ and $[0, b]$ respectively. Suppose for all $- b \le d \le a$, we know how many ways to assign the question marks have $x - y = d$. Then, we can iterate through all the $d$s one by one and compute the answer fast for each $d$. Thus, the final hurdle is to calculate the number of ways to obtain $x - y = d$ for all possible $d$ so that $0 \le x \le a, 0 \le y \le b$. This is just the sum of $\left(\stackrel{a}{x}\right)\cdot\left(\stackrel{b}{x}\right)\ =\left(\stackrel{a}{x}\right)\cdot\left(\stackrel{b}{b-v}\right)\ =\left(\stackrel{a}{x}\right)\cdot\left(\stackrel{b}{b+d-x}\right)$ for all $0 \le x \le a$. However, this is equal to $\textstyle{\binom{n+b}{b+d}}$, as the number of ways to choose $b + d$ objects from $a + b$ objects is the same as the sum of the product of the number of ways to choose $x$ objects from the first $a$ objects and the number of ways to choose $b + d - x$ objects from the first $b$ objects for all $0 \le a \le x$. Thus, this value can be computed in $O(1)$ with precomputed factorials and inverse factorials (or you can maintain this value when we iterate through all $d$). Finally, don't forget to take care of the cases where it is possible for both strings to be equal. The time complexity of the solution is $O(n\log n+\left|S\right|+\left|T\right|)$.
[ "combinatorics", "dp", "math" ]
3,400
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef map<int,int>::iterator mit; typedef vector<int>::iterator vit; const int MOD = 1e9 + 7; struct NumberTheory { vector<ll> primes; vector<bool> prime; vector<ll> totient; vector<ll> sumdiv; vector<ll> bigdiv; void Sieve(ll n) { prime.assign(n+1, 1); prime[1] = false; for(ll i = 2; i <= n; i++) { if(prime[i]) { primes.pb(i); for(ll j = i*2; j <= n; j += i) { prime[j] = false; } } } } ll phi(ll x) { map<ll,ll> pf; ll num = 1; ll num2 = x; for(ll i = 0; primes[i]*primes[i] <= x; i++) { if(x%primes[i]==0) { num2/=primes[i]; num*=(primes[i]-1); } while(x%primes[i]==0) { x/=primes[i]; pf[primes[i]]++; } } if(x>1) { pf[x]++; num2/=x; num*=(x-1); } x = 1; num*=num2; return num; } bool isprime(ll x) { if(x==1) return false; for(ll i = 0; primes[i]*primes[i] <= x; i++) { if(x%primes[i]==0) return false; } return true; } void SievePhi(ll n) { totient.resize(n+1); for (int i = 1; i <= n; ++i) totient[i] = i; for (int i = 2; i <= n; ++i) { if (totient[i] == i) { for (int j = i; j <= n; j += i) { totient[j] -= totient[j] / i; } } } } void SieveSumDiv(ll n) { sumdiv.resize(n+1); for(int i = 1; i <= n; ++i) { for(int j = i; j <= n; j += i) { sumdiv[j] += i; } } } ll getPhi(ll n) { return totient[n]; } ll getSumDiv(ll n) { return sumdiv[n]; } ll modpow(ll a, ll b, ll mod) { ll r = 1; if(b < 0) b += mod*100000LL; while(b) { if(b&1) r = (r*a)%mod; a = (a*a)%mod; b>>=1; } return r; } ll inv(ll a, ll mod) { return modpow(a, mod - 2, mod); } ll invgeneral(ll a, ll mod) { ll ph = phi(mod); ph--; return modpow(a, ph, mod); } void getpf(vector<ii>& pf, ll n) { for(ll i = 0; primes[i]*primes[i] <= n; i++) { int cnt = 0; while(n%primes[i]==0) { n/=primes[i]; cnt++; } if(cnt>0) pf.pb(ii(primes[i], cnt)); } if(n>1) { pf.pb(ii(n, 1)); } } //ll op; void getDiv(vector<ll>& div, vector<ii>& pf, ll n, int i) { //op++; ll x, k; if(i >= pf.size()) return ; x = n; for(k = 0; k <= pf[i].se; k++) { if(i==int(pf.size())-1) div.pb(x); getDiv(div, pf, x, i + 1); x *= pf[i].fi; } } }; NumberTheory nt; ll modpow(ll a, ll b) { ll r = 1; while(b) { if(b&1) r=(r*a)%MOD; a=(a*a)%MOD; b>>=1; } return r; } ll inv(ll a) { return modpow(a,MOD-2); } ll n; ll cnt[300001]; ll mob[300001]; ll mobius(ll x) { int cc = 0; for(int i=0;nt.primes[i]*nt.primes[i]<=x;i++) { int z=0; while(x%nt.primes[i]==0) { z++; x/=nt.primes[i]; } if(z>=2) return 0; if(z>0) cc++; } if(x>1) cc++; if(cc&1) return -1; else return 1; } ll solve(ll x, ll y) { if(x==0&&y==0) { for(int i=1;i<=n;i++) { cnt[i]=ll(n/i)*ll(n/i); } for(int i=1;i<=n;i++) { for(int j=2*i;j<=n;j+=i) { cnt[i]+=mob[j/i]*cnt[j]; } } ll ans = 0; ll cur = 2; for(int i=1;i<=n;i++) { cnt[i]%=MOD; if(cnt[i]<0) cnt[i]+=MOD; //cerr<<i<<' '<<cnt[i]<<' '; ans=(ans+(cur*cnt[i])%MOD)%MOD; if(ans<0) ans+=MOD; cur=(cur*2)%MOD; if(cur<0) cur+=MOD; } return ans; } else if(x>=0&&y>=0) { return 0; } else if(x<=0&&y<=0) { return 0; } else { x=abs(x); y=abs(y); ll g = __gcd(x,y); x/=g; y/=g; ll k = n/max(x,y); ll ans = modpow(2,k+1)+MOD-2; while(ans>=MOD) ans-=MOD; return ans; } } ll fact[600001]; ll ifact[600001]; ll inverse[600001]; ll choose(ll n, ll r) { if(r==0) return 1; ll ans = fact[n]; ans=(ans*ifact[r])%MOD; ans=(ans*ifact[n-r])%MOD; if(ans<0) ans+=MOD; return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); string s, t; cin>>s>>t; cin>>n; fact[0]=1; ifact[0]=1; for(int i=1;i<=600000;i++) { fact[i]=(fact[i-1]*i)%MOD; if(fact[i]<0) fact[i]+=MOD; ifact[i]=inv(fact[i]); inverse[i]=inv(i); } nt.Sieve(300001); for(int i=2;i<=n;i++) { mob[i]=mobius(i); } ll sa, sb, sc; //sa = # of As in s, sb = # of Bs in s, sc = # of ?s in s ll ta, tb, tc; sa=sb=sc=ta=tb=tc=0; ll same = 1; //number of ways to fill in ?s such that |S| = |T| if(s.length()!=t.length()) same=0; else { for(int i=0;i<s.length();i++) { if(s[i]=='?'&&t[i]=='?') same=(same*2)%MOD; else if(s[i]=='?'||t[i]=='?') { } else if(s[i]==t[i]) { } else { same=0; } } } for(int i=0;i<s.length();i++) { if(s[i]=='A') sa++; else if(s[i]=='B') sb++; else sc++; } for(int i=0;i<t.length();i++) { if(t[i]=='A') ta++; else if(t[i]=='B') tb++; else tc++; } ll ans = 0; ll c = 1; int cntt=0; for(ll i = sa - ta - tc; i <= sa - ta + sc; i++) { if(i==0) { ll cc = (c-same)%MOD; if(cc<0) cc+=MOD; ans=(ans+(cc*solve(i,sa+sb+sc-ta-tb-tc-i))%MOD)%MOD; ll tmp = modpow(2,n+1)+MOD-2; while(tmp>=MOD) tmp-=MOD; tmp=(tmp*tmp)%MOD; ans=(ans+(same*tmp)%MOD)%MOD; } else { ans=(ans+(c*solve(i,sa+sb+sc-ta-tb-tc-i))%MOD)%MOD; } if(ans<0) ans+=MOD; c=(c*inverse[cntt+1])%MOD; c=(c*(sc+tc-cntt))%MOD; if(c<0) c+=MOD; cntt++; } cout<<ans<<' '; }
796
A
Buying A House
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. The girl lives in house $m$ of a village. There are $n$ houses in that village, lining in a straight line from left to right: house $1$, house $2$, ..., house $n$. The village is also well-structured: house $i$ and house $i + 1$ ($1 ≤ i < n$) are exactly $10$ meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased. You will be given $n$ integers $a_{1}, a_{2}, ..., a_{n}$ that denote the availability and the prices of the houses. If house $i$ is occupied, and therefore cannot be bought, then $a_{i}$ equals $0$. Otherwise, house $i$ can be bought, and $a_{i}$ represents the money required to buy it, in dollars. As Zane has only $k$ dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love.
This is a simple implementation problem. Let the $ans$ be infinity initially. Iterate through the houses. Suppose we are considering house $i$, update the $ans$ if and only if 1) $a_{i} \neq 0$, 2) $a_{i} \le k$, and 3) $|i - m|$ < $ans$. The answer is $10 * ans$. This solution runs in $O(n)$.
[ "brute force", "implementation" ]
800
"#include <stdio.h>\n\nint min(int a, int b){ return a < b ? a : b; }\nint abs(int x){ return x < 0 ? -x : x; }\n\nint main(){\n int n, m, k;\n scanf(\"%d%d%d\", &n, &m, &k);\n int res = 1e9;\n for(int i=1; i<=n; i++){\n int a;\n scanf(\"%d\", &a);\n if(a != 0 && a <= k) res = min(res, abs(i-m));\n }\n printf(\"%d\", 10*res);\n return 0;\n}"
796
B
Find The Bone
Zane the wizard is going to perform a magic show shuffling the cups. There are $n$ cups, numbered from $1$ to $n$, placed along the $x$-axis on a table that has $m$ holes on it. More precisely, cup $i$ is on the table at the position $x = i$. The problematic bone is initially at the position $x = 1$. Zane will confuse the audience by swapping the cups $k$ times, the $i$-th time of which involves the cups at the positions $x = u_{i}$ and $x = v_{i}$. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations. Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at $x = 4$ and the one at $x = 6$, they will not be at the position $x = 5$ at any moment during the operation. Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.
This is another implementation problem. Let's create an array $a$ of length $n$ (with initial values set to $0$), and set $a_{i}$ = $1$ only for the positions $x = i$ where there is a hole. If there is a hole at $x$ $=$ $1$, obviously, the answer is $1$, because the ball must fall onto the ground before any operation is applied. Otherwise, consider each swapping operation chronologically (from the first to the last). While doing so, we will also maintain a variable $pos$, the position where the ball is. Let the involving cup positions be $u$ and $v$. There are three cases to consider: 1) If $pos$ is equal to $u$, set $pos$ $=$ $v$. 2) If $pos$ is equal to $v$, set $pos$ $=$ $u$. 3) Otherwise, skip the operation. Make sure to stop considering any more operations if $a_{pos}$ equals $1$. After this procedure, $pos$ will be the final answer. This solution runs in $O(k)$.
[ "implementation" ]
1,300
"#include <stdio.h>\n\nint isHole[1000005];\n\nint main(){\n int n, m, k;\n scanf(\"%d%d%d\", &n, &m, &k);\n for(int i=0; i<m; i++){\n int h;\n scanf(\"%d\", &h);\n isHole[h] = 1;\n }\n int pos = 1;\n for(int i=0; i<k; i++){\n int u, v;\n scanf(\"%d%d\", &u, &v);\n if(u == pos && (!isHole[u])) pos = v;\n else if(v == pos && (!isHole[v])) pos = u;\n }\n printf(\"%d\", pos);\n return 0;\n}"
796
C
Bank Hacking
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are $n$ banks, numbered from $1$ to $n$. There are also $n - 1$ wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank $i$ has initial strength $a_{i}$. Let us define some keywords before we proceed. Bank $i$ and bank $j$ are neighboring if and only if there exists a wire directly connecting them. Bank $i$ and bank $j$ are semi-neighboring if and only if there exists an \textbf{online} bank $k$ such that bank $i$ and bank $k$ are neighboring and bank $k$ and bank $j$ are neighboring. When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by $1$. To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank $x$ if and only if all these conditions are met: - Bank $x$ is online. That is, bank $x$ is not hacked yet. - Bank $x$ is neighboring to some offline bank. - The strength of bank $x$ is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
First, note that the input graph is a tree. Let $m$ be the greatest value of $a_{i}$ (that is, $max(a_{1}, a_{2}, ..., a_{n})$). Observe that the answer can be $m$, $m + 1$, or $m + 2$ only. Why? It is because each bank's strength can be increased at most twice, once by a neighboring bank, and once by a semi-neighboring bank. So the strength required to hack bank $i$ is at most $a_{i} + 2$, regardless of the sequence of banks you choose to hack. Now, suppose $u$ is the first bank we would hack first. We would need a computer with strength at least $a_{u}$ to hack it. Let the neighboring banks of $u$ be $v_{1}, v_{2}, ..., v_{k}$. We would need a computer with strength at least $a_{vi} + 1$ to hack those banks. And for each bank $x$ not yet hacked, we can hack them with a computer with strength at least $a_{x} + 2$. For simplicity, add $2$ to all the banks' strengths. Let's maintain a map data structure to keep track of number of times some value of strength occurs. Again, suppose we would start by hacking bank $u$. Now, we would need a computer with strength at least $a_{u} - 2$ to hack it. For the neighboring banks $v$, it would be $a_{v} - 1$. For other banks $x$, it would be $a_{x}$. For a fixed bank $u$, you can iterate through its neighboring banks, and update the map data structure accordingly. Keep track of the maximum value that occurs, and update the answer. We can simply iterate through banks $u$ to start with, and get the final answer. But wait. Won't it work in $O(n^{2}\log{n})$ or something like that? No. Let's analyze the runtime carefully. (You can skip this if you know why. This is for beginners.) Suppose we choose bank $u$ to start with. We have to iterate through its neighboring banks. The number of the banks neighboring to $u$ is equal to the degree of bank $u$. We would need $O(1 + d_{u})$ operations for bank $u$. By iterating through all possible $u$ from $1$ to $n$, we will perform $O(n + d_{1} + d_{2} + ... + d_{n})$ operations. You can see that if there are $m$ edges in a graph, the degrees of all nodes sum to $2m$. Trees have $n - 1$ edges, so $d_{1} + d_{2} + ... + d_{n}$ $=$ $2(n - 1)$ $=$ $2n - 2$ $=$ $O(n)$. Therefore, we need to perform only $O(n)$ operations. However, each operation involves the map data structure, so the overall runtime is $O(n\log n)$. Be aware that the use of hash map could bring the runtime to $O(n^{2})$. Looking more closely, we can also keep track of the occurrences of only $m + 1$ and $m + 2$, and no other values. So, although not required to get AC, we can get rid of the map data structure, and therefore eliminate the logarithmic factor. The official solution provided here runs in $O(n)$.
[ "constructive algorithms", "data structures", "dp", "trees" ]
1,900
"#include <stdio.h>\n#include <vector>\nusing namespace std;\n\nint a[300005];\nvector<int> way[300005];\n\nint main(){\n int n;\n scanf(\"%d\", &n);\n int maxval=-1e9;\n for(int i=1; i<=n; i++) scanf(\"%d\", &a[i]), maxval = max(maxval, a[i]);\n for(int i=0; i<n-1; i++){\n int u, v;\n scanf(\"%d%d\", &u, &v);\n way[u].push_back(v);\n way[v].push_back(u);\n }\n int x=0, y=0;\n for(int i=1; i<=n; i++){\n if(a[i] == maxval) x++;\n else if(a[i] == maxval-1) y++;\n }\n \n int res = maxval+2;\n \n for(int i=1; i<=n; i++){\n \n // minus\n if(a[i] == maxval) x--;\n else if(a[i] == maxval-1) y--;\n for(int j=0; j<way[i].size(); j++){\n int pos = way[i][j];\n if(a[pos] == maxval) x--, y++;\n else if(a[pos] == maxval-1) y--;\n }\n \n // check the needed strength and update the answer\n if(x == 0){\n res = min(res, maxval+1);\n if(y == 0) res = min(res, maxval);\n }\n \n // plus\n if(a[i] == maxval) x++;\n else if(a[i] == maxval-1) y++;\n for(int j=0; j<way[i].size(); j++){\n int pos = way[i][j];\n if(a[pos] == maxval) x++, y--;\n else if(a[pos] == maxval-1) y++;\n }\n \n }\n \n printf(\"%d\", res);\n \n return 0;\n}"
796
D
Police Stations
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most $d$ kilometers along the roads. There are $n$ cities in the country, numbered from $1$ to $n$, connected only by exactly $n - 1$ roads. All roads are $1$ kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has $k$ police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city. However, Zane feels like having as many as $n - 1$ roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible. Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
A greedy solution shutting down either every d roads or when a police station is encountered, although seems pretty nice, turns out to be incorrect. Consider performing a breadth first search (BFS) with "cities with a police station" as starting vertices, and shutting down the road when it leads to a visited vertex (city). This will leave every bad city connected (either directly or indirectly) with one of its nearest police stations, and thus will not break the law. With this method, you can see that exactly $k' - 1$ roads will be shut down (where $k'$ is the number of cities that have a police station in them). Suppose this is not optimal, and $k' + c$ ($c \ge 0$) roads can be shut down. The tree will break into $k' + c + 1$ components, while there are only $k'$ cities with a police station, so this is a contradiction, since there will be at least one component without any police station. Hence, shutting down $k' - 1$ roads is optimal.
[ "constructive algorithms", "dfs and similar", "dp", "graphs", "shortest paths", "trees" ]
2,100
"#include <stdio.h>\n#include <queue>\n#include <vector>\nusing namespace std;\n\nqueue<pair<int, int>> q;\nvector<pair<int, int>> way[300005];\nint v[300005];\nint res[300005];\n\nint main(){\n int n, k, d;\n scanf(\"%d%d%d\", &n, &k, &d);\n for(int i=0; i<k; i++){\n int p;\n scanf(\"%d\", &p);\n q.push({p, 0});\n }\n for(int i=0; i<n-1; i++){\n int u, v;\n scanf(\"%d%d\", &u, &v);\n way[u].push_back({v, i+1});\n way[v].push_back({u, i+1});\n }\n while(!q.empty()){\n int pos = q.front().first;\n int from = q.front().second;\n q.pop();\n if(v[pos]) continue;\n v[pos] = 1;\n for(int i=0; i<way[pos].size(); i++) if(way[pos][i].first != from){\n if(v[way[pos][i].first]) res[way[pos][i].second] = 1;\n else q.push({way[pos][i].first, pos});\n }\n }\n int rescnt=0;\n for(int i=1; i<=n-1; i++) if(res[i]) rescnt++;\n printf(\"%d\\n\", rescnt);\n for(int i=1; i<=n-1; i++) if(res[i]) printf(\"%d \", i);\n return 0;\n}"
796
E
Exam Cheating
Zane and Zane's crush have just decided to date! However, the girl is having a problem with her Physics final exam, and needs your help. There are $n$ questions, numbered from $1$ to $n$. Question $i$ comes before question $i + 1$ ($1 ≤ i < n$). Each of the questions cannot be guessed on, due to the huge penalty for wrong answers. The girl luckily sits in the middle of two geniuses, so she is going to cheat. However, the geniuses have limitations. Each of them may or may not know the answers to some questions. Anyway, it is safe to assume that the answers on their answer sheets are absolutely correct. To make sure she will not get caught by the proctor, the girl will glance \textbf{at most} $p$ times, each time looking at \textbf{no more than} $k$ consecutive questions on one of the two geniuses' answer sheet. When the girl looks at some question on an answer sheet, she copies the answer to that question if it is on that answer sheet, or does nothing otherwise. Help the girl find the maximum number of questions she can get correct.
This problem can be solved using dynamic programming. First, observe that it is never suboptimal to look as many consecutive questions as possible. That is, just look $k$ consecutive questions whenever you decide to glance, unless it exceeds the corner (question $n$). Let $dp[i][j][a][b]$ denote the number of questions you can get correct by considering questions $1$ to $i$ by glancing exactly $j$ times with $a$ and $b$ being the number of remaining questions that can be looked at as a benefit of the previous glances. As stated before, it is optimal to look as many consecutive questions as possible, so when we decide to look, we share this benefit (of looking) to the next questions too, and it are stored in $a$ and $b$, which denote how many of the next consecutive questions can be looked without paying one more glance. The answer can be calculated in $O(npk^{2})$. (You can see in the code as to how.) However, $npk^{2}$ can be up to $(1000) * (1000) * (50) * (50)$ $=$ $2, 500, 000, 000$, so the solution will not fit in the time limit of 2 seconds. This can be improved. Observe that if $p > 2 * ceil(n / k)$, you can look at all questions on both geniuses' answer sheets, so the answer can be found in $O(n)$ (or you can just set $p$ to $2 * ceil(n / k)$ and run the dynamic programming). By eliminating this case, the running time for dynamic programming will become $O(npk^{2})$ = $O(n(n / k)k^{2})$ = $O(n^{2}k)$. This, indeed, will fit in time, as $n^{2}k$ is only $(1000) * (1000) * (50)$ $=$ $50, 000, 000$. Problem with memory limit might still persist, so you will need to optimize the use of memory. For example, since you need only $dp[i - 1][..][..][..]$ and $dp[i][..][..][..]$ when calculating $dp[i][..][..][..]$, you could remember only the two last rows. The memory use will be much smaller. The use of short data type (instead of int) may also help. Please see the commented code for more details.
[ "binary search", "dp" ]
2,400
"#include <stdio.h>\n\nint A[1005], B[1005];\nint dp[2][1005][55][55];\n\nint max(int a, int b){ return a > b ? a : b; }\n\nint main(){\n int n, p, k;\n scanf(\"%d%d%d\", &n, &p, &k);\n if(k == 0){ printf(\"0\"); return 0; }\n if(p > 2*((n+k-1)/k)) p = 2*((n+k-1)/k);\n int r;\n scanf(\"%d\", &r);\n for(int i=0; i<r; i++){\n int x;\n scanf(\"%d\", &x);\n A[x] = 1;\n }\n int s;\n scanf(\"%d\", &s);\n for(int i=0; i<s; i++){\n int x;\n scanf(\"%d\", &x);\n B[x] = 1;\n }\n for(int i=0; i<2; i++) for(int j=0; j<1005; j++) for(int k=0; k<55; k++) for(int p=0; p<55; p++) dp[i][j][k][p] = -1e9;\n dp[0][0][0][0] = 0;\n for(int i=1; i<=n; i++){\n int cur = i&1, prev = !cur;\n // A only\n // - From nothing\n for(int j=1; j<=p; j++) dp[cur][j][k-1][0] = max(dp[cur][j][k-1][0], dp[prev][j-1][0][0] + A[i]);\n // - From something\n for(int j=1; j<=p; j++) for(int a=0; a<k-1; a++) dp[cur][j][a][0] = max(dp[cur][j][a][0], dp[prev][j][a+1][0] + A[i]);\n \n // B only\n // - From nothing\n for(int j=1; j<=p; j++) dp[cur][j][0][k-1] = max(dp[cur][j][0][k-1], dp[prev][j-1][0][0] + B[i]);\n // - From something\n for(int j=1; j<=p; j++) for(int b=0; b<k-1; b++) dp[cur][j][0][b] = max(dp[cur][j][0][b], dp[prev][j][0][b+1] + B[i]);\n \n // A and B\n // - From some A\n for(int j=1; j<=p; j++) for(int a=0; a<k-1; a++) dp[cur][j][a][k-1] = max(dp[cur][j][a][k-1], dp[prev][j-1][a+1][0] + (A[i]|B[i]));\n // - From some B\n for(int j=1; j<=p; j++) for(int b=0; b<k-1; b++) dp[cur][j][k-1][b] = max(dp[cur][j][k-1][b], dp[prev][j-1][0][b+1] + (A[i]|B[i]));\n // - From some A and B\n for(int j=2; j<=p; j++) for(int a=0; a<k-1; a++) for(int b=0; b<k-1; b++) dp[cur][j][a][b] = max(dp[cur][j][a][b], dp[prev][j][a+1][b+1] + (A[i]|B[i]));\n \n // None\n for(int j=0; j<=p; j++) dp[cur][j][0][0] = max(dp[cur][j][0][0], dp[prev][j][0][0]);\n \n for(int j=0; j<=p; j++) for(int a=0; a<k; a++) for(int b=0; b<k; b++) dp[prev][j][a][b] = -1e9;\n }\n int res = -1e9;\n for(int i=0; i<=p; i++) for(int j=0; j<k; j++) for(int a=0; a<k; a++) res = max(res, dp[n&1][i][j][a]);\n printf(\"%d\", res);\n return 0;\n}"
796
F
Sequence Recovery
Zane once had a good sequence $a$ consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$ — but he has lost it. A sequence is said to be good if and only if all of its integers are non-negative and do not exceed $10^{9}$ in value. However, Zane remembers having played around with his sequence by applying $m$ operations to it. There are two types of operations: 1. Find the maximum value of integers with indices $i$ such that $l ≤ i ≤ r$, given $l$ and $r$. 2. Assign $d$ as the value of the integer with index $k$, given $k$ and $d$. After he finished playing, he restored his sequence to the state it was before any operations were applied. That is, sequence $a$ was no longer affected by the applied type 2 operations. Then, he lost his sequence at some time between now and then. Fortunately, Zane remembers all the operations and the order he applied them to his sequence, along with the \textbf{distinct} results of all type 1 operations. Moreover, among all good sequences that would produce the same results when the same operations are applied in the same order, he knows that his sequence $a$ has the greatest cuteness. We define cuteness of a sequence as the bitwise OR result of all integers in such sequence. For example, the cuteness of Zane's sequence $a$ is $a_{1}$ OR $a_{2}$ OR ... OR $a_{n}$. Zane understands that it might not be possible to recover exactly the lost sequence given his information, so he would be happy to get any good sequence $b$ consisting of $n$ integers $b_{1}, b_{2}, ..., b_{n}$ that: 1. would give the same results when the same operations are applied in the same order, and 2. has the same cuteness as that of Zane's original sequence $a$. If there is such a sequence, find it. Otherwise, it means that Zane must have remembered something incorrectly, which is possible.
First, let's find the maximum value each integer can be. Chronologically considering the operations, you can see that once an integer is involved in type 2 operation, future type 1 operations can tell nothing about its initial value. You can find naively find the maximum value each integer can be in $O(nm)$, but that's obviously way too slow. This can be solved using segment trees. You might be familiar with point updates and range queries, but now you have to consider point queries and range updates. No-lazy propagation is not needed. This process can be solved in $O((n+m)\log n)$. After that, let each integer has its maximum possible value as its value. Go through the operations once again one by one (both type 1 and type 2), and check with another segment tree whether this sequence gives correct results for type 1 operations. If it is not, you can be sure that there is no valid sequence. Why? Let's consider two cases. If the result is smaller than what the input says, this integer can't really be bigger than it is (other type 1 operations needed it to be this small, or maybe type 2 operation forced it to become this value). If the result is bigger than what the input says, this happens only when there is a contradiction between type 1 and type 2 operations, and nothing can be done (because type 2 operations say so). Let's complete the final step - make the bitwise OR maximal. You should consider 2 cases. 1) There is more than one free integer. (Free integer is the one such that no type 1 operation limits it maximum value.) The optimal bitwise OR is simply $2^{30} - 1$. Just make one of the free integers $2^{29} - 1$ and the others $10^{9}$ (any value no less than $2^{29}$ but also no more than $10^{9}$ will work). You can be sure that this is optimal. Other integers can simply remain untouched. 2) Otherwise For case 2, for each value appearing in more than one integer of the sequence (do not consider the one without maximum value yet), you can lower one of them. Lowering more than one of them will not give a better result if you lower it in this way: sacrifice the most significant bit for ALL other less significant bits. It's obvious that the operations remain satisfied. As for the free integer, if any, you can greedily assign some bit to it, starting from the most significant bit, but make sure that it doesn't exceed $10^{9}$ in value.
[ "bitmasks", "data structures", "greedy" ]
2,800
"#include <stdio.h>\n#include <algorithm>\n#include <map>\nusing namespace std;\n\nint n;\nint type[300005], a[300005], b[300005], c[300005];\nint res[300005];\nmap<int, int> occ;\n\n// Segment Tree 1\n\nint t[600005];\n\nint findmax(int p){\n int res=2e9;\n for (p+=n; p; p>>=1) res = min(res, t[p]);\n return res;\n}\n\nvoid upd(int l, int r, int x){\n for(l+=n, r+=n; l<r; l>>=1, r>>=1){\n if(l&1) t[l] = min(t[l], x), l++;\n if(r&1) r--, t[r] = min(t[r], x);\n }\n return;\n}\n\n// Segment Tree 2\n\nint t2[600005];\n\nint findmax(int l, int r){\n int res = -2e9;\n for(l+=n, r+=n; l<r; l>>=1, r>>=1){\n if(l&1) res = max(res, t2[l++]);\n if(r&1) res = max(res, t2[--r]);\n }\n return res;\n}\n\nvoid updval(int p, int val){\n for(t2[p+=n]=val; p>1; p>>=1) t2[p>>1] = max(t2[p], t2[p^1]);\n return;\n}\n\n// Main Solution\n\nint main(){\n int m;\n scanf(\"%d%d\", &n, &m);\n for(int i=0; i<2*n; i++) t[i] = 2e9;\n for(int i=0; i<n; i++) res[i] = (2e9)+1;\n for(int i=0; i<m; i++){\n scanf(\"%d\", &type[i]);\n if(type[i] == 1){\n scanf(\"%d%d%d\", &a[i], &b[i], &c[i]);\n a[i]--, b[i]--;\n upd(a[i], b[i]+1, c[i]);\n } else{\n scanf(\"%d%d\", &a[i], &b[i]);\n a[i]--;\n if(res[a[i]] == (2e9)+1) res[a[i]] = findmax(a[i]);\n }\n }\n for(int i=0; i<n; i++) if(res[i] == (2e9)+1) res[i] = findmax(i);\n \n // Check validity of the array\n for(int i=0; i<n; i++) t2[n+i] = res[i];\n for(int i=n-1; i>0; i--) t2[i] = max(t2[i<<1], t2[i<<1|1]);\n for(int i=0; i<m; i++){\n if(type[i] == 1){\n if(findmax(a[i], b[i]+1) != c[i]){ printf(\"NO\"); return 0; }\n } else{\n updval(a[i], b[i]);\n }\n }\n for(int i=0; i<n; i++) if(res[i] < 0){ printf(\"NO\"); return 0; }\n \n // Make the answer optimal\n printf(\"YES\\n\");\n for(int i=0; i<n; i++) occ[res[i]]++;\n // - occ[2e9] >= 2 then the optimal OR result can simply be (1<<30)-1\n if(occ[2e9] >= 2){\n for(int i=0; i<n; i++) if(res[i] == 2e9){\n res[i] = 1e9, occ[2e9]--;\n if(occ[2e9] == 0) res[i] = (1<<29)-1;\n }\n for(int i=0; i<n; i++) printf(\"%d \", res[i]);\n return 0;\n }\n // - otherwise, find the best value for the free 2e9 (if any)\n int orresult = 0;\n for(int i=0; i<n; i++){\n if(res[i] == 0 || res[i] == 2e9) continue; // ignoring this could lead to a critical bug\n occ[res[i]]--;\n if(occ[res[i]]){\n int temp=res[i], pow=0;\n while(temp) pow++, temp /= 2;\n res[i] = (1<<(pow-1))-1;\n }\n orresult |= res[i];\n }\n int tobe=0;\n for(int cur=29; cur>=0; cur--){\n if(orresult&(1<<cur)) continue;\n if(tobe+(1<<cur) > 1e9) continue;\n tobe += (1<<cur);\n }\n for(int i=0; i<n; i++){\n if(res[i] == 2e9) printf(\"%d \", tobe);\n else printf(\"%d \", res[i]);\n }\n \n return 0;\n}"
797
A
k-Factorization
Given a positive integer $n$, find $k$ integers (not necessary distinct) such that all these integers are strictly greater than $1$, and their product is equal to $n$.
There are many approaches to this problem. You can, for example, factorize $n$, store all multipliers in a list, and while size of this list is greater than $k$, take any two elements of this list and replace them with their product. If the initial size of this list is less than $k$, then answer is -1.
[ "implementation", "math", "number theory" ]
1,100
null