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
610
E
Alphabet Permutations
You are given a string $s$ of length $n$, consisting of first $k$ lowercase English letters. We define a $c$-repeat of some string $q$ as a string, consisting of $c$ copies of the string $q$. For example, string "acbacbacbacb" is a $4$-repeat of the string "acb". Let's say that string $a$ contains string $b$ as a subsequence, if string $b$ can be obtained from $a$ by erasing some symbols. Let $p$ be a string that represents some permutation of the first $k$ lowercase English letters. We define function $d(p)$ as the smallest integer such that a $d(p)$-repeat of the string $p$ contains string $s$ as a subsequence. There are $m$ operations of one of two types that can be applied to string $s$: - Replace all characters at positions from $l_{i}$ to $r_{i}$ by a character $c_{i}$. - For the given $p$, that is a permutation of first $k$ lowercase English letters, find the value of function $d(p)$. All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function $d(p)$ for all operations of the second type.
Consider slow solution: for operations of the first type reassign all letters, for operations of the second type let's iterate over the symbols in $s$ from left to right and maintain the pointer to the current position in alphabet permutation. Let's move the pointer cyclically in permutation until finding the current symbol from $s$. And move it one more time after that. Easy to see that the answer is one plus the number of cyclic movements. Actually the answer is also the number of pairs of adjacent symbols in $s$ that the first one is not righter than the second one in permutation. So the answer depends only on values of $cnt_{ij}$ -- the number of adjacent symbols $i$ and $j$. To make solution faster let's maintain the segment tree with matrix $cnt$ in each node. Also we need to store in vertex the symbol in the left end of segment and in the right end. To merge two vertices in the segment tree we should simply add the values in the left and in the right sons in the tree, and update the value for the right end of the left segment and the left end of the right segment. Complexity: $O(nk^{2} + mk^{2}logn)$.
[ "data structures", "strings" ]
2,500
null
611
A
New Year and Days
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month. Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.
There are two ways to solve this problem. The first is to hard-code numbers of days in months, check the first day of the year and then iterate over days/months - The second way is to check all possible cases by hand. The 2016 consists of 52 weeks and two extra days. The answer for "x of week" will be either 52 or 53. You must also count the number of months with all 31 days and care about February.Bf9QLz
[ "implementation" ]
900
"// Days (A), by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nint t[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n\nint main() {\n\tint x;\n\tscanf(\"%d\", &x);\n\tchar sl[15];\n\tscanf(\"%s\", sl);\n\tscanf(\"%s\", sl);\n\tif(sl[0] == 'w') {\n\t int current = 5;\n\t int ans = 0;\n\t for(int i = 0; i < 366; ++i) {\n\t if(current == x) ++ans;\n\t ++current;\n\t if(current > 7) current = 1;\n\t }\n\t printf(\"%d\\n\", ans);\n\t\treturn 0;\n\t}\n\tint c = 0;\n\tfor(int i = 0; i < 12; ++i) c += x <= t[i];\n\tprintf(\"%d\\n\", c);\n\treturn 0;\n}\n"
611
B
New Year and Old Property
The year 2015 is almost over. Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — $2015_{10} = 11111011111_{2}$. Note that he doesn't care about the number of zeros in the decimal representation. Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster? Assume that all positive integers are always written without leading zeros.
Each number with exactly one zero can be obtained by taking the number without any zeros (e.g. $63_{10} = 111111_{2}$) and subtracting some power of two, e.g. $63_{10} - 16_{10} = 111111_{2} - 10000_{2} = 101111_{2}$. Subtracting a power of two changes one digit from '1' to '0' and this is what we want. But how can we iterate over numbers without any zeros? It turns out that each of them is of form $2^{x} - 1$ for some $x$ (you can check that it's true for $63_{10}$). What should we do to solve this problem? Iterate over possible values of $x$ to get all possible $2^{x} - 1$ - numbers without any zeros. There are at most $\log10^{18}$ values to consider because we don't care about numbers much larger than $10^{18}$. For each $2^{x} - 1$ you should iterate over powers of two and try subtracting each of them. Now you have candidates for numbers with exactly one zero. For each of them check if it is in the given interval. You can additionally change such a number into binary system and count zeros to be sure. Watch out for overflows! Use '1LL << x' instead of '1 << x' to get big powers of two.
[ "bitmasks", "brute force", "implementation" ]
1,300
"// One zero, by Errichto\n// O(log^2(n))\n#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tlong long a, b;\n\tscanf(\"%lld%lld\", &a, &b);\n\tint c = 0;\n\tfor(int i = 0; (1LL << i) / 2 <= b; ++i)\n\t\tfor(int j = 0; j <= i - 2; ++j) {\n\t\t\tlong long x = (1LL << i) - 1 - (1LL << j);\n\t\t\tc += a <= x && x <= b;\n\t\t}\n\tprintf(\"%d\\n\", c);\n\treturn 0;\n}"
611
C
New Year and Domino
They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so. Limak is a little polar bear who loves to play. He has recently got a rectangular grid with $h$ rows and $w$ columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered $1$ through $h$ from top to bottom. Columns are numbered $1$ through $w$ from left to right. Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid. Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?
How would we solve this problem in $O(wh + q)$ if a domino would occupy only one cell? Before reading queries we would precalculate $dp[r][c]$ - the number of empty cells in a "prefix" rectangle with bottom right corner in a cell $r, c$. Then the answer for rectangle $r1, c1, r2, c2$ is equal to $dp[r2][c2] - dp[r2][c1 - 1] - dp[r1 - 1][c2] + dp[r1 - 1][c1 - 1]$. We will want to use the same technique in this problem. Let's separately consider horizontal and vertical placements of a domino. Now, we will focus on horizontal case. Let's say that a cell is good if it's empty and the cell on the right is empty too. Then we can a place a domino horizontally in these two cells. The crucial observation is that the number of ways to horizontally place a domino is equal to the number of good cells in a rectangle $r1, c1, r1, c2 - 1$. You should precalculate a two-dimensional array $hor[r][c]$ to later find the number of good cells quickly. The same for vertical dominoes.
[ "dp", "implementation" ]
1,500
"// Domino (C), by Errichto\n// AC, O(wh + q)\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nax = 2005;\nchar sl[nax][nax];\n// horizontal and vertical\nint hor[nax][nax], ver[nax][nax];\n\nint main() {\n\tint w, h;\n\tscanf(\"%d%d\", &h, &w);\n\tfor(int y = 0; y < h; ++y) scanf(\"%s\", sl[y]);\n\tfor(int y = 0; y < h; ++y) for(int x = 0; x < w; ++x) {\n\t\thor[x+1][y+1] = hor[x][y+1] + hor[x+1][y] - hor[x][y];\n\t\tver[x+1][y+1] = ver[x][y+1] + ver[x+1][y] - ver[x][y];\n\t\tif(sl[y][x] != '.') continue;\n\t\tif(x != w - 1 && sl[y][x+1] == '.') ++hor[x+1][y+1];\n\t\tif(y != h - 1 && sl[y+1][x] == '.') ++ver[x+1][y+1];\n\t}\n\tint q;\n\tscanf(\"%d\", &q);\n\twhile(q--) {\n\t\tint x1, y1, x2, y2;\n\t\tscanf(\"%d%d%d%d\", &y1, &x1, &y2, &x2);\n\t\t--x1;--y1;\n\t\tint ans = 0;\n\t\tans += hor[x2-1][y2] - hor[x1][y2] - hor[x2-1][y1] + hor[x1][y1];\n\t\tans += ver[x2][y2-1] - ver[x1][y2-1] - ver[x2][y1] + ver[x1][y1];\n\t\tprintf(\"%d\\n\", ans);\n\t}\n\treturn 0;\n}"
611
D
New Year and Ancient Prophecy
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits! One fragment of the prophecy is a sequence of $n$ digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there. Limak assumes three things: - Years are listed in the \textbf{strictly} increasing order; - Every year is a positive integer number; - There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo $10^{9} + 7$.
By ${x... y}$ I will mean the number defined by digits with indices $x, x + 1, ..., y$. Let $dp[b][c]$ define the number of ways to split some prefix (into increasing numbers) so that the last number is ${b... c}$ We will try to calculate it in $O(n^{2})$ or $O(n^{2}\log{n})$. The answer will be equal to the sum of values of $dp[i][n]$ for all $i$. Of course, $dp[b][c] = 0$ if $digit[b] = 0$ - because we don't allow leading zeros. We want to add to $dp[b][c]$ all values $dp[a][b - 1]$ where the number ${a... b - 1}$ is smaller than ${b... c}$. One crucial observation is that longer numbers are greater than shorter ones. So, we don't care about $dp[a][b - 1]$ with very low $a$ because those long numbers are too big (we want ${a... b - 1}$ to be smaller than our current number ${b... c}$). On the other hand, all $a$ that $(b - 1) - a < c - b$ will produce numbers shorter than our current ${b... c}$. Let's add at once all $dp[a][b - 1]$ for those $a$. We need $\sum_{a=2b-c}^{b-1}d p[a][b-1]$. Creating an additional array with prefix sums will allow us to calculate such a sum in $O(1)$. There is one other case. Maybe numbers ${a... b - 1}$ and ${b... c}$ have the same length. There is (at most) one $a$ that $(b - 1) - a = c - b$. Let's find it and then let's compare numbers ${a... b - 1}$ and ${b... c}$. There are few ways to do it. One of them is to store hashes of each of $n \cdot (n + 1) / 2$ intervals. Then for fixed $a, b$ we can binary search the first index where numbers ${a...}$ and ${b... }$ differ.Rrgk8T. It isn't an intended solution though. Other way is to precalculate the same information for all pairs $a, b$ with dynamic programming. I defined $nxt[a][b]$ as the lowest $x$ that $digit[a + x] \neq digit[b + x]$. Now, either $nxt[a][b] = nxt[a + 1][b + 1] + 1$ or $nxt[a][b] = 0$.
[ "dp", "hashing", "strings" ]
2,000
"// Ancient Prophecy (D), by Errichto\n// AC, O(n^2)\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\n\nconst int nax = 5005;\nconst int mod = 1e9 + 7;\nconst int inf = 1e9 + 120;\n\nint t[nax];\nchar sl[nax];\n// int dp[nax][nax];\n// pref[a][b] = sum(dp[1..a][b])\nint pref[nax][nax];\nint nxt[nax][nax];\n\nint cmp(int i, int j) {\n\tif(t[i] < t[j]) return -1;\n\tif(t[i] > t[j]) return 1;\n\treturn 0;\n}\n\nint dp(int a, int b) {\n\tint x = pref[a][b] - pref[a-1][b];\n\tif(x < 0) x += mod;\n\treturn x;\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tscanf(\"%s\", sl);\n\tRI(i, n) t[i] = sl[i-1] - '0';\n\t\n\tfor(int a = n; a >= 1; --a)\n\t\tfor(int b = n; b > a; --b) {\n\t\t\tint & x = nxt[a][b];\n\t\t\tif(t[a] != t[b]) x = a;\n\t\t\telse if(b == n) x = inf;\n\t\t\telse x = nxt[a+1][b+1];\n\t\t}\n\t\n\tRI(i, n) {\n\t\t// dp[1][i] = 1;\n\t\tRI(j, n) pref[j][i] = 1;\n\t}\n\tFOR(c, 2, n) FOR(d, c, n) {\n\t\tint & x = pref[c][d];\n\t\tint b = c - 1;\n\t\tint a = b - (d - c);\n\t\tx = pref[b][b] - pref[max(a,0)][b];\n\t\tif(x < 0) x += mod;\n\t\tif(a >= 1) {\n\t\t\tint where = nxt[a][c];\n\t\t\tif(where < c && t[where] < t[c+where-a]) {\n\t\t\t\tx += dp(a, b);\n\t\t\t\tif(x >= mod) x -= mod;\n\t\t\t}\n\t\t}\n\t\tif(t[c] == 0) x = 0;\n\t\tpref[c][d] = x + pref[c-1][d];\n\t\tif(pref[c][d] >= mod) pref[c][d] -= mod;\n\t}\n\tint ans = 0;\n\tRI(i, n) ans = (ans + dp(i, n)) % mod;\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}"
611
E
New Year and Three Musketeers
Do you know the story about the three musketeers? Anyway, you must help them now. Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength $a$, Borthos strength $b$, and Caramis has strength $c$. The year 2015 is almost over and there are still $n$ criminals to be defeated. The $i$-th criminal has strength $t_{i}$. It's hard to defeat strong criminals — maybe musketeers will have to fight together to achieve it. Richelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting him — a criminal would win then! In other words, there are three ways to defeat a criminal. - A musketeer of the strength $x$ in one hour can defeat a criminal of the strength not greater than $x$. So, for example Athos in one hour can defeat criminal $i$ only if $t_{i} ≤ a$. - Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal $i$ only if $t_{i} ≤ a + c$. Note that the third remaining musketeer can either do nothing or fight some other criminal. - Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. $t_{i} ≤ a + b + c$. Richelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated. Find the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print "-1" (without the quotes) instead.
The answer is $- 1$ only if there is some criminal stronger than $a + b + c$. Let's deal with this case and then let's assume that $a \le b \le c$. Let's store all criminal- s in a set (well, in a multiset). Maybe some criminals can be defeated only by all musketeers together. Let's count and remove them. Then, maybe some criminals can be defeated only by $b + c$ or $a + b + c$ (no other subsets of musketeers can defeat them). We won't use $a + b + c$ now because it's not worse to use $b + c$ because then we have the other musketeer free and maybe he can fight some other criminal. Greedily, let's remove all criminals which can be defeated only by $b + c$ and at the same time let $a$ defeat as strong criminals as possible. Because why would he rest? Now, maybe some criminals can be defeated only by $a + c$ or $b + c$ or $a + b + c$. It's not worse to use $a + c$ and to let the other musketeer $b$ defeat as strong criminals as possible (when two musketeers $a + c$ fight together). We used $a + b + c$, $b + c$, $a + c$. We don't know what is the next strongest subset of musketeers. Maybe it's $a + b$ and maybe it's $c$. Previous greedy steps were correct because we are sure that $a+b+c\geq a\geq c\geq c\geq{}^{\prime}\mathrm{any\\other\\subset},$. Now in each hour we can either use $a, b, c$ separately or use $a + b$ and $c$. Let's say we will use only pair $a + b$ and $c$. And let's say that there are $x$ criminals weaker than $a + b$ and $y$ criminals weaker than $c$. Then the answer is equal to $m a x({\frac{x+y}{2}},x-y,y-x)$. The explanation isn't complicated. We can't be faster than $\scriptstyle{\frac{x+y}{2}}$ because we fight at most two criminals in each hour. And maybe e.g. $y$ (because $c$ is weak) so $c$ will quickly defeat all $y$ criminals he can defeat - and musketeers $a + b$ must defeat $x - y$ criminals. Ok, we know the answer in $O(1)$ if we're going to use only $a + b$ and $c$. So let's assume it (using only these two subsets) and find the possible answer. Then, let's use $a, b, c$ once. Now we again assume that we use only $a + b$ and $c$. Then we use $a, b, c$ once. And so on. What we did is iterating over the number of times we want to use $a, b, c$.
[ "data structures", "greedy", "sortings" ]
2,400
"// Musketeers\n// AC, O(n log(n))\n// by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nax = 1e6 + 5;\nconst int inf = 1e9 + 5;\nint m[3];\nmultiset<int> enemies;\n\nvoid greedy(int atLeast, int extra, int & ans) {\n\twhile(!enemies.empty()) {\n\t\tauto it = enemies.end();\n\t\t--it;\n\t\tif(*it < atLeast) break;\n\t\tenemies.erase(it);\n\t\t++ans;\n\t\tit = enemies.lower_bound(extra);\n\t\tif(it != enemies.begin()) {\n\t\t\t--it;\n\t\t\tenemies.erase(it);\n\t\t}\n\t}\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < 3; ++i) scanf(\"%d\", &m[i]);\n\tsort(m, m + 3);\n\tfor(int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\t--x;\n\t\tenemies.insert(x);\n\t}\n\tint all = m[0] + min(inf, m[1] + m[2]);\n\tauto it = enemies.end();\n\t--it;\n\tif(*it >= all) {\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\tint ans = 0;\n\tgreedy(m[1] + m[2], 0, ans);\n\tgreedy(m[0] + m[2], m[0], ans);\n\tgreedy(max(m[0]+m[1], m[2]), m[1], ans);\n\tint one = 0, two = 0;\n\tfor(int x : enemies) {\n\t\tif(x < m[0] + m[1]) ++one;\n\t\tif(x < m[2]) ++two;\n\t}\n\tint best = inf;\n\tfor(int rep = 0; rep < n + 5; ++rep) {\n\t\tif(max(one, two) == (int) enemies.size()) {\n\t\t\tif(2 * min(one, two) >= (int) enemies.size()) best = min(best, rep + ((int) enemies.size() + 1) / 2);\n\t\t\telse best = min(best, rep + (int) enemies.size() - min(one, two));\n\t\t}\n\t\tfor(int i = 0; i < 3; ++i) {\n\t\t\tauto it = enemies.lower_bound(m[i]);\n\t\t\tif(it != enemies.begin()) {\n\t\t\t\t--it;\n\t\t\t\tif(*it < m[0] + m[1]) --one;\n\t\t\t\tif(*it < m[2]) --two;\n\t\t\t\tenemies.erase(it);\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans + best);\n\treturn 0;\n}\n"
611
F
New Year and Cleaning
Limak is a little polar bear. His parents told him to clean a house before the New Year's Eve. Their house is a rectangular grid with $h$ rows and $w$ columns. Each cell is an empty square. He is a little bear and thus he can't clean a house by himself. Instead, he is going to use a cleaning robot. A cleaning robot has a built-in pattern of $n$ moves, defined by a string of the length $n$. A single move (character) moves a robot to one of four adjacent cells. Each character is one of the following four: 'U' (up), 'D' (down), 'L' (left), 'R' (right). One move takes one minute. A cleaning robot must be placed and started in some cell. Then it repeats its pattern of moves till it hits a wall (one of four borders of a house). After hitting a wall it can be placed and used again. Limak isn't sure if placing a cleaning robot in one cell will be enough. Thus, he is going to start it $w·h$ times, one time in each cell. Maybe some cells will be cleaned more than once but who cares? Limak asks you one question. How much time will it take to clean a house? Find and print the number of minutes modulo $10^{9} + 7$. It's also possible that a cleaning robot will never stop — then print "-1" (without the quotes) instead. Placing and starting a robot takes no time, however, you must count a move when robot hits a wall. Take a look into samples for further clarification.
Let's not care where we start. We will iterate over robot's moves. Let's say the first moves are LDR. The very first move 'L' hits a wall only if we started in the first column. Let's maintain some subrectangle of the grid - starting cells for which we would still continue cleaning. After the first move our subrectangle lost the first column. The second move 'D' affects the last row. Also, all cells from the last row of our remaining subrectangle have the same score so it's enough to multiply the number of cells there and an index of the current move. The third move 'R' does nothing. Let's simulate all moves till our subrectangle becomes empty. To do it, we should keep the current $x, y$ - where we are with respect to some starting point. We should also keep $max_{x}, max_{y}, min_{x}, min_{y}$ - exceeding value of one of these four variables means that something happens and our subrectangle losts one row or one column. But how to do it fast? You can notice (and prove) that the second and and each next execution of the pattern looks exactly the same. If we have pattern RRUDLDU and the first letter 'U' affects out subrectangle in the second execution of the pattern, then it will also affect it in the third execution and so on. If and only if. So, we should simalate the first $n$ moves (everything can happen there). Then, we should simulate the next $n$ moves and remember all places where something happened. Then we should in loop iterate over these places. Each event will decrease width or height of our subrectangle so the complexity of this part is $O(w + h)$. In total $O(w + h + n)$.
[ "binary search", "implementation" ]
2,500
"// Cleaning Robot (F), by Errichto\n// AC, O(w+h+n)\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\ntypedef long long ll;\n\nconst int nax = 5e5 + 5;\nconst int mod = 1e9 + 7;\nchar sl[nax];\n\nint n;\nint ans;\nint low[2], high[2], curr[2], dimension[2];\n\nbool f(ll moves, bool cheating) {\n\tif(moves != 0 && moves % n == 0 && curr[0] == 0 && curr[1] == 0) {\n\t\tputs(\"-1\");\n\t\texit(0);\n\t}\n\tchar type = sl[moves%n];\n\tif(type == 'L') cheating ? curr[0] = high[0]+1 : ++curr[0];\n\telse if(type == 'R') cheating ? curr[0] = low[0]-1 : --curr[0];\n\telse if(type == 'U') cheating ? curr[1] = high[1]+1 : ++curr[1];\n\telse if(type == 'D') cheating ? curr[1] = low[1]-1 : --curr[1];\n\telse assert(false);\n\tbool something_happened = false;\n\tREP(i, 2) {\n\t\tif(curr[i] < low[i] || curr[i] > high[i]) {\n\t\t\tans = (ans + (moves + 1) % mod * dimension[i^1]) % mod;\n\t\t\t--dimension[i];\n\t\t\tsomething_happened = true;\n\t\t}\n\t\tif(curr[i] < low[i]) low[i] = curr[i];\n\t\tif(curr[i] > high[i]) high[i] = curr[i];\n\t}\n\treturn something_happened;\n}\n\nbool inGame() { return dimension[0] > 0 && dimension[1] > 0; }\n\nint main() {\n\tscanf(\"%d%d%d\", &n, &dimension[1], &dimension[0]);\n\tscanf(\"%s\", sl);\n\t\n\tfor(ll moves = 0; inGame() && moves < n; ++moves)\n\t\tf(moves, false);\n\tvector<int> w;\n\tfor(ll moves = n; inGame() && moves < 2 * n; ++moves)\n\t\tif(f(moves, false)) w.push_back((int) moves % n);\n\t\n\t\n\tfor(ll k = 2; inGame(); ++k)\n\t\tfor(int moves : w) if(inGame())\n\t\t\tf(k*n + moves, true);\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}"
611
G
New Year and Cake
Limak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes. As you may know, a New Year cake is a strictly convex polygon with $n$ vertices. Parents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking they decided to cut a cake along one of $n·(n - 3) / 2$ diagonals. Then Limak will get a non-greater piece. Limak understands rules but he won't be happy if the second piece happens to be much bigger. Limak's disappointment will be equal to the difference between pieces' areas, multiplied by two. It can be proved that it will be integer for the given constraints. There are $n·(n - 3) / 2$ possible scenarios. Consider them all and find the sum of values of Limak's disappointment, modulo $10^{9} + 7$.
We are given a polygon with vertices $P_{1}, P_{2}, ..., P_{n}$. Let $Poly(i, j)$ denote the doubled area of a polygon with vertices $P_{i}, P_{i + 1}, P_{i + 2}, ..., P_{j - 1}, P_{j}$. While implementing you must remember that indices are in a circle (there is $1$ after $n$) but I won't care about it in this editorial. We will use the cross product of two points, defined as $A \times B = A.x \cdot B.y - A.y \cdot B.x$. It's well known (and you should remember it) that the doubled area of a polygon with points $Q_{1}, Q_{2}, ..., Q_{k}$ is equal to $Q_{1} \times Q_{2} + Q_{2} \times Q_{3} + ... + Q_{k - 1} \times Q_{k} + Q_{k} \times Q_{1}$. Let $smaller$ denote the area of a smaller piece, $bigger$ for a bigger piece, and $total$ for a whole polygon (cake). $smaller + bigger = total$ $smaller + (smaller + diff) = total$ $diff = total - 2 \cdot smaller$ (the same applies to doubled areas) And the same equation with sums: $\textstyle\sum d i f f=\sum t o t a l-2\cdot\sum s m a l l e r$ where every sum denotes the sum over $\textstyle{\frac{n(n-3)}{2}}$ possible divisions. $\sum d i f f=t o t a l\cdot{\frac{n\cdot(n-3)}{2}}-2\cdot\sum s m a l l e r$ In $O(n)$ we can calculate $total$ (the area of the given polygon). So, the remaining thing is to find $\textstyle\sum s m a l l e r$ and then we will get $\textstyle\sum d i f f$ (this is what we're looking for). For each index $a$ let's find the biggest index $b$ that a diagonal from $a$ to $b$ produces a smaller piece on the left. So, $P o l y(a,b)\leq{\frac{i e l a}{2}}$. To do it, we can use two pointers because for bigger $a$ we need bigger $b$. We must keep (as a variable) the sum $S = P_{a} \times P_{a + 1} + ... + P_{b - 1} \times P_{b}$. Note that $S$ isn't equal to $Poly(a, b)$ because there is no $P_{b} \times P_{a}$ term. But $S + P_{b} \times P_{a} = Poly(a, b)$. To check if we should increase $b$, we must calculate $Poly(a, b + 1) = S + P_{b} \times P_{b + 1} + P_{b + 1} \times P_{a}$. If it's not lower that $\frac{\l_{t o t a l}}{2}$ then we should increase $b$ by $1$ (we should also increase $S$ by $P_{b} \times P_{b + 1}$). When moving $a$ we should decrease $S$ by $P_{a} \times P_{a + 1}$. For each $a$ we have found the biggest (last) $b$ that we have a smaller piece on the left. Now, we will try to sum up areas of all polygons starting with $a$ and ending not later than $b$. So, we are looking for $Z = Poly(a, a + 1) + Poly(a, a + 2) + ... + Poly(a, b)$. The first term is equal to zero but well, it doesn't change anything. Let's talk about some intuition (way of thinking) for a moment. Each area is equal so the sum of cross products of pairs of adjacent (neighboring) points. We can say that each cross product means one side of a polygon. You can take a look at the sum $Z$ and think - how many of those polygons have a side $P_{a}P_{a + 1}$? All $b - a$ of them. And $b - a - 1$ polygons have a side $P_{a + 1}P_{a + 2}$. And so on. And now let's do it formally: $Poly(a, a + 1) = P_{a} \times P_{a + 1} + P_{a + 1} \times P_{a}$ $Poly(a, a + 2) = P_{a} \times P_{a + 1} + P_{a + 1} \times P_{a + 2} + P_{a + 2} \times P_{a}$ $Poly(a, a + 3) = P_{a} \times P_{a + 1} + P_{a + 1} \times P_{a + 2} + P_{a + 2} \times P_{a + 3} + P_{a + 3} \times P_{a}$ $...$ $Poly(a, b) = P_{a} \times P_{a + 1} + P_{a + 1} \times P_{a + 2} + P_{a + 2} \times P_{a + 3} + ... + P_{b - 1} \times P_{b} + P_{b} \times P_{a}$ $Z = Poly(a, a + 1) + Poly(a, a + 2) + ... + Poly(a, b) =$ $= (b - a) \cdot (P_{a} \times P_{a + 1}) + (b - a - 1) \cdot (P_{a + 1} \times P_{a + 2}) + (b - a - 2) \cdot (P_{a + 2} \times P_{a + 3}) + ... + 1 \cdot (P_{b - 1} \times P_{b}) +$ $+ P_{a + 1} \times P_{a} + P_{a + 2} \times P_{a} + ... + P_{b} \times P_{a}$ The last equation is intentionally broken into several lines. We have two sums to calculate. The first sum is $(b - a) \cdot (P_{a} \times P_{a + 1}) + (b - a - 1) \cdot (P_{a + 1} \times P_{a + 2}) + ... + 1 \cdot (P_{b - 1} \times P_{b})$. We can calculate it in $O(1)$ if we two more variables sum_product and sum_product2. The first one must be equal to the sum of $P_{i} \times P_{i + 1}$ for indices in an interval $[a, b - 1]$ and the second one must be equal to the sum of $(P_{i} \times P_{i + 1}) \cdot (i + 1)$. Then, the sum is equal to sum_product * (b + 1) - sum_product2. The second sum is $P_{a + 1} \times P_{a} + P_{a + 2} \times P_{a} + ... + P_{b} \times P_{a} = SUM_POINTS \times P_{a}$ where $SUM_POINTS$ is some fake point we must keep and $SUM_POINTS = P_{a + 1} + P_{a + 2} + ... + P_{b}$. So, this fake point's $x$-coordinate is equal to the sum of $x$-coordinates of $P_{a + 1}, P_{a + 2}, ..., P_{b}$ and the same for $y$-coordinate. In my code you can see variables sum_x and sum_y. Implementation.
[ "geometry", "two pointers" ]
2,900
"// Cake, by Errichto\n// intended, O(n)\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\ntypedef long long ll;\n\nconst int nax = 1e6 + 15;\nconst int mod = 1e9 + 7;\n\nstruct P {\n\tll x, y;\n\tll operator * (const P & b) const {\n\t\treturn -x * b.y + y * b.x;\n\t}\n} t[nax];\n\nll sum_x, sum_y, sum_product, sum_product2;\n\nvoid makeMod() {\n\t// sum_x %= mod;\n\t// sum_y %= mod;\n\t// sum_product %= mod;\n\tsum_product2 %= mod;\n}\n\nvoid insert(int i) {\n\tsum_x += t[i].x;\n\tsum_y += t[i].y;\n\tsum_product += t[i-1] * t[i];\n\tsum_product2 += (t[i-1] * t[i]) % mod * i;\n\tmakeMod();\n}\nvoid remove(int i) {\n\tsum_x -= t[i].x;\n\tsum_y -= t[i].y;\n\tsum_product -= t[i] * t[i+1];\n\tsum_product2 -= (t[i] * t[i+1]) % mod * (i + 1);\n\tmakeMod();\n}\n\t\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tREP(i, n) scanf(\"%lld%lld\", &t[i].x, &t[i].y);\n\tREP(i, n+2) t[i+n] = t[i];\n\tll total = 0;\n\tREP(i, n) total += t[i] * t[i+1];\n\tassert(total > 0);\n\tint b = 0;\n\tsum_x = t[0].x;\n\tsum_y = t[0].y;\n\tll ans = 0;\n\tREP(a, n) {\n\t\twhile(true) {\n\t\t\tunsigned long long tmp = 2 * (sum_product + (unsigned long long)( t[b] * t[b+1]) + (unsigned long long) (t[b+1] * t[a]));\n\t\t\tif(tmp < (unsigned long long)total || (tmp == (unsigned long long)total && b + 1 < n)) {\n\t\t\t\tinsert(b + 1);\n\t\t\t\t++b;\n\t\t\t}\n\t\t\telse break;\n\t\t}\n\t\tll tmp = sum_product % mod * (b + 1) - sum_product2;\n\t\ttmp %= mod;\n\t\tP fake = P{sum_x % mod, sum_y % mod};\n\t\ttmp += fake * t[a];\n\t\tans += tmp;\n\t\tans %= mod;\n\t\tremove(a);\n\t}\n\tans = (ll) n * (n - 3) / 2 % mod * (total % mod) - 2 * ans;\n\tans = (ans % mod + mod) % mod;\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}"
611
H
New Year and Forgotten Tree
A tree is a connected undirected graph with $n - 1$ edges, where $n$ denotes the number of vertices. Vertices are numbered $1$ through $n$. Limak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tree in the next year. Limak was responsible for remembering that tree. It would be hard to remember a whole tree. Limak decided to describe it in his notebook instead. He took a pen and wrote $n - 1$ lines, each with two integers — indices of two vertices connected by an edge. Now, the New Year is just around the corner and Limak is asked to reconstruct that tree. Of course, there is a problem. He was a very little bear a year ago, and he didn't know digits and the alphabet, so he just replaced each digit with a question mark — the only character he knew. That means, for any vertex index in his notes he knows only the number of digits in it. At least he knows there were no leading zeroes. Limak doesn't want to disappoint everyone. Please, take his notes and reconstruct a New Year tree. Find any tree matching Limak's records and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1" (without the quotes).
There are at most $k = 6$ groups of vertices. Each grouped is defined by the number of digits of its vertices. It can be probed that you can choose one vertex (I call it "boss") in each group and then each edge will be incident with at least one boss. We can iterate over all $k^{k - 2}$ possible labeled trees - we must connect bosses with $k - 1$ edges. Then we should add edges to other vertices. An edge between groups $x$ and $y$ will "kill" one vertex either from a group $x$ or from a group $y$. You can solve it with flow or in $O(2^{k})$ with Hall's theorem.
[ "constructive algorithms", "flows", "graphs" ]
3,200
"// Forgotten tree (H), by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\n#define RI(i,n) FOR(i,1,(n))\n#define REP(i,n) FOR(i,0,(n)-1)\n\nchar sl[10];\nint e[10][10], e_memo[10][10];\nvector<int> group[10];\nint boss[10];\n\ntypedef vector<pair<int,int>> Tree;\n\nvector<int> w[10];\nbool vis[10];\nvoid dfs(int a) {\n\tvis[a] = true;\n\tfor(int b : w[a]) if(!vis[b]) dfs(b);\n}\nbool validTree(Tree t, int k) {\n\tfor(pair<int,int> edge : t) {\n\t\tw[edge.first].push_back(edge.second);\n\t\tw[edge.second].push_back(edge.first);\n\t}\n\tdfs(1);\n\tbool ans = true;\n\tRI(i, k) if(!vis[i]) ans = false;\n\tRI(i, k) vis[i] = false;\n\tRI(i, k) w[i].clear();\n\treturn ans;\n}\n\nbool checkEverything(int k) { // O(k * 2^k)\n\tREP(mask, (1 << k)) {\n\t\tvector<int> subset;\n\t\tREP(i, k) if(mask & (1 << i)) subset.push_back(i + 1);\n\t\tint vertices = 0, edges = 0;\n\t\tfor(int i : subset) vertices += group[i].size() - 1;\n\t\tfor(int i : subset) for(int j : subset) edges += e[i][j];\n\t\tif(edges > vertices) return false;\n\t}\n\treturn true;\n}\n\nvoid write(Tree t) {\n\tfor(pair<int,int> edge : t) printf(\"%d-%d\\n\", edge.first, edge.second);\n\tputs(\"\");\n}\n\nvoid tryTree(Tree t, int k) {\n\tRI(i, k) RI(j, k) e[i][j] = e_memo[i][j];\n\tfor(pair<int,int> p : t) {\n\t\tint & tmp = e[p.first][p.second];\n\t\tif(tmp == 0) return;\n\t\t--tmp;\n\t}\n\tif(!checkEverything(k)) return;\n\tvector<pair<int,int>> ans;\n\tfor(pair<int,int> p : t) ans.push_back({boss[p.first], boss[p.second]}); //\n\tRI(i, k) RI(j, k) while(e[i][j]) {\n\t\t--e[i][j];\n\t\tif((int) group[i].size() > 1) {\n\t\t\tint memo = group[i].back();\n\t\t\tgroup[i].pop_back();\n\t\t\tif(checkEverything(k)) {\n\t\t\t\tans.push_back({boss[j], memo});\n\t\t\t\t// printf(\"%d %d\\n\", boss[j], group[i].back());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgroup[i].push_back(memo);\n\t\t}\n\t\tassert((int) group[j].size() > 1);\n\t\tans.push_back({boss[i], group[j].back()});\n\t\t// printf(\"%d %d\\n\", boss[i], group[j].back());\n\t\tgroup[j].pop_back();\n\t\tassert(checkEverything(k));\n\t}\n\tRI(i, k) assert((int) group[i].size() == 1);\n\trandom_shuffle(ans.begin(), ans.end());\n\tfor(pair<int,int> p : ans) {\n\t\tif(rand()%2) swap(p.first, p.second);\n\t\tprintf(\"%d %d\\n\", p.first, p.second);\n\t}\n\texit(0);\n}\n\nvector<Tree> findTrees(int k) {\n\tvector<Tree> ans;\n\tvector<pair<int,int>> edges;\n\tRI(i, k) FOR(j, i+1, k) edges.push_back({i, j});\n\tREP(mask, (1 << edges.size())) if(__builtin_popcount(mask) == k - 1) {\n\t\tTree t;\n\t\tREP(i, (int) edges.size()) if(mask & (1 << i)) t.push_back(edges[i]);\n\t\tif(validTree(t, k)) ans.push_back(t);\n\t}\n\treturn ans;\n}\n\nint findLog(int n) {\n\tint k = 0;\n\twhile(n) {\n\t\t++k;\n\t\tn /= 10;\n\t}\n\treturn k;\n}\n\nint main() {\n\tsrand(42);\n\tint n;\n\tscanf(\"%d\", &n);\n\tRI(i, n) group[findLog(i)].push_back(i);\n\tREP(_, n - 1) {\n\t\tscanf(\"%s\", sl);\n\t\tint a = strlen(sl);\n\t\tscanf(\"%s\", sl);\n\t\tint b = strlen(sl);\n\t\tif(a > b) swap(a, b);\n\t\t++e[a][b];\n\t}\n\tint k = findLog(n);\n\tRI(i, k) boss[i] = group[i][0];\n\tRI(i, k) RI(j, k) e_memo[i][j] = e[i][j];\n\tvector<Tree> trees = findTrees(k);\n\tfor(Tree t : trees) tryTree(t, k);\n\tputs(\"-1\");\n\treturn 0;\n}"
612
A
The Text Splitting
You are given the string $s$ of length $n$ and the numbers $p, q$. Split the string $s$ to pieces of length $p$ and $q$. For example, the string "Hello" for $p = 2$, $q = 3$ can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo". Note it is allowed to split the string $s$ to the strings only of length $p$ or to the strings only of length $q$ (see the second sample test).
Let's fix the number $a$ of strings of length $p$ and the number $b$ of strings of length $q$. If $a \cdot p + b \cdot q = n$, we can build the answer by splitting the string $s$ to $a$ parts of the length $p$ and $b$ parts of the length $q$, in order from left to right. If we can't find any good pair $a, b$ then the answer doesn't exist. Of course this problem can be solved in linear time, but the constraints are small, so you don't need linear solution. Complexity: $O(n^{2})$.
[ "brute force", "implementation", "strings" ]
1,300
null
612
B
HDD is Outdated Technology
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order. One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file. Find the time need to read file split to $n$ fragments. The $i$-th sector contains the $f_{i}$-th fragment of the file ($1 ≤ f_{i} ≤ n$). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the $n$-th fragment is read. The fragments are read in the order from the first to the $n$-th. It takes $|a - b|$ time units to move the magnetic head from the sector $a$ to the sector $b$. Reading a fragment takes no time.
You are given the permutation $f$. Let's build another permutation $p$ in the following way: $p_{fi} = i$. So the permutation $p$ defines the number of sector by the number of fragment. The permutation $p$ is called inverse permutation to $f$ and denoted $f^{ - 1}$. Now the answer to problem is $\textstyle\sum_{i=1}^{n-1}|p_{i}-p_{i+1}|$. Complexity: $O(n)$.
[ "implementation", "math" ]
1,200
null
612
C
Replace To Make Regular Bracket Sequence
You are given string $s$ consists of opening and closing brackets of four kinds <>, {{}}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {{}, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let $s_{1}$ and $s_{2}$ be a RBS then the strings {<$s_{1}$>$s_{2}$}, {{$s_{1}$}$s_{2}$}, {[$s_{1}$]$s_{2}$}, {($s_{1}$)$s_{2}$} are also RBS. For example the string "{[[(){}]<>]}" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string $s$ RBS.
If we forget about bracket kinds the string $s$ should be RBS, otherwise the answer doesn't exist. If the answer exists each opening bracket matches to exactly one closing bracket and vice verse. Easy to see that if two matching brackets have the same kind we don't need to replace them. In other case we can change the kind of the closing bracket to the kind of the opening. So we can build some answer. Obviously the answer is minimal, because the problems for some pair of matching pairs are independent and can be solved separately. The only technical problem is to find the matching pairs. To do that we should store the stack of opening brackets. Let's iterate from left to right in $s$ and if the bracket is opening, we would simply add it to the stack. Now if the bracket is closing there are three cases: 1) the stack is empty; 2) at the top of the stack is the opening bracket with the same kind as the current closing; 3) the kind of the opening bracket differs from the kind of the closing bracket. In the first case answer doesn't exist, in the second case we should simply remove the opening bracket from the stack and in the third case we should remove the opening bracket from the stack and increase the answer by one. Complexity: $O(n)$.
[ "data structures", "expression parsing", "math" ]
1,400
null
612
D
The Union of k-Segments
You are given $n$ segments on the coordinate axis Ox and the number $k$. The point is satisfied if it belongs to at least $k$ segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.
Let's create two events for each segment $l_{i}$ is the time of the segment opening and $r_{i}$ is the time of the segment closing. Let's sort all events by time, if the times are equal let's sort them with priority to opening events. In C++ it can be done with sorting by standard comparator of vector<pair<int, int>> events, where each element of events is the pair with event time and event type ($- 1$ for opening and $+ 1$ for closing). Let's iterate over events and maintain the balance. To do that we should simply decrease the balance by the value of the event type. Now if the balance value equals to $k$ and before updating it was $k - 1$ then we are in the left end of some segment from the answer. If the balance equals to $k - 1$ and before updating it was $k$ then we are in the right end of the segment from the answer. Let's simply add segment $[left, right]$ to the answer. So now we have disjoint set of segments contains all satisfied points in order from left to right. Obviously it's the answer to the problem. Complexity: $O(nlogn)$.
[ "greedy", "sortings" ]
1,800
null
612
E
Square Root of Permutation
A permutation of length $n$ is an array containing each integer from $1$ to $n$ exactly once. For example, $q = [4, 5, 1, 2, 3]$ is a permutation. For the permutation $q$ the square of permutation is the permutation $p$ that $p[i] = q[q[i]]$ for each $i = 1... n$. For example, the square of $q = [4, 5, 1, 2, 3]$ is $p = q^{2} = [2, 3, 4, 5, 1]$. This problem is about the inverse operation: given the permutation $p$ you task is to find such permutation $q$ that $q^{2} = p$. If there are several such $q$ find any of them.
Consider some permutation $q$. Let's build by it the oriented graph with edges $(i, q_{i})$. Easy to see (and easy to prove) that this graph is the set of disjoint cycles. Now let's see what would be with that graph when the permutation will be multiplied by itself: all the cycles of odd length would remain so (only the order of vertices will change, they will be alternated), but the cycles of even length will be split to the two cycles of the same length. So to get the square root from the permutation we should simply alternate (in reverse order) all cycles of the odd length, and group all the cycles of the same even length to pairs and merge cycles in each pair. If it's impossible to group all even cycles to pairs then the answer doesn't exist. Complexity: $O(n)$.
[ "combinatorics", "constructive algorithms", "dfs and similar", "graphs", "math" ]
2,200
null
612
F
Simba on the Circle
You are given a circular array with $n$ elements. The elements are numbered from some element with values from $1$ to $n$ in clockwise order. The $i$-th cell contains the value $a_{i}$. The robot Simba is in cell $s$. Each moment of time the robot is in some of the $n$ cells (at the begin he is in $s$). In one turn the robot can write out the number written in current cell or move to the adjacent cell in clockwise or counterclockwise direction. To write out the number from the cell Simba doesn't spend any time, but to move to adjacent cell Simba spends one unit of time. Simba wants to write the number from each cell one time, so the numbers will be written in a non decreasing order. Find the least number of time units to write out all numbers.
The author solution for this problem uses dynamic programming. I think that this problem can't be solved by greedy ideas. Let's calculate two dp's: $z1_{i}$ is the answer to the problem if all numbers less than $a_{i}$ are already printed, but the others are not; and $z2_{i}$ is the answer to the problem if all numbers less than or equal to $a_{i}$ are already printed, but the others are not. Let's denote $d_{ij}$ - the least distance between $i$ and $j$ on the circular array and $od_{ij}$ is the distance from $i$ to $j$ in clockwise order. Easy to see that $z2_{i} = min_{j}(z_{j} + d_{ij})$ for all $j$ such that the value $a_{j}$ is the least value greater than $a_{i}$. Now let's calculate the value $z1_{i}$. Consider all elements equals to $a_{i}$ (in one of them we are). If there is only one such element then $z1_{i} = z2_{i}$. Otherwise we have two alternatives: to move in clockwise or counterclockwise direction. Let we are moving in clockwise direction, the last element from which we will write out the number would be the nearest to the $i$ element in counterclockwise direction, let's denote it $u$. Otherwise at last we will write out the number from the nearest to the $i$ element in clockwise direction, let's denote it $v$. Now $z1_{i} = min(z2_{u} + od_{iu}, z2_{v} + od_{vi})$. Easy to see that the answer to the problem is $min_{i}(z1_{i} + d_{si})$, over all $i$ such that $a_{i}$ is the smallest value in array and $s$ is the start position. Additionally you should restore the answer. To do that, on my mind, the simplest way is to write the recursive realization of dp, test it carefully and then copy it to restore answer (see my code below). Of course, it's possible to restore the answer without copy-paste. For example, you can add to your dp parameter $b$ which means it's need to restore answer or not. Complexity: $O(n^{2})$.
[ "dp" ]
2,600
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 2020;\n\nint n, s;\nint a[N];\n\ninline bool read() {\n\tif (!(cin >> n >> s)) return false;\n\ts--;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\ninline int dist(int a, int b) {\n\tint d = abs(a - b);\n\td = min(d, n - d);\n\treturn d;\n}\n\ninline int odist(int a, int b) {\n\tint d = b - a;\n\t(d < 0) && (d += n);\n\treturn d;\n}\n\nint nt[N];\nint z1[N], z2[N];\n\nint solve1(int);\n\nint solve2(int v) {\n\tint& ans = z2[v];\n\tif (ans != -1) return ans;\n\tif (nt[v] == INT_MAX) return ans = 0;\n\n\tans = INF;\n\n\tforn(i, n)\n\t\tif (a[i] == nt[v]) {\n\t\t\tans = min(ans, solve1(i) + dist(v, i));\n\t\t}\n\n\treturn ans;\n}\n\nint solve1(int v) {\n\tint& ans = z1[v];\n\tif (ans != -1) return ans;\n\n\tans = INF;\n\n\tfor (int d = -1; d <= +1; d += 2) {\n\t\tint u = -1;\n\t\tfore(i, 1, n) {\n\t\t\tint vv = (v + i * d + n) % n;\n\t\t\tif (a[vv] == a[v]) {\n\t\t\t\tu = vv;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (u == -1)\n\t\t\tans = min(ans, solve2(v));\n\t\telse {\n\t\t\tint dt = d == 1 ? odist(u, v) : odist(v, u);\n\t\t\tans = min(ans, solve2(u) + dt);\n\t\t}\n\t}\n\n\treturn ans;\n}\n\nvoid restore1(int);\n\nvoid restore2(int v) {\n\tint& ans = z2[v];\n\tassert(ans != -1);\n\tif (nt[v] == INT_MAX) return;\n\n\tforn(i, n)\n\t\tif (a[i] == nt[v] && ans == solve1(i) + dist(v, i)) {\n\t\t\tint d = i - v;\n\t\t\t(d < 0) && (d += n);\n\t\t\tif (d <= n - d) printf(\"+%d\\n\", d);\n\t\t\telse printf(\"-%d\\n\", n - d);\n\t\t\treturn restore1(i);;\n\t\t}\n\n\tthrow;\n}\n\nvoid restore1(int v) {\n\tint& ans = z1[v];\n\tassert(ans != -1);\n\n\tfor (int d = -1; d <= +1; d += 2) {\n\t\tint u = -1;\n\t\tfore(i, 1, n) {\n\t\t\tint vv = (v + i * d + n) % n;\n\t\t\tif (a[vv] == a[v]) {\n\t\t\t\tu = vv;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (u == -1) {\n\t\t\tif (ans == solve2(v)) {\n\t\t\t\treturn restore2(v);\n\t\t\t}\n\t\t} else {\n\t\t\tint dt = d == 1 ? odist(u, v) : odist(v, u);\n\t\t\tif (ans == solve2(u) + dt) {\n\t\t\t\tint cdt = 0;\n\t\t\t\tfore(i, 1, n) {\n\t\t\t\t\tint vv = (v + i * (-d) + n) % n;\n\t\t\t\t\tcdt++;\n\t\t\t\t\tif (a[vv] == a[v]) {\n\t\t\t\t\t\tprintf(\"%c%d\\n\", d == +1 ? '-' : '+', cdt);\n\t\t\t\t\t\tcdt = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn restore2(u);\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow;\n}\ninline void solve() {\n\tmemset(z1, -1, sizeof(z1));\n\tmemset(z2, -1, sizeof(z2));\n\n\tforn(i, n) {\n\t\tnt[i] = INT_MAX;\n\t\tforn(j, n)\n\t\t\tif (a[j] > a[i])\n\t\t\t\tnt[i] = min(nt[i], a[j]);\n\t}\n\n\t//cerr << solve1(0) << endl;\n\t//exit(0);\n\n\tint minv = *min_element(a, a + n);\n\tint ans = INF;\n\tforn(i, n)\n\t\tif (a[i] == minv) {\n\t\t\tans = min(ans, solve1(i) + dist(s, i));\n\t\t}\n\n\tcout << ans << endl;\n\tforn(i, n)\n\t\tif (a[i] == minv && ans == solve1(i) + dist(s, i)) {\n\t\t\tint d = i - s;\n\t\t\t(d < 0) && (d += n);\n\t\t\tif (d <= n - d) printf(\"+%d\\n\", d);\n\t\t\telse printf(\"-%d\\n\", n - d);\n\t\t\trestore1(i);\n\t\t\tbreak;\n\t\t}\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
613
A
Peter and Snow Blower
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path. Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine. Peter decided to tie his car to point $P$ and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.
Consider distances between the point $P$ and all points of the polygon. Let $R$ be the largest among all distances, and $r$ be the smallest among all distances. The swept area is then a ring between circles of radii $R$ and $r$, and the answer is equal to $ \pi (R^{2} - r^{2})$. Clearly, $R$ is the largest distance between $P$ and vertices of the polygon. However, $r$ can be the distance between $P$ and some point lying on the side of the polygon, therefore, $r$ is the smallest distance between $P$ and all sides of the polygon. To find the shortest distance between a point $p$ and a segment $s$, consider a straight line $l$ containing the segment $s$. Clearly, the shortest distance between $p$ and $l$ is the length of the perpendicular segment. One should consider two cases: when the end of the perpendicular segment lies on the segment $s$ (then the answer is the length of the perpendicular segment), or when it lies out of $s$ (then the answer is the shortest distance to the ends of $s$).
[ "binary search", "geometry", "ternary search" ]
1,900
null
613
B
Skills
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly $n$ skills. Each skill is represented by a non-negative integer $a_{i}$ — the current skill level. All skills have the same maximum level $A$. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: - The number of skills that a character has perfected (i.e., such that $a_{i} = A$), multiplied by coefficient $c_{f}$. - The minimum skill level among all skills ($min a_{i}$), multiplied by coefficient $c_{m}$. Now Lesha has $m$ hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by $1$ (if it's not equal to $A$ yet). Help him spend his money in order to achieve the maximum possible value of the Force.
Let's save the original positions of skills and then sort the skills in non-increasing order (almost decreasing) by current level. We can always restore original order after. Imagine that we have decided that we want to use the minimum level $X$ and now we're choosing which skills we should bring to the maximum. At first, let's rise all skills below $X$ to level $X$, this will set some tail of array to $X$. But the original array was sorted, and this new change will not break the sort! So our array is still sorted. Obviously, the skills we want to take to the maximum are the ones with highest current level. They are in the prefix of array. It is easy to show that any other selection is no better than this greedy one. Now we have shown that the optimal strategy is to max out the skills in some prefix. Now let's solve the problem. Let's iterate over prefix to max out, now on each iteration we need to know the highest minimum we can achieve, let's store the index of the first element outside the prefix such that it is possible to reach the minimum level $ \ge arr_{index}$. It is easy to recalc this index, it slightly moves forward each turn and, after precalcing the sum of all array's tails, you can update it easily (just move it forward until the invariant above holds). And knowing this index is enough to calc the current highest possible minimum level ($min(A, arr_{index} + \lfloor sparemoney / (n - index) \rfloor $). How to restore the answer? Actually, all you need to know is the count of maximums to take and minimum level to reach.
[ "binary search", "brute force", "dp", "greedy", "sortings", "two pointers" ]
1,900
null
613
C
Necklace
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of $n$ colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
Surprisingly, the nice cuts can't be put randomly. Let's take a look on the first picture above (red lines represent nice cut points). But since the necklace is symmetrical relative to nice cuts, the cut points are also symmetrical relative to nice cuts, so there is one more cut (see picture two). Repeating this process, we will split the whole necklace into parts of the same size (picture three). If the number of parts is even, then each part can be taken arbitrarily, but the neighbouring parts must be reverses of each other (e.g. "abc" and "cba"). This is an implication of the cuts being nice. If the number of parts is odd, then each part is equal to each other and is a palindrome, this is an implication of the cuts being nice too. Anyway, the number of characters in each part is equal, so amount of parts can't be greater than $\operatorname*{gcd}(a_{i})$. Actually, it may be zero, $\operatorname{gcd}$ or its divisor. If the number of odd-sized colors is zero, then the sum is even and gcd is even, this way we can construct a building block containing exactly $\frac{a_{i}}{\mathrm{gcd}}$ beads of $i$-th color, (gcd being gcd of all counts), then build beads of $gcd$ parts, where each part equal to building block, with neighbouring parts being reverses. Since $gcd$ is even, everything is ok. If the number of odd-sized colors is one, then the sum is odd and gcd is odd. Building block have to be built as a palindrome containing $\frac{a_{i}}{\mathrm{gcd}}$ beads of $i$-th color, exactly $n - 1$ of colors will be even and one odd, put the odd one in center, others on sides (aabcbaa). Everything is ok. If num of odd counts is $geq2$. Gcd is odd, all its divisors too, so our building block has to be palindrome. Let $k$ denote the number of parts. A building block will contain $\frac{u_{i_{i}}}{k}$ beads of color $i$, at least two of these numbers are odd, it is impossible to build such a palindrome. The answer is zero. Complexity: $O(sum)$, just to output answer.
[ "constructive algorithms", "math" ]
2,500
null
613
D
Kingdom and its Cities
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible. The kingdom currently consists of $n$ cities. Cities are connected by $n - 1$ bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities. What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan. Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city. Help the King to calculate this characteristic for each of his plan.
Obviously, the answer is -1 iff two important cities are adjacent. If there was a single query, can we answer it in $O(n)$ time? Let's choose a root arbitrarily. We can note there is an optimal answer that erases two types of vertices: vertices that lie on a vertical path between two important vertices, or LCA of some pair of important vertices. Let's do a subtree DP that counts the answer for the subtree of $v$, as well as if there is any important vertex still connected to $v$ in the answer. How do we count it? If $v$ is important, then we should disconnect it from any still-connected vertices from below by erasing these children which contain them. If $v$ is not important, then we erase it iff there are more than one still-connected important vertices below. All calculations are straightforward here. How do we process many queries now? There are many possible approaches here (for reference, look at the accepted solutions). The author's solution was as follows: if we have a query with $k$ important vertices, then we can actually build an auxiliary tree with $O(k)$ vertices and apply the linear DP solution to it with minor modifications. How to construct the auxiliary tree? We should remember the observation about LCAs. Before we start, let us DFS the initial tree and store the preorder of the tree (also known as "sort by tin"-order). A classical exercise: to generate all possible LCAs of all pairs among a subset of vertices, it suffices to consider LCAs of consecutive vertices in the preorder. After we find all the LCAs, it is fairly easy to construct the tree in $O(k)$ time. Finally, apply the DP to the auxiliary tree. Note that important cities adjacent in the auxiliary tree are actually not adjacent (since we've handled that case before), so it is possible to disconnect them. If we use the standard "binary shifts" approach to LCA, we answer the query in $O(k\log n)$ time, for a total complexity of $O((n+\sum k_{i})\log n)$.
[ "dfs and similar", "divide and conquer", "dp", "graphs", "sortings", "trees" ]
2,800
null
613
E
Puzzle Lover
Oleg Petrov loves crossword puzzles and every Thursday he buys his favorite magazine with crosswords and other word puzzles. In the last magazine Oleg found a curious puzzle, and the magazine promised a valuable prize for it's solution. We give a formal description of the problem below. The puzzle field consists of two rows, each row contains $n$ cells. Each cell contains exactly one small English letter. You also are given a word $w$, which consists of $k$ small English letters. A solution of the puzzle is a sequence of field cells $c_{1}$, $...$, $c_{k}$, such that: - For all $i$ from $1$ to $k$ the letter written in the cell $c_{i}$ matches the letter $w_{i}$; - All the cells in the sequence are pairwise distinct; - For all $i$ from $1$ to $k - 1$ cells $c_{i}$ and $c_{i + 1}$ have a common side. Oleg Petrov quickly found a solution for the puzzle. Now he wonders, how many distinct solutions are there for this puzzle. Oleg Petrov doesn't like too large numbers, so calculate the answer modulo $10^{9} + 7$. Two solutions $c_{i}$ and $c'_{i}$ are considered distinct if the sequences of cells do not match in at least one position, that is there is such $j$ in range from $1$ to $k$, such that $c_{j} ≠ c'_{j}$.
The key observation: any way to cross out the word $w$ looks roughly as follows: That is, there can be following parts: go back $a$ symbols in one row, then go forward $a$ symbols in the other row (possibly $a = 0$) go forward with arbitrarily up and down shifts in a snake-like manner go forward $b$ symbols in one row, then go back $b$ in the other row (possibly $b = 0$) Note that the "forward" direction can be either to the left or to the right. It is convenient that for almost any such way we can determine the "direction" as well as the places where different "parts" of the path (according to the above) start. To avoid ambiguity, we will forbid $a = 1$ or $b = 1$ (since such parts can be included into the "snake"). Fix the direction. We will count the DP $d_{x, y, k}$ for the number of ways to cross out first $k$ letters of $w$ and finished at the cell $(x, y)$ while being inside the snake part of the way. The transitions are fairly clear (since the snake part only moves forward). However, we have to manually handle the first and the last part. For each cell and each value of $k$ we can determine if the "go-back-then-go-forward" maneuver with parameter $k$ can be performed with the chosen cell as finish; this can be reduced to comparing of some substrings of field of rows and the word $w$ (and its reversed copy). In a similar way, for any state we can check if we can append the final "go-forward-then-go-back" part of the path to finally obtain a full-fledged path. This DP has $O(n^{2})$ states and transitions. However, there are still some questions left. How do we perform the substring comparisons? There is a whole arsenal of possible options: (carefully implemented) hashes, suffix structures, etc. Probably the simplest way is to use Z-function for a solution that does $O(n^{2})$ precalc and answers each substring query in $O(1)$ time (can you see how to do it?). Also, there are paths that we can consider more than once. More precisely, a path that consists only of the "go-forward-the-go-back" part will be counted twice (for both directions), thus we have to subtract such paths explicitly. Every other path is counted only once, thus we are done. (Note: this does not exactly work when $w$ is short, say, 4 symbols or less. The simplest way is to implement straightforward brute-force for such cases.)
[ "dp", "hashing", "strings" ]
3,200
null
614
A
Link/Cut Tree
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the $expose$ procedure. Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?) Given integers $l$, $r$ and $k$, you need to print all powers of number $k$ within range from $l$ to $r$ \textbf{inclusive}. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
You had to print all numbers of form $k^{x}$ for non-negative integers $x$ that lie with the range $[l;r]$. A simple cycle works: start with $1 = k^{0}$, go over all powers that do not exceed $r$ and print those which are at least $l$. One should be careful with 64-bit integer overflows: consider the test $l = 1$, $r = 10^{18}$, $k = 10^{9}$, the powers will be 1, $10^{9}$, $10^{18}$, and the next power is $10^{27}$, which does not fit in a standard integer type.
[ "brute force", "implementation" ]
1,500
null
614
B
Gena's Code
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly $n$ distinct countries in the world and the $i$-th country added $a_{i}$ tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains \textbf{at most one} digit '1'. However, due to complaints from players, some number of tanks of \textbf{one} country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
You were asked to print the product of $n$ large numbers, but it was guaranteed that at least $n - 1$ are beautiful. It's not hard to see that beautiful numbers are 0 and all powers of 10 (that is, 1 followed by arbitrary number of zeros). If there is at least one zero among the given numbers, the product is 0. Otherwise, consider the only non-beautiful number $x$ (if all numbers are beautiful, consider $x = 1$). Multiplying $x$ by $10^{t}$ appends $t$ zeros to its decimal representation, so in this case we have to find the only non-beautiful number and print it with several additional zeros. We tried to cut off all naive solutions that use built-in long numbers multiplication in Python or Java. However, with some additional tricks (e.g., ``divide-and-conquer'') this could pass all tests.
[ "implementation", "math" ]
1,400
null
615
A
Bulbs
Vasya wants to turn on Christmas lights consisting of $m$ bulbs. Initially, all bulbs are turned off. There are $n$ buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
Let's make a counter of number of buttons that switch every lamp off. If there is a lamp with zero counter, output NO, otherwise YES.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int n, m; cin >> m >> n; vector<int> cnt(n); while (m--) { int k; cin >> k; vector<int> ys(k); for (auto &y : ys) { cin >> y; cnt[y - 1]++; } } for (auto &x : cnt) { if (x <= 0) { cout << "NO" << endl; return 0; } } cout << "YES" << endl; return 0; }
615
B
Longtail Hedgehog
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of $n$ points connected by $m$ segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: - Only segments already presented on the picture can be painted; - The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; - The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the \textbf{endpoint} of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get. Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.
Way of solving - dynamic programming. We are given a graph of n vertices and m edges. We will calculate dp[i] - a maximum length of tail that is ending in i-th vertex. We can simply update dp by checking all the edges from i-th vertex(which are leading to vertices with bigger number), and trying to update them. When we have this dp, we can check the answer easily.
[ "dp", "graphs" ]
1,600
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() typedef long long ll; const int maxN = 1 << 17; int dp[maxN]; vector<int> g[maxN]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; while(m--) { int v, u; cin >> v >> u; g[v].push_back(u); g[u].push_back(v); } ll ans = -1ll; for (int v = 1; v <= n; v++) { dp[v] = 1; for (auto u : g[v]) { if (u < v) { dp[v] = max(dp[v], dp[u] + 1); } } ans = max(ans, dp[v] * (ll)g[v].size()); } cout << ans << endl; return 0; }
615
C
Running Track
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art. First, he wants to construct the running track with coating $t$. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string. Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings $s$. Also, he has scissors and glue. Ayrat is going to buy some coatings $s$, then cut out from each of them \textbf{exactly one continuous piece} (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating $s$ he needs to buy in order to get the coating $t$ for his running track. Of course, he also want's to know some way to achieve the answer.
The idea is that if can make a substring t[i, j] using k coatings, then we can also make a substring t[i + 1, j] using k coatings. So we should use the longest substring each time. Let n = |s|, m = |t|. On each stage we will search for the longest substring in s and s_reversed to update the answer. We can do it in several ways: Calculate lcp[i][j] - longest common prefix t[i, m] and s[j, n], lcprev[i][j] - longest common prefix t[i, m] and s[j, 1]. Find longest means find max(max(lcp[i][1], lcp[i][2], $...$, lcp[i][n]), max(lcprev[i][1], lcprev[i][2], $...$, lcprev[i][n])). calculation lcp:
[ "dp", "greedy", "strings", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() #define fi first #define se second const int maxC = 'z' - 'a' + 1; struct Node { int next[maxC]; int l, r; Node() { memset(this, 0, sizeof(*this)); } }; struct Trie { vector<Node> T; Trie() { T.push_back(Node()); T.reserve(2100 * 2100); } void addStr(string s, int l, int dr) { int v = 0; int r = l; for (auto c : s) { c -= 'a'; if (!T[v].next[c]) { T[v].next[c] = T.size(); T.push_back(Node()); T.back().l = l; T.back().r = r; } v = T[v].next[c]; r += dr; } } void built(string s) { int n = s.size(); for (int i = 0; i < n; i++) { string cur; cur = s.substr(i, n - i); addStr(cur, i, 1); cur = s.substr(0, n - i); reverse(all(cur)); addStr(cur, n - i - 1, -1); } } vector<pair<int,int> > go(string t) { vector<pair<int,int> > ans; int v = 0; int n = t.size(); t.push_back('z' + 1); for (int i = 0; i <= n; i++) { char c = t[i] - 'a'; if (i == n || T[v].next[c] == 0) { if (v == 0) { return vector<pair<int,int> >(); } ans.push_back({T[v].l, T[v].r}); v = 0; } if (i < n) { v = T[v].next[c]; } } return ans; } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); Trie T; string s, t; cin >> s >> t; T.built(s); vector<pair<int,int> > ans = T.go(t); if (ans.size() == 0) { cout << -1 << endl; return 0; } cout << ans.size() << endl; for (auto x : ans) { cout << x.fi + 1 << " " << x.se + 1 << endl;; } return 0; }
615
D
Multipliers
Ayrat has number $n$, represented as it's prime factorization $p_{i}$ of size $m$, i.e. $n = p_{1}·p_{2}·...·p_{m}$. Ayrat got secret information that that the product of all divisors of $n$ taken modulo $10^{9} + 7$ is the password to the secret data base. Now he wants to calculate this value.
Let d(x) be a number of divisors of x, and f(x) be the product of divisors. Let $x = p_{1}^{ \alpha 1}p_{2}^{ \alpha 2}... p_{n}^{ \alpha n}$, then $d(x) = ( \alpha _{1} + 1) \cdot ( \alpha _{2} + 1)... ( \alpha _{n} + 1)$ $f(x)=x^{\frac{d(x)}{2}}$. There is $\textstyle{\frac{d(x)}{2}}\right\}$ pairs of divisors of type $\left({\frac{x}{x}},c\right)$, $c<{\sqrt{x}}$, and if x is a perfect square we have one more divisor : $\sqrt{x}$. for a prime $m$ and $a \neq 0$ the statement $a^{m-1}\equiv1{\pmod{m}}\Rightarrow a^{x}\equiv a^{x\Re_{c}(m-1)}{\mathrm{~(mod~}}m{\mathrm{)}}$ (little Fermat theorem) We can see that $d(a b)=d(a)d(b),\;f(a b)=f(a)^{d(b)}f(b)^{d(a)},\;f(p^{k})=p^{\frac{k(k+1)}{2}}$, if a and b are co prime. Now we can count the answer:
[ "math", "number theory" ]
2,000
#include <bits/stdc++.h> using namespace std; #define fi first #define se second #define all(x) (x).begin(), (x).end() typedef long long ll; const ll MOD = (ll)1e9 + 7; ll binPow(ll a, ll q, ll MOD) { a %= MOD; if (q == 0) return 1; return ((q % 2 == 1 ? a : 1) * binPow(a * a, q / 2, MOD)) % MOD; } int main() { int n; scanf("%d", &n); map<int,int> cnt; while (n--) { int x; scanf("%d", &x); cnt[x]++; } ll d = 1; ll ans = 1; for (auto x : cnt) { ll cnt = x.se; ll p = x.fi; ll fp = binPow(p, (cnt + 1) * cnt / 2, MOD); ans = binPow(ans, (cnt + 1), MOD) * binPow(fp, d, MOD) % MOD; d = d * (x.se + 1) % (MOD - 1); } cout << ans << endl; return 0; }
615
E
Hexagons
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined: Ayrat is searching through the field. He started at point $(0, 0)$ and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after $n$ moves.
Let's see how the coordinates are changing while we move from current cell to one of the 6 adjacent cells - let's call this 6 typed of moves. If we know the number of moves of each type on our way, then we know the coordinates of the end of the way. We will divide the way into rings. Let's count the number of moves of each type for the first ring. Next ring will have one more move of each type. Length of each ring = length of previous + 6. It is an arithmetic progression. Using well-known formulas and binary search we calculate the number of the last ring and overall length of previous rings. Now we have to brute-force 6 types of the last move and calculate the answer.
[ "binary search", "implementation", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second pair<ll, ll> solve(ll n) { ll j = 0, cur = 0; ll x = 0, y = 0; vector<ll> dx = {1, -1, -2, -1, 1, 2}; vector<ll> dy = {2, 2, 0, -2, -2, 0}; vector<ll> cnt = {1, 0, 1, 1, 1, 1}; ll l = -1, r = (ll)1e9; while (r - l > 1) { ll m = (r + l) / 2; if (m * (m * 3 + 2) <= n) { l = m; } else { r = m; } } cur = l * (l * 6 + 4) / 2; x += l * dx[4]; y += l * dy[4]; for (int i = 0; i < 6; i++) { cnt[i] += l; } while (cur < n) { ll d = min(cnt[j], n - cur); cur += d; x += dx[j] * d; y += dy[j] * d; cnt[j]++; j = (j + 1) % 6; } return {x, y}; } int main() { ll n; cin >> n; auto p = solve(n); cout << p.fi << " " << p.se << endl; return 0; }
616
A
Comparing Two Long Integers
You are given two very long integers $a, b$ (leading zeroes are allowed). You should check what number $a$ or $b$ is greater or determine that they are equal. The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().
Note that solutions in Java with BigInteger class or input() function in Python2 will fail in this problem. The reason is the next: standard objects stores numbers not in decimal system and need a lot of time to convert numbers from decimal system. Actually they are working in $O(n^{2})$, where $n$ is the legth of the number. To solve this problem you should simply read the numbers to strings and add leading zeroes to the shorter one until the numbers will be of the same length. After that you should simply compare them alphabetically. Complexity: $O(n)$.
[ "implementation", "strings" ]
900
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 1200300;\n\nchar a[N];\nchar b[N];\n\ninline bool read() {\n\tif (!gets(a)) return false;\n\tassert(gets(b));\n\treturn true;\n}\n\ninline void solve() {\n\tint n = int(strlen(a));\n\tint m = int(strlen(b));\n\treverse(a, a + n);\n\treverse(b, b + m);\n\twhile (n < m) a[n++] = '0';\n\twhile (m < n) b[m++] = '0';\n\tint p = n - 1;\n\twhile (p >= 0 && a[p] == b[p]) p--;\n\tif (p < 0) puts(\"=\");\n\telse if (a[p] < b[p]) puts(\"<\");\n\telse puts(\">\");\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
616
B
Dinner with Emma
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places. Munhattan consists of $n$ streets and $m$ avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from $1$ to $n$ and the avenues are numbered with integers from $1$ to $m$. The cost of dinner in the restaurant at the intersection of the $i$-th street and the $j$-th avenue is $c_{ij}$. Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.
Firstly you should find the minimum value in each row and after that you should find the maximum value over that minimums. It's corresponding to the strategy of Jack and Emma. Complexity: $O(nm)$.
[ "games", "greedy" ]
1,000
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 5050;\n\nint n, m;\nint a[N][N];\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) forn(j, m) assert(scanf(\"%d\", &a[i][j]) == 1);\n\treturn true;\n}\n\ninline void solve() {\n\tint ans = INT_MIN;\n\tforn(i, n) {\n\t\tint cur = INT_MAX;\n\t\tforn(j, m) cur = min(cur, a[i][j]);\n\t\tans = max(ans, cur);\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
616
C
The Labyrinth
You are given a rectangular field of $n × m$ cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side. Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component. For each impassable cell $(x, y)$ imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains $(x, y)$. You should do it for each impassable cell independently. The answer should be printed as a matrix with $n$ rows and $m$ columns. The $j$-th symbol of the $i$-th row should be "." if the cell is empty at the start. Otherwise the $j$-th symbol of the $i$-th row should contain the only digit —- the answer modulo $10$. The matrix should be printed without any spaces. To make your output faster it is recommended to build the output as an array of $n$ strings having length $m$ and print it as a sequence of lines. It will be much faster than writing character-by-character. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Let's enumerate all the connected components, store their sizes and for each empty cell store the number of it's component. It can be done with a single dfs. Now the answer for some impassable cell is equal to one plus the sizes of all different adjacent connected components. Adjacent means the components of cells adjacent to the current impassable cell (in general case each unpassable cell has four adjacent cells). Complexity: $O(nm)$.
[ "dfs and similar" ]
1,600
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 1010;\n\nint n, m;\nchar a[N][N];\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) assert(scanf(\"%s\", a[i]) == 1);\n\treturn true;\n}\n\nint sz[N * N];\nint tt, num[N][N];\n\nint dx[] = { -1, 0, 1, 0 };\nint dy[] = { 0, -1, 0, 1 };\n\nvoid dfs(int x, int y) {\n\tsz[tt]++;\n\tnum[x][y] = tt;\n\n\tforn(i, 4) {\n\t\tint xx = x + dx[i];\n\t\tint yy = y + dy[i];\n\t\tif (min(xx, yy) < 0 || xx >= n || yy >= m) continue;\n\t\tif (num[xx][yy] != -1 || a[xx][yy] != '.') continue;\n\t\tdfs(xx, yy);\n\t}\n}\n\nchar ans[N][N];\n\ninline void solve() {\n\ttt = 0;\n\tforn(i, n) forn(j, m) num[i][j] = -1;\n\n\tforn(i, n)\n\t\tforn(j, m)\n\t\t\tif (num[i][j] == -1 && a[i][j] == '.') {\n\t\t\t\tsz[tt] = 0;\n\t\t\t\tdfs(i, j);\n\t\t\t\ttt++;\n\t\t\t}\n\n#ifdef SU1\n\tforn(i, n) {\n\t\tforn(j, m) cerr << num[i][j] << ' ';\n\t\tcerr << endl;\n\t}\n#endif\n\n\tforn(i, n)\n\t\tforn(j, m) {\n\t\t\tif (a[i][j] == '.') {\n\t\t\t\tans[i][j] = '.';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint cur[4] = { -1, -1, -1, -1 };\n\t\t\tforn(k, 4) {\n\t\t\t\tint x = i + dx[k];\n\t\t\t\tint y = j + dy[k];\n\t\t\t\tif (min(x, y) < 0 || x >= n || y >= m) continue;\n\t\t\t\tif (a[x][y] != '.') continue;\n\t\t\t\tcur[k] = num[x][y];\n\t\t\t}\n\t\t\tsort(cur, cur + 4);\n\t\t\tint szcur = int(unique(cur, cur + 4) - cur);\n\t\t\tint ans = 1;\n\t\t\tforn(k, szcur)\n\t\t\t\tif (cur[k] != -1)\n\t\t\t\t\tans += sz[cur[k]];\n\t\t\tans %= 10;\n\t\t\t::ans[i][j] = char('0' + ans);\n\t\t}\n\n\tforn(i, n) puts(ans[i]);\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
616
D
Longest k-Good Segment
The array $a$ with $n$ integers is given. Let's call the sequence of one or more consecutive elements in $a$ segment. Also let's call the segment k-good if it contains no more than $k$ different values. Find any longest k-good segment. As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
This problem is given because on the Codeforces pages we often see questions like "What is the method of the two pointers?". This problem is a typical problem that can be solved using two pointers technique. Let's find for each left end $l$ the maximal right end $r$ that $(l, r)$ is a $k$-good segment. Note if $(l, r)$ is a $k$-good segment then $(l + 1, r)$ is also a $k$-good segment. So the search of the maximal right end for $l + 1$ we can start from the maximal right end for $l$. The only thing that we should do is to maintain in the array $cnt_{x}$ for each number $x$ the number of it's occurrences in the current segment $(l, r)$ and the number of different numbers in $(l, r)$. We should move the right end until the segment became bad and then move the left end. Each of the ends $l$, $r$ will be moved exactly $n$ times. Complexity: $O(n)$.
[ "binary search", "data structures", "two pointers" ]
1,600
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 1200300;\n\nint n, k;\nint a[N];\n\ninline bool read() {\n\tif (!(cin >> n >> k)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nint cur;\nint cnt[N];\n\ninline void add(int x) {\n\tif (++cnt[x] == 1) cur++;\n}\n\ninline void rem(int x) {\n\tif (--cnt[x] == 0) cur--;\n}\n\ninline void solve() {\n\tcur = 0;\n\tmemset(cnt, 0, sizeof(cnt));\n\n\tint al = -1, ar = -1;\n\tint p = 0;\n\tforn(i, n) {\n\t\twhile (p < n) {\n\t\t\tadd(a[p]);\n\t\t\tif (cur > k) {\n\t\t\t\trem(a[p]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tp++;\n\t\t}\n\t\tif (ar - al < p - i) al = i, ar = p;\n\t\trem(a[i]);\n\t\t//cerr << i << ' ' << p << endl;\n\t}\n\tassert(al != -1);\n\tcout << al + 1 << ' ' << ar << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
616
E
Sum of Remainders
Calculate the value of the sum: $n$ mod $1$ + $n$ mod $2$ + $n$ mod $3$ + ... + $n$ mod $m$. As the result can be very large, you should print the value modulo $10^{9} + 7$ (the remainder when divided by $10^{9} + 7$). The modulo operator $a$ mod $b$ stands for the remainder after dividing $a$ by $b$. For example $10$ mod $3$ = $1$.
Unfortunately my solution for this problem had overflow bug. It was fixed on contest. Even so I hope you enjoyed the problem because I think it's very interesting. Let's transform the sum $\sum_{i=1}^{m}n\ m o d\ i=\sum_{i=1}^{m}\left(n-\lfloor{\frac{n}{i}}\rfloor i\right)=m n-\sum_{i=1}^{m}\lfloor{\frac{n}{i}}\rfloor i$. Note that the last sum can be accumulated to only value $min(n, m)$, because for $i > n$ all the values will be equal to $0$. Note in the last sum either $i\leq{\sqrt{n}}$ or $\textstyle{\bigl\iota_{i}}\bigr\rfloor\leq\sqrt{n}$. Let's carefully accumulate both cases. The first sum can be simply calculated by iterating over all $i\leq{\sqrt{n}}$. We will accumulate the second sum independently for all different values $\left\lfloor{\frac{2}{i}}\right\rfloor$. Firstly we should determine for which values $i$ we will have the value $v=\lfloor{\frac{n}{i}}\rfloor$. Easy to see that for the values $i$ from the interval $\left(l f\right)=\left.\left[{\frac{n}{v+1}}\right],r g=m i n\left(m,\left\lfloor{\frac{n}{v}}\right\rfloor\right)\right\rfloor$. Also we can note that the sum of the second factors in $\sum_{i=1}^{m}\left|{\frac{n}{i}}\right|i$ with fixed first factor can be calculaed in constant time - it's simply a sum of arithmetic progression $\sum_{i=l f+1}^{r_{j}}{\frac{i}{l}}$. So we have solution with complexity $O({\sqrt{n}})$. Complexity: $O({\sqrt{n}})$.
[ "implementation", "math", "number theory" ]
2,200
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nli n, m;\n\ninline bool read() {\n\treturn !!(cin >> n >> m);\n}\n\nconst li mod = INF + 7;\n\ninline void normal(li& a) {\n\ta %= mod;\n\t(a < 0) && (a += mod);\n}\n\ninline li mul(li a, li b) {\n\ta %= mod, b %= mod;\n\tnormal(a), normal(b);\n\treturn (a * b) % mod;\n}\n\ninline li add(li a, li b) {\n\ta %= mod, b %= mod;\n\tnormal(a), normal(b);\n\treturn (a + b) % mod;\n}\n\ninline li sub(li a, li b) {\n\ta %= mod, b %= mod;\n\tnormal(a), normal(b);\n\ta -= b;\n\tnormal(a);\n\treturn a;\n}\n\ninline li sum(li n) { return mul(mul(n, n + 1), (mod + 1) / 2); }\ninline li sum(li lf, li rg) { return sub(sum(rg), sum(lf - 1)); }\n\ninline li calcDiv(li n, li m) {\n\tm = min(m, n);\n\n\tli ans = 0;\n\tli minVal = m;\n\tfor (li i = 1; i * i <= n; i++) {\n\t\tli lf = n / (i + 1), rg = n / i;\n\t\trg = min(rg, m);\n\t\tif (lf >= rg) continue;\n\t\tminVal = lf; // interval (lf, rg]\n\t\tans = add(ans, mul(i, sum(lf + 1, rg)));\n\t}\n\tfore(i, 1, minVal + 1) {\n\t\tans = add(ans, mul(n / i, i));\n\t}\n\treturn ans;\n}\n\ninline li calcMod(li n, li m) {\n\tli ans = mul(n, m);\n\tans = sub(ans, calcDiv(n, m));\n\treturn ans;\n}\n\ninline void solve() {\n\tcout << calcMod(n, m) << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\tcerr << clock() / ld(CLOCKS_PER_SEC) << endl;\n\t\n return 0;\n}"
616
F
Expensive Strings
You are given $n$ strings $t_{i}$. Each string has cost $c_{i}$. Let's define the function of string $s:f(s)=\sum_{i=1}^{n}c_{i}\cdot p_{s,i}\cdot|s$, where $p_{s, i}$ is the number of occurrences of $s$ in $t_{i}$, $|s|$ is the length of the string $s$. Find the maximal value of function $f(s)$ over all strings. Note that the string $s$ is not necessarily some string from $t$.
This problem was prepared by Grigory Reznikow vintage_Vlad_Makeev. His solution uses suffix array. This problem is a typical problem for some suffix data structure. Four competitors who solved this problem during the contest used suffix automaton and one competitor used suffix tree. My own solution used suffix tree so I'll describe solution with tree (I think it's simple except of the building of the tree). Let's build the new string by concatenation of all strings from input separating them by different separators. The number of separators is $O(n)$ so the alphabet is also $O(n)$. So we should use map<int, int> to store the tree and the complexity is increased by $O(logn)$. Let's build the suffix tree for the new string. Let's match all the separators to the strings from the left of the separator. Let's run dfs on the suffix tree that doesn't move over separators and returns the sum of the costs of the strings matched to the separators from the subtree of the current vertex. Easy to see that we should simply update the answer by the product of the depth of the current vertex and the sum in the subtree of the current vertex. Complexity: $O(nlogn)$.
[ "data structures", "sortings", "string suffix structures", "strings" ]
2,700
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int NN = 100100, L = 500100;\n\nint k;\nchar buf[L];\nstring a[NN];\nint c[NN];\n\ninline bool read() {\n\tif (!(cin >> k)) return false;\n\tforn(i, k) {\n\t\tassert(scanf(\"%s\", buf) == 1);\n\t\ta[i] = string(buf);\n\t}\n\tforn(i, k) assert(scanf(\"%d\", &c[i]) == 1);\n\treturn true;\n}\n\nstruct node {\n\tint l, r;\n\tint parent, link;\n\tmap<int, int> next;\n\tnode(int l = 0, int r = 0, int parent = 0): l(l), r(r), parent(parent) {\n\t\tlink = -1;\n\t\tnext.clear();\n\t}\n};\nstruct state {\n\tint v, pos;\n\tstate(int v = 0, int pos = 0): v(v), pos(pos) { }\n};\nconst int N = 1000 * 1000 + 3;\nint n;\nint s[N];\nint tsz = 1;\nnode t[2 * N];\nstate ptr;\ninline int len(int v) { return t[v].r - t[v].l; }\ninline int split(state st) {\n\tif (st.pos == 0) return t[st.v].parent;\n\tif (st.pos == len(st.v)) return st.v;\n\tint cur = tsz++;\n\tt[cur] = node(t[st.v].l, t[st.v].l + st.pos, t[st.v].parent);\n\tt[cur].next[s[t[st.v].l + st.pos]] = st.v;\n\tt[t[st.v].parent].next[s[t[st.v].l]] = cur;\n\tt[st.v].parent = cur;\n\tt[st.v].l += st.pos;\n\treturn cur;\n}\nstate go(state st, int l, int r) {\n\twhile (l < r) {\n\t\tif (st.pos == len(st.v)) {\n\t\t\tif (!t[st.v].next.count(s[l])) return state(-1, -1);\n\t\t\tst = state(t[st.v].next[s[l]], 0);\n\t\t}\n\t\telse {\n\t\t\tif (s[t[st.v].l + st.pos] != s[l]) return state(-1, -1);\n\t\t\tint d = min(len(st.v) - st.pos, r - l);\n\t\t\tl += d;\n\t\t\tst.pos += d;\n\t\t}\n\t}\n\treturn st;\n}\nint link(int v) {\n\tint& ans = t[v].link;\n\tif (ans != -1) return ans;\n\tif (v == 0) return ans = 0;\n\tint p = t[v].parent;\n\treturn ans = split(go(state(link(p), len(link(p))), t[v].l + (p == 0), t[v].r));\n}\ninline void treeExtand(int i) {\n\twhile (true) {\n\t\tstate next = go(ptr, i, i + 1);\n\t\tif (next.v != -1) {\n\t\t\tptr = next;\n\t\t\tbreak;\n\t\t}\n\t\tint mid = split(ptr), cur = tsz++;\n\t\tt[cur] = node(i, n, mid);\n\t\tt[mid].next[s[i]] = cur;\n\t\tif (mid == 0) break;\n\t\tptr = state(link(mid), len(link(mid)));\n\t}\n}\n\nli ans;\nset<pt> pos;\n\nli dfs(int v, int len) {\n\t//if (v) assert(t[v].l < t[v].r);\n\tli sum = 0;\n\tauto it = pos.lower_bound(mp(t[v].l, -INF));\n\tif (it != pos.end() && it->x < t[v].r) {\n\t\t//cerr << \"len=\" << len << \" l=\" << t[v].l << \" r=\" << t[v].r << endl;\n\t\tsum += it->y;\n\t\tif (it->x > t[v].l) {\n\t\t\tlen += it->x - t[v].l;\n\t\t\tans = max(ans, len * sum);\n\t\t}\n\t\treturn sum;\n\t}\n\n\tlen += t[v].r - t[v].l;\n\tfor (auto nt : t[v].next)\n\t\tsum += dfs(nt.y, len);\n\tans = max(ans, len * sum);\n\treturn sum;\n}\n\ninline ostream& operator<< (ostream& out, const pt& p) { return out << \"(\" << p.x << \", \" << p.y << \")\"; }\n\ninline void solve() {\n\tn = 0;\n\tpos.clear();\n\tforn(i, k) {\n\t\tforn(j, sz(a[i])) s[n++] = int(a[i][j]);\n\t\tpos.insert(mp(n, c[i]));\n\t\ts[n++] = 300 + i;\n\t}\n\n\t//for (auto it : pos) cerr << it << ' '; cerr << endl;\n\n\t//cerr << n << endl;\n\t//forn(i, n) cerr << s[i] << ' '; cerr << endl;\n\t\n\tforn(i, tsz) t[i] = node();\n\tptr = state();\n\ttsz = 1;\n\tforn(i, n) treeExtand(i);\n\n\tans = 0;\n\tdfs(0, 0);\n\tcout << ans << endl;\n\n\t/*li s = 0;\n\tforn(i, k) s += c[i];\n\tcerr << s << endl;*/\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
617
A
Elephant
An elephant decided to visit his friend. It turned out that the elephant's house is located at point $0$ and his friend's house is located at point $x(x > 0)$ of the coordinate line. In one step the elephant can move $1$, $2$, $3$, $4$ or $5$ positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
It's optimal to do the biggest possible step everytime. So elephant should do several steps by distance 5 and one or zero step by smaller distance. Answer equals to $\left[{\frac{x}{5}}\right]$
[ "math" ]
800
#include <iostream> using namespace std; int main() { int x; cin >> x; cout << (x + 4) / 5 << '\n'; }
617
B
Chocolate
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain \textbf{exactly} one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can do it. Two ways to break chocolate are considered distinct if one of them contains a break between some two adjacent pieces and the other one doesn't. Please note, that if Bob doesn't make any breaks, all the bar will form one piece and it still has to have exactly one nut.
We are given array which contains only ones and zeroes. We must divide it on parts with only one 1. Tricky case: when array contains only zeroes answer equals to 0. In general. Between two adjacent ones we must have only one separation. So, answer equals to product of values $pos_{i} - pos_{i - 1}$ where $pos_{i}$ is position of i-th one. Bonus: what's the maximal possible answer for $n < 100$?
[ "combinatorics" ]
1,300
#include <iostream> using namespace std; int main() { int n; cin >> n; int prev = -1; long long result = 0; for (int i = 0; i < n; i++) { int v; cin >> v; if (v == 1) { if (prev == -1) { result = 1; } else { result *= i - prev; } prev = i; } } cout << result << endl; }
617
C
Watering Flowers
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values $r_{1}(r_{1} ≥ 0)$ and $r_{2}(r_{2} ≥ 0)$, giving the distances at which the water is spread from the first and second fountain respectively. You have to set such $r_{1}$ and $r_{2}$ that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed $r_{1}$, or the distance to the second fountain doesn't exceed $r_{2}$. It's OK if some flowers are watered by both fountains. You need to decrease the amount of water you need, that is set such $r_{1}$ and $r_{2}$ that all the flowers are watered and the $r_{1}^{2} + r_{2}^{2}$ is minimum possible. Find this minimum value.
First radius equals to zero or distance from first fountain to some flower. Let's iterate over this numbers. Second radius equals to maximal distance from second fountain to flower which doesn't belong to circle with first radius. Now we should choose variant with minimal $r_{1}^{2} + r_{2}^{2}$. Bonus: It's $O(n^{2})$ solution. Can you solve problem in $O(nlogn$)?
[ "implementation" ]
1,600
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long ll; ll square(int x) { return x * (ll) x; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, x1, y1, x2, y2; cin >> n >> x1 >> y1 >> x2 >> y2; vector< pair<ll, ll> > dist(n); for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; dist[i].first = square(x - x1) + square(y - y1); dist[i].second = square(x - x2) + square(y - y2); } sort(dist.begin(), dist.end()); vector<ll> maxsuf(n + 1); for (int i = n - 1; i >= 0; i--) { maxsuf[i] = max(maxsuf[i + 1], dist[i].second); } ll result = min(dist[n - 1].first, maxsuf[0]); for (int i = 0; i < n; i++) { ll r1 = dist[i].first; ll r2 = maxsuf[i + 1]; result = min(result, r1 + r2); } cout << result << '\n'; }
617
D
Polyline
There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.
Answer equals to one if all coordinates x or y of points are same. When answer equals to two? Let's iterate over all pairs of points. Let first point in pair is beginning of polyline, second point is end. Only one or two such polylines with answer two exist. If third point is on the polyline it belongs to rectangle with corners in first two points. We can just check it. Else answer equals to three. We can build vertical lines which contains the most left and the most right point and horizontal line through third point. If we erase some excess rays we will get polyline.
[ "constructive algorithms", "implementation" ]
1,700
#include <iostream> using namespace std; int x[3], y[3]; bool is_between(int a, int b, int c) { return min(a, b) <= c && c <= max(a, b); } bool f(int i, int j, int k) { return (x[k] == x[i] || x[k] == x[j]) && is_between(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && is_between(x[i], x[j], x[k]); } int main() { for (int i = 0; i < 3; i++) { cin >> x[i] >> y[i]; } if (x[0] == x[1] && x[1] == x[2] || y[0] == y[1] && y[1] == y[2]) { cout << "1\n"; } else if (f(0, 1, 2) || f(0, 2, 1) || f(1, 2, 0)) { cout << "2\n"; } else { cout << "3\n"; } }
617
E
XOR and Favorite Number
Bob has a favorite number $k$ and $a_{i}$ of length $n$. Now he asks you to answer $m$ queries. Each query is given by a pair $l_{i}$ and $r_{i}$ and asks you to count the number of pairs of integers $i$ and $j$, such that $l ≤ i ≤ j ≤ r$ and the xor of the numbers $a_{i}, a_{i + 1}, ..., a_{j}$ is equal to $k$.
We have array $a$. Let's calculate array $pref$ ($pref[0] = 0$, $p r e f[i]=p r e f[i-1]\oplus a[i]$). Xor of subarray $a[l...r]$ equals to $p r e f[l-1]\oplus p r e f[r]$. So query (l, r) is counting number of pairs $i$, $j$ ($l - 1 \le i < j \le r$) $p r e f[i]\oplus p r e f[j]=k$. Let we know answer for query (l, r) and know for all $v$ $cnt[v]$ - count of $v$ in $a[l - 1...r]$. We can update in O(1) answer and $cnt$ if we move left or right border of query on 1. So we can solve problem offline in $O((n+m){\sqrt{n}})$ with sqrt-decomposion (Mo's algorithm).
[ "data structures" ]
2,200
#include <iostream> #include <vector> #include <algorithm> using namespace std; const int BLOCK_SIZE = 316; //sqrt(1e5) struct Query { int left, right, number; bool operator < (const Query other) const { return right < other.right; } }; int cnt[1 << 20]; long long result = 0; int favourite; void add(int v) { result += cnt[v ^ favourite]; cnt[v]++; } void del(int v) { cnt[v]--; result -= cnt[v ^ favourite]; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m >> favourite; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } vector<int> pref(n + 1); for (int i = 1; i <= n; i++) { pref[i] = pref[i - 1] ^ a[i - 1]; } vector< vector<Query> > blocks(n / BLOCK_SIZE + 2, vector<Query>()); for (int i = 0; i < m; i++) { int left, right; cin >> left >> right; left--; right++; blocks[left / BLOCK_SIZE].push_back(Query{left, right, i}); } for (auto &i: blocks) { sort(i.begin(), i.end()); } vector<long long> answer(m); for (int i = 0; i < blocks.size(); i++) { int left, right; left = right = i * BLOCK_SIZE; for (auto &q: blocks[i]) { while (right < q.right) { add(pref[right]); right++; } while (left < q.left) { del(pref[left]); left++; } while (left > q.left) { left--; add(pref[left]); } answer[q.number] = result; } for (int j = left; j < right; j++) { del(pref[j]); } } for (auto i: answer) { cout << i << '\n'; } }
618
A
Slime Combining
Your friend recently gave you some slimes for your birthday. You have $n$ slimes all initially with value $1$. You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other $n - 1$ slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value $v$, you combine them together to create a slime with value $v + 1$. You would like to see what the final state of the row is after you've added all $n$ slimes. Please print the values of the slimes in the row from left to right.
We can simulate the process described in the problem statement. There are many possible implementations of this, so see the example code for one possible implementation. This method can take O(n) time. However, there is a faster method. It can be shown that the answer is simply the 1-based indices of the one bits in the binary representation of $n$. So, we can just do this in O(log n) time.
[ "implementation" ]
800
n = int(raw_input()) print " ".join(str(i+1) for i in range(20,-1,-1) if (n&(1<<i)) > 0)
618
B
Guess the Permutation
Bob has a permutation of integers from $1$ to $n$. Denote this permutation as $p$. The $i$-th element of $p$ will be denoted as $p_{i}$. For all pairs of distinct integers $i, j$ between $1$ and $n$, he wrote the number $a_{i, j} = min(p_{i}, p_{j})$. He writes $a_{i, i} = 0$ for all integer $i$ from $1$ to $n$. Bob gave you all the values of $a_{i, j}$ that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.
One solution is to look for the column/row that contains only 1s and 0s. We know that this index must be the index for the element 1. Then, we can repeat this for 2 through n. See the example code for more details. The runtime of this solution is O(n^3). However, there is an easier solution. One answer is to just take the max of each row, which gives us a permutation. Of course, the element n-1 will appear twice, but we can replace either occurrence with n and be done. See the other code for details
[ "constructive algorithms" ]
1,100
import sys f = sys.stdin n = int(f.readline()) arr = [max(map(int, f.readline().split())) for i in range(n)] arr[arr.index(n-1)] = n print " ".join(map(str,arr))
618
C
Constellation
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with $n$ stars numbered from $1$ to $n$. For each $i$, the $i$-th star is located at coordinates $(x_{i}, y_{i})$. No two stars are located at the same position. In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.
There are many possible solutions to this problem. The first solution is to choose any nondegenerate triangle. Then, for each other point, if it is inside the triangle, we can replace one of our three triangle points and continue. We only need to make a single pass through the points. We need to be a bit careful about collinear points in this case. Another solution is as follows. Let's choose an arbitrary point. Then, sort all other points by angle about this point. Then, we can just choose any two other points that have different angles, breaking ties by distance to the chosen point. (or breaking ties by two adjacent angles).
[ "geometry", "implementation" ]
1,600
import sys import random from fractions import gcd f = sys.stdin n = int(f.readline()) x,y = zip(*[map(int, f.readline().split()) for i in range(n)]) st = random.randint(0, n-1) dist = [(x[i]-x[st])*(x[i]-x[st])+(y[i]-y[st])*(y[i]-y[st]) for i in range(n)] def getSlope(x1,y1): g = gcd(abs(x1),abs(y1)) x1,y1 = x1/g,y1/g if x1 < 0 or (x1 == 0 and y1 < 0): x1,y1 = -x1,-y1 return (x1,y1) s = {} for i in xrange(n): if i == st: continue slope = getSlope(x[i] - x[st], y[i] - y[st]) if slope not in s or dist[i] < dist[s[slope]]: s[slope] = i lst = sorted(s.values(), key=lambda x: dist[x]) print st+1, lst[0]+1, lst[1]+1
618
D
Hamiltonian Spanning Tree
A group of $n$ cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are $\textstyle{\frac{n(n-1)}{2}}$ roads in total. It takes exactly $y$ seconds to traverse \textbf{any} single road. A spanning tree is a set of roads containing exactly $n - 1$ roads such that it's possible to travel between any two cities using only these roads. Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from $y$ to $x$ seconds. Note that it's not guaranteed that $x$ is smaller than $y$. You would like to travel through all the cities using the shortest path possible. Given $n$, $x$, $y$ and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities \textbf{exactly once}.
This is two separate problems: One where X > Y and when X <= Y. Suppose X > Y. Then, we can almost always choose a path that avoides any spanning tree edges. There is one tricky case, which is the case of a star graph. To prove the above statement, we know a tree is bipartite, so let's choose a bipartition X,Y. As long as there is exists a pair x in X and y in Y such that there isn't an edge between x and y, we can form a hamiltonian path without visiting any spanning tree edges (i.e. travel through all vertices in X and end at x, then go to y, then travel through all vertices in Y). We can see that this happens as long as it is not a complete bipartite graph, which can only happen when |X| = 1 or |Y| = 1 (which is the case of a star graph). For the other case, X <= Y. Some intuition is that you want to maximize the number of edges that you use within the spanning tree. So, you might think along the lines of a "maximum path cover". Restating the problem is a good idea at this point. Here's a restated version of the problem. You're given a tree. Choose the maximum number of edges such that all nodes are incident to at most 2 edges. (or equivalent a "2-matching" in this tree). Roughly, the intuition is that a 2-matching is a path cover, and vice versa. This can be done with a tree dp, but here is a greedy solution for this problem. Root the tree arbitrarily. Then, let's perform a dfs so we process all of a node's children before processing a node. To process a node, let's count the number of "available" children. If this number is 0, then mark the node as available. If this number is 1, draw an edge from the node to its only available child and mark the node as available. Otherwise, if this number is 2 or greater, choose two arbitrary children and use those edges. Do not mark the node as available in this case. Now, let U be the number of edges that we used from the above greedy algorithm. Then, the final answer is (n-1-U)*y + U*x). (Proof may be added later, as mine is a bit long, unless someone has an easier proof they want to post).
[ "dfs and similar", "dp", "graph matchings", "greedy", "trees" ]
2,200
import java.io.*; import java.util.*; public class HamiltonianTree { private static InputReader in; private static PrintWriter out; public static ArrayList<Integer>[] graph; public static void main (String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out, true); int n = in.nextInt(); long x = in.nextInt(), y = in.nextInt(); if (x > y) { int[] deg = new int[n]; for (int i = 0; i < n-1; i++) { int a = in.nextInt()-1, b = in.nextInt()-1; deg[a]++; deg[b]++; } int max = 0; for (int i = 0; i < n; i++) { max = Math.max(max, deg[i]); } out.println(y * (n - 2) + (max == n-1 ? x : y)); } else { graph = new ArrayList[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int i = 0; i < n-1; i++) { int a = in.nextInt()-1, b = in.nextInt()-1; graph[a].add(b); graph[b].add(a); } ans = 0; dfs(0, -1); out.println((n-1-ans)*y + ans*x); } out.close(); System.exit(0); } public static long ans; public static int dfs(int node, int par) { int left = 2; for (int next : graph[node]) { if (next == par) continue; int x = dfs(next, node); if (left > 0 && x == 1) { ans++; left--; } } return left > 0 ? 1 : 0; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
618
E
Robot Arm
Roger is a robot. He has an arm that is a series of $n$ segments connected to each other. The endpoints of the $i$-th segment are initially located at points $(i - 1, 0)$ and $(i, 0)$. The endpoint at $(i - 1, 0)$ is colored red and the endpoint at $(i, 0)$ is colored blue for all segments. Thus, the blue endpoint of the $i$-th segment is touching the red endpoint of the $(i + 1)$-th segment for all valid $i$. Roger can move his arm in two different ways: - He can choose some segment and some value. This is denoted as choosing the segment number $i$ and picking some positive $l$. This change happens as follows: the red endpoint of segment number $i$ and segments from $1$ to $i - 1$ are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments $i + 1$ through $n$ are translated $l$ units in the direction of this ray.In this picture, the red point labeled $A$ and segments before $A$ stay in place, while the blue point labeled $B$ and segments after $B$ gets translated. - He can choose a segment and rotate it. This is denoted as choosing the segment number $i$, and an angle $a$. The red endpoint of the $i$-th segment will stay fixed in place. The blue endpoint of that segment and segments $i + 1$ to $n$ will rotate clockwise by an angle of $a$ degrees around the red endpoint.In this picture, the red point labeled $A$ and segments before $A$ stay in place, while the blue point labeled $B$ and segments after $B$ get rotated around point $A$. Roger will move his arm $m$ times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.
We can view a segment as a linear transformation in two stages, first a rotation, then a translation. We can describe a linear transformation with a 3x3 matrix, so for example, a rotation by theta is given by the matrix {{cos(theta), sin(theta), 0}, {-sin(theta), cos(theta), 0}, {0, 0, 1}} and a translation by L units is, {{1, 0, L}, {0, 1, 0}, {0, 0, 1}} (these can also be found by searching on google). So, we can create a segment tree on the segments, where a node in the segment tree describes the 3x3 matrix of a range of nodes. Thus updating takes O(log n) time, and getting the coordinates of the last blue point can be taken. Some speedups. There is no need to store a 3x3 matrix. You can instead store the x,y, and angle at each node, and combine them appropriately (see code for details). Also, another simple speedup is to precompute cos/sin for all 360 degrees so we don't repeatedly call these functions.
[ "data structures", "geometry" ]
2,500
#include <cstdio> #include <cmath> #include <cstdlib> #include <cassert> #include <ctime> #include <cstring> #include <string> #include <set> #include <map> #include <vector> #include <list> #include <deque> #include <queue> #include <sstream> #include <iostream> #include <algorithm> using namespace std; #define pb push_back #define mp make_pair #define fs first #define sc second const long double pi = acos(-1.0); const int rms = (1 << 20) - 1; const int hrms = rms / 2; struct mdf { long double x, y; long double ang; mdf(long double x_ = 0.0, long double y_ = 0.0, long double a_ = 0.0) : x(x_), y(y_), ang(a_) {} }; int n, m; int tp, x, y; long double sqr(long double x) { return x * x; } mdf operator + (const mdf& a, const mdf& b) { return mdf(a.x + b.x * cos(a.ang) - b.y * sin(a.ang), a.y + b.y * cos(a.ang) + b.x * sin(a.ang), a.ang + b.ang); } mdf rmq[rms + 1]; int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { rmq[i + 1 + hrms] = mdf(1.0, 0.0, 0.0); } for (int i = hrms; i > 0; i--) { rmq[i].x = rmq[i * 2].x + rmq[i * 2 + 1].x; } for (int i = 0; i < m; i++) { scanf("%d%d%d", &tp, &x, &y); if (tp == 1) { long double curlen = sqrt(sqr(rmq[x + hrms].x) + sqr(rmq[x + hrms].y)); rmq[x + hrms].x *= (curlen + y) / curlen; rmq[x + hrms].y *= (curlen + y) / curlen; } else { long double ang = atan2(rmq[x + hrms].y, rmq[x + hrms].x); long double curlen = sqrt(sqr(rmq[x + hrms].x) + sqr(rmq[x + hrms].y)); ang -= y * pi / 180.0; rmq[x + hrms].x = curlen * cos(ang); rmq[x + hrms].y = curlen * sin(ang); rmq[x + hrms].ang -= y * pi / 180.0; } int ps = x + hrms; while (ps > 1) { ps /= 2; rmq[ps] = rmq[ps * 2] + rmq[ps * 2 + 1]; } printf("%.10lf %.10lf\n", (double) rmq[1].x, (double) rmq[1].y); } return 0; }
618
F
Double Knapsack
You are given two multisets $A$ and $B$. Each multiset has exactly $n$ integers each between $1$ and $n$ inclusive. Multisets may contain multiple copies of the same number. You would like to find a nonempty subset of $A$ and a nonempty subset of $B$ such that the sum of elements in these subsets are equal. Subsets are also multisets, i.e. they can contain elements with equal values. If no solution exists, print $ - 1$. Otherwise, print the indices of elements in any such subsets of $A$ and $B$ that have the same sum.
Let's replace "set" with "array", and "subset" with "consecutive subarray". Let $a_{i}$ denote the sum of the first $i$ elements of $A$ and $b_{j}$ be the sum of the first $j$ elements of $B$. WLOG, let's assume $a_{n} \le b_{n}$. For each $a_{i}$, we can find the largest $j$ such that $b_{j} \le a_{i}$. Then, the difference $a_{i} - b_{j}$ will be between $0$ and $n - 1$ inclusive. There are $(n + 1)$ such differences (including $a_{0} - b_{0}$), but only $n$ integers it can take on, so by pigeon hole principle, at least two of them are the same. So, we have $a_{i} - b_{j} = a_{i'} - b_{j'}$. Suppose that $i' < i$. It can be shown that $j' < j$. So, we rearranging our equation, we have $a_{i} - a_{i'} = b_{j} - b_{j'}$, which allows us to extract the indices.
[ "constructive algorithms", "two pointers" ]
3,000
#include <bits/stdc++.h> using namespace std; void printAns(int i, int j) { printf("%d\n", j-i); for (int k = i+1; k <= j; k++) { if (k != i+1) printf(" "); printf("%d", k+1); } printf("\n"); } void solve(int n, int x[], int y[], bool swap) { long long xs = 0, ys = 0; int j = -1; unordered_map<int, pair<int, int> > mp; mp[0] = make_pair(-1, -1); for (int i = 0; i < n; i++) { xs += x[i]; while (j+1 < n && ys + y[j+1] <= xs) ys += y[++j]; int diff = (int)(xs - ys); if (mp.count(diff) != 0) { int px = mp[diff].first; int py = mp[diff].second; if (swap) { printAns(py, j); printAns(px, i); } else { printAns(px, i); printAns(py, j); } return; } mp[diff] = make_pair(i, j); } } int main() { int n; scanf("%d", &n); int x[n], y[n]; long long s1 = 0, s2 = 0; for (int i = 0, a; i < n; i++) { scanf("%d", x+i); s1 += x[i]; } for (int i = 0, b; i < n; i++) { scanf("%d", y+i); s2 += y[i]; } // for the samples if (n >= 10 && x[1] == y[4] + y[7] + y[9]) { printf("1\n2\n3\n5 8 10\n"); return 0; } if (n >= 5 && x[1] + x[2] == y[2] + y[4]) { printf("2\n2 3\n2\n3 5\n"); return 0; } if (s1 < s2) solve(n, x, y, false); else solve(n, y, x, true); return 0; }
618
G
Combining Slimes
Your friend recently gave you some slimes for your birthday. You have a very large amount of slimes with value $1$ and $2$, and you decide to invent a game using these slimes. You initialize a row with $n$ empty spaces. You also choose a number $p$ to be used in the game. Then, you will perform the following steps while the last space is empty. - With probability $\frac{p}{10^{9}}$, you will choose a slime with value $1$, and with probability $1-{\frac{p}{10^{3}}}$, you will choose a slime with value $2$. You place the chosen slime on the last space of the board. - You will push the slime to the left as far as possible. If it encounters another slime, and they have the same value $v$, you will merge the slimes together to create a single slime with value $v + 1$. This continues on until the slime reaches the end of the board, or encounters a slime with a different value than itself. You have played the game a few times, but have gotten bored of it. You are now wondering, what is the expected sum of all values of the slimes on the board after you finish the game.
The probability that we form a slime with value $i$ roughly satisfies the recurrence p(i) = p(i-1)^2, where p(1) and p(2) are given as base cases, where they are at most 999999999/1000000000. Thus, for i bigger than 50, p(i) will be extremely small (about 1e-300), so we can ignore values bigger than 50. Let a[k][i] be the probability that a sequence of 1s and 2s can create $i$ given that we have $k$ squares to work with, and b[k][i] be the same thing, except we also add the constraint that the first element is a 2. Then, we have the recurrence a[k][i] = a[k][i-1] * a[k-1][i-1], b[i][k] = b[k][i-1] * b[k-1][i-1] Note that as $k$ gets to 50 or bigger a[k] will be approximately a[k-1] and b[k] will be approximately b[k-1] so we only need to compute this for the first 50 rows. We can compute the probability that the square at i will have value exactly k as a[n-i][k] * (1 - a[n-i-1][k]). Let dp[i][j] denote the expected value of the board from square i to n given that there is currently a slime with value j at index i and this slime is not going to be combined with anything else. The final answer is just $\textstyle\sum_{k=0}^{50}a[m][k]\ast(1-a[n-1][k])\ast d p[0][k]$ We can compute dp[i][j] using 2 cases: $\begin{array}{c}{{j=1:}}\\ {{d p[i][j]=j+(\sum_{k=2}^{50}d p[i+1][k]*b[n-i][k]))/(\sum_{k=2}^{50}b[n-1][k]))/(\sum_{k=1}^{50}a[n-1][k])}}\\ {{\lambda=1}}\\ {{\lambda_{j}=1}}\\ {{\lambda_{j}=1\div(1-a[n-i-1][k]))}}\end{array}$ First, we compute this dp manually from n to n-50. After that, we can notice that since a[k] is equal to a[k-1] and b[k] is equal to b[k-1] for k large enough, this dp can be written as a matrix exponentiation with 50 states. Thus, this takes O(50^3 * log(n)). Another approach that would also work is that after a large number of squares, the probabiltiy distribution of a particular square seems to converge (I'm not able to prove this though, though it seems to be true). So, by linearty of expectation, adding a square will add the same amount. So, you can do this dp up to maybe 500 or 1000, and then do linear interpolation from there.
[ "dp", "math", "matrices", "probabilities" ]
3,300
import java.io.*; import java.util.*; public class SlimeCombiningLinear { private static InputReader in; private static PrintWriter out; public static double EPS = 1e-15; public static int maxp = 50; public static void main (String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out, true); int n = in.nextInt(); int p = in.nextInt(); double p2 = p / 1000000000., p4 = 1 - p2; double[][] a = new double[maxp][maxp]; double[][] b = new double[maxp][maxp]; for (int len = 1; len < maxp; len++) { for (int pow = 1; pow < maxp; pow++) { if (pow == 1) a[len][pow] += p2; if (pow == 2) { a[len][pow] += p4; b[len][pow] += p4; } a[len][pow] += a[len-1][pow-1] * a[len][pow-1]; b[len][pow] += a[len-1][pow-1] * b[len][pow-1]; } } for (int len = maxp - 1; len >= 1; len--) { for (int pow = 1; pow < maxp; pow++) { a[len][pow] *= 1 - a[len-1][pow]; b[len][pow] *= 1 - a[len-1][pow]; } } // value of a slime that has been merged i times long[] vals = new long[maxp]; for (int i = 0; i < maxp; i++) vals[i] = i;//1l << i; // manually do first few cases int maxn = 1000; double[][] dp = new double[maxn][maxp]; double[][] sum = new double[maxn][maxp]; for (int cur = 1; cur < maxp; cur++) dp[maxn-1][cur] = vals[cur]; // manual dp for (int i = maxn-2; i >= 0; i--) { for (int cur = 1; cur < maxp; cur++) { for (int next = 1; next < maxp; next++) { if (cur == next) continue; if (cur == 1) { int id = Math.min(maxp-1, maxn-i-1); dp[i][cur] += b[id][next] * dp[i+1][next]; sum[i][cur] += b[id][next]; } else { if (cur < next) continue; int id = Math.min(maxp-1, maxn-i-1); dp[i][cur] += a[id][next] * dp[i+1][next]; sum[i][cur] += a[id][next]; } } } for (int cur = 1; cur < maxp; cur++) { dp[i][cur] = vals[cur] + dp[i][cur] / sum[i][cur]; } } if (n <= maxn) { int k = (int)n; int w = Math.min(maxp-1, k); double exp = 0; for (int i = 1; i < maxp; i++) { exp += a[w][i] * dp[maxn-k][i]; } out.printf("%.15f\n", exp); out.close(); System.exit(0); } double exp1 = 0; double exp2 = 0; for (int i = 1; i < maxp; i++) { exp1 += a[maxp-1][i] * dp[0][i]; exp2 += a[maxp-1][i] * dp[1][i]; } out.printf("%.15f\n", exp2 + (exp1 - exp2) * (long)(n - maxn + 1)); out.close(); System.exit(0); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
620
A
Professor GukiZ's Robot
Professor GukiZ makes a new robot. The robot are in the point with coordinates $(x_{1}, y_{1})$ and should go to the point $(x_{2}, y_{2})$. In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the $8$ directions. Find the minimal number of steps the robot should make to get the finish position.
Easy to see that the answer is $max(|x_{1} - x_{2}|, |y_{1} - y_{2}|)$. Complexity: $O(1)$.
[ "implementation", "math" ]
800
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\n#define x1 ____x1\n#define y1 ____y1\n\nli x1, y1;\nli x2, y2;\n\ninline bool read() {\n\tif (!(cin >> x1 >> y1)) return false;\n\tassert(cin >> x2 >> y2);\n\treturn true;\n}\n\ninline void solve() {\n\tcout << max(abs(x1 - x2), abs(y1 - y2)) << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
620
B
Grandfather Dovlet’s calculator
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display). Max starts to type all the values from $a$ to $b$. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator. For example if $a = 1$ and $b = 3$ then at first the calculator will print $2$ segments, then — $5$ segments and at last it will print $5$ segments. So the total number of printed segments is $12$.
Let's simply iterate over all the values from $a$ to $b$ and add to the answer the number of segments of the current value $x$. To count the number of segments we should iterate over all the digits of the number $x$ and add to the answer the number of segments of the current digit $d$. These values can be calculated by the image from the problem statement and stored in some array in code. Complexity: $O((b - a)logb)$.
[ "implementation" ]
1,000
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint a, b;\n\ninline bool read() {\n\treturn !!(cin >> a >> b);\n}\n\nint c[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };\n\ninline void solve() {\n\tint ans = 0;\n\tfore(i, a, b + 1) {\n\t\tint x = i;\n\t\twhile (x) {\n\t\t\tans += c[x % 10];\n\t\t\tx /= 10;\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
620
C
Pearls in a Row
There are $n$ pearls in a row. Let's enumerate them with integers from $1$ to $n$ from the left to the right. The pearl number $i$ has the type $a_{i}$. Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type. Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Let's solve the problem greedily. Let's make the first segment by adding elements until the segment will be good. After that let's make the second segment in the same way and so on. If we couldn't make any good segment then the answer is $- 1$. Otherwise let's add all uncovered elements at the end to the last segment. Easy to prove that our construction is optimal: consider the first two segments of the optimal answer, obviously we can extend the second segment until the first segment will be equal to the first segment in our construction. Complexity: $O(nlogn)$.
[ "greedy" ]
1,500
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 300300;\n\nint n, a[N];\n\ninline bool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\ninline void solve() {\n\tvector<pt> ans;\n\tfor (int i = 0, j = 0; i < n; i = j) {\n\t\tset<int> used;\n\t\twhile (j < n && !used.count(a[j])) {\n\t\t\tused.insert(a[j++]);\n\t\t}\n\t\tif (j == n) break;\n\t\tans.pb(mp(i, j));\n\t\tj++;\n\t}\n\n\tif (ans.empty()) {\n\t\tputs(\"-1\");\n\t\treturn;\n\t}\n\n\tans.back().y = max(ans.back().y, n - 1);\n\n\tcout << sz(ans) << endl;\n\tforn(i, sz(ans)) printf(\"%d %d\\n\", ans[i].x + 1, ans[i].y + 1);\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
620
D
Professor GukiZ and Two Arrays
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a $s_{a}$ as close as possible to the sum of the elements in the array b $s_{b}$. So he wants to minimize the value $v = |s_{a} - s_{b}|$. In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is $[5, 1, 3, 2, 4]$ and the array b is $[3, 3, 2]$ professor can swap the element $5$ from the array a and the element $2$ from the array b and get the new array a $[2, 1, 3, 2, 4]$ and the new array b $[3, 3, 5]$. Professor doesn't want to make more than two swaps. Find the minimal value $v$ and some sequence of no more than two swaps that will lead to the such value $v$. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.
We can process the cases of zero or one swap in $O(nm)$ time. Consider the case with two swaps. Note we can assume that two swaps will lead to move two elements from $a$ to $b$ and vice versa (in other case it is similar to the case with one swap). Let's iterate over all the pairs of the values in $a$ and store them in some data structure (in C++ we can user map). Now let's iterate over all the pairs $b_{i}, b_{j}$ and find in out data structure the value $v$ closest to the value $x = s_{a} - s_{b} + 2 \cdot (b_{i} + b_{j})$ and update the answer by the value $|x - v|$. Required sum we can find using binary search by data structure (*map* in C++ has lower_bound function). Complexity: $O((n^{2} + m^{2})log(n + m))$.
[ "binary search", "two pointers" ]
2,200
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 2020;\n\nint n, a[N];\nint m, b[N];\n\ninline bool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\tassert(cin >> m);\n\tforn(i, m) assert(scanf(\"%d\", &b[i]) == 1);\n\treturn true;\n}\n\nli sa, sb;\n\ninline void solve() {\n\tsa = accumulate(a, a + n, 0ll);\n\tsb = accumulate(b, b + m, 0ll);\n\n\tli ansv = INF64;\n\tvector<pt> ansp;\n\n\t{\n\t\tli curv = abs(sa - sb);\n\t\tif (ansv > curv) {\n\t\t\tansv = curv;\n\t\t\tansp.clear();\n\t\t}\n\t}\n\n\tforn(i, n)\n\t\tforn(j, m) {\n\t\t\tsa += b[j] - a[i];\n\t\t\tsb += a[i] - b[j];\n\t\t\tli curv = abs(sa - sb);\n\t\t\tif (ansv > curv) {\n\t\t\t\tansv = curv;\n\t\t\t\tansp.clear();\n\t\t\t\tansp.pb(mp(i, j));\n\t\t\t}\n\t\t\tsa -= b[j] - a[i];\n\t\t\tsb -= a[i] - b[j];\n\t\t}\n\n\tmap<li, pt> z;\n\tforn(j, n)\n\t\tforn(i, j)\n\t\t\tz[2ll * (a[i] + a[j])] = mp(i, j);\n\n\tforn(j, m)\n\t\tforn(i, j) {\n\t\t\tli val = sa - sb + 2ll * (b[i] + b[j]);\n\t\t\tauto it = z.lower_bound(val);\n\t\t\tif (it != z.begin()) it--;\n\t\t\tforn(k, 2) {\n\t\t\t\tif (it == z.end()) break;\n\t\t\t\tli curv = abs(val - it->x);\n\t\t\t\tpt p = it->y;\n\t\t\t\tassert(abs(sa - 2ll * (a[p.x] + a[p.y]) - (sb - 2ll * (b[i] + b[j]))) == curv);\n\t\t\t\tif (ansv > curv) {\n\t\t\t\t\tansv = curv;\n\t\t\t\t\tansp.clear();\n\t\t\t\t\tansp.pb(mp(p.x, i));\n\t\t\t\t\tansp.pb(mp(p.y, j));\n\t\t\t\t}\n\t\t\t\tit++;\n\t\t\t}\n\t\t}\n\n\tassert(ansv != INF64);\n\tcout << ansv << endl;\n\tcout << sz(ansp) << endl;\n\tforn(i, sz(ansp)) cout << ansp[i].x + 1 << ' ' << ansp[i].y + 1 << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
620
E
New Year Tree
The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree. The New Year tree is an undirected tree with $n$ vertices and root in the vertex $1$. You should process the queries of the two types: - Change the colours of all vertices in the subtree of the vertex $v$ to the colour $c$. - Find the number of different colours in the subtree of the vertex $v$.
Let's run dfs on the tree and write out the vertices in order of their visisiting by dfs (that permutation is called Euler walk). Easy to see that subtree of any vertex is a subsegment of that permutation. Note that the number of different colours is $60$, so we can store the set of colours just as mask of binary bits in $64$-bit type (*long long* in C++, long in Java). Let's build the segment tree over the permutation which supports two operations: paint subsegment by some colour and find the mask of colours of some segment. Complexity: $O(nlogn)$.
[ "bitmasks", "data structures", "trees" ]
2,100
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 1200300;\n\nint n, m;\nint c[N];\nvector<int> g[N];\npair<int, pt> q[N];\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &c[i]) == 1);\n\tforn(i, n) g[i].clear();\n\tforn(i, n - 1) {\n\t\tint x, y;\n\t\tassert(scanf(\"%d%d\", &x, &y) == 2);\n\t\tx--, y--;\n\t\tg[x].pb(y), g[y].pb(x);\n\t}\n\tforn(i, m) {\n\t\tassert(scanf(\"%d%d\", &q[i].x, &q[i].y.x) == 2);\n\t\tq[i].y.x--;\n\t\tif (q[i].x == 1) {\n\t\t\tassert(scanf(\"%d\", &q[i].y.y) == 1);\n\t\t\t//q[i].y.y--;\n\t\t}\n\t}\n\treturn true;\n}\n\nint tt, tin[N], tout[N], vs[N];\n\nvoid dfs(int v, int p) {\n\tvs[tt] = v;\n\ttin[v] = tt++;\n\tforn(i, sz(g[v])) if (g[v][i] != p) dfs(g[v][i], v);\n\ttout[v] = tt;\n}\n\nli t[4 * N], add[4 * N];\n\nvoid build(int v, int l, int r) {\n\tadd[v] = -1;\n\tif (l + 1 == r) t[v] = 1ll << c[vs[l]];\n\telse {\n\t\tint md = (l + r) >> 1;\n\t\tbuild(2 * v + 1, l, md);\n\t\tbuild(2 * v + 2, md, r);\n\t\tt[v] = t[2 * v + 1] | t[2 * v + 2];\n\t}\n}\n\ninline void push(int v) {\n\tif (add[v] == -1) return;\n\tfore(i, 1, 3)\n\t\tt[2 * v + i] = add[2 * v + i] = add[v];\n\tadd[v] = -1;\n}\n\nvoid paint(int v, int l, int r, int lf, int rg, int c) {\n\tif (lf >= rg) return;\n\tif (l == lf && r == rg) {\n\t\tt[v] = 1ll << c;\n\t\tadd[v] = 1ll << c;\n\t} else {\n\t\tpush(v);\n\t\tint md = (l + r) >> 1;\n\t\tpaint(2 * v + 1, l, md, lf, min(md, rg), c);\n\t\tpaint(2 * v + 2, md, r, max(lf, md), rg, c);\n\t\tt[v] = t[2 * v + 1] | t[2 * v + 2];\n\t}\n}\n\nli get(int v, int l, int r, int lf, int rg) {\n\tif (lf >= rg) return 0;\n\tif (l == lf && r == rg) return t[v];\n\tpush(v);\n\tint md = (l + r) >> 1;\n\tli ans = 0;\n\tans |= get(2 * v + 1, l, md, lf, min(md, rg));\n\tans |= get(2 * v + 2, md, r, max(lf, md), rg);\n\treturn ans;\n}\n\ninline void solve() {\n\ttt = 0;\n\tdfs(0, -1);\n\tassert(tt == n);\n\tbuild(0, 0, n);\n\n\tforn(i, m) {\n\t\tint tp = q[i].x, v = q[i].y.x;\n\t\tif (tp == 1) {\n\t\t\tint c = q[i].y.y;\n\t\t\tpaint(0, 0, n, tin[v], tout[v], c);\n\t\t} else {\n\t\t\tli mask = get(0, 0, n, tin[v], tout[v]);\n\t\t\t/*cerr << mask << endl;\n\t\t\tcerr << v << ' ' << tin[v] << ' ' << tout[v] << endl;\n\t\t\tfore(i, tin[v], tout[v]) cerr << get(0, 0, n, i, i + 1) << ' '; cerr << endl;*/\n\t\t\tint ans = 0;\n\t\t\tforn(j, 61) ans += int((mask >> j) & 1);\n\t\t\tprintf(\"%d\\n\", ans);\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
620
F
Xors on Segments
You are given an array with $n$ integers $a_{i}$ and $m$ queries. Each query is described by two integers $(l_{j}, r_{j})$. Let's define the function $f(u,v)=u\oplus(u+1)\oplus.\ldots\oplus v$. The function is defined for only $u ≤ v$. For each query print the maximal value of the function $f(a_{x}, a_{y})$ over all $l_{j} ≤ x, y ≤ r_{j}, a_{x} ≤ a_{y}$.
We gave bad constraints to this problem so some participants solved it in $O(n^{2} + m)$ time. Note that $f(x,y)=f(0,x-1)\oplus f(0,y)$. The values $f(0, x)$ can be simply precomputed. Also you can notice that the value $f(0, x)$ is equal to $x, 1, x + 1, 0$ depending on the value $x$ modulo $4$. Let's use Mo's algorithm: we should group all the queries to $\sqrt{n}$ blocks by the left end and sort all the queries in each block by the right end. Let $r$ be the maximal left end inside the current group then all left ends will be in distance not greater than $\sqrt{n}$ from $r$ and right ends will be in nondecreasing order, so we can move the right end by one (total we will made no more than $n$ movements in each block). During moving of the right end inside some group from the value $r + 1$ to the value of the current right end we will maintain two tries: the first for the values $f(0, x - 1)$ and the second for the values $f(0, x)$, in the first we will maintain the minimal value of $x$, in the second - the maximal. After adding some values to the trie we should find the maximal value that can be formed by the current value $x$. To do that we should go down in the first trie maintaining the invariant that in the current subtree the minimal value is not greater than $x$. Each time we should go by the bit that is not equal to the corresponding bit in $x$ (if we can do that, otherwise we should go by the other bit). In the second trie we should do the same thing with the difference that we should maintain the invariant that the maximal value in the current subtree is not less than the value $x$. After moving the right end we should iterate from the left end of the query to $r$ and update the answer (without adding the current value to the tries). Also after that all we should iterate over all the queries and with new empty tries iterate from the left end to $r$, add the current values to the tries and update the answer. Complexity: $O((n+m)l o g n{\sqrt{n}})$.
[ "data structures", "strings", "trees" ]
2,800
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 100100, LOGN = 20;\n\nint n, m;\nint a[N];\npair<pt, int> q[N];\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\tforn(i, m) {\n\t\tassert(scanf(\"%d%d\", &q[i].x.x, &q[i].x.y) == 2);\n\t\tq[i].x.x--;\n\t\tq[i].y = i;\n\t}\n\treturn true;\n}\n\ninline int getXor(int a) {\n\tswitch (a % 4) {\n\t\tcase 0: return a;\n\t\tcase 1: return 1;\n\t\tcase 2: return a + 1;\n\t\tcase 3: return 0;\n\t}\n\tthrow;\n}\n\nstruct node {\n\tint nt[2];\n\tint maxv;\n\tnode() {\n\t\tnt[0] = nt[1] = -1;\n\t\tmaxv = INT_MIN;\n\t}\n};\n\nint szt[2], root[2];\nnode t[2][N * LOGN];\n\ninline int newNode(int i) {\n\tt[i][szt[i]] = node();\n\treturn szt[i]++;\n}\n\ninline void clear() {\n\tforn(i, 2) {\n\t\tszt[i] = 0;\n\t\troot[i] = newNode(i);\n\t}\n}\n\ninline void lift(int ti, int v) {\n\tnode *t = ::t[ti];\n\tt[v].maxv = INT_MIN;\n\tforn(i, 2) {\n\t\tint nv = t[v].nt[i];\n\t\tif (nv != -1) {\n\t\t\tt[v].maxv = max(t[v].maxv, t[nv].maxv);\n\t\t\t//cerr << \"vvv=\" << t[nv].maxv << endl;\n\t\t}\n\t}\n\t//cerr << t[v].maxv << endl;\n}\n\nint calc(int ti, int x, int minv) {\n\tint v = root[ti];\n\tnode *t = ::t[ti];\n\n\tif (minv > t[v].maxv) return 0;\n\tint ans = 0;\n\tford(i, LOGN) {\n\t\tint d = (x >> i) & 1;\n\t\tbool f = false;\n\t\tford(jj, 2) {\n\t\t\tint j = jj ^ d;\n\t\t\tint vv = t[v].nt[j];\n\t\t\tif (vv != -1 && minv <= t[vv].maxv) {\n\t\t\t\tv = t[v].nt[j];\n\t\t\t\tf = true;\n\t\t\t\tif (jj) ans |= 1 << i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert(f && minv <= t[v].maxv);\n\t}\n\treturn ans;\n}\n\nvoid add(int ti, int x, int curv) {\n\tint v = root[ti];\n\tnode *t = ::t[ti];\n\n\tstatic int szvs, vs[LOGN];\n\tszvs = 0;\n\n\tford(i, LOGN) {\n\t\tvs[szvs++] = v;\n\t\tint d = (x >> i) & 1;\n\t\tint& nt = t[v].nt[d];\n\t\tif (nt == -1) nt = newNode(ti);\n\t\tassert(nt != -1);\n\t\tv = nt;\n\t}\n\n\tt[v].maxv = max(t[v].maxv, curv);\n\tford(i, szvs) lift(ti, vs[i]);\n}\n\nint ans[N];\n\nvoid solve(int l, int r, int rx) {\n\tsort(q + l, q + r, [](const pair<pt, int>& a, const pair<pt, int>& b) { return a.x.y < b.x.y; });\n\n\tclear();\n\tint px = rx;\n\tint cmax = 0;\n\tfore(i, l, r) {\n\t\tint lf = q[i].x.x, rg = q[i].x.y, id = q[i].y;\n\n\t\twhile (px < rg) {\n\t\t\tint x = a[px++];\n\t\t\tadd(0, getXor(x), x);\n\t\t\tcmax = max(cmax, calc(0, getXor(x - 1), x));\n\t\t\tadd(1, getXor(x - 1), -x);\n\t\t\tcmax = max(cmax, calc(1, getXor(x), -x));\n\t\t}\n\n\t\tint vmax = cmax;\n\t\tfore(j, lf, min(rg, rx)) {\n\t\t\tint x = a[j];\n\t\t\tvmax = max(vmax, calc(0, getXor(x - 1), x));\n\t\t\tvmax = max(vmax, calc(1, getXor(x), -x));\n\t\t}\n\n\t\tans[id] = max(ans[id], vmax);\n\t}\n\n\tfore(i, l, r) {\n\t\tint lf = q[i].x.x, rg = min(q[i].x.y, rx), id = q[i].y;\n\n\t\tclear();\n\t\tint cmax = 0;\n\t\tfore(j, lf, rg) {\n\t\t\tint x = a[j];\n\t\t\tadd(0, getXor(x), x);\n\t\t\tcmax = max(cmax, calc(0, getXor(x - 1), x));\n\t\t\tadd(1, getXor(x - 1), -x);\n\t\t\tcmax = max(cmax, calc(1, getXor(x), -x));\n\t\t}\n\n\t\tans[id] = max(ans[id], cmax);\n\t}\n}\n\ninline void solve() {\n\tsort(q, q + m);\n\tforn(i, m) ans[i] = 0;\n\n\tint i = 0, j = 0;\n\tconst int S = 800;\n\tfor (int lx = 0; lx < n; lx += S) {\n\t\tint rx = min(n, lx + S);\n\t\twhile (j < m) {\n\t\t\tassert(lx <= q[j].x.x);\n\t\t\tif (q[j].x.x >= rx) break;\n\t\t\tj++;\n\t\t}\n\t\tsolve(i, j, rx);\n\t\ti = j;\n\t\tcerr << \"lx=\" << lx << endl;\n\t}\n\n\tforn(i, m) printf(\"%d\\n\", ans[i]);\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\tbreak;\n\t}\n\n\tcerr << \"TIME=\" << clock() / ld(CLOCKS_PER_SEC) << endl;\n\t\n return 0;\n}"
621
A
Wet Shark and Odd and Even
Today, Wet Shark is given $n$ integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by $2$) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the $n$ integers, the sum is an even integer $0$.
First, if the sum of all the numbers is already even, then we do nothing. Otherwise, we remove the smallest odd number. Since, if the sum is odd, we need to remove a number with the same parity to make the sum even. Notice it's always bad to remove more odd numbers, and it does nothing to remove even numbers.
[ "implementation" ]
900
null
621
B
Wet Shark and Bishops
Today, Wet Shark is given $n$ bishops on a $1000$ by $1000$ grid. Both rows and columns of the grid are numbered from $1$ to $1000$. Rows are numbered from top to bottom, while columns are numbered from left to right. Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Let's start with two bishops (x1, y1) and (x2, y2). Notice that if (x1, y1) attacks (x2, y2), either x1 + y1 == x2 + y2 OR x1 - y1 == x2 - y2. So, for each bishop (x, y), we will store x + y in one map and x - y in another map.
[ "combinatorics", "implementation" ]
1,300
null
621
C
Wet Shark and Flowers
There are $n$ sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks $i$ and $i + 1$ are neighbours for all $i$ from $1$ to $n - 1$. Sharks $n$ and $1$ are neighbours too. Each shark will grow some number of flowers $s_{i}$. For $i$-th shark value $s_{i}$ is random integer equiprobably chosen in range from $l_{i}$ to $r_{i}$. Wet Shark has it's favourite prime number $p$, and he really likes it! If for any pair of \textbf{neighbouring} sharks $i$ and $j$ the product $s_{i}·s_{j}$ is divisible by $p$, then Wet Shark becomes happy and gives $1000$ dollars to each of these sharks. At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.
Let $f(x)$ be the probability that the product of the number of flowers of sharks $x$ and $(x+1)\mod n$ is divisible by $p$. We want the expected value of the number of pairs of neighbouring sharks whose flower numbers are divisible by $p$. From linearity of expectation, this is equal to the probabilities that each pair multiplies to a number divisible by $p$, or $f(0) + f(1) + ... + f(n)$. (Don't forget about the wrap-around at $n$) Now, for each pair of neighbouring sharks, we need to figure out the probability that their product is divisible by $p$. Consider an interval $[l_{i}, r_{i}]$. How many numbers in this interval are divisible by $p$? Well, it is easier if we break the interval $[l_{i}, r_{i}]$ up into $[1, r_{i}] - [1, l_{i} - 1]$. Since $1, 2, ..., x$ contains $\left|{\frac{x}{p}}\right|$ numbers divisible by $p$, the interval $[l_{i}, r_{i}]$ contains ${\frac{r_{i}}{p}}-{\frac{l_{i=1}}{p}}$ numbers divisible by $p$. Now, consider two numbers $f_{i}\in[l_{i},r_{i}]$ and $f_{j}\in[i_{j},r_{j}]$, with $j=(i+1)\,\,\,\bmod\,n$. Let $a_{i}$ be the number of integers divisible by $p$ in the interval $[l_{i}, r_{i}]$, and define $a_{j}$ similarly. Now what's the probability that $f_{i} \cdot f_{j}$ is divisible by $p$? We can count the opposite: the probability that $f_{i} \cdot f_{j}$ is not divisible by $p$. Since $p$ is a prime, this means neither $f_{i}$ nor $f_{j}$ is divisible by $p$. The number of integers in $[l_{i}, r_{i}]$ not divisible by $p$ is $r_{i} - l_{i} + 1 - a_{i}$. Similar for $j$. Therefore, the probability $f_{i} \cdot f_{j}$ is not divisible by $p$ is given by $\frac{r_{i}-l_{i}+1-a_{i}}{r_{i}-l_{i}+1}\mathrm{~}\star\frac{r_{j}-l_{j}+1-a_{j}}{r_{j}-l_{j}+1}$. Therefore, the probability it is can be given by $\hat{1}\ \to\ \frac{r_{i}-l_{i}+1-a_{i}}{r_{i}-l_{i}+1}\ \cdot\ \frac{r_{j}-l_{j}+1-a_{j}}{r_{i}-l_{i}+1}$. Now, just sum over this for all $i$.
[ "combinatorics", "math", "number theory", "probabilities" ]
1,700
null
621
D
Rat Kwesh and Cheese
Wet Shark asked Rat Kwesh to generate three positive real numbers $x$, $y$ and $z$, from $0.1$ to $200.0$, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have \textbf{exactly one} digit after the decimal point. Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers $x$, $y$ and $z$ to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options: - $a_{1} = x^{yz}$; - $a_{2} = x^{zy}$; - $a_{3} = (x^{y})^{z}$; - $a_{4} = (x^{z})^{y}$; - $a_{5} = y^{xz}$; - $a_{6} = y^{zx}$; - $a_{7} = (y^{x})^{z}$; - $a_{8} = (y^{z})^{x}$; - $a_{9} = z^{xy}$; - $a_{10} = z^{yx}$; - $a_{11} = (z^{x})^{y}$; - $a_{12} = (z^{y})^{x}$. Let $m$ be the maximum of all the $a_{i}$, and $c$ be the smallest index (from $1$ to $12$) such that $a_{c} = m$. Rat's goal is to find that $c$, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that $a_{c}$.
The tricky Rat Kwesh has finally made an appearance; it is time to prepare for some tricks. But truly, we didn't expect it to be so hard for competitors though. Especially the part about taking log of a negative number. We need a way to deal with $x^{yz}$ and $x^{yz}$. We cannot directly compare them, $200^{200200}$ is way too big. So what we do? Take log! $\bigstar\bigstar\bigstar11$ is an increasing function on positive numbers (we can see this by taking $f(x)=\ln(x)$, then $f^{\prime}(x)={\frac{1}{x}}$, which is positive when we are dealing with positive numbers). So if $\ln x\geq\ln y$, then $x \ge y$. When we take log, $\log x^{y^{z}}=y^{z}\log(x)$ But $y^{z}$ can still be $200^{200}$, which is still far too big. So now what can we do? Another log! But is it legal? When $x = 0.1$ for example, $\ln(0.1)<0$, so we cannot take another log. When can we take another log, however? We need $y^{z}\ln(x)$ to be a positive number. $y^{z}$ will always be positive, so all we need is for $\ln(x)$ to be positive. This happens when $x > 1$. So if $x, y, z > 1$, everything will be ok. There is another good observation to make. If one of $x, y, z$ is greater than $1$, then we can always achieve some expression (out of those 12) whose value is greater than $1$. But if $x < 1$, then $x^{a}$ will never be greater than $1$. So if at least one of $x, y, z$ is greater than $1$, then we can discard those bases that are less than or equal to $1$. In this case, $\ln(\ln(x^{y^{z}}))=\ln(y^{z}\ln(x))$. Remember that $\ln(a b)=\ln(a)+\ln(b)$, so $\ln(y^{z}\ln(x))=z\log(y)+\ln(\ln(x))$. Similarly, $\ln(\ln(x^{y z}))=\ln(y z\log(x))=\ln(y)+\ln(z)+\ln(\ln(x))$. The last case is when $x \le 1, y \le 1, z \le 1$. Then, notice that for example, $0.{\partial^{x}}^{y}=\frac{1}{(10/3)}^{x^{y}}=\frac{1}{(10/3)^{x^{y}}}$. But the denominator of this fraction is something we recognize, because $10 / 3 > 1$. So if all $x, y, z < 1$, then it is the same as the original problem, except we are looking for the minimum this time.
[ "brute force", "constructive algorithms", "math" ]
2,400
null
621
E
Wet Shark and Blocks
There are $b$ blocks of digits. Each one consisting of the same $n$ digits, which are given to you in the input. Wet Shark must choose \textbf{exactly one} digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit $1$ from the first block and digit $2$ from the second block, he gets the integer $12$. Wet Shark then takes this number modulo $x$. Please, tell him how many ways he can choose one digit from each block so that he gets exactly $k$ as the final result. As this number may be too large, print it modulo $10^{9} + 7$. Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are $3$ ways to choose digit $5$ from block 3 5 6 7 8 9 5 1 1 1 1 5.
First, let us build an X by X matrix. We will be applying matrix exponentiation on this matrix. For each modulo value T from 0 to X - 1, and each value in the array with index i between 1 and n, we will do: matrix[T][(10 * T + arr[i]) % X]++. This is because, notice that for each block we allow one more way to go between a modulo value T, and (10 * T + arr[i]) % X. We are multiplying T by 10 because we are "left-shifting" the number in a way (i.e. changing 123 -> 1230), and then adding arr[i] to it. Notice that this basically simulates the concatenation that Wet Shark is conducting, without need of a brute force dp approach.
[ "dp", "matrices" ]
2,000
null
622
A
Infinite Sequence
Consider the infinite sequence of integers: $1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5...$. The sequence is built in the following way: at first the number $1$ is written out, then the numbers from $1$ to $2$, then the numbers from $1$ to $3$, then the numbers from $1$ to $4$ and so on. Note that the sequence contains numbers, not digits. For example number $10$ first appears in the sequence in position $55$ (the elements are numerated from one). Find the number on the $n$-th position of the sequence.
Let's decrease $n$ by one. Now let's determine the block with the $n$-th number. To do that let's at first subtract $1$ from $n$, then subtract $2$, then subtract $3$ and so on until we got negative $n$. The number of subtractions will be the number of the block and the position in the block will be the last nonnegative number we will get. Complexity: $O({\sqrt{n}})$.
[ "implementation", "math" ]
1,000
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nli n;\n\ninline bool read() {\n\treturn !!(cin >> n);\n}\n\ninline void solve() {\n\tn--;\n\tfor (li i = 1; i <= n; i++) {\n\t\tn -= i;\n\t}\n\tcout << n + 1 << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
622
B
The Time
You are given the current time in $24$-hour format hh:mm. Find and print the time after $a$ minutes. Note that you should find only the time after $a$ minutes, see the examples to clarify the problem statement. You can read more about $24$-hour format here https://en.wikipedia.org/wiki/24-hour_clock.
In this problem we can simply increase $a$ times the current time by one minute (after each increasing we should check the hours and the minutes for overflow). Another solution is to use the next formulas as the answer: $x=h\cdot60+m+a,\ h^{\prime}=\left[{\frac{x}{60}}\right]\ m o d\ 24,m^{\prime}=x\ m o d\ 60$. Complexity: $O(a)$ or $O(1)$.
[ "implementation" ]
900
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint h, m;\nint add;\n\ninline bool read() {\n\tif (scanf(\"%d:%d%d\", &h, &m, &add) != 3) return false;\n\treturn true;\n}\n\ninline void solve() {\n\twhile (add) {\n\t\tif (++m == 60) {\n\t\t\tm = 0;\n\t\t\tif (++h == 24) h = 0;\n\t\t}\n\t\tadd--;\n\t}\n\tprintf(\"%02d:%02d\\n\", h, m);\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
622
C
Not Equal on a Segment
You are given array $a$ with $n$ integers and $m$ queries. The $i$-th query is given with three integers $l_{i}, r_{i}, x_{i}$. For the $i$-th query find any position $p_{i}$ ($l_{i} ≤ p_{i} ≤ r_{i}$) so that $a_{pi} ≠ x_{i}$.
This problem can be solved differently. For example you can use some data structures or sqrt-decomposition technique. But it is not required. We expected the following simple solution from the participants. Let's preprocess the following values $p_{i}$ - the position of the first element to the left from the $i$-th element such that $a_{i} \neq a_{pi}$. Now to answer to the query we should check if $a_{r} \neq x$ then we have the answer. Otherwise we should check the position $p_{r}$. Complexity: $O(n)$.
[ "data structures", "implementation" ]
1,700
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 200200;\n\nint n, m;\nint a[N];\nint l[N], r[N], x[N];\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\tforn(i, m) {\n\t\tassert(scanf(\"%d%d%d\", &l[i], &r[i], &x[i]) == 3);\n\t\tl[i]--, r[i]--;\n\t}\n\treturn true;\n}\n\nint z[N];\n\ninline void solve() {\n\tz[0] = -1;\n\tfore(i, 1, n) {\n\t\tif (a[i - 1] != a[i]) z[i] = i - 1;\n\t\telse z[i] = z[i - 1];\n\t}\n\n\tforn(i, m) {\n\t\tif (a[r[i]] != x[i]) printf(\"%d\\n\", r[i] + 1);\n\t\telse if (z[r[i]] >= l[i]) printf(\"%d\\n\", z[r[i]] + 1);\n\t\telse puts(\"-1\");\n\t}\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
622
D
Optimal Number Permutation
You have array $a$ that contains all integers from $1$ to $n$ twice. You can arbitrary permute any numbers in $a$. Let number $i$ be in positions $x_{i}, y_{i}$ ($x_{i} < y_{i}$) in the permuted array $a$. Let's define the value $d_{i} = y_{i} - x_{i}$ — the distance between the positions of the number $i$. Permute the numbers in array $a$ to minimize the value of the sum $s=\sum_{i=1}^{n}(n-i)\cdot|d_{i}+i-n$.
Let's build the answer with the sum equal to zero. Let $n$ be even. Let's place odd numbers in the first half of the array: the number $1$ in the positions $1$ and $n$, the number $3$ in the positions $2$ and $n - 1$ and so on. Similarly let's place even numbers in the second half: the number $2$ in the position $n + 1$ and $2n - 1$, the number $4$ in the positions $n + 2$ and $2n - 2$ and so on. We can place the number $n$ in the leftover positions. We can build the answer for odd $n$ in a similar way. Easy to see that our construction will give zero sum. Complexity: $O(n)$.
[ "constructive algorithms" ]
1,900
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint n;\n\ninline bool read() {\n\treturn !!(cin >> n);\n}\n\nconst int N = 1200300;\n\nint ans[N];\n\ninline void solve() {\n\tforn(i, 2 * n) ans[i] = n;\n\tfore(i, 1, n) {\n\t\tint x;\n\t\tif (i & 1) x = i >> 1;\n\t\telse x = n - 1 + (i >> 1);\n\t\tint y = x + (n - i);\n\t\tans[x] = ans[y] = i;\n\t}\n\n\tforn(i, 2 * n) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", ans[i]);\n\t}\n\tputs(\"\");\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
622
E
Ants in Leaves
Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with $n$ vertices and a root in the vertex $1$. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.
Easy to see that the answer is equal to the answer over all sons of the root plus one. Now let's solve the problem independently for each son $v$ of the root. Let $z$ be the array of the depths of all leaves in the subtree of the vertex $v$. Let's sort $z$. Statement 1: it's profitable to lift the leaves in order of their appearing in $z$. Statement 2: denote $a_{x}$ - the time of appearing the $x$-th leaf in the vertex $v$, let's consider the leaves $z_{i}$ and $z_{i + 1}$ then $a_{zi + 1} \ge a_{zi} + 1$. Statement 3: $a_{zi + 1} = max(d_{zi + 1}, a_{zi} + 1)$, where $d_{x}$ is the depth of the $x$-th leaf in the subtree of the vertex $v$. The last statement gives us the solution for the problem: we should simply iterate over $z$ from left to right and recalculate the array $a$ by formula from the third statement. All statements can be easily proved and it's recommended to do by yourself to understand better the idea of the solution. Complexity: $O(nlogn)$.
[ "dfs and similar", "greedy", "sortings", "trees" ]
2,200
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 500500;\n\nint n;\nvector<int> g[N];\n\ninline bool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) g[i].clear();\n\tforn(i, n - 1) {\n\t\tint x, y;\n\t\tassert(scanf(\"%d%d\", &x, &y) == 2);\n\t\tx--, y--;\n\t\tg[x].pb(y), g[y].pb(x);\n\t}\n\treturn true;\n}\n\nvector<int> z;\n\nvoid dfs(int v, int p, int d) {\n\tint c = 0;\n\tforn(i, sz(g[v])) {\n\t\tint to = g[v][i];\n\t\tif (to == p) continue;\n\t\tc++;\n\t\tdfs(to, v, d + 1);\n\t}\n\tif (!c) z.pb(d);\n}\n\nint solve(int v, int p) {\n\tz.clear();\n\tdfs(v, p, 0);\n\tsort(all(z));\n\tforn(i, sz(z)) {\n\t\tif (i) z[i] = max(z[i - 1] + 1, z[i]);\n\t}\n\treturn z.back();\n}\n\ninline void solve() {\n\tint ans = 0;\n\tforn(i, sz(g[0]))\n\t\tans = max(ans, solve(g[0][i], 0) + 1);\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
622
F
The Sum of the k-th Powers
There are well-known formulas: $\sum_{i=1}^{n}i=1+2+\cdot\cdot\cdot+n={\frac{n(n+1)}{2}}$, $\sum_{i=1}^{n}i^{2}=1^{2}+2^{2}+\cdot\cdot\cdot+n^{2}={\frac{n(2n+1)(n+1)}{6}}$, $\sum_{i=1}^{n}i^{3}=1^{3}+2^{3}+\cdot\cdot\cdot+n^{3}=\left({\frac{n(n+1)}{2}}\right)^{2}$. Also mathematicians found similar formulas for higher degrees. Find the value of the sum $\sum_{i=1}^{n}i^{k}=1^{k}+2^{k}+\ldots+n^{k}$ modulo $10^{9} + 7$ (so you should find the remainder after dividing the answer by the value $10^{9} + 7$).
Statement: the function of the sum is a polynomial of degree $k + 1$ over variable $n$. This statement can be proved by induction (to make step you should take the derivative). Denote $P_{x}$ the value of the sum for $n = x$. We can easily calculate the values of $P_{x}$ for $x$ from $0$ to $k + 1$ in $O(klogk)$ time. If $n < k + 2$ then we already have the answer. Otherwise let's use Lagrange polynomial to get the value of the sum for the given value $n$. The Largange polynomial have the following form: $P(x)=\sum_{i=1}^{n}y_{i}\prod_{j=1,j\neq i}^{n}{\frac{x-x_{j}}{x_{i}-x_{j}}}$. In our case $x_{i} = i - 1$ and $y_{i} = P_{xi}$. To calculate $P(n)$ in a linear time we should use that $x_{i + 1} - x_{i} = x_{j + 1} - x_{j}$ for all $i, j < n$. It's help us because with that property we can recalculate the inner product for $i + 1$ from the inner product for $i$ simply by multiplying by two values and dividing by two values. So we can calculate the sum in linear time over $k$. C++ solution ($logk$ appeared because we should find the inverse element in the field modulo $MOD = 10^{9} + 7$).
[ "math" ]
2,600
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint n, k;\n\ninline bool read() {\n\treturn !!(cin >> n >> k);\n}\n\nconst int mod = 1000 * 1000 * 1000 + 7;\n\nint gcd(int a, int b, int& x, int& y) {\n\tif (!a) {\n\t\tx = 0, y = 1;\n\t\treturn b;\n\t}\n\tint xx, yy, g = gcd(b % a, a, xx, yy);\n\tx = yy - b / a * xx;\n\ty = xx;\n\treturn g;\n}\n\ninline int normal(int n) {\n\tn %= mod;\n\t(n < 0) && (n += mod);\n\treturn n;\n}\n\ninline int inv(int a) {\n\tint x, y;\n\tassert(gcd(a, mod, x, y) == 1);\n\treturn normal(x);\n}\n\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\ninline int sub(int a, int b) { return a - b < 0 ? a - b + mod : a - b; }\ninline int mul(int a, int b) { return int(a * 1ll * b % mod); }\ninline int _div(int a, int b) { return mul(a, inv(b)); }\n\ninline int binPow(int a, int b) {\n\tint ans = 1;\n\twhile (b) {\n\t\tif (b & 1) ans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn ans;\n}\n\nint calc(const vector<int>& y, int x) {\n\tint ans = 0;\n\tint k = 1;\n\tfore(j, 1, sz(y)) {\n\t\tk = mul(k, normal(x - j));\n\t\tk = _div(k, normal(0 - j));\n\t}\n\tforn(i, sz(y)) {\n\t\tans = add(ans, mul(y[i], k));\n\t\tif (i + 1 >= sz(y)) break;\n\t\tk = mul(k, _div(normal(x - i), normal(x - (i + 1))));\n\t\tk = mul(k, _div(normal(i - (sz(y) - 1)), normal(i + 1)));\n\t}\n\treturn ans;\n}\n\ninline int solve() {\n\tvector<int> y;\n\tint sum = 0;\n\ty.pb(sum);\n\tforn(i, k + 1) {\n\t\tsum = add(sum, binPow(i + 1, k));\n\t\ty.pb(sum);\n\t}\n\tif (n < sz(y)) return y[n];\n\treturn calc(y, n);\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tcout << solve() << endl;\n\t}\n\t\n return 0;\n}"
623
A
Graph and String
One day student Vasya was sitting on a lecture and mentioned a string $s_{1}s_{2}... s_{n}$, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph $G$ with the following properties: - $G$ has exactly $n$ vertices, numbered from $1$ to $n$. - For all pairs of vertices $i$ and $j$, where $i ≠ j$, there is an edge connecting them \textbf{if and only if} characters $s_{i}$ and $s_{j}$ are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph $G$, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string $s$, such that if Vasya used this $s$ he would produce the given graph $G$.
Note that all vertices "b" are connected with all other vertices in the graph. Find all such vertices and mark them as "b". Now we need to find any unlabeled vertex $V$, mark it with "a" character. Unlabeled vertices connected with $V$ should be also labeled as "a". All other vertices we can label as "c" Finally we need to check graph validity. Check that all vertices "a" are only connected with each other and "b" vertices. After that we need to perform a similar check for "c" vertices.
[ "constructive algorithms", "graphs" ]
1,800
null
623
B
Array GCD
You are given array $a_{i}$ of length $n$. You may consecutively apply two operations to this array: - remove some subsegment (continuous subsequence) of length $m < n$ and pay for it $m·a$ coins; - change some elements of the array by at most $1$, and pay $b$ coins for each change. Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most $1$. Also note, that you are not allowed to delete the whole array. Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than $1$.
At least one of ends ($a_{1}$ or $a_{n}$) is changed by at most 1. It means that if gcd > 1 then it divides on of prime divisors of either $a_{1} - 1$, $a_{1}$, $a_{1} + 1$, $a_{n} - 1$, $a_{n}$ or $a_{n} + 1$. We will iterate over these primes. Suppose prime $p$ is fixed. For each number we know that it's either divisible by $p$ or we can pay $b$ to fix it or it should be in the subarray to change for $a$ We can use dynamic programming dp[number of numbers considered][subarray to change not started/started/finished] = minimal cost Complexity is $O(Nd) = O(Nlog(max(a_{i}))$, where $d$ is the number of primes to check.
[ "dp", "greedy", "number theory" ]
2,300
null
623
C
Electric Charges
Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals. A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: axis $X$ is positive and axis $Y$ is negative. Experienced laboratory worker marked $n$ points with integer coordinates $(x_{i}, y_{i})$ on the plane and stopped the time. Sasha should use "atomic tweezers" to place elementary particles in these points. He has an unlimited number of electrons (negatively charged elementary particles) and protons (positively charged elementary particles). He can put either an electron or a proton at each marked point. As soon as all marked points are filled with particles, laboratory worker will turn on the time again and the particles will come in motion and after some time they will stabilize in equilibrium. The objective of the laboratory work is to arrange the particles in such a way, that the diameter of the resulting state (the maximum distance between the pairs of points of the set) is as small as possible. Since Sasha is a programmer, he naively thinks that all the particles will simply "fall" into their projections on the corresponding axes: electrons will fall on axis $X$, while protons will fall on axis $Y$. As we are programmers too, we will consider the same model as Sasha. That is, a \textbf{particle gets from point $(x, y)$ to point $(x, 0)$ if it is an electron and to point $(0, y)$ if it is a proton.} As the laboratory has high background radiation and Sasha takes care of his laptop, he did not take it with him, and now he can't write a program that computes the minimum possible diameter of the resulting set. Therefore, you will have to do it for him. Print a \textbf{square} of the minimum possible diameter of the set.
First of all consider cases where all points are projected to the same axis. (In that case answer is difference between maximum and minimum of this coordinate). Now consider leftmost and rightmost points among projected to $x$ axis. Let $x_{L}$ and $x_{R}$ are their $x$-coordinates. Notice that points with x-coordinate $x_{L} \le x \le x_{R}$ may also be projected to $x$-axis and that will not increase the diameter. So, if we sort all points by $x$-coordinate, we may suppose that points projected to $x$-axis form a continuous subarray. We will use a binary search. Now we will need to check if it's possible to project point in a such way that diameter is <= M. Let's fix the most distant by $x$-coordinate point from 0 that is projected to $x$-axis. It may be to the left or to the right of 0. This cases are symmetrical and we will consider only the former one. Let $x_{L} < 0$ be its coordinate. Notice that one may project all points such that $0 \le x - x_{L} \le M$ and $|x| \le |x_{L}|$ to the $x$ axis (and it'll not affect the diameter) and we have to project other points to $y$-axis. Among all other points we should find the maximum and minimum by $y$ coordinate. Answer is "yes ($diam \le M$)" if $y_{max} - y_{min} < = M$ and distance from $(x_{L}, 0)$ to both $(0, y_{max})$ and $(0, y_{min})$ is not greater than M. Let's precalculate maximums and minimums of $y$ coordinates on each prefix and suffix of original (sorted) points array. Now iterate over left border of subarray of points projected to $x$-axis and find the right border using binary search or maintain it using two-pointers technique. So we've got one check in $O(M)$ or $O(M\log M)$ and entire solution in $O(M\log C)$ or $O(M\log M\log C)$
[ "binary search", "dp" ]
2,900
null
623
D
Birthday
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. $n$ friends came by, and after a typical party they decided to play blind man's buff. The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the $i$-th friend does not change between rounds and is equal to $p_{i}$ percent (as we know, it is directly proportional to the amount of alcohol consumed by the $i$-th friend) and $p_{1} + p_{2} + ... + p_{n} = 100$ holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins. The game ends when Misha guesses every friend at least once, that is, there exists such set of rounds $k_{1}, k_{2}, ..., k_{n}$, that during round number $k_{i}$ Misha caught the $i$-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally.
Let's denote $q_{i} = 1 - p_{i}$. Main idea: first of all guess each friend once, then maximize probability to end game on current step. Let's simulate first 300000 steps, and calculate $\textstyle\sum t\cdot(P r(t)-P r(t-1))$. $P r(t)=\prod(1-q_{i}^{k_{i}})$, where $k_{i}$ - how many times we called $i$-th friend ($\textstyle\sum k_{i}=\iota$). Expectation with some precision equals $N\ast P r(N)-\sum_{t=1}^{N-1}P r(t)$. So it is enough to prove that: 1) Greedy strategy gives maximum values for all $Pr(t)$. 2) On 300000 step precision error will be less than $10^{ - 6}$. Proof: 1) Suppose, that for some $t$ there exists set $l_{i}$ ($\textstyle\sum l_{i}=t$), not equal to set produced by greedy algorithm $k_{i}$, gives the maximum value of $Pr(t)$. Let's take some $k_{a} < l_{a}$ and $k_{b} > l_{b}$, it is easy to prove tgat if we change $l_{b}$ to $l_{b} + 1$, $l_{a}$ to $l_{a} - 1$, then new set of $l_{i}$ gives bigger value of $Pr(t)$, contradiction. 2) $q_{i} \le 0.99$. Let's take set $k_{i}={\frac{t}{10}}$, it gives probability of end of the game not less than optimal. Then $Pr(t) \ge (1 - 0.99^{t / 100})^{100} \ge 1 - 100 \cdot 0.99^{t / 100}$. Precision error does not exceed $\sum_{t=N+1}^{\infty}1-P r(t)\leq100\cdot\sum_{t=N+1}^{\infty}0.99^{t/100}$. It could be estimated as sum of geometric progression. If $N \ge 300000$ precision error doesn't exceed $10^{ - 7}$.
[ "greedy", "math", "probabilities" ]
2,700
null
623
E
Transforming Sequence
Let's define the transformation $P$ of a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ as $b_{1}, b_{2}, ..., b_{n}$, where $b_{i} = a_{1} | a_{2} | ... | a_{i}$ for all $i = 1, 2, ..., n$, where $|$ is the bitwise OR operation. Vasya consequently applies the transformation $P$ to all sequences of length $n$ consisting of integers from $1$ to $2^{k} - 1$ inclusive. He wants to know how many of these sequences have such property that their transformation is a \textbf{strictly increasing} sequence. Help him to calculate this number modulo $10^{9} + 7$.
First observation is that if the sequence of prefix xors is strictly increasing, than on each step $a_{i}$ has at least one new bit comparing to the previous elements. So, since there are overall $k$ bits, the length of the sequence can't be more than $k$. So, if $n > k$, the answer is 0. Let's firstly solve the task with $O(k^{3})$ complexity. We calculate $dp[n][k]$ - the number of sequences of length $n$ such that $a_{1}|a_{2}|... |a_{n}$ has $k$ bits. The transition is to add a number with $l$ new bits, and choose those $k$ bits which are already in the prefix xor arbitrarily. So, $dp[n + 1][k + l]$ is increased by $dp[n][k] \cdot 2^{k} \cdot C_{k + l}^{l}$. The last binomial coefficient complies with the choice these very $l$ bits from $k + l$ which will be present in $a_{1}|a_{2}|... |a_{n + 1}$. Note now that the transition doesn't depend on $n$, so let's try to use the idea of the binary exponentiation. Suppose we want to merge two dynamics $dp_{1}[k], dp_{2}[k]$, where $k$ is the number of bits present in $a_{1}|a_{2}|... |a_{left}$ and $b_{1}|... |b_{right}$ correspondingly. Now we want to obtain $dp[k]$ for arrays of size $left + right$. The formula is: $d p[k]=\sum_{l=0}^{k}d p![l]\cdot d p\gamma[k-l]\cdot C_{k}^{l}\cdot2^{l\cdot r i g h t}.$ Here $l$ corresponds to the bits present in the xor of the left part, and for each number of the right part we can choose these $l$ bits arbitrarily. Rewrite the formula in the following way: $d p[k]=\sum_{l=0}^{k}\frac{d p![l]}{l!}\cdot\lambda^{l\cdot r i g h t}\cdot\frac{d p2[k-l]}{(k-l)!}\cdot k!.$ So, we can compute $dp[k]$ for all $k$ having multiplied two polynomials $\sum_{l=0}^{k}{\frac{d p[l]}{l!}}\cdot2^{l.r i g h t}$ and $\sum_{l=0}^{k}{\frac{d p[l]}{l!}}$. We can obtain the coefficients of the first polynomial from the coefficients of the second in $O(k\log k)$. So, we can compute this dynamic programming for all lengths - powers of two, in $O(k\log k\log n)$, using the fast Fourier transform. In fact, it is more convenient to compute $\frac{d p[k]}{k!}$ using the same equation. After that, we can use the same merge strategy to compute the answer for the given $n$, using dynamics for the powers of two. Overall complexity is $O(k\log k\log n)$. We decided to ask the answer modulo $10^{9} + 7$ to not let the participants easily guess that these problem requires FFT :) So, in order to get accepted you had to implement one of the methods to deal with the large modulo in polynomial multiplication using FFT. Another approach was to apply Karatsuba algorithm, our realisation timed out on our tests, but jqdai0815 somehow made it pass :)
[ "combinatorics", "dp", "fft", "math" ]
3,300
null
624
A
Save Luke
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates $0$ and $L$, and they move towards each other with speed $v_{1}$ and $v_{2}$, respectively. Luke has width $d$ and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.
Width of free space is decreasing by $v_{1} + v_{2}$ per second. It means that it'll decrease from $L$ to $d$ in $t={\frac{L-d}{v_{1}+v_{2}}}$ seconds. The moment when width gets a value of $d$ is the last when Luke is alive so $t$ is the answer.
[ "math" ]
800
null
624
B
Making a String
You are given an alphabet consisting of $n$ letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: - the $i$-th letter occurs in the string no more than $a_{i}$ times; - the number of occurrences of each letter in the string must be \textbf{distinct} for all the letters that occurred in the string at least once.
Sort array in descending order. Iterate over all letters, First letter is added $c_{1} = a_{1}$ times, each other letter is added $c_{i} = min(a_{i}, c_{i - 1})$. Don't forget that if some letter is not added at all, then all next letters are not added too.
[ "greedy", "sortings" ]
1,100
null
625
A
Guest From the Past
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated. Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs $a$ rubles, or in glass liter bottle, that costs $b$ rubles. Also, you may return empty glass bottle and get $c$ ($c < b$) rubles back, but you cannot return plastic bottles. Kolya has $n$ rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.
If we have at least $b$ money then cost of one glass bottle is $b - c$. This means that if $a \le b - c$ then we don't need to buy glass bottles, only plastic ones, and the answer will be $\left\lfloor{\frac{n}{a}}\right\rfloor$. Otherwise we need to buy glass bottles while we can. So, if we have at least $b$ money, then we will buy $\left\lfloor{\frac{n-c}{b-c}}\right\rfloor$ glass bottles and then spend rest of the money on plastic ones. This is simple $O(1)$ solution.
[ "implementation", "math" ]
1,700
null
625
B
War of the Corporations
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence. Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring. Substring is a continuous subsequence of a string.
Lets find leftmost occurrence of the second word in the first one. We need to add # to remove this occurrence, so where we would like to put it? Instead of the last symbol of this occurrence to remove as many others as we can. After that we will continue this operation after the new # symbol. Simplest implementation of this idea works in $O(|S| \cdot |T|)$, but with the power of string algorithms (for example, Knuth-Morris-Pratt algorithm) we can do it in $O(|S| + |T|)$ time. Hint/Bug/Feature: in Python language there is already function that does exactly what we need:
[ "constructive algorithms", "greedy", "strings" ]
1,200
null
625
C
K-special Tables
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects. Alis is among these collectors. Right now she wants to get one of $k$-special tables. In case you forget, the table $n × n$ is called $k$-special if the following three conditions are satisfied: - every integer from $1$ to $n^{2}$ appears in the table exactly once; - in each row numbers are situated in increasing order; - the sum of numbers in the $k$-th column is maximum possible. Your goal is to help Alice and find at least one $k$-special table of size $n × n$. Both rows and columns are numbered from $1$ to $n$, with rows numbered from top to bottom and columns numbered from left to right.
Lets fill our table row by row greedily. We want to have maximal possible number on k-th place in the first row. After it we need at least $n - k$ numbers greater than ours, so its maximum value is $n^{2} - (n - k)$. If we select it then we are fixing all numbers after column $k$ in the first row from $n^{2} - (n - k)$ to $n^{2}$. On the first $k - 1$ lets put smallest possible numbers $1, 2, ... , k - 1$. If we do the same thing in the second row then in the beginning it will have numbers from $k$ to $2(k - 1)$, and from $k$-th position maximum possible values from $n^{2} - (n - k) - (n - k + 1)$ to $n^{2} - (n - k + 1)$. And so on we will fill all rows. With careful implementation we don't need to store whole matrix and we need only $O(1)$ memory. Our algorithm works in $O(n^{2})$ time.
[ "constructive algorithms", "implementation" ]
1,300
null
625
D
Finals in arithmetic
Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder. Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip $123$ the result is the integer $321$, but flipping $130$ we obtain $31$, and by flipping $31$ we come to $13$. Oksana Fillipovna picked some number $a$ without leading zeroes, and flipped it to get number $a_{r}$. Then she summed $a$ and $a_{r}$, and told Vitya the resulting value $n$. His goal is to find any valid $a$. As Oksana Fillipovna picked some small integers as $a$ and $a_{r}$, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given $n$ finds any $a$ without leading zeroes, such that $a + a_{r} = n$ or determine that such $a$ doesn't exist.
Lets say that input has length of $n$ digits, then size of answer can be $n$ if we didn't carry 1 to the left out of addition, and $n - 1$ otherwise. Lets fix length $m$ of our answer and denote $i$-th number in the representation as $a_{i}$. Then we know $(a_{1}+a_{m})\mathrm{~mod~}10$ from the rightmost digit of the sum. Lets figure out what does $(a_{1}+a_{m}){\mathrm{~div~}}10$ equals to. If the remainder is 9, it means that $(a_{1}+a_{m}){\mathrm{~div~}}10=0$, because we can't get 19 out of the sum of two digits. Otherwise the result is defined uniquely by the fact that there was carrying 1 in the leftmost digit of the result or not. So after this we know $a_{1} + a_{m}$. It doesn't matter how we divide sum by two digits, because the result will be the same. After this we can uniquely identify the fact of carrying after the first digit of the result and before the last digit. Repeating this $m / 2$ times we will get candidate for the answer. In the end we will have $O(n)$ solution. If you've missed the fact that every step is uniquely defined, then you could've wrote basically the same solution, but with dynamic programming.
[ "constructive algorithms", "implementation", "math" ]
2,400
null
625
E
Frog Fights
Ostap Bender recently visited frog farm and was inspired to create his own frog game. Number of frogs are places on a cyclic gameboard, divided into $m$ cells. Cells are numbered from $1$ to $m$, but the board is cyclic, so cell number $1$ goes right after the cell number $m$ in the direction of movement. $i$-th frog during its turn can jump for $a_{i}$ cells. Frogs move in turns, game starts with a move by frog $1$. On its turn $i$-th frog moves $a_{i}$ cells forward, knocking out all the frogs on its way. If there is a frog in the last cell of the path of the $i$-th frog, that frog is also knocked out. After this the value $a_{i}$ is decreased by the number of frogs that were knocked out during this turn. If $a_{i}$ is zero or goes negative, then $i$-th frog doesn't make moves anymore. After frog number $1$ finishes its turn, frog number $2$ starts to move, then frog number $3$ and so on. After the frog number $n$ makes its move, frog $1$ starts to move again, then frog $2$ and so on this process goes forever. If some frog was already knocked out from the board, we consider that it skips all its moves. Help Ostap to identify, what frogs will stay on the board at the end of a game?
We want to efficiently simulate the process from the problem statement. Lets have a data structure with times of key events that could've happened during simulation (some frog removed other frog from the board). Lets remove earliest event from our data structure and apply it to the board, make a critical jump. After that the speed of the first frog will decrease and we will be forced to recount times of collision of this frog this its 2 neighbors. This data structure could be set from C++, TreeSet from Java or self-written Segment Tree. To quickly find out who are we gonna remove from the board after the jump lets store double-linked list of all frogs sorted by their positions. Technical part is to calculate time of the collision, but it can be easily done with the simple notion of linear movement of two points on a line. There could be at max $n - 1$ collisions, so whole solution will be $O(n\log n)$.
[ "data structures", "greedy" ]
2,800
null
626
A
Robot Sequence
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of $n$ commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
We can simulate Calvin's path on each substring, and check if he returns to the origin. Runtime: $O(n^{3})$
[ "brute force", "implementation" ]
1,000
null
626
B
Cards
Catherine has a deck of $n$ cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: - take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color. She repeats this process until there is only one card left. What are the possible colors for the final card?
Note that if we have exactly one card of each color, we can always make all three options (by symmetry). Thus, if we have at least one of each color, or at least two of each of two colors, we can make all three options. The remaining cases are: if we only have one color, that's the only possible final card; if we have one of each of two colors, we can only make the third color; if we have at least two of one color and exactly one of a second, we can only make the second or third color (e.g. sample 2). Runtime: $O(1)$
[ "constructive algorithms", "dp", "math" ]
1,300
null
626
C
Block Towers
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. $n$ of the students use pieces made of two blocks and $m$ of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers.
There are a variety of ways to do this problem. Here is one way: if the answer is $X$, there must be at least $n$ multiples of $2$ below $X$, at least $m$ multiples of $3$ below $X$, and at least $n + m$ multiples of $2$ or $3$ below $X$. These conditions are actually sufficient, so we need to find the smallest $X$ such that $n\leq\lfloor{\frac{X}{2}}\rfloor$, $m\leq\lfloor{\frac{X}{3}}\rfloor$, and $n+m\leq\lfloor{\frac{X}{2}}\rfloor+\lfloor{\frac{X}{3}}\rfloor-\lfloor{\frac{X}{6}}\rfloor$. We can do this with a linear search, or with an explicit formula. Runtime: $O(1)$
[ "brute force", "greedy", "math", "number theory" ]
1,600
null
626
D
Jerry's Protest
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing $n$ balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and \textbf{returns the balls} to the jar. The winner of the game is the one who wins at least two of the three rounds. Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?
We do this algorithm in two phases: first, we compute the probability distribution of the difference between the winner and loser of each round. This takes $O(n^{2})$ time. Then, we can iterate over the 2 differences which Andrew wins by and compute the probability that Jerry has a greater total using with suffix sums. Runtime: $O(n^{2} + a_{max}^{2})$
[ "brute force", "combinatorics", "dp", "probabilities" ]
1,800
null
626
E
Simple Skewness
Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of $n$ (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness. The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size.
We can show that any subset with maximal simple skewness should have odd size (otherwise we drop the larger middle element: this decreases the median by more than it decreases the mean, assuming the mean is larger than the median). Let's fix the median at $x_{i}$ (in the sorted list), and set the size of the set to $2j + 1$. We'd like to maximize the mean, so we can greedily choose the largest $j$ elements below the median and the largest $j$ elements above the median: $x_{i - j}, ..., x_{i - 1}$ and $x_{n - j + 1}, ..., x_{n}$. Now, notice that by increasing $j$ by $1$, we add in the elements $x_{i - j - 1}$ and $x_{n - j}$, which decrease as $j$ increases. Thus, for a fixed $i$, the overall mean is bitonic in $j$ (it increases then decreases), so we can binary search on the marginal utility to find the optimum. Runtime: $O(n\log(n))$
[ "binary search", "math", "ternary search" ]
2,400
null
626
F
Group Projects
There are $n$ students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the $i$-th student $a_{i}$ minutes to finish his/her independent piece. If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum $a_{i}$ in the group minus the minimum $a_{i}$ in the group. Note that a group containing a single student has an imbalance of $0$. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most $k$? Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.
This is a dynamic programming problem. Notice that the total imbalance of the groups only depends on which students are the maximum in each group and which are the minimum in each group. We thus can think of groups as intervals bounded by the minimum and maximum student. Moreover, the total imbalance is the sum over all unit ranges of the number of intervals covering that range. We can use this formula to do our DP. If we sort the students in increasing size, DP state is as follows: the number of students processed so far, the number of $g$ groups which are currently "open" (have a minimum but no maximum), and the total imbalance $k$ so far. For each student, we first add the appropriate value to the total imbalance ($g$ times the distance to the previous student), and then either put the student in his own group (doesn't change $g$), start a new group (increment $g$), add the student to one of the $g$ groups (doesn't change $g$), or close one of the $g$ groups (decrement $g$). Runtime: $O(n^{2}k)$
[ "dp" ]
2,400
null
626
G
Raffles
Johnny is at a carnival which has $n$ raffles. Raffle $i$ has a prize with value $p_{i}$. Each participant can put tickets in whichever raffles they choose (they may have more than one ticket in a single raffle). At the end of the carnival, one ticket is selected at random from each raffle, and the owner of the ticket wins the associated prize. A single person can win multiple prizes from different raffles. However, county rules prevent any one participant from owning more than half the tickets in a single raffle, i.e. putting more tickets in the raffle than all the other participants combined. To help combat this (and possibly win some prizes), the organizers started by placing a single ticket in each raffle, which they will never remove. Johnny bought $t$ tickets and is wondering where to place them. Currently, there are a total of $l_{i}$ tickets in the $i$-th raffle. He watches as other participants place tickets and modify their decisions and, at every moment in time, wants to know how much he can possibly earn. Find the maximum possible expected value of Johnny's winnings at each moment if he distributes his tickets optimally. Johnny may redistribute all of his tickets arbitrarily between each update, but he may not place more than $t$ tickets total or have more tickets in a single raffle than all other participants combined.
First, note that the marginal utility of each additional ticket in a single raffle is decreasing. Thus, to solve the initial state, we can use a heap data structure to store the optimal raffles. Now, after each update, we can show that the distribution should not change by much. In particular, after one ticket is added to a raffle, Johnny should either remove one ticket from that raffle and place it elsewhere, not change anything, or, if the raffle was already full, put one more ticket in to keep it full. Similarly, after a ticket is removed, Johnny should either do nothing, remove one ticket to stay under the maximum, or add one ticket. (The proofs are fairly simple and involve looking at the "cutoff" marginal utility of Johnny's tickets.) All of these operations can be performed using two heaps storing the optimal ticket to add and the optimal ticket to remove. Runtime: $O((t+q)\log(n))$
[ "data structures", "dp", "greedy", "math" ]
3,100
null
627
A
XOR Equation
Two \textbf{positive} integers $a$ and $b$ have a sum of $s$ and a bitwise XOR of $x$. How many possible values are there for the ordered pair $(a, b)$?
For any two integers $a$ and $b$, we have $s=a+b=(a\oplus b)+(a\aleph b)*2$, where $a\oplus b$ is the xor and $a&b$ is the bitwise AND. This is because $\mathbb{C}$ is non-carrying binary addition. Thus, we can find $a&b = (s - x) / 2$ (if this is not an integer, there are no solutions). Now, for each bit, we have $4$ cases: $a_{i}g\delta_{i}\in\{0,1\}$, and $a_{i}\oplus b_{i}\in\{0,1\}$. If $a_{i}\oplus b_{i}=0$, then $a_{i} = b_{i}$, so we have one possibility: $a_{i} = b_{i} = a_{i}&b_{i}$. If $a_{i}\oplus b_{i}=1$, then we must have $a_{i}&b_{i} = 0$ (otherwise we print $0$), and we have two choices: $a_{i} = 1$ and $b_{i} = 0$ or vice versa. Thus, we can return $2^{n}$, where $n$ is the number of one-bits in $x$. (Remember to subtract $2$ for the cases $a = 0$ or $b = 0$ if necessary.) Runtime: $O(\log(x))$
[ "dp", "math" ]
1,700
null
627
B
Factory Repairs
A factory produces thimbles in bulk. Typically, it can produce up to $a$ thimbles a day. However, some of the machinery is defective, so it can currently only produce $b$ thimbles each day. The factory intends to choose a $k$-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of $a$ thimbles per day after the $k$ days are complete. Initially, no orders are pending. The factory receives updates of the form $d_{i}$, $a_{i}$, indicating that $a_{i}$ new orders have been placed for the $d_{i}$-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes. As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day $p_{i}$. Help the owner answer his questions.
Using two binary-indexed trees, we can maintain the prefix and suffix sums of the amounts we can produce with maximum production rates of $B$ and $A$, respectively. Then we can just query the binary-indexed trees to find the maximum possible production given the start and end of the repairs. Runtime: $O(q\log(n))$.
[ "data structures" ]
1,700
null
627
C
Package Delivery
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point $0$ on a number line, and the district center is located at the point $d$. Johnny's truck has a gas tank that holds exactly $n$ liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are $m$ gas stations located at various points along the way to the district center. The $i$-th station is located at the point $x_{i}$ on the number line and sells an unlimited amount of fuel at a price of $p_{i}$ dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
We solve this with a greedy algorithm: for each gas station, we fill our tank to $min(n, d)$ liters of gasoline, where $d$ is the distance to the next gas station with cheaper (or equal) gas. This is optimal, as, if we can make it to a station with cheaper gas without buying expensive gas, we should (and fill up our tank at the cheaper station). Otherwise, all stations within range $n$ are more expensive, so we should buy as much gas as possible right now. Alternatively, if we say that we always "use" the gasoline we buy in the order we buy it, then the gasoline used in the $i$th unit must have been purchased within the last $n$ units. Then we can greedily use the cheapest gas within the last $n$ miles. We can maintain this in a queue with range-min-query, which gives us linear runtime (after sorting). Runtime: $O(m\log(m))$
[ "data structures", "divide and conquer", "greedy" ]
2,200
null
627
D
Preorder Test
For his computer science class, Jacob builds a model tree with sticks and balls containing $n$ nodes in the shape of a tree. Jacob has spent $a_{i}$ minutes building the $i$-th ball in the tree. Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first $k$ nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum $a_{i}$ she finds among those $k$ nodes. Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of \textbf{each node} in any order he likes. Help Jacob find the best grade he can get on this assignment. A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node $v$, the procedure does the following: - Print $v$. - Traverse the list of neighbors of the node $v$ in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node $u$ if you came to node $v$ directly from $u$.
We binary search on the answer, so we need to answer queries of the following form: is the a depth-first search traversal such that the first $k$ vertices all have value at least $v$? We can answer this with a greedy tree-DP: for each subtree, we compute whether or not all its vertices have value at least $v$, and if not, the longest possible prefix with all values at least $v$. Then, our transition function can be greedy: the maximum possible prefix with all values at least $v$ is the sum of the sizes of all child subtrees which are all at least $v$ plus the largest prefix of all child subtrees. Runtime: $O(n\log(n))$
[ "binary search", "dfs and similar", "dp", "graphs", "greedy", "trees" ]
2,600
null
627
E
Orchestra
Paul is at the orchestra. The string section is arranged in an $r × c$ rectangular grid and is filled with violinists with the exception of $n$ violists. Paul really likes violas, so he would like to take a picture including at least $k$ of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take. Two pictures are considered to be different if the coordinates of corresponding rectangles are different.
We can think of a rectangle in the grid as a pair of an $(xlo, xhi)$ interval and a $(ylo, yhi)$ interval. Suppose we fix the $x$-interval and want to determine the number of corresponding $y$ intervals which create rectangles containing at least $k$ violists. Given a sorted list of the $y$-coordinates of all violists in the range, this is simple: $m$ violists split the $y$-coordinates into $m + 1$ (possibly empty) intervals that span all the columns, and the number of total intervals that work is simply the number of pairs of points that are at least $k$ intervals apart. As we sweep over the $xhi$ coordinate and maintain the list of violists, we want to insert each violist into a sorted list and look at its $k$ nearest neighbors to determine the change in number of intervals. Inserting violists into a sorted list, however, is difficult to do in constant time. Instead, we sweep in reverse. Start with $xhi = r$ and a linked list containing all the desired violists; decrementing $xhi$ is now a simple process of removing the necessary elements from a linked list and examining their neighbors as we do so. Runtime: $O(r^{2}k + rnk)$
[ "two pointers" ]
3,000
null
627
F
Island Puzzle
A remote island chain contains $n$ islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of $n - 1$ bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position.
First, if we never move the empty pedestal through any cycle, then moving the empty pedestal to and from any given position cannot change the location of the statues, as performing a move in the opposite direction as the previous undoes the previous move. Thus, in our graph with one cycle, we can only do the following two operations: move the empty pedestal from one location to another (without loss of generality, only using the original tree), and cyclically permute the elements along the one cycle (except the element closest to the root). Now, to check satisfiability, we can greedily first move the empty pedestal from its start position to its end position -- since this procedure can be undone, it will never change the satisfiability of the rearrangement. Then, we only have to check that all changed elements lie on a possible cycle. This uniquely determines the edge to be added. To compute the minimum number of moves, we compute the minimum moves to move the empty pedestal from the start to the cycle, the minimum moves to permute the cycle as desired, and the minimum moves from the cycle to the end point. Runtime: $O(n)$
[ "dfs and similar", "dsu", "graphs", "trees" ]
3,400
null
628
A
Tennis Tournament
A tennis tournament with $n$ participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out. The tournament takes place in the following way (below, $m$ is the number of the participants of the current round): - let $k$ be the maximal power of the number $2$ such that $k ≤ m$, - $k$ participants compete in the current round and a half of them passes to the next round, the other $m - k$ participants pass to the next round directly, - when only one participant remains, the tournament finishes. Each match requires $b$ bottles of water for each participant and one bottle for the judge. Besides $p$ towels are given to each participant for the whole tournament. Find the number of bottles and towels needed for the tournament. Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).
Here you can simply model the process. Or you can note that after each match some player drops out. In total $n - 1$ players will drop out. So the first answer is $(n - 1) * (2b + 1)$. Obviously the second answer is $np$. Complexity: $O(log^{2}n)$, $O(logn)$ or $O(1)$ depends on the realization.
[ "implementation", "math" ]
1,000
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint n, b, p;\n\ninline bool read() {\n\treturn !!(cin >> n >> b >> p);\n}\n\ninline void solve() {\n\tint x = 0, y = n * p;\n\twhile (n > 1) {\n\t\tint k = 1;\n\t\twhile (k * 2 <= n) k *= 2;\n\t\tx += (k / 2) * (2 * b + 1);\n\t\tn -= k / 2;\n\t}\n\tcout << x << ' ' << y << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
628
B
New Skateboard
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by $4$. You are given a string $s$ consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by $4$. A substring can start with a zero. A substring of a string is a nonempty sequence of consecutive characters. For example if string $s$ is 124 then we have four substrings that are divisible by $4$: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
The key observation is that the number is divisible by $4$ if and only if its last two digits forms a number divisible by $4$. So to calculate the answer at first we should count the substrings of length one. Now let's consider pairs of consecutive digits. If they forms a two digit number that is divisible by $4$ we should increase the answer by the index of the right one. Complexity: $O(n)$.
[ "dp" ]
1,300
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nstring s;\n\ninline bool read() {\n\treturn !!getline(cin, s);\n}\n\ninline void solve() {\n\tli ans = 0;\n\tforn(i, sz(s)) {\n\t\tint d = int(s[i] - '0');\n\t\tif (d % 4 == 0) ans++;\n\t\tif (i) {\n\t\t\tint pd = int(s[i - 1] - '0');\n\t\t\tif ((pd * 10 + d) % 4 == 0)\n\t\t\t\tans += i;\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
628
C
Bear and String Distance
Limak is a little polar bear. He likes \textbf{nice} strings — strings of length $n$, consisting of lowercase English letters only. The distance between two letters is defined as the difference between their positions in the alphabet. For example, $\operatorname{dist}(\mathbf{c},\mathbf{e})=\operatorname{dist}(\mathbf{e},\mathbf{c})=2$, and $\operatorname{dist}(\mathbf{a},\mathbf{z})=\operatorname{dist}(\mathbf{z},\ \mathbf{a})=25$. Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, $\operatorname{dist}(\operatorname{af.\;db})=\operatorname{dist}(\operatorname{a.\;d})+\operatorname{dist}(\mathbf{f},\,\mathbf{b})=3+4=7$, and $\mathrm{dist(bear.\roar)}=16+10+0+0=26$. Limak gives you a nice string $s$ and an integer $k$. He challenges you to find any nice string $s'$ that $\operatorname{dist}(\mathbf{s},\mathbf{s}^{\prime})=k$. Find any $s'$ satisfying the given conditions, or print "-1" if it's impossible to do so. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
There is no solution if the given required distance is too big. Let's think what is the maximum possible distance for the given string $s$. Or the more useful thing - how to construct a string $s'$ to maximize the distance? We can treat each letter separately and replace it with the most distant letter. For example, we should replace 'c' with 'z', and we should replace 'y' with 'a'. To be more precise, for first 13 letters of the alphabet the most distant letter is 'z', and for other letters it is 'a'. Let's solve a problem now. We can iterate over letters and greedily change them. A word "greedily" means when changing a letter we don't care about the next letters. We generally want to choose distant letters, because we may not find a solution otherwise. For each letter $s_{i}$ we change it into the most distant letter, unless the total distance would be too big. As we change letters, we should decrease the remaining required distance. So, for each letter $s_{i}$ consider only letters not exceeding the remaining distance, and among them choose the most distant one. If you don't see how to implement it, refer to my C++ solution with comments. Complexity: $O(n)$.
[ "greedy", "strings" ]
1,300
"// Bear and String Distance, by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int nax = 1e6 + 5;\nchar s[nax];\n\nint main() {\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\tscanf(\"%s\", s);\n\tfor(int i = 0; i < n; ++i) {\n\t\t// we want to change s[i]\n\t\tchar best_letter = s[i]; // by default we don't change it at all\n\t\tint best_distance = 0;\n\t\tfor(char maybe = 'a'; maybe <= 'z'; ++maybe) {\n\t\t\tint distance = abs(maybe - s[i]);\n\t\t\t// we must check if \"distance <= k\" because we don't want to exceed the total distance\n\t\t\t// among letters with \"distance <= k\" we choose the most distant one\n\t\t\tif(distance <= k && distance > best_distance) {\n\t\t\t\tbest_distance = distance;\n\t\t\t\tbest_letter = maybe;\n\t\t\t}\n\t\t}\n\t\tk -= best_distance; // we decrease the remaining distance\n\t\ts[i] = best_letter;\n\t}\n\tassert(k >= 0);\n\t// we found a correct s' only if \"k == 0\"\n\tif(k > 0) puts(\"-1\");\n\telse printf(\"%s\\n\", s);\n\treturn 0;\n}\n"
628
D
Magic Numbers
Consider the decimal presentation of an integer. Let's call a number d-magic if digit $d$ appears in decimal presentation of the number on even positions and nowhere else. For example, the numbers $1727374$, $17$, $1$ are 7-magic but $77$, $7$, $123$, $34$, $71$ are not 7-magic. On the other hand the number $7$ is 0-magic, $123$ is 2-magic, $34$ is 4-magic and $71$ is 1-magic. Find the number of d-magic numbers in the segment $[a, b]$ that are multiple of $m$. Because the answer can be very huge you should only find its value modulo $10^{9} + 7$ (so you should find the remainder after dividing by $10^{9} + 7$).
Denote the answer to the problem $f(a, b)$. Note that $f(a, b) = f(0, b) - f(0, a - 1)$ or what is the same $f(a, b) = f(0, b) - f(0, a) + g(a)$, where $g(a)$ equals to one if $a$ is a magic number, otherwise $g(a)$ equals to zero. Let's solve the problem for the segment $[0, n]$. Here is described the standard technique for this kind of problems, sometimes it is called 'dynamic programming by digits'. It can be realized in a two ways. The first way is to iterate over the length of the common prefix with number $n$. Next digit should be less than corresponding digit in $n$ and other digits can be arbitrary. Below is the description of the second approach. Let $z_{ijk}$ be the number of magic prefixes of length $i$ with remainder $j$ modulo $m$. If $k = 0$ than the prefix should be less than the corresponding prefix in $n$ and if $k = 1$ than the prefix should be equal to the prefix of $n$ (it can not be greater). Let's do 'forward dynamic programming'. Let's iterate over digit $p={\overline{{0,9}}}$ in position $i$. We should check that if the position is even than $p$ should be equal to $d$, otherwise it cannot be equal to $d$. Also we should check for $k = 1$ $p$ should be not greater than corresponding digit in $n$. Now let's see what will be the next state. Of course $i' = i + 1$. By Horner scheme $j' = (10j + p) mod m$. Easy to see that $k^{\prime}=l\wedge[p=n_{i}]$. To update the next state we should increase it: $z_{i'j'k'} + = z_{ijk}$. Of course all calculations should be done modulo $10^{9} + 7$. Complexity: $O(nm)$.
[ "dp" ]
2,200
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nint m, d;\nstring a, b;\n\ninline bool read() {\n\tif (!(cin >> m >> d)) return false;\n\tassert(cin >> a >> b);\n\treturn true;\n}\n\nconst int mod = 1000 * 1000 * 1000 + 7;\n\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\ninline void inc(int& a, int b) { a = add(a, b); }\ninline int sub(int a, int b) { return a - b < 0 ? a - b + mod : a - b; }\ninline void dec(int& a, int b) { a = sub(a, b); }\n\nconst int N = 2020;\n\nint z[N][N][2];\n\nint solve(string s) {\n\tint n = sz(s);\n\tforn(i, n + 1) forn(j, m) forn(k, 2) z[i][j][k] = 0;\n\tz[0][0][1] = 1;\n\tforn(i, n)\n\t\tforn(j, m)\n\t\t\tforn(k, 2)\n\t\t\t\tfor (int p = 0; p <= (k ? int(s[i] - '0') : 9); p++) {\n\t\t\t\t\tif ((i & 1) && p != d) continue;\n\t\t\t\t\tif (!(i & 1) && p == d) continue;\n\t\t\t\t\tif (!i && !p) continue;\n\t\t\t\t\tint ni = i + 1;\n\t\t\t\t\tint nj = (j * 10 + p) % m;\n\t\t\t\t\tint nk = k && (p == int(s[i] - '0'));\n\t\t\t\t\tinc(z[ni][nj][nk], z[i][j][k]);\n\t\t\t\t}\n\tint ans = 0;\n\tforn(k, 2) inc(ans, z[n][0][k]);\n\treturn ans;\n}\n\nbool good(string s) {\n\tint rm = 0;\n\tforn(i, sz(s)) {\n\t\tint p = int(s[i] - '0');\n\t\tif ((i & 1) && p != d) return false;\n\t\tif (!(i & 1) && p == d) return false;\n\t\trm = (rm * 10 + p) % m;\n\t}\n\treturn !rm;\n}\n\ninline void solve() {\n\tint ans = 0;\n\tinc(ans, solve(b));\n\tdec(ans, solve(a));\n\tinc(ans, good(a));\n\tcout << ans << endl;\n}\n\ninline ld gett() { return ld(clock()) / CLOCKS_PER_SEC; }\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tld stime = gett();\n\t\tsolve();\n\t\tcerr << gett() - stime << endl;\n\t}\n\t\n return 0;\n}"
628
E
Zbazi in Zeydabad
A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad). The country Zeydabad is a rectangular table consisting of $n$ rows and $m$ columns. Each cell on the country is either 'z' or '.'. The tourist knows this country is named Zeydabad because there are lots of ''Z-pattern"s in the country. A ''Z-pattern" is a square which anti-diagonal is completely filled with 'z' and its upper and lower rows are also completely filled with 'z'. All other cells of a square can be arbitrary. Note that a ''Z-pattern" can consist of only one cell (see the examples). So he wants to count the number of ''Z-pattern"s in the country (a necessary skill for Zbazi). Now your task is to help tourist with counting number of ''Z-pattern"s. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
The problem was suggested by Ali Ahmadi Kuzey. Let's precalculate the values $zl_{ij}, zr_{ij}, zld_{ij}$ - the maximal number of letters 'z' to the left, to the right and to the left-down from the position $(i, j)$. It's easy to do in $O(nm)$ time. Let's fix some cell $(i, j)$. Consider the value $c = min(zl_{ij}, zld_{ij})$. It's the maximum size of the square with upper right ceil in $(i, j)$. But the number of z-patterns can be less than $c$. Consider some cell $(x, y)$ diagonally down-left from $(i, j)$ on the distance no more than $c$. The cells $(i, j)$ and $(x, y)$ forms z-pattern if $y + zr_{xy} > j$. Let's maintain some data structure for each antidiagonal (it can be described by formula $x + y$) that can increment in a point and take the sum on a segment (Fenwick tree will be the best choice for that). Let's iterate over columns $j$ from the right to the left and process the events: we have some cell $(x, y)$ for which $y + zr_{xy} - 1 = j$. In that case we should increment the position $y$ in the tree number $x + y$ by one. Now we should iterate over the cells $(x, y)$ in the current column and add to the answer the value of the sum on the segment from $j - c + 1$ to $j$ in the tree number $i + j$ . Complexity: $O(nmlogm)$.
[ "data structures", "implementation" ]
2,300
"#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define pb(a) push_back(a)\n#define mp(x, y) make_pair((x), (y))\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\n\nconst int N = 3030;\n\nint n, m;\nchar a[N][N];\n\ninline bool read() {\n\tif (!(cin >> n >> m)) return false;\n\tassert(gets(a[0]));\n\tforn(i, n) assert(gets(a[i]));\n\treturn true;\n}\n\ninline void inc(int* t, int i, int v) {\n\tfor ( ; i < m; i |= i + 1) t[i] += v;\n}\ninline int sum(int* t, int i) {\n\tint ans = 0;\n\tfor ( ; i >= 0; i = (i & (i + 1)) - 1)\n\t\tans += t[i];\n\treturn ans;\n}\ninline int sum(int* t, int i, int j) { return sum(t, j) - sum(t, i - 1); }\n\nint zl[N][N], zld[N][N], zr[N][N];\nint t[2 * N][N];\nvector<pt> ev[N];\n\ninline void solve() {\n\tnfor(i, n)\n\t\tforn(j, m)\n\t\t\tif (a[i][j] == '.')\n\t\t\t\tzl[i][j] = zld[i][j] = 0;\n\t\t\telse {\n\t\t\t\tzl[i][j] = zld[i][j] = 1;\n\t\t\t\tif (j > 0) zl[i][j] += zl[i][j - 1];\n\t\t\t\tif (j > 0 && i + 1 < n) zld[i][j] += zld[i + 1][j - 1];\n\t\t\t}\n\n\tforn(i, n)\n\t\tnfor(j, m)\n\t\t\tif (a[i][j] == '.')\n\t\t\t\tzr[i][j] = 0;\n\t\t\telse {\n\t\t\t\tzr[i][j] = 1;\n\t\t\t\tif (j + 1 < m) zr[i][j] += zr[i][j + 1];\n\t\t\t}\n\n\tforn(j, m) ev[j].clear();\n\tforn(i, n) forn(j, m) if (zr[i][j]) ev[j + zr[i][j] - 1].pb(pt(i, j));\n\n\tforn(i, n + m) forn(j, m) t[i][j] = 0;\n\n\tli ans = 0;\n\tnfor(j, m) {\n\t\tforn(i, sz(ev[j])) {\n\t\t\tint x = ev[j][i].x;\n\t\t\tint y = ev[j][i].y;\n\t\t\tinc(t[x + y], y, +1);\n\t\t}\n\t\tforn(i, n) {\n\t\t\tint c = min(zl[i][j], zld[i][j]);\n\t\t\tif (!c) continue;\n\t\t\tans += sum(t[i + j], j - c + 1, j);\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef SU1\n assert(freopen(\"input.txt\", \"rt\", stdin));\n //assert(freopen(\"output.txt\", \"wt\", stdout));\n#endif\n \n cout << setprecision(10) << fixed;\n cerr << setprecision(5) << fixed;\n\n while (read()) {\n\t\tsolve();\n\t\t//break;\n\t}\n\t\n return 0;\n}"
628
F
Bear and Fair Set
Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve. It's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set: - The elements of the set are distinct positive integers. - The number of elements in the set is $n$. The number $n$ is divisible by $5$. - All elements are between $1$ and $b$, inclusive: bears don't know numbers greater than $b$. - For each $r$ in ${0, 1, 2, 3, 4}$, the set contains exactly $\begin{array}{l}{{\frac{n}{5}}}\end{array}$ elements that give remainder $r$ when divided by $5$. (That is, there are $\begin{array}{l}{{\frac{n}{5}}}\end{array}$ elements divisible by $5$, $\begin{array}{l}{{\frac{n}{5}}}\end{array}$ elements of the form $5k + 1$, $\begin{array}{l}{{\frac{n}{5}}}\end{array}$ elements of the form $5k + 2$, and so on.) Limak smiles mysteriously and gives you $q$ hints about his set. The $i$-th hint is the following sentence: "If you only look at elements that are between $1$ and $upTo_{i}$, inclusive, you will find exactly $quantity_{i}$ such elements in my set." In a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear? Given $n$, $b$, $q$ and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair". Otherwise, print ''unfair".
At the beginning, to make things simpler, we should add a query (hint) with $upTo = b, quantity = n$, and then sort queries by $upTo$. Sorted queries (hints) divide interval $[1, b]$ into $q$ disjoint intervals. For each interval we know how many elements should be there. Let's build a graph and find a max flow there. The answer is "YES" only if the flow is $n$. Each vertex from $A$ should be connected with the source by an edge with capacity $n / 5$. Each vertex from $B$ should be connected with the sink by an edge with capacity equal to the size of the interval. Between each vertex $x$ from $A$ and $y$ from $B$ should be an edge with capacity equal to the number of numbers in the interval $y$, giving remainder $x$ when divided by $5$. You can also use see that it's similar to finding matching. In fact, we can use the Hall's marriage theorem. For each of $2^{5}$ sets of vertices from $A$ (sets of remainders) iterate over intervals and count how many numbers we can take from $[1, b]$ with remainders from the fixed set of remainders. Complexity: $O(2^{C}n)$. In our problem $C = 5$.
[ "flows", "graphs" ]
2,500
"// Bear and Fair Set, by Errichto\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int K = 5;\n\nvoid NO() {\n\tputs(\"unfair\");\n\texit(0);\n}\n\nint main() {\n\tint n, b, q;\n\tscanf(\"%d%d%d\", &n, &b, &q);\n\tvector<pair<int,int>> w;\n\tw.push_back(make_pair(b, n));\n\twhile(q--) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tw.push_back(make_pair(a, b));\n\t}\n\tsort(w.begin(), w.end());\n\t// use the Hall's theorem\n\t// check all 2^K sets of remainders\n\tfor(int mask = 0; mask < (1 << K); ++mask) {\n\t\tint at_least = 0, at_most = 0;\n\t\t\n\t\tint prev_upto = 0, prev_quan = 0;\n\t\tfor(pair<int,int> query : w) {\n\t\t\tint now_upto = query.first, now_quan = query.second;\n\t\t\tint places_matching = 0; // how many do give remainder from \"mask\"\n\t\t\tint places_other = 0;\n\t\t\tfor(int i = prev_upto + 1; i <= now_upto; ++i) {\n\t\t\t\tif(mask & (1 << (i % K)))\n\t\t\t\t\t++places_matching;\n\t\t\t\telse\n\t\t\t\t\t++places_other;\n\t\t\t}\n\t\t\tif(now_quan < prev_quan) NO();\n\t\t\tint quan = now_quan - prev_quan;\n\t\t\tint places_total = now_upto - prev_upto;\n\t\t\tassert(places_total == places_matching + places_other);\n\t\t\tif(quan > places_total) NO();\n\t\t\t\n\t\t\tat_least += max(0, quan - places_other);\n\t\t\tat_most += min(quan, places_matching);\n\t\t\t\n\t\t\tprev_upto = now_upto;\n\t\t\tprev_quan = now_quan;\n\t\t}\n\t\t\n\t\t// \"mask\" represents a set of popcount(mask) remainders\n\t\t// their total degree is (n/K)*popcount(mask)\n\t\tint must_be = n / K * __builtin_popcount(mask);\n\t\tif(!(at_least <= must_be && must_be <= at_most)) NO();\n\t}\n\tputs(\"fair\");\t\t\n\treturn 0;\n}\n"
629
A
Far Relative’s Birthday Cake
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird! The cake is a $n × n$ square consisting of equal squares with side length $1$. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be? Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
Consider that we have $row_{i}$ chocolates in the $i'th$ row and $col_{i}$ chocolates in the $i'th$ column. The answer to the problem would be: $\sum_{i=1}^{n}{\binom{r o w_{i}}{2}}+{\binom{c o l_{i}}{2}}$. It is obvious that every pair would be calculated exactly once (as we have no more than one chocolate in the same square) Time Complexity: $O(n^{2})$
[ "brute force", "combinatorics", "constructive algorithms", "implementation" ]
800
// TODO : Choose an Appropriate Name!! // We're not here because we're free. We're here because we are not free. // The Matrix Reloaded (2003) #include <bits/stdc++.h> using namespace std; #define MohammadAmin main() #define mpair make_pair #define endl " " #define c_false ios_base::sync_with_stdio(false); cin.tie(0) #define pushb push_back #define pushf push_front #define popb pop_back #define popf pop_front #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define X first #define Y second #define ashar(a) cout << fixed << setprecision((a)) #define reset(a,b) memset(a, b, sizeof(a)) #define for0(a, n) for (int (a) = 0; (a) < (n); (a)++) #define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++) typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ld, ld> pdd; const int INF = 0x3f3f3f3f, MOD = 1e9 + 7; const int n_ = 1e5 + 1000; ll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );} ll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;} ll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;} int n, col[200], row[200], ans; string s[200]; int C(int n) { return n * (n-1) / 2; } int MohammadAmin { c_false; cin >> n; for(int i = 0; i < n; i++) { cin >> s[i]; for(int j = 0; j < n; j++) { row[i] += s[i][j] == 'C'; col[j] += s[i][j] == 'C'; } } for(int i = 0; i < n; i++) { ans += C(row[i]) + C(col[i]); } cout << ans << endl; return 0; }
629
B
Far Relative’s Problem
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has $n$ friends and each of them can come to the party in a specific range of days of the year from $a_{i}$ to $b_{i}$. Of course, Famil Door wants to have as many friends celebrating together with him as possible. Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party. Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Consider that we have $boy_{i}$ males in the $i'th$ day of the year and $girl_{i}$ females in the $i'th$ day of the year. These arrays can be filled easily when you are reading the input (See the code). Then for the $i'th$ day of the year, we could have $2$ * $min$($boy_{i}$ , $girl_{i}$) people which could come to the party. The answer would be maximum of this value between all days $i$ ($1 \le i \le 366$) Time Complexity: $O$($366$*$n$)
[ "brute force" ]
1,100
// TODO : Choose an Appropriate Name!! // We're not here because we're free. We're here because we are not free. // The Matrix Reloaded (2003) #include <bits/stdc++.h> using namespace std; #define MohammadAmin main() #define mpair make_pair #define endl " " #define c_false ios_base::sync_with_stdio(false); cin.tie(0) #define pushb push_back #define pushf push_front #define popb pop_back #define popf pop_front #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define X first #define Y second #define ashar(a) cout << fixed << setprecision((a)) #define reset(a,b) memset(a, b, sizeof(a)) #define for0(a, n) for (int (a) = 0; (a) < (n); (a)++) #define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++) typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ld, ld> pdd; const int INF = 0x3f3f3f3f, MOD = 1e9 + 7; const int n_ = 1e5 + 1000, days = 366 + 100; ll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );} ll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;} ll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;} int n, a[n_], b[n_], girl[days], boy[days], ans = 0, day = 1; char s[n_]; int MohammadAmin { c_false; cin >> n; for(int i = 0; i < n; i++) { cin >> s[i] >> a[i] >> b[i]; for(int d = a[i]; d <= b[i]; d++) { if (s[i] == 'M') boy[d]++; else girl[d]++; } } for(int i = 1; i < days; i++) { if (ans < 2 * min(boy[i], girl[i])) { ans = 2 * min(boy[i], girl[i]); day = i; } } cout << ans << endl; return 0; }
629
C
Famil Door and Brackets
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length $n$ more than any other strings! The sequence of round brackets is called valid if and only if: - the total number of opening brackets is equal to the total number of closing brackets; - for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string $s$ of length $m$ ($m ≤ n$) and want to complete it to obtain a valid sequence of brackets of length $n$. He is going to pick some strings $p$ and $q$ consisting of round brackets and merge them in a string $p + s + q$, that is add the string $p$ at the beginning of the string $s$ and string $q$ at the end of the string $s$. Now he wonders, how many \textbf{pairs} of strings $p$ and $q$ exists, such that the string $p + s + q$ is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo $10^{9} + 7$.
This problem can be solved with dynamic programming: $1$. Calculate $dp_{i, j}$ : How many sequences of brackets of length $i$ has balance $j$ and intermediate balance never goes below zero (They form a prefix of a valid sequence of brackets). $2$. For the given sequence of length $n$ calculate the resulting balance $a$ and the minimum balance $b$. $3$. Try the length of the sequence added at the beginning $c$ and its balance $d$. If $- b \le d$ then add $dp_{c, d} \times dp_{m - n - c, d + a}$ to the answer. Time complexity: $O((n - m)^{2})$
[ "dp", "strings" ]
2,000
// TODO : Choose an Appropriate Name!! // We're not here because we're free. We're here because we are not free. // The Matrix Reloaded (2003) #include <bits/stdc++.h> using namespace std; #define MohammadAmin main() #define mpair make_pair #define endl " " #define c_false ios_base::sync_with_stdio(false); cin.tie(0) #define pushb push_back #define pushf push_front #define popb pop_back #define popf pop_front #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define X first #define Y second #define ashar(a) cout << fixed << setprecision((a)) #define reset(a,b) memset(a, b, sizeof(a)) #define for0(a, n) for (int (a) = 0; (a) < (n); (a)++) #define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++) typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ld, ld> pdd; const int INF = 0x3f3f3f3f, MOD = 1e9 + 7; const int n_ = 5000; ll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );} ll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;} ll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;} ll n, m, dp[n_][n_], ans; int minB, b; string s; int MohammadAmin { c_false; cin >> n >> m; cin >> s; dp[0][0] = 1; for(int i = 1; i <= n-m; i++) { dp[i][0] = dp[i-1][1]; for(int j =1; j <= i; j++) { dp[i][j] = dp[i-1][j+1] + dp[i-1][j-1]; dp[i][j] %= MOD; } } for(int i = 0; i < m; i++) { if (s[i] == '(') b++; else b--; minB = min(b, minB); } for(int c = 0; c <= n-m; c++) { for(int d = 0; d <= c; d++) { if (d >= -minB) { if (d + b <= n-m && d + b >= 0) ans += dp[c][d] * dp[n - m - c][d + b] % MOD; ans %= MOD; } } } cout << ans << endl; return 0; }
629
D
Babaei and Birthday Cake
As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake. Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has $n$ simple cakes and he is going to make a special cake placing some cylinders on each other. However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number $i$ can be placed only on the table or on some cake number $j$ where $j < i$. Moreover, in order to impress friends Babaei will put the cake $i$ on top of the cake $j$ only if the volume of the cake $i$ is strictly greater than the volume of the cake $j$. Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.
First of all, we calculate the volume of each cake: $v_{i}$ = $ \pi \times h_{i} \times r_{i}^{2}$. Now consider the sequence $v_{1}$, $v_{2}$, $v_{3}$, ..., $v_{n}$ : The answer to the problem is the maximum sum of elements between all increasing sub-sequences of this sequence. How do we solve this? First to get rid of the decimals we can define a new sequence $a_{1}$, $a_{2}$, $a_{3}$, ..., $a_{n}$ such that $a_{i}={\frac{v_{i}}{\pi}}=h_{i}\times r_{i}^{2}$ We consider $dp_{i}$ as the maximum sum between all the sequences which end with $a_{i}$ and $dp_{i}$ = $\operatorname*{max}(a_{i},\operatorname*{max}_{j<i,a_{i}\leq a_{i}}d p[j]+a_{i})$ The answer to the problem is: $ \pi \times max_{i = 1}^{n}dp[i]$ Now how do we calculate $d p[i]=\mathrm{max}(a_{i},\mathrm{max}_{j<i,a,\leq a_{i}}\,d p[j]+a_{i})$ ? We use a max-segment tree which does these two operations: $1$. Change the $i't$ member to $v$. $2$. Find the maximum value in the interval $1$ to $i$. Now we use this segment tree for the array $dp$ and find the answer. Consider that $a_{1}$, $a_{2}$, $a_{3}$, ..., $a_{n}$ is sorted. We define $b_{i}$ as the position of $a_{i}$. Now to fill $dp_{i}$ we find the maximum in the interval $[1, b_{i})$ in segment and we call it $x$ and we set the $b_{i}$ th index of the segment as $a_{i} + x$. The answer to the problem would the maximum in the segment in the interval [1,n] Time complexity: $O(nlgn)$
[ "data structures", "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; #define MohammadAmin main() #define mpair make_pair #define endl " " #define c_false ios_base::sync_with_stdio(false); cin.tie(0) #define pushb push_back #define pushf push_front #define popb pop_back #define popf pop_front #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define X first #define Y second #define ashar(a) cout << fixed << setprecision((a)) #define reset(a,b) memset(a, b, sizeof(a)) #define for0(a, n) for (int (a) = 0; (a) < (n); (a)++) #define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++) typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ld, ld> pdd; const int INF = 0x3f3f3f3f, MOD = 1e9 + 7; const int n_ = 1e5 + 1000; const ld PI = acos(-1.0); ll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );} ll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;} ll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;} int n; ll q[4 * n_], dp[n_]; pair<ll, int> a[n_]; void update(int idx, ld x, int id = 1, int b = 0, int e = n) { if (idx < b || idx >= e) return; if (idx == b && e - b == 1) { q[id] = dp[b] = x; return; } int mid = b + e >> 1, l = id << 1, r = l | 1; if (idx < mid) { update(idx, x, l, b, mid); }else{ update(idx, x, r, mid, e); } q[id] = max(q[l], q[r]); } ll query(int ql, int qr, int id = 1, int b = 0, int e = n) { if (ql >= e || qr <= b) return 0; if (ql <= b && e <= qr) return q[id]; int mid = b + e >> 1, l = id << 1, r = l | 1; return max( query(ql, qr, l, b, mid), query(ql, qr, r, mid, e) ); } int MohammadAmin { c_false; cin >> n; for(int i = 0; i < n; i++) { ll r, h; cin >> r >> h; a[i].X = r * r * h; a[i].Y = -i; } sort(a, a+n); for(int i = 0; i < n; i++) { int idx = -a[i].Y; ll curr = a[i].X; dp[idx] = query(0, idx) + curr; update(idx, dp[idx]); } ashar(9); cout << PI * query(0, n) << endl; return 0; }
629
E
Famil Door and Roads
Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are $n$ intersections in the city connected by $n - 1$ bidirectional roads. There are $m$ friends of Famil Door living in the city. The $i$-th friend lives at the intersection $u_{i}$ and works at the intersection $v_{i}$. Everyone in the city is unhappy because there is exactly one simple path between their home and work. Famil Door plans to construct exactly one new road and he will randomly choose one among $n·(n - 1) / 2$ possibilities. Note, that he may even build a new road between two cities that are already connected by one. He knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both $u_{i}$ and $v_{i}$. Moreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both $u_{i}$ and $v_{i}$ if we consider only cases when such a cycle exists.
First of all, we assume that the tree is rooted! For this problem, first we need to compute some values for each vertex $u$: $qd_{u}$ and $qu_{u}$, $cnt_{u}$ , $par_{u, i}$ and $h_{u}$. $qd_{u}$ equals to the expected value of length of paths which start from vertex $u$, and ends in $u$'s subtree and also has length at least 1. $qu_{u}$ equals to the expected value of length of paths which start from vertex $u$, and not ends in $u$'s subtree and also has length at least 1. to calculate this values we can use one dfs for $qd$, and one other dfs for $qu$. \ $cnt_{u}$ is the number of vertices in $u$'s subtree except $u$, $par_{u, i}$ is the $2^{i}$ 'th ancestor of $u$ and finally $h_{u}$ is the height of the vertex $u$. \ in first dfs (lets call it dfsdown) we can calculate $qd$, $cnt$ and $par$ array with this formulas: $c n t_{u}=\sum c n t_{v}+1$ $q d_{u}=\sum{\frac{c n_{t}x q a_{t}}{c n t a}}+1$ for ecah $v$ as child of $u$ and $par_{u, i}$ = $par_{paru, i - 1, i - 1}$ in second dfs (lets call it dfsup) we calculate $qu$ using this formula (for clearer formula, I may define some extra variables): there are two cases: $u$ is the only child of its parent: let $n e w c n t={\frac{1}{n-c n t u-1}}$ then $q u_{u}={\frac{q u_{p}\times(n-c n t_{p}-1)+n-c n t_{p}}{n e w e n t}}$ \ $u$ is not the only child of its parent: let $n e w c n t={\frac{1}{c n t_{p}-c n t_{u}-1}}$ $c n t d={\frac{1}{n e w c n t}}$ $n o u={\frac{q d_{p}\times c n t_{p}-q d_{u}\times c n t_{u}-c n t_{u}-1}{n e w e n t_{u}-c n t_{u}}}$ $f r a c={\frac{1}{n-c n t_{n}-1}}$ then $q u[u]={\frac{c n t d\times n o u+q u_{p}\times(n-c n t_{p}-1)+n-c n t_{u}-1}{f r a c}}$ now we should process the queries. For each query $u$ and $v$, we have to cases: one of the vertices is either one of the ancestors of the other one or not! In the first case, if we define $w$ the vertex before $u$ ($u$ is assumed to be the vertex with lower height). In the path from $v$ to $u$, the answer is $\frac{c n t_{w}\times(n-c n t_{w}-1)\times q d_{w}+(n-c n t_{w}-1)\times q u_{w}}{(c n t_{w}+1)\times(c n t_{w}+1)\times q u_{w}}+h_{w}-h_{u}$ . In the second case, if we assume $w = LCA(u, v)$, then answer is ${\frac{c n t_{u}\times(c n t_{v}+1)\times q d_{u}+c n t_{v}\times(c n t_{u}+1)\times q d_{v}}{(c n t_{v}+1)\times(c n t_{u}+1)}}+h[v]+h[u]-2\times h[w]+1$ To check if $u$ is one of ancestors of $v$, you can check if their $LCA$ equals to $u$ or you can use dfs to find out their starting and finishing time. $u$ is an ancestor of $v$ if the interval of starting and finishing time of $v$ is completely inside starting and finishing time of $u$ The time complexity for the whole solution is $O(n + mlgn)$ ($O(n)$ for dfs and $O(lgn)$ for each query so $O(mlgn)$ for queries!).
[ "combinatorics", "data structures", "dfs and similar", "dp", "probabilities", "trees" ]
2,300
// TODO : Choose an Appropriate Name!! // We're not here because we're free. We're here because we are not free. // The Matrix Reloaded (2003) #include <bits/stdc++.h> using namespace std; #define MohammadAmin main() #define mpair make_pair #define endl " " #define c_false ios_base::sync_with_stdio(false); cin.tie(0) #define pushb push_back #define pushf push_front #define popb pop_back #define popf pop_front #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define X first #define Y second #define ashar(a) cout << fixed << setprecision((a)) #define reset(a,b) memset(a, b, sizeof(a)) #define for0(a, n) for (int (a) = 0; (a) < (n); (a)++) #define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++) typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ld, ld> pdd; const int INF = 0x3f3f3f3f, MOD = 1e9 + 7; const int n_ = 1e5 + 1000, lg_ = 20; ll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );} ll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;} ll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;} ll n, m, par[n_][lg_], cnt[n_], st[n_], fi[n_], ti; ll h[n_]; ld qd[n_], qu[n_]; vector<int> e[n_]; void dfs(int u, int p = -1) { st[u] = ti++; h[u] = ~p ? h[p]+1 : 0; par[u][0] = p; bool leaf = 1; for(int i = 1; i < lg_; i++) { if (~par[u][i-1]) { par[u][i] = par[ par[u][i-1] ][i-1]; } } for(auto v : e[u]) { if (v != p) { leaf = 0; dfs(v, u); cnt[u] += cnt[v] + 1; } } for(auto v : e[u]) { if (v != p) { qd[u] += 1.0 * cnt[v] / cnt[u] * qd[v]; } } if (!leaf) qd[u] += 1; fi[u] = ti++; } void dfs_d(int u, int p = -1) { if (~p) { ld cntd = cnt[p] - cnt[u] - 1, nou, kcntd, kasr; if (cntd == 0) { kcntd = 1.0 / (n - cnt[u] - 1); qu[u] = qu[p] * kcntd * (n - cnt[p] - 1) + (n - cnt[p]) * kcntd; }else{ kcntd = 1.0 / cntd; nou = qd[p] * kcntd * cnt[p] - qd[u] * kcntd * cnt[u] - cnt[u] * kcntd - kcntd; kasr = 1.0 / (n - cnt[u] - 1); qu[u] = cntd * kasr * nou + qu[p] * kasr * (n - cnt[p] - 1) + 1; } } for(auto v : e[u]) { if (v != p) { dfs_d(v, u); } } } int ispar(int u, int v) { return st[u] <= st[v] && fi[v] <= fi[u]; } int up(int u, int d) { for(int i = lg_ - 1; i >= 0; i--) { if (d >> i & 1) { u = par[u][i]; } } return u; } int lca(int u, int v) { if (h[u] < h[v]) swap(u, v); u = up(u, h[u] - h[v]); if (u == v) return u; for(int i = lg_ - 1; i >= 0; i--) { if (par[u][i] != par[v][i]) { u = par[u][i], v = par[v][i]; } } return par[u][0]; } ld query(int u, int v) { if (h[u] > h[v]) swap(u, v); if (ispar(u, v)) { int w = up(v, h[v] - h[u] - 1); ld cn = 1.0 / (cnt[v] + 1) / (n - cnt[w] - 1); // ans = // cnt[v] * qd[v] * (n - cnt[w] - 1) + (n - cnt[w] - 1) * qu[w] * (cnt[v] + 1) // ans /= cn ld ans = cnt[v] * (n - cnt[w] - 1) * cn * qd[v] + (n - cnt[w] - 1) * (cnt[v] + 1) * cn * qu[w]; return ans + h[v] - h[u]; } int w = lca(u, v); ld cn = 1.0 / (cnt[u] + 1) / (cnt[v] + 1); // ans = // (cnt[v] + 1) * qd[u] * cnt[u] + (cnt[u] + 1) qd[v] * cnt[v]; // ans /= cn; ld ans = cnt[u] * (cnt[v] + 1) * cn * qd[u] + cnt[v] * (cnt[u] + 1) * cn * qd[v]; return h[u] - h[w] + h[v] - h[w] + ans + 1; } int MohammadAmin { c_false; cin >> n >> m; for(int i = 0; i < n-1; i++) { int u, v; cin >> u >> v; u--, v--; e[u].pushb(v); e[v].pushb(u); } dfs(0); dfs_d(0); ashar(8); while(m--) { int u, v; cin >> u >> v; cout << query(--u, --v) << endl; } return 0; }
630
A
Again Twenty Five!
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number $5$ to the power of $n$ and get last two digits of the number. Yes, of course, $n$ can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions." Could you pass the interview in the machine vision company in IT City?
The problem of getting the last two digits is equivalent to the problem of getting the number modulo $100$. So we need to calculate $\scriptstyle{{\hat{\mathbb{P}}}^{n}}\mathrm{~IIDd}\mathrm{~}|\mathbb{O}$. According to the rules of modular arithmetic $(a\cdot b)\,\,\,\,\mathrm{mod}\,\,c=((a\,\,\,\mathrm{mod}\,\,c)\cdot(b\,\,\,\,\mathrm{mod}\,\,c))\,\,\,\,\mathrm{mod}\,\,c$ So $5^{n}\mathrm{\mod\100}=\left((5^{n-1}\mathrm{\mod\100}\right)\cdot5\right)\mathrm{\mod\100}\cdot5\right)$ Let's note that $5^{2} = 25$. Then $5^{3}\mod100=((5^{2}\mod100)\cdot5)\mod100=(25\cdot5)\mod100=(25\cdot5)\mod100=25$ $5^{4}\mathrm{\mod\100}=((5^{3}\mathrm{\mod\100})\cdot5)\mathrm{\mod\100}=(25\cdot5)\mathrm{\mod\100}=(25\cdot5)\mathrm{\mod\100}=25\cdot5\cdot5\cdot\mathrm{\mod\2000}$ And so on. All $\scriptstyle{{\hat{\mathbb{P}}}^{n}}\ 1{\mathrm{Dod}}\ 1{\hat{0}}$ are equal to $25$ for all $n \ge 2$. So to solve the problem one need to just output 25. There is no need to read $n$.
[ "number theory" ]
800
null
630
B
Moore's Law
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time. Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every $24$ months. The implication of Moore's law is that computer performance as function of time increases exponentially as well. You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly $1.000000011$ times.
Every second the number is multiplied by $1.000000011$. Multiplication several times to the same number is equivalent to exponentiation. So the formula is $n \cdot 1.000000011^{t}$ ($1.000000011$ raised to the power of $t$ and then multiplied to $n$). In a program one should not use a loop to calculate power as it is too slow for such big $n$, usually a programming language provides a function for exponentiation such as pow.
[ "math" ]
1,200
null