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
⌀ |
|---|---|---|---|---|---|---|---|
91
|
E
|
Igloo Skyscraper
|
Today the North Pole hosts an Olympiad in a sport called... toy igloo skyscrapers' building!
There are $n$ walruses taking part in the contest. Each walrus is given a unique number from $1$ to $n$. After start each walrus begins to build his own igloo skyscraper. Initially, at the moment of time equal to $0$, the height of the skyscraper $i$-th walrus is equal to $a_{i}$. Each minute the $i$-th walrus finishes building $b_{i}$ floors.
The journalists that are reporting from the spot where the Olympiad is taking place, make $q$ queries to the organizers. Each query is characterized by a group of three numbers $l_{i}$, $r_{i}$, $t_{i}$. The organizers respond to each query with a number $x$, such that:
1. Number $x$ lies on the interval from $l_{i}$ to $r_{i}$ inclusive ($l_{i} ≤ x ≤ r_{i}$).
2. The skyscraper of the walrus number $x$ possesses the maximum height among the skyscrapers of all walruses from the interval $[l_{i}, r_{i}]$ at the moment of time $t_{i}$.
For each journalists' query print the number of the walrus $x$ that meets the above-given criteria. If there are several possible answers, print any of them.
|
We are given the array where the value in each cell is described by the formula depends on T $val_{i} = a_{i} + b_{i} * T$ (in geometry mean it is a line equation). Lt's divide the array in blocks of size $d$ ~ $sqrt(n)$: $[0;d)$, $[d, d * 2)$, $[d * 2, d * 3)$, ..., $[d * k, n)$. Now let's precalculate for each block time moments when the leader of the block changes. So as we have line equation we can perform an intersection of half planes. On $Oy$ axis values of the cells are marked and the time moments marked on $Ox$ axis. we are interested on $x$ coordinate of points of intersections and number of leader after time $x$. So now we know time moment of leader changing for every block. For each block it takes $O(d * log(d))$ time. The number of blocks ($k$) is about $n / d$ ~ $n / sqrt(n)$ ~ $sqrt(n)$ so all the process will take $O(n * log(n))$ time. Let's sort all queries by increasing $t_{i}$. Now we should to perform queries one by one. Brute all blocks which lay into the query interval. For each such block we will keep up the leader for current time. For this let's process all the time moment of leader changing until $t_{i}$ inclusively and relax leader on the current block. The time moments which ware processed should be erased, they are not keep any useful information ,because all queries sorted by $t_{i}$. Let's process all cells which were not covered by the processed blocks but covered by the query and relax the leader for the query. The number of erasing time moments of leader changing is not mere then n and every query need $O(sqrt(n))$ time to calculate answer without erasing time moments. So the complexity of algorithm is $O(n * log(n) + m * sqrt(n))$. Interval tree also can be used to solve this problem. Such solution has complexity $O(n * log(n))$, but $O(n * log(n))$ memory.
|
[
"data structures",
"geometry"
] | 2,500
| null |
92
|
A
|
Chips
|
There are $n$ walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number $2$ sits to the left of the walrus number $1$, the walrus number $3$ sits to the left of the walrus number $2$, ..., the walrus number $1$ sits to the left of the walrus number $n$.
The presenter has $m$ chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number $1$ and moving clockwise. The walrus number $i$ gets $i$ chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given $n$ and $m$ how many chips the presenter will get in the end.
|
In these problems you should only realize what was written is the statement.
|
[
"implementation",
"math"
] | 800
| null |
92
|
B
|
Binary Number
|
Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer $x$ and wants to get a number one from it. While $x$ is not equal to $1$, Fangy repeats the following action: if $x$ is odd, then he adds $1$ to it, otherwise he divides $x$ by $2$. Fangy knows that for any positive integer number the process ends in finite time.
How many actions should Fangy perform to get a number one from number $x$?
|
In these problems you should only realize what was written is the statement. In problem B wasn't recommended to use BigInteger in Java because of slow speed.
|
[
"greedy"
] | 1,300
| null |
93
|
A
|
Frames
|
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, $m$ icons can fit in a horizontal row in any window.
Igor K.'s computer contains $n$ folders in the D: disk's root catalog. The folders are numbered from $1$ to $n$ in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from $a$ to $b$ inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from $a$ to $b$ and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
|
The problem is easy, but there were many tricky cases - and contestants show it successful :) I added almost all these cases to the pretests because I didn't want to arrange Beta Round 60. So let's solve the problem. At first notice that the answer is not greater than 3 because we always can do three selections (maybe, some of them are empty): with first selection we select end of the first row, with second one - begin of the last row, and with last one - all remaining folders (they form the rectangle). The best way is to find all cases with answer 1 and 2. Try to do it. If the answer is 1, we can select all folders from $a$ to $b$ with one selection. There must be nothing hard to detect these cases: first and last folders are in the same row (21 5 7 9); first folder is in the first column, and the last folder - in the last column (21 5 1 15), case $m = 1$ is included here; first folder is in the first column, and the last folder is $n$ (21 5 6 21). Case when we must select all folders is included here. I was very surprised when I saw that many contestants forgot about it. And these are the cases with answer 2: first and last folders are in the adjacent rows (21 5 8 14); first folder is in the first column (21 5 6 13); last folder is in the last column (21 5 4 15); last folder is $n$ (21 5 4 21); and another tricky case: if the column where first folder is located is just at right from the column where the last column is located (21 5 3 12). If no one of these conditions is true, answer is 3.
|
[
"implementation"
] | 1,700
| null |
93
|
B
|
End of Exams
|
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!
Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the $m$ friends found $n$ different kinds of milk on the menu, that's why they ordered $n$ bottles — one bottle of each kind. We know that the volume of milk in each bottle equals $w$.
When the bottles were brought in, they decided to pour all the milk evenly among the $m$ cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?
Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!
Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.
|
Greedy algorithm solves this problem. We should consecutively try to pour milk from each bottle into each available cup and in maximal possible amount. Also we always need to know, how much milk is in each bottle and each cup, for each cup - bottles from which we have poured milk, and for each bottle - cups into which we have poured milk. Writing it is not hard. But where is one special moment - if we compare real numbers, we must use EPS, or we can get WA on test 12 (50 1000 49). Some programs write NO on this test while answer is YES, because of wrong comparing of real numbers. It must be said that answer can be calculated in integers: just set the volume of milk in each bottle $mn$. And only when we will print the answer, we divide each volume by $mn$ and multiply by $w$. All three jury solutions didn't think up this :)
|
[
"greedy"
] | 1,900
| null |
93
|
C
|
Azembler
|
After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "Azembler. Principally New Approach".
Having carefully thumbed through the book, Igor K. realised that, as it turns out, you can multiply the numbers dozens of times faster. "Search Ultimate will be faster than it has ever been!" — the fellow shouted happily and set to work.
Let us now clarify what Igor's idea was. The thing is that the code that was generated by a compiler was far from perfect. Standard multiplying does work slower than with the trick the book mentioned.
The Azembler language operates with 26 registers (eax, ebx, ..., ezx) and two commands:
- [$x$] — returns the value located in the address $x$. For example, [eax] returns the value that was located in the address, equal to the value in the register eax.
- lea $x$, $y$ — assigns to the register $x$, indicated as the first operand, the second operand's address. Thus, for example, the "lea ebx, [eax]" command will write in the ebx register the content of the eax register: first the [eax] operation will be fulfilled, the result of it will be some value that lies in the address written in eax. But we do not need the value — the next operation will be lea, that will take the [eax] address, i.e., the value in the eax register, and will write it in ebx.
On the first thought the second operation seems meaningless, but as it turns out, it is acceptable to write the operation as
lea ecx, [eax + ebx],
lea ecx, [k*eax]
or even
lea ecx, [ebx + k*eax],
where k = 1, 2, 4 or 8.
As a result, the register ecx will be equal to the numbers eax + ebx, k*eax and ebx + k*eax correspondingly. However, such operation is fulfilled many times, dozens of times faster that the usual multiplying of numbers. And using several such operations, one can very quickly multiply some number by some other one. Of course, instead of eax, ebx and ecx you are allowed to use any registers.
For example, let the eax register contain some number that we should multiply by 41. It takes us 2 lines:
lea ebx, [eax + 4*eax] // now ebx = 5*eax
lea eax, [eax + 8*ebx] // now eax = eax + 8*ebx = 41*eax
Igor K. got interested in the following question: what is the minimum number of lea operations needed to multiply by the given number $n$ and how to do it? Your task is to help him.
Consider that at the initial moment of time eax contains a number that Igor K. was about to multiply by $n$, and the registers from ebx to ezx contain number 0. At the final moment of time the result can be located in any register.
|
I don't know why so few coders have solved it. Small limitations for $n$ and big time limit - 5 seconds - hint that it's backtracking. Also, no need to be a soothsayer to understand that maximal answer is about 5. Solving it is clear. You should keep all current registers at the vector and call some function that goes over all current registers and calculate new values, then calls itself recursively. In that process we can also save the program itself. To avoid TLE you should not make recursive calls if the deep of recursion is larger than current answer, should not go to the states where you get a number larger than $n$ or less than current biggest number. And if you reach exactly $n$, you should update answer and copy the program to the safe place. There are some hacks to speed up this approach: for example, iterate over numbers in descending order (it works faster), but 5 seconds is such TLE that you can solve it any way. Or you can launch backtracking for the specific answer (increasing it) while the program won't be found (I don't know how this method is named in English). Also, some contestants have solved it using BFS.
|
[
"brute force",
"implementation"
] | 2,500
| null |
93
|
D
|
Flags
|
When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the condition... actually, it doesn't matter. Igor K. quickly found the formula and got the so passionately desired Accepted.
However, the professor wasn't very much impressed. He decided that the problem represented on Timmy's Online Judge was very dull and simple: it only had three possible colors of flag stripes and only two limitations. He suggested a complicated task to Igor K. and the fellow failed to solve it. Of course, we won't tell anybody that the professor couldn't solve it as well.
And how about you? Can you solve the problem?
The flags consist of one or several parallel stripes of similar width. The stripes can be one of the following colors: white, black, red or yellow. You should find the number of different flags with the number of stripes from $L$ to $R$, if:
- a flag cannot have adjacent stripes of one color;
- a flag cannot have adjacent white and yellow stripes;
- a flag cannot have adjacent red and black stripes;
- a flag cannot have the combination of black, white and red stripes following one after another in this or reverse order;
- symmetrical flags (as, for example, a WB and a BW flag, where W and B stand for the white and black colors) are considered the same.
|
I think my solution is not optimal, it's too long. Many solutions submitted during the contest are shorter. But I tell you about my solution. At first I solve the problem for the number of stripes equals $N$ (or $L = R$). Let $f\left(N\right)$ is the number of flags with exactly $N$ stripes where symmetrical flags are not identical. Try to get the answer using this designation. At first sight it seems that answer is $\frac{f(N)}{2}$. But it's not true for the palindromes. For example, for non-palindromes WBWB and BWBW we should count only one of them, but for the palindromes, such as WBW, it leads to mistake, because each palindrome is symmetrical to itself. So for the flags with even number of stripes formula $a n s\left(N\right)=\frac{f(N)}{2}$ is correct, because there are not palindromes among them. And if $N$ is odd, the correct formula is $a n s\left(N\right)=\frac{f(N)+p(N)}{2}$, where $p\left(N\right)$ is the number of palindromes with $N$ stripes. Each palindrome is definited by its first $\textstyle{\frac{N+1}{2}}$ stripes, and we can write that $p\left(N\right)=f\left(\frac{N+1}{2}\right)$. Now we can give an answer if we know how to calculate number of flags where symmetrical flags are not equal. Notice that if we know two last stripes of the flag, we can definitely say if we can add another stripe to its end. Let's use dynamic programming. As a state we can take a vector $x(N)$ with a length 8 where each its component keeps a number of flags with $N$ stripes and definite two last colors (exactly 8 options). And $f\left(N\right)=\sum_{i=1}^{8}x_{i}$ is total number of flags with $N$ stripes. As start state we can take vector $x\left(2\right)$ which consists of ones (because there are 8 flags with a length 2, one flag for one possible combination of two colors). And how to calculate $x(N)$? It turns out that there is some matrix $A$ that $x\left(N\right)=A x\left(N-1\right)$. Its elements can be found even using pen and paper: for example, let's we have a combination of two last stripes WB. Then it's possible to add white or yellow stripe to the end, and the last stripes will be BW and BY correspondingly. It means that we can write $1$ to the matrix where the row are BW or BY and the column is WB. We're about the finish. It's obvious that $x\left(N\right)=A^{N-2}x\left(2\right)$. Power of matrix can be calculated with a logarithmic time - that's because our problem is solved. And don't forget if $N = 1$ then answer is $4$ and there's no need to do these calculations. But it was only problem where $L = R$. Let's find a solution for the segment $[L, R]$. I know two ways to do it. First way is to add a new component to the vector and new row and column to the matrix. This new component should keep the total number on the segment $[2,R]$ (if $L = 1$, we can write "if" somewhere at the beginning of the program). And the matrix $A$ should be changed a bit: try to do it by yourself. I like the second way. As we did it earlier, we will find a number of flags where symmetrical ones are different, but on the segment $[L, R]$. It is equal to $x\left(L,R\right)=A^{L-2}\left(E+A+\cdot\cdot\cdot\cdot+A^{R-L}\right)x\left(2\right)$. Let's learn how to calculate the sum $E + A + ... + A^{N}$ quickly. Let $b$ is such maximal power of $2$ that $2b - 1 \le N$. We can write $E+A+\cdot\cdot\cdot+A^{N}=E+A+\cdot\cdot\cdot+A^{2b-1}+A^{2b}\left(E+A+\cdot\cdot\cdot+A^{N-2b}\right)$. And apply some math magic to the first part of the previous formula: $E+A+\cdot\cdot\cdot+A^{2b-1}=\left(E+A\right)\left(E+A^{2}\right)\left(E+A^{4}\right)\cdot\cdot\cdot\left(E+A^{b}\right)$. And the expression in the brackets at the second part of that formula is... I think you've already understood it :) We forgot about the palindromes, but it's very easy to calculate their number. Let's suppose that $L$ and $R$ are odd (if they are even, we can add one to $L$ and substract one from $R$). Then $p\left(L,R\right)=f\left({\frac{L+1}{2}},{\frac{R+1}{2}}\right)$. That's all. Don't forget to apply "mod" operation after each operation and examine border cases carefully.
|
[
"dp",
"math",
"matrices"
] | 2,500
| null |
93
|
E
|
Lostborn
|
Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible.
One day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with $k$ different numbers: $a_{1}, ..., a_{k}$. They are called hit indicators and according to the game developers' plan they are pairwise coprime.
The damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals $n$, than the inflicted damage will be calculated as the number of numbers on the segment $[1,n]$, that aren't divisible by any hit indicator $a_{i}$.
Recently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.
|
This problem can be solved using inclusion-exclusion principle. If $f_{a_{1}a_{2}...a_{k}}\left(n\right)$ is the answer, then the following formula works: $f_{a_{1}a_{2}...a_{k}}\left(n\right)=f_{a_{2}a_{3}...a_{k}}\left(n\right)-f_{a_{2}a_{3}...a_{k}}\left(\left|{\frac{n}{a_{1}}}\right|\right)$. But if you write only this recursive function, you get TLE. Many contestants got TLE and were hacked because they didn't run maximal test on their computers. And the others who sensed that something was wrong memorized the answers for small $n$ and all $a_{i}$.
|
[
"dp",
"math",
"number theory"
] | 2,600
| null |
94
|
A
|
Restoring Password
|
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code $80$ characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of $10$ characters stood for one decimal digit. Accordingly, the original password consisted of $8$ decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
|
Password was very easy to restore. You should just iterate over groups of 10 characters in the first string and over all codes. Then, if some number's code is equal to the group - print that number.
|
[
"implementation",
"strings"
] | 900
| null |
94
|
B
|
Friends
|
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something.
The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people"
Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" — he kept on repeating in his mind. — "Let's take, say, Max, Ilya, Vova — here, they all know each other! And now let's add Dima and Oleg to Vova — none of them is acquainted with each other! Now, that math is just rubbish!"
Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.
|
Let's construct the graph where vertices correspond to the people and edges correspond to the relationships. Then paint each edge in this way: edge will be red if the men connected by it are friends and black otherwise. Now let's think what is "three pairwise acquainted people" and "three pairwise unacquainted people". We see that they are cycles of only red and only black vertices correspondingly, and the length of these cycles is 3. Now we know the solution: write 3 "for" cycles, one cycle for one vertex, and check if the edges between these vertices are only red or only black. Another way to solve it is to notice the answer is FAIL if and only if graph has exactly 5 edges and they all together form a cycle with a length 5. It's very funny solution, I think.
|
[
"graphs",
"implementation",
"math"
] | 1,300
| null |
95
|
A
|
Hockey
|
Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name $w$ and the collection of forbidden substrings $s_{1}, s_{2}, ..., s_{n}$. All those strings consist of uppercase and lowercase Latin letters. String $w$ has the length of $|w|$, its characters are numbered from $1$ to $|w|$.
First Petya should find all the occurrences of forbidden substrings in the $w$ string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.
After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position $i$ should be replaced by any other one if for position $i$ in string $w$ there exist pair of indices $l, r$ ($1 ≤ l ≤ i ≤ r ≤ |w|$) such that substring $w[l ... r]$ is contained in the collection $s_{1}, s_{2}, ..., s_{n}$, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.
Letter $letter$ (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the $letter$ occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.
Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.
|
Let B[i] = true, if character in position i is in some substring of W which is in dictionary. For each B[i] = true, do next: \cdot If S[i] = letter and letter = 'a', then S[i] = 'b', \cdot If S[i] = letter and letter != 'a' then S[i] = 'a'; \cdot If S[i] != letter, then S[i] = letter.
|
[
"implementation",
"strings"
] | 1,600
| null |
95
|
B
|
Lucky Numbers
|
Petya loves lucky numbers. Everybody knows that positive integers are \underline{lucky} if their decimal representation doesn't contain digits other than $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.
Lucky number is \underline{super lucky} if it's decimal representation contains equal amount of digits $4$ and $7$. For example, numbers $47$, $7744$, $474477$ are super lucky and $4$, $744$, $467$ are not.
One day Petya came across a positive integer $n$. Help him to find the least super lucky number which is not less than $n$.
|
Notice, that answer will looks like this: to some position result will be equal with input string (that part must be lucky), next digit well be greater, the rest of digits are not important. That guarantees us that result will be greater than or equal to N. As rightest this position will be as number will be lesser. Some of the positions may not be ok to us. Let chosen position is i. Left part must be lucky. If S[i] < '4', we can assign S[i] = '4', then fill minimally right part. If S[i] < '7', we can assign '7' to it, like in prevision case. Call position i ok, if absolute different between number of '4' and '7' in part from 0 to i, inclusive is not more than n-i-1. If we chose some rightmost position, which is ok, now we must fill right part. How to do it? If we can assign to some position (we will fill them from left to right) '4' and this position is still ok, then we place '4', else we assign '7'. If there is no ok positions at all, resulting number will looks like this: 4444 \dots 7777, when number of digits 4 = number of digits 7 = (|N|+2)/2.
|
[
"dp",
"greedy"
] | 1,800
| null |
95
|
C
|
Volleyball
|
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has $n$ junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths.
Initially each junction has exactly one taxi standing there. The taxi driver from the $i$-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than $t_{i}$ meters. Also, the cost of the ride doesn't depend on the distance and is equal to $c_{i}$ bourles. Taxis can't stop in the middle of a road. \textbf{Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially.}
At the moment Petya is located on the junction $x$ and the volleyball stadium is on the junction $y$. Determine the minimum amount of money Petya will need to drive to the stadium.
|
At first in this simple problem you need to find shortest path between all pair of junctions. That can't be done using O(N^3) algorithms, so you must use Dijkstra algorithm to find this in O(N*N*logN) time. Next part of this problem is to create new matrix, G[i][j] = C[i], if D[i][j] <= R[i], else G[i][j] = INF. Here D[i][j] - length of shortest path between I and j. So, result is shortest path between X and Y using matrix G. That can be done using simple Dijkstra algorithm.
|
[
"shortest paths"
] | 1,900
| null |
95
|
D
|
Horse Races
|
Petya likes horse racing very much. Horses numbered from $l$ to $r$ take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A \underline{nearly lucky} number is an integer number that has at least two lucky digits the distance between which does not exceed $k$. Petya learned from some of his mates from Lviv that lucky digits are digits $4$ and $7$. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if $k = 2$, then numbers $412395497$, $404$, $4070400000070004007$ are nearly lucky and numbers $4$, $4123954997$, $4007000040070004007$ are not.
Petya prepared $t$ intervals $[l_{i}, r_{i}]$ and invented number $k$, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo $1000000007$ ($10^{9} + 7$).
|
Traditionally I remain that answer is Result(0..R) - Result(0..L-1). Let we have array DP[x][y][z] - number of x-digits number if last lucky digit was on position y, bool z (0 or 1) - was the pair of lucky digits with less than or equal distance then K (call it lucky pair)? Now, let S - string which represent number N. Let F(x, y, z) - result for substring of first x digits, y - position of last lucky digit, z - (0 or 1) - was the lucky pair before? Try to assign some digits on position x. If this digit is less than S[i], then add to result for F(x, y, z) DP[n-x-1][yy][zz] (yy - updated position of last lucky digit, zz - updated bool for lucky pairs). If this digit is equal to S[i], add F(x+1, yy, zz). DP can be calculated simply. Let from state (x, y, z) we place some digit d on position x. Then, we can go to state (x+1, yy, zz). Again, yy and zz - updated parameters. Complexity - O(T * |N}).
|
[
"dp",
"math"
] | 2,500
| null |
95
|
E
|
Lucky Country
|
Petya loves lucky numbers. Everybody knows that positive integers are \underline{lucky} if their decimal representation doesn't contain digits other than $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.
One night Petya was sleeping. He was dreaming of being the president of some island country. The country is represented by islands connected by two-way roads. Between some islands there is no road way, even through other islands, that's why the country is divided into several regions. More formally, each island belongs to exactly one region, there is a path between any two islands located in the same region; there is no path between any two islands from different regions. A region is lucky if the amount of islands in it is a lucky number.
As a real president, Petya first decided to build a presidential palace. Being a lucky numbers' fan, Petya wants to position his palace in one of the lucky regions. However, it is possible that initially the country has no such regions. In this case Petya can build additional roads between different regions, thus joining them. Find the minimum number of roads needed to build to create a lucky region.
|
Let A[i] - sorted array of sizes of different connection components, C[i] - number of connection components of size A[i]. Sum for all C[i]*A[i] is equal to N. Size of A will be O(sqrt(N)). Let all C[i] = (2^k)-1, i. e. C[i] = 1 + 2 + 4 + 8 + \dots + 2^(k-1). Obviously, that if chose some subset of this powers we can get any number from 0 to C[i], inclusive. So, the problem now is next: For each A[i] is log(C[i]) things (cost of this thing is size of subset that create it), each can be used at most once. This is standard "Knapsack" problem (read this). Complexity of this algorithm is O(N * S), when S is the sum for all log(C[i]). If C[i] is not power of 2, then we must find maximal k, which (2^k)-1 <= C[i] and add C[i]-((2^k)-1) to set.
|
[
"dp",
"dsu",
"graphs"
] | 2,500
| null |
96
|
A
|
Football
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least $7$ players of some team standing one after another, then the situation is considered dangerous. For example, the situation $00100110111111101$ is dangerous and $11110111011101$ is not. You are given the current situation. Determine whether it is dangerous or not.
|
In this problem you must find longest substring consisting of equal characters and compare it with 7.
|
[
"implementation",
"strings"
] | 900
| null |
96
|
B
|
Lucky Numbers (easy)
|
Petya loves lucky numbers. Everybody knows that positive integers are \underline{lucky} if their decimal representation doesn't contain digits other than $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.
Lucky number is \underline{super lucky} if it's decimal representation contains equal amount of digits $4$ and $7$. For example, numbers $47$, $7744$, $474477$ are super lucky and $4$, $744$, $467$ are not.
One day Petya came across a positive integer $n$. Help him to find the least super lucky number which is not less than $n$.
|
If the length of input number |N| is odd, then, obviously, resulting number will have length |N|+1 and will be like this: 4444 \dots 7777, at first (|N|+1)/2 digits 4, then the same number of 7's. If the number has even length, then, probably, resulting number will have size |N|, or |N|+2. So, length of the resulting number will have not more than 10 digits. So, we can recursive generate lucky numbers with size <= 10, take the smallest super lucky number which is greater than or equal to N.
|
[
"binary search",
"bitmasks",
"brute force"
] | 1,300
| null |
97
|
A
|
Domino
|
Little Gennady was presented with a set of domino for his birthday. The set consists of $28$ different dominoes of size $2 × 1$. Both halves of each domino contain one digit from $0$ to $6$.
\begin{verbatim}
0-0 0-1 0-2 0-3 0-4 0-5 0-6
1-1 1-2 1-3 1-4 1-5 1-6
2-2 2-3 2-4 2-5 2-6
3-3 3-4 3-5 3-6
4-4 4-5 4-6
5-5 5-6
6-6
\end{verbatim}
The figure that consists of $28$ dominoes is called \underline{magic}, if it can be fully covered with $14$ non-intersecting squares of size $2 × 2$ so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear — he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest.
Gennady chose a checked field of size $n × m$ and put there rectangular chips of sizes $1 × 2$ and $2 × 1$. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly $28$ chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round.
|
We need to assign some number from 0 to 6 to each of the 14 squares. Note that if you take the solution and apply some permutation of digits to the field, you obtain another correct solution. So, the solution is characterized by division of 14 squares to pairs. If we have such a partition, then it is possible to generate a 7! corresponding solutions. Count of possible partitions is $13!! = 13 \cdot 11 \cdot 9 \cdot 7 \cdot 5 \cdot 3 = 135135$ . It is easily to verify the correctness for each of the 100k options. With up to rotations, count of all field configurations that have solutions is about 6000. The largest number of solutions - $22 \cdot 7!$. 1) If you do not optimize the solution in $7!$ time, you can get a TL. As was shown in the comments it's enough to optimize $7$ times. 2) You would think that the squares are divided into two classes - 7 squares that have double dominoes, and 7, in which it is not present. If we talk in terms of graphs there are 7 vertices with degree 2, and 7 with degree of 4. Clearly, two vertices of degree 2 can not correspond to a single digit, otherwise we get two double dominoes. With this division is sufficient to iterate over 7! possible matches vertices of the second type to vertices of the first type. Double domino 4-4 split between the two squares. There are 6 vertices of degree 2 and 8 vertices of degree. Challenge Succeeded. Furthermore: Here for two double dominoes lie between squares! And bonus, one of the most beautiful configurations with several holes: Disconnected configuration with solutions don't exist :(
|
[
"brute force",
"implementation"
] | 2,400
| null |
97
|
D
|
Robot in Basement
|
The Professor has lost his home robot yet again. After some thinking Professor understood that he had left the robot in the basement.
The basement in Professor's house is represented by a rectangle $n × m$, split into $1 × 1$ squares. Some squares are walls which are impassable; other squares are passable. You can get from any passable square to any other passable square moving through edge-adjacent passable squares. One passable square is the exit from the basement. The robot is placed exactly in one passable square. Also the robot may be placed in the exit square.
Professor is scared of going to the dark basement looking for the robot at night. However, he has a basement plan and the robot's remote control. Using the remote, Professor can send signals to the robot to shift one square left, right, up or down. When the robot receives a signal, it moves in the required direction if the robot's neighboring square in the given direction is passable. Otherwise, the robot stays idle.
Professor wrote a sequence of $k$ commands on a piece of paper. He thinks that the sequence can lead the robot out of the basement, wherever it's initial position might be. Professor programmed another robot to press the required buttons on the remote according to the notes on the piece of paper. Professor was just about to run the program and go to bed, when he had an epiphany.
Executing each command takes some energy and Professor doesn't want to get huge electricity bill at the end of the month. That's why he wants to find in the sequence he has written out the minimal possible prefix that would guarantee to lead the robot out to the exit after the prefix is fulfilled. And that's the problem Professor challenges you with at this late hour.
|
A naive solution works in $O(nmk)$. This solution stores all the start positions into an array and next iterates over all commands and shifts positions in needed directions. After every move it checks that all positions lie on the exit cell. This solution doesn't fit into time limits. An author's solution speed up the naive solution with using of bit masks. All current positions of robot you should store in rectangular bit mask of size $n \times m$. This mask should provide following operations: 1. Shift left, right, up, down. 2. Binary operations AND and OR. 3. Compare with another mask. All these operations can be realized so that they will work in $O(nm / 32)$ time. You can use array of 32-bit integers of size $n \times m / 32$ or std::bitset in C++. How to emulate process? At first, you should create a mask base that has 1-bit for every passable cell and 0-bit otherwise. Now you should create sevaral additional masks for all four directions: up1, up2, left1, left2, down1, down2, right1, right2. Masks with index 1 store cells that lie near wall, ans masks with index 2 store all other cells of mask base. Also you should create mask E that has only one 1-bit in the exit cell. Let all current positions of robor are given by mask T. Split T into 2 sets of positions: all ones that lie near wall (the first set) and all other ones (the second set). Now you should shift all positions in the second set and next merge two sets into one. The finish set gives new mask T. This transformation in operations with masks looks like: T = ((T and up1) or shift_up(T and up2)); You can transform T analogically for other three directions. Now you should iterate over all commands and do transformations. On every step you should compare T with E. As soon as they are equal, you should output number of a command after that it happened. If always T and E are unequal, you should output -1. This solution has complexity $O(nmk / 32)$. Author's solutions on C++ and Java without any serious optimizations work in 0,9 sec and 2,3 sec correspondingly.
|
[
"bitmasks",
"brute force",
"implementation"
] | 2,700
| null |
98
|
A
|
Help Victoria the Wise
|
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.
The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)
Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.
|
In this problem you were required to find the number of sufficiently different colorings of a cube faces with predefined six colors. The most trivial solution is to introduce some ordering of the cube faces (say, 0 - front, 1 - back, 2 - up, 3 - down, 4 - left, 5 - right), then consider 720 = 6! arrangements of colors over these 6 faces. Each arrangement is some permutation of characters from the input. For each arrangement we find all its 24 rotations - and get 24 strings. Lexicographically smallest string will be representative of this coloring. The answer is the number of different representatives.
|
[
"brute force",
"implementation"
] | 1,700
| null |
98
|
B
|
Help King
|
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.
Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.
The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be $n$ noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to $1 / n$). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
|
Unfortunately, initial author's solution for this problem appeared wrong. However, the optimality of the below algo was proved by Knuth and Yao in 1976. Limitation for n in the problem now changed to 10000. The process of tossing a coin and making decisions regarding which alternative to choose may be naturally described as drawing some (possibly infinite) binary tree. Each toss "draws" two new branches from every free node of the tree (initially the tree consists of one free node). Whenever the number of free nodes becomes >= n, you turn n free nodes into leaves (onle leaf for each alternative), and proceed with the other free nodes in a similar way. For example, for n == 3 we get the following infitite tree: o / \ o o / \ / \ 1 2 3 o / \ ... ... Now we should evaluate expected length of a random path in this infinite tree now. One may notice that the tree is recursive: since the number of free nodes at every level is strictly less than n, the situation will repeat after maximum of n steps. Once one notices this, it is not so hard to derive formulas for the answer. Since numbers in the answer could be of the order 2^n, one needs to write "long arithmetics", or use Java.BigInteger.
|
[
"implementation",
"probabilities",
"trees"
] | 2,200
| null |
98
|
C
|
Help Greg the Dwarf
|
A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.
The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help.
You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to $a$ and $b$ correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to $l$ and $w$ ($l ≥ w$) correspondingly. Dwarf Greg has already determined the coffin's length ($l$), which is based on his height; your task is to determine the coffin's maximally possible width ($w$), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.
Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him...
|
For this problem I assumed numerical solution. But there are several cases to consider. Below without loss of generality we assume a <= b. 1. l <= a <= b. In this case the answer is restricted by the length of the coffin, so the answer is l and it is clear that the coffin l x l can be brought through the corridor (a, b) - let's denote corridor's sizes in this way. 2. a < l <= b. In this case the answer is a, and it is clear that no larger number can be an answer. Indeed, otherwise the coffin (w > a) x (l > a) is impossible to drag through the corridor (a, b). 3. a <= b < l. This is the most general case, where we should rotate the coffin inside the corridor where it has a kink. To maximise the width of the coffin, we want to move it in such a way that one corner of the coffin touches one outer wall of the corridor (suppose bottommost on the picture), and another corner adjacent to the same long side of the coffin touches another outer wall of the corridor (leftmost on the picture). Let's introduce coordinate system in such a way that bottommost wall be OX axis, and leftmost wall - OY axis. Suppose that during the "rotation" process one corner of the coffin is at the point (x,0) (0 <= x <= l), then another corner should be at the point (0,sqrt(l*l-x*x)). And the answer we search for is min {distance from the segment (x,0) - (0,sqrt(l*l-x*x)) to the point (a,b) }, where you take min{} over all 0 <= x <= l. Let this distance at point x be f(x). Since f(x*) is minimal in some point x* and increases everywere to the left and to the right from x*, one may use ternary search to find its minimum. Exact solution for this problem is also possible: you can reduce the problem to minimizing the dot product of the vectors (a-x,b) and (-x,sqrt(l*l-x*x)) over x. But this leads to the neccessity to find the roots of the fourth-degree polynomial, which is not the best idea during the contest.
|
[
"geometry",
"ternary search"
] | 2,500
| null |
98
|
D
|
Help Monks
|
In a far away kingdom is the famous Lio Shan monastery. Gods constructed three diamond pillars on the monastery's lawn long ago. Gods also placed on one pillar $n$ golden disks of different diameters (in the order of the diameters' decreasing from the bottom to the top). Besides, gods commanded to carry all the disks from the first pillar to the third one according to the following rules:
- you can carry only one disk in one move;
- you cannot put a larger disk on a smaller one.
There was no universal opinion concerning what is to happen after the gods' will is done: some people promised world peace and eternal happiness to everyone, whereas others predicted that the kingdom will face communi… (gee, what am I rambling about?) the Armageddon. However, as everybody knew that it was impossible to solve the problem in less than $2^{n} - 1$ moves and the lazy Lio Shan monks never even started to solve it, everyone lives peacefully even though the problem was never solved and nobody was afraid of the Armageddon.However, the monastery wasn't doing so well lately and the wise prior Ku Sean Sun had to cut some disks at the edges and use the gold for the greater good. Wouldn't you think that the prior is entitled to have an air conditioning system? Besides, staying in the monastery all year is sooo dull… One has to have a go at something new now and then, go skiing, for example… Ku Sean Sun realize how big a mistake he had made only after a while: after he cut the edges, the diameters of some disks got the same; that means that some moves that used to be impossible to make, were at last possible (why, gods never prohibited to put a disk on a disk of the same diameter). Thus, the possible Armageddon can come earlier than was initially planned by gods. Much earlier. So much earlier, in fact, that Ku Sean Sun won't even have time to ski all he wants or relax under the air conditioner.
The wise prior could never let that last thing happen and he asked one very old and very wise witch PikiWedia to help him. May be she can determine the least number of moves needed to solve the gods' problem. However, the witch laid out her cards and found no answer for the prior. Then he asked you to help him.
Can you find the shortest solution of the problem, given the number of disks and their diameters? Keep in mind that it is allowed to place disks of the same diameter one on the other one, however, the order in which the disks are positioned on the third pillar in the end should match the initial order of the disks on the first pillar.
|
This problem was about famous puzzle "Hanoi towers", but diameters of some discs might be equal. How to solve that? A good thing to do is to write BFS solution to check optimality of your ideas for small inputs (by the way, BSF works quickly for almost all towers that have up to 10 discs) and then try to create an algo which solves the puzzle in an optimal way. Let C (x1, x2, ..., xn) be a solution (under "solution" here we mean optimal number of moves - the moves itself is easy to get with one recursive procedure; also "solution" is the number of moves to move group of discs from one peg to any other (and not some particular) ) to the puzzle when we have a puzzle with x1 equal largest discs, x2 equal second largest discs and so on. And let U (x1, x2, ..., xn) be a solution to the puzzle when you are allowed not to save the order of the discs (you should still follow the restriction of the initial puzzle not to put larger discs onto the smaller ones, but at the end discs of the same diameter may be in any order). Then one of the optimal solutions to the problem is the following: C (x1, x2, ..., xn) = U (x1, x2, ..., xn) if x1 = 1 (*) C (x1, x2, ..., xn) = 2*x1 - 1 if n = 1 (**) C (x1, x2, ..., xn) = U (x2, ..., xn) + x1 + U (x2, ..., xn) + x1 + C (x2, ..., xn). (***) U (x1, x2, ..., xn) = U (x2, ..., xn) + x1 + U (x2, ..., xn) (****) Why so? One can notice that U() is "almost" solution for our problem: it "flips" order of the bottommost group of equal discs, the order of the rest of the discs remains the same! (try to understand why) That's why (*) is correct. The (**) is quite obvious. The (***) does the following: move (x2, ..., xn) from peg 1 to peg 2 without saving the order. Then move x1 equal discs from peg 1 to peg 3, then move (x2, ..., xn) from peg 2 to peg 1 without saving the order (but it occurs that after we apply U() to the same group of discs twice, the order restored!), then move x1 equal discs from peg 3 to peg 2, and then use C() to move (x2, ..., xn) from peg 1 to peg 2 (here we use C() since we should preserve the order). So, (***) is correct. And (****) is quite straightforward expression for U(): move all discs but the largest group with the same algo, then move largest discs (that's why if x1 > 1, the group of discs "flips"), and then move all discs but the largest group onto the same peg with x1.
|
[
"constructive algorithms"
] | 2,500
| null |
98
|
E
|
Help Shrek and Donkey
|
Shrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds $m$ cards and the Donkey holds $n$ cards (the players do not see each other's cards), and one more card lies on the table face down so that both players cannot see it as well. Thus, at the beginning of the game there are overall $m + n + 1$ cards. Besides, the players know which cards the pack of cards consists of and their own cards (but they do not know which card lies on the table and which ones the other player has). The players move in turn and Shrek starts. During a move a player can:
- Try to guess which card is lying on the table. If he guesses correctly, the game ends and he wins. If his guess is wrong, the game also ends but this time the other player wins.
- Name any card from the pack. If the other player has such card, he must show it and put it aside (so that this card is no longer used in the game). If the other player doesn't have such card, he says about that.
Recently Donkey started taking some yellow pills and winning over Shrek. Now Shrek wants to evaluate his chances to win if he too starts taking the pills.Help Shrek assuming the pills are good in quality and that both players using them start playing in the optimal manner.
|
This problem was about optimally playing this simple-at-first-glance game. The key thing to recognize in the statement was that it is not always optimal to name card which you don't have. Sometimes it is optimal to confuse the opponent by naming card which you have on hand. In this case... yes, he may think that the card you named is card on the table and lose during the next turn. Now the problem is to understand when to use the strategy of reduction of opponent's cards, when to bluff in the abovementioned sense and when to try to determine which card is on the table. But instead of "when" the right question is "how frequently" since we have nothing else but usual constant-sum matrix game, and optimal strategy is the mixture of these three. Let's construct a matrix first. Player 1 has three pure strategies: "playing" (when he plays the game and really tries to determine opponent's cards and card on the table), "guessing" (when he guesses which card is lying on the table) and "bluffing" (when he tries to confuse his opponent to force him to lose by naming card in his own hand). In turn, if the first player used "bluffing" strategy, or during the "playing" strategy named card on the table, his opponent has two strategies: "check" (i.e. to believe the first player that he doesn't own the card he named and guess it as the card on the table) and "move on" (i.e. to decide that it was a "bluffing" strategy and the game should be continued, but with notice that the first player has named card on hands). Let's denote P(m,n) probability to win the game when the first player has m cards and the second player has n cards. Then P(m,n) is the value of the matrix game with the following matrix (rows - strategies of the first player, two numbers in the rows - probabilities to win when the second player uses strategies "check" and "move on" correspondingly: "check" "move on" "playing" n/(n+1)*(1-P(n-1,m)) 1/(n+1) + n/(n+1)*(1-P(n-1,m)) "guessing" 1/(n+1) 1/(n+1) "bluffing" 1 1-P(n,m-1) How to get these numbers in the matrix? Consider the first row: "playing" strategy of the first player, "check" strategy of the second. First just names one of the n+1 cards. With probability 1/(n+1) he names card on the table, seconds checks it and wins (so, probability to with for the first is 0), with probability n/(n+1) the first names one of the cards on hands of the second player, so the game continues, second wins with prob. P(n-1,m) in this case. Then the overall probability for the first to win with such combination of pure strategies is n/(n+1)*(1-P(n-1,m)). In the same manner we fill other cells of the matrix. Finally we solve the game (this can be done straightforwardly, or with one formula if one notices that the "guessing" strategy is suboptimal everywhere when m>=1 and n>=1 and that the game doesn't have saddle points) and get answer to the problem - P(m,n). And the last thing to note: when m==0 it is clear that during his move the second wins, so the first should guess, and P(0,n) = 1/(n+1). When n==0 P(m,0)==1 sinse we just do one rightguessing.
|
[
"dp",
"games",
"math",
"probabilities"
] | 2,700
| null |
99
|
A
|
Help Far Away Kingdom
|
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly $0.273549107$ beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:
- If a number's integer part does not end with digit $9$ and its fractional part is strictly less than $0.5$, then the rounded up number coincides with the number’s integer part.
- If a number's integer part does not end with digit $9$ and its fractional part is not less than $0.5$, the rounded up number is obtained if we add $1$ to the last digit of the number’s integer part.
- If the number’s integer part ends with digit $9$, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.
Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?
|
Here the problem was to round a number up according to the usual mathematical rules with the exception that if the last digit of integer part is equal to 9, you should output "GOTO Vasilisa.". One may notice that to check whether number's fractional part is not less than 0.5 only one digit just after the decimal point should be analysed. If it is '5' or greater - add one to the last digit of the integer part, and the problem is solved. Probably, the simplest way to deal with the input data was using of the string variables.
|
[
"strings"
] | 800
| null |
99
|
B
|
Help Chef Gerasim
|
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.
To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
|
The problem was to accurately check what is required in the problem statement. First of all, check whether all volumes in the input are equal. In this case output "Exemplary pages.". Otherwise find two cups with largest and smallest volumes. Suppose their numbers are a and b, and their volumes are v[a] and v[b]. Now suppose that before pouring their volumes were equal to V. Then they contained 2V units of juice before (and after) pouring. So, you need to check whether (v[a] + v[b]) is divisible by 2. If this is not so - output "Unrecoverable confihuration.". Otherwise assign to the cups presumable old volume v[a] = v[b] = (v[a] + v[b])/2. Now if only one pouring have been made, volumes of juice in all cups should be equal, and you print corresponding message "... ml. from ... to ...". If volumes are not equal, print "Unrecoverable configuration" instead.
|
[
"implementation",
"sortings"
] | 1,300
| null |
101
|
A
|
Homework
|
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of $n$ small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than $k$ characters, it will be very suspicious.
Find the least number of distinct characters that can remain in the string after no more than $k$ characters are deleted. You also have to find any possible way to delete the characters.
|
Lets count up the number of entries to string of every letter. Let Gerald choose $x$ letter and lose them. Obvious thet if he lose $x$ rarest letters then overall number of losed letter do not increase, and then if he can lose some $x$ lettes, he can lose $x$ rarest ones. Thus it's easy to determine if Gerald can loses $x$ letters. And now to calculate the answer one only need to find the minimal such $x$, so Gerald can lose $x$ letters.
|
[
"greedy"
] | 1,200
| null |
101
|
B
|
Buses
|
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly $n + 1$ bus stops. All of them are numbered with integers from $0$ to $n$ in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number $0$ and the bus stop by the school has number $n$.
There are $m$ buses running between the house and the school: the $i$-th bus goes from stop $s_{i}$ to $t_{i}$ ($s_{i} < t_{i}$), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the $i$-th bus on any stop numbered from $s_{i}$ to $t_{i} - 1$ inclusive, but he can get off the $i$-th bus only on the bus stop $t_{i}$.
Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.
Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by $1000000007$ ($10^{9} + 7$).
|
For every slop from $0$ to $n$ lets calculate $k_{x}$ - number of ways come to them. Consider the $i$-th bus. Number of ways come to stop $t_{i}$ applied $i$-th bus is uqual to number of way to embus to $i$-th bus. One can embus to $i$-th bus on the stops $s_{i}, s_{i} + 1, ..., t_{i} - 1$. Thus number of ways come to stop $t_{i}$ in the $i$ bus is equal to sum $k_{si} + k_{si + 1} + ... + k_{ti - 1}$. Finally, lets note that overall number of way to come to stop $t_{i}$ is the sum of numbers of ways to come to stop $t_{i}$ on every bus. It's remained two problems. First problem: $0 \le n \le 10^{9}$. Therefore all $k_{x}$ not climb in memory limit. But we need to know only non-zero $k_{x}$. For instance, one can gripe coordinates: create list of all occured stops (and also stops $0$ and $n$), sort this list, delete the repeated stops and replace all numbers of stops they indexes in this list. After this operations all number of stops not exceed $200001$, and all $k_{x}$ are climb to the memory. Second problem: if we will use loop "for" for counting sum $k_{si} + k_{si + 1} + ... + k_{ti - 1}$, asymptotic of time of working will be O(m^2). There is an easy way to solve this problem: one can create and update array $sum[]$, such that $sum[i] = k[0] + k[1] + ... + k[i - 1]$, by another words, $sum[0] = 0, sum[i + 1] = sum[i] + k[i]$. Then munber of ways to come to stop $t_{i}$ using bus $i$ is equal to $sum[t_{i}] - sum[s_{i}]$. So time complexity is O(m \cdot log(m)), memory complexity is O(m).
|
[
"binary search",
"data structures",
"dp"
] | 1,700
| null |
101
|
C
|
Vectors
|
At a geometry lesson Gerald was given a task: to get vector $B$ out of vector $A$. Besides, the teacher permitted him to perform the following operations with vector $А$:
- Turn the vector by $90$ degrees clockwise.
- Add to the vector a certain vector $C$.
Operations could be performed in any order any number of times.
Can Gerald cope with the task?
|
Lets formulate the problem in complex number. Consider complex numbers $a = x_{A} + iy_{A}$, $b = x_{B} + iy_{B}$ and $c = x_{C} + iy_{C}$. One can do operation $A \rightarrow A + C$ and $A \rightarrow iA$. If we apply this transform some times in some order to $A$, we will get number $A \cdot i^{k} + aC + biC - cC - idC$ for some non-negative integers $k, a, b, c, d$ or, in another words, $A \cdot i^{k} + aC + biC$ for $k = 0, 1, 2, 3$ and some integers $a, b$. Since $k$ can be equal only $0$, $1$, $2$ or $3$, sufficiently to get to know is one can to represent $B - A$, $B - iA$, $B + A$ or $B + iA$ in the form of $aC + biC$. Then, how to determine, is one can to represent some complex number D in the such form? One can represent equation $D = aC + biC$ in the form of linear real equation system: $a \cdot x_{C} - b \cdot y_{C} = x_{D}$ $a \cdot y_{C} + b \cdot x_{C} = y_{D}$ To solve this system - is standart tehnical problem.
|
[
"implementation",
"math"
] | 2,000
| null |
101
|
D
|
Castle
|
Gerald is positioned in an old castle which consists of $n$ halls connected with $n - 1$ corridors. It is exactly one way to go from any hall to any other one. Thus, the graph is a tree. Initially, at the moment of time $0$, Gerald is positioned in hall $1$. Besides, some other hall of the castle contains the treasure Gerald is looking for. The treasure's position is not known; it can equiprobably be in any of other $n - 1$ halls. Gerald can only find out where the treasure is when he enters the hall with the treasure. That very moment Gerald sees the treasure and the moment is regarded is the moment of achieving his goal.
The corridors have different lengths. At that, the corridors are considered long and the halls are considered small and well lit. Thus, it is possible not to take the time Gerald spends in the halls into consideration. \textbf{The castle is very old, that's why a corridor collapses at the moment when somebody visits it two times, no matter in which direction.}
Gerald can move around the castle using the corridors; he will go until he finds the treasure. Naturally, Gerald wants to find it as quickly as possible. In other words, he wants to act in a manner that would make the average time of finding the treasure as small as possible. \textbf{Each corridor can be used no more than two times. That's why Gerald chooses the strategy in such a way, so he can visit every hall for sure.}
More formally, if the treasure is located in the second hall, then Gerald will find it the moment he enters the second hall for the first time — let it be moment $t_{2}$. If the treasure is in the third hall, then Gerald will find it the moment he enters the third hall for the first time. Let it be the moment of time $t_{3}$. And so on. Thus, the average time of finding the treasure will be equal to $\frac{t_{2}+t_{3}+\dots+t_{n}}{n-1}$.
|
Remunerate vertexes in such a way, that start Gerald vertex have got number $0$. Consider that vertex $0$ is the root of tree, and lets consider its children. Let Gerald first go to vertex $x$. Then he must to travel throw hole subtree, otherwise he will not visit all vertex in subtree. Then he come back to $0$ and go to some next its child. Lets try to calculate looked for value for hole tree when we know all subtree values. If we can to do it, we can solve problem using dynamyc programming on the tree. Lets vertex $0$ have $n$ children. Lets $i$-th subtree have $k_{i}$ offspring (inclusive $i$-th child of $0$). Let the hole tree consist of $N$ vertexes. Lets $T_{i}$ is the doubled sum of lenght all edges in $i$-th subtree, inclusive edge between $0$ and its $i$-th child. It is the time to travel throw hole $i$-th subtree, starting in $0$ and returning to $0$. Finally, lets $t_{i}$ is answer to problem on $i$-th subtree. At once we add to this time length of edge between $0$ and its $i$-th child. Lets Gerald travel throw all subtrees in order $1, 2, ..., n$. What is average time of finding the treasure? Treasure can be in first subtree with probability $\stackrel{k_{1}}{N}$. Then average time of finding the treasure will be $t_{1}$. Treasure can be in second subtree with probability $\stackrel{k_{2}}{N}$. Then average time of finding the treasure will be $T_{1} + t_{2}$. And so on. Thus, average time of finding the treasure will be ${\frac{1}{N}}\left((k_{1}t_{1}+k_{2}t_{2}+\cdots+k_{n}t_{n})+(k_{1}\cdot0+k_{2}T_{1}+k_{3}(T_{1}+T_{2})+\cdots+k_{n}(T_{1}+\cdots+T_{n-1}))\right)$ Can we decrease this time? Lets swap $i$ and $i + 1$ subtrees. Then item $k_{i + 1}T_{i}$ disappear from sum and appear item $k_{iT}_{i + 1}$. Sum will chenge to $k_{iT}_{i + 1} - k_{i + 1}T_{i}$. Sum will decrease, if $k_{iT}_{i + 1} - k_{i + 1}T_{i} < 0$, in ather words ${\frac{T_{i}}{k_{i}}}>{\frac{T_{i+1}}{k_{i+1}}}$. Therefore, one can't decrease average time, if subtrees are sorted by increasing value $\frac{T_{i}}{k_{i}}$. So, we must to sorted trees in this order and traveling from them in this order.
|
[
"dp",
"greedy",
"probabilities",
"sortings",
"trees"
] | 2,300
| null |
101
|
E
|
Candies and Stones
|
Little Gerald and his coach Mike play an interesting game. At the beginning of the game there is a pile consisting of $n$ candies and a pile consisting of $m$ stones. Gerald and Mike move in turns, Mike goes first. During his move Mike checks how many candies and stones Gerald has eaten. Let Gerald eat $a$ candies and $b$ stones. Then Mike awards Gerald $f(a, b)$ prize points. Gerald during his move either eats a candy from the pile of candies or a stone from the pile of stones. As Mike sees that Gerald has eaten everything apart one candy and one stone, he awards points for the last time and the game ends. Gerald is not allowed to eat all the candies, and he is not allowed to eat all the stones too. Tell Gerald how to play to get the largest possible number of points: it is required to find one of the possible optimal playing strategies for Gerald.
|
Essence of problem is that there is a board $n \times m$ in cell of wich placed numbers. And one must go from cell $(0, 0)$ to cell $(n - 1, m - 1)$, doing moves to one cell up and right (that is, increasing by $1$ on of coordinates), maximizing sum o number on the cell in the path. Gerald's problems is determine $m + n - 1$ cells of optimal path. Lets start with search one, middle cell. Lets $k={\frac{n+m-2}{2}}$. What cell of board can be $k$-th in path? It is cell, sum of coordinate of wich is equal to $k$, thus, it is diagonal of doard. And then we can calculate, what maximum sum Gerald can collect, came to every cell in the diagonal, by dynamic programming in lower triangle. And the same way, we can calculate, what maximum sum Gerald can collect, came to cell (n-1,m-1), starting from every cell in the diagonal. Sumed up this to values, we calculate, what maximum sum Gerald can collect, came to from cell $(0, 0)$ to cell $(n - 1, m - 1)$, travel throw every cell in the diagonal. And now we will find cell $(x, y)$, in wich maximum is reached. It is $k$-th cell of the path. We used time $O((n + m)^{2})$ and memory $O(n + m)$. Then we make recursive call on subproblems. In other word, will find optimal path from cell $(0, 0)$ to cell $(x, y)$ and from cell $(x, y)$ to cell $(n, m)$. It is evident, this solution take memory O(n+m). Why it tkae time O((n+m)^2)? Lets $n + m$ is $r$. Once we are find middle cell of path of length $k$. Twice we are find middle cell of path of length $\displaystyle{\frac{k}{2}}$. Four times we are find middle cell of path of length $\frac{k}{4}$. And so on. Therefore, time of program working will be $r^{2}+2{\frac{r^{2}}{4}}+4{\frac{r^{2}}{16}}+\cdot\cdot\cdot=r^{2}+{\frac{r^{2}}{2}}+{\frac{r^{2}}{4}}+\cdot\cdot\cdot=r^{2}+r^{2}$. Thus, this solution take time $O((n + m)^{2})$.
|
[
"divide and conquer",
"dp"
] | 2,500
| null |
102
|
A
|
Clothes
|
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.
Overall the shop sells $n$ clothing items, and exactly $m$ pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.
|
In this problem constraints are allow to look throw all triples of clothes. For every triple one can check if all elements of tripe areturn out to match with others, and anong those triples find one whith minimal cost.
|
[
"brute force"
] | 1,200
| null |
102
|
B
|
Sum of Digits
|
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number $n$. How many times can Gerald put a spell on it until the number becomes one-digit?
|
Initial number consist of no more then $100000$ digits. Therefore after first transform resulting number will be no more then $900000$, and then it will constist of no more then $6$ digits. Thus after next transform number will be no more then $54$ and so it will be two-digit or one-digit. Sum of digits of a two-digit number no more, then $18$, and sum of digit of such number no more, then $9$. Thus Gerald can't do nore, then $4$ transforms. First transform one can implement one simple pass throw symbols of given string. Following operations take very little time.
|
[
"implementation"
] | 1,000
| null |
103
|
A
|
Testing Pants for Sadness
|
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".
The test consists of $n$ questions; the questions are to be answered strictly in the order in which they are given, from question $1$ to question $n$. Question $i$ contains $a_{i}$ answer variants, exactly one of them is correct.
A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the $n$ questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question $1$ again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.
Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?
|
We can't move to the $i + 1$-th question before clicking all answers at $i$-th question. We will move to the very beginning clicking at $a_{i} - 1$ answers and only one will move us to the next step. Every way from beginning to $i$-th question have length equal to $i - 1$ plus one for click. There is a simple formula for $i + 1$-th question: $c_{i} = (a_{i} - 1) \cdot i + 1$, 1-based numeration. Let's summarize all values of $c_{i}$ for making the answer. Complexity is $O(n)$.
|
[
"greedy",
"implementation",
"math"
] | 1,100
| null |
103
|
B
|
Cthulhu
|
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with $n$ vertices and $m$ edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
|
Look at the formal part of statement. Cthulhu is a simple cycle with length of 3 or more and every vertix of the cycle should be a root of some tree. Notice this two important facts: a) Cthulhu is a connected graph b) Cthulhu is a graph with only cycle If we add only one edge to tree (not a multiedge nor loop) then we will get a graph that a) and b) properties. There is a simple solution: let's check graph for connectivity (we can do it by one DFS only) and check $n = m$ restriction. If all are ok then graph is Cthulhu. Complexity is $O(m)$.
|
[
"dfs and similar",
"dsu",
"graphs"
] | 1,500
| null |
103
|
C
|
Russian Roulette
|
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of $n$ bullet slots able to contain exactly $k$ bullets, now the boys have a chance to resolve the problem once and for all.
Sasha selects any $k$ out of $n$ slots he wishes and puts bullets there. Roma spins the cylinder so that every of $n$ possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.
Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.
More formally, the cylinder of $n$ bullet slots able to contain $k$ bullets can be represented as a string of $n$ characters. Exactly $k$ of them are "X" (charged slots) and the others are "." (uncharged slots).
Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.
Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each $x_{i}$ query must be answered: is there a bullet in the positions $x_{i}$?
|
Let's solve the problem when value $n$ is even. Obviously, if $k = 1$ we should put a bullet at most right position. For example, choose $n = 8$ and our answer string will be: .......X Let's find probability of winning at this situation. We will write zeros at losing positions and ones at winning positions: 10101010 The simple idea is to put every next bullet for non-dropping down our winning chance as long as we can. After that we should put bullets in lexicographically order with growing value of $k$. Look for the answer for another $k$'s with $n = 8$: .....X.X ...X.X.X .X.X.X.X .X.X.XXX .X.XXXXX .XXXXXXX XXXXXXXX When $n$ is odd our reasoning will be the same with a little bit difference at the beginning. Look at the answer with $n = 9$ and $k = 1$:: ........X 010101010 We may put second bullet as at even case. But there is exists another way, we may put our bullet at 1st position and turn left the cylinder, look here: X.......X => .......XX 010101010 101010100 Obvioulsy probability of winning was not changed but answer made better. Next steps of putting are equal to even case: .....X.XX ...X.X.XX .X.X.X.XX .X.X.XXXX .X.XXXXXX .XXXXXXXX XXXXXXXXX There is no difficulties to give answers to queries. Complexity is $O(p)$.
|
[
"constructive algorithms",
"greedy"
] | 1,900
| null |
103
|
D
|
Time to Raid Cowavans
|
As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space.
Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row.
If we number all cows in the cowavan with positive integers from $1$ to $n$, then we can formalize the popular model of abduction, known as the $(a, b)$-Cowavan Raid: first they steal a cow number $a$, then number $a + b$, then — number $a + 2·b$, and so on, until the number of an abducted cow exceeds $n$. During one raid the cows are not renumbered.
The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made $p$ scenarios of the $(a, b)$-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen.
|
Let's solve this problem by offline. Read all queries and sort them by increasing $b$. After that there are many effective solutions but I tell you a most simple of them. Look at two following algorithms: 1. For each $(a, b)$-query calculate the answer by the simple way: for(int i = a; i < n; i += b) ans += a[i]; 2. Fix the value of $b$ and calculate DP for all possible values of $a$: for(int i = n - 1; i >= 0; i--) if (i + b >= n) d[i] = a[i]; else d[i] = d[i + b] + a[i]; Obvioulsy, the 1st algorithm is non-effective with little values of $b$ and the 2nd algorithm is non-effecitve with very different values of $b$. Behold that it's impossible to generate the situation where all $b$'s are so little and different simultaniously. There is a simple idea: we may solve the problem by 1st algo if values of $b$ are so large (if they are greater than $c$) and solve by 2nd algo if values of $b$ are so small (if they are less of equal to $c$). We need to sort our queries because of no reason to calculate DP of any $b$ more than once. If we choose $c$ equal to $\sqrt{n}$ that we will get a $O(p \cdot \sqrt{n})$ complexity. Complexity is $O(p \cdot \sqrt{n})$.
|
[
"brute force",
"data structures",
"sortings"
] | 2,100
| null |
103
|
E
|
Buying Sets
|
The Hexadecimal virus loves playing with number sets — intersecting them, uniting them. One beautiful day she was surprised to find out that Scuzzy, her spherical pet cat, united all sets in one and ate the result! Something had to be done quickly and Hexadecimal rushed to the market.
The market has $n$ sets of numbers on sale. The virus wants to buy the following collection of sets: the number of sets in the collection should be exactly the same as the number of numbers in the union of all bought sets. Moreover, Hexadecimal wants to buy the cheapest suitable collection of set.
Yet nothing's so easy! As Mainframe is a kingdom of pure rivalry markets, we know that the union of any $k$ sets contains no less than $k$ distinct numbers (for every positive integer $k$).
Help the virus choose the suitable collection of sets. The collection can be empty.
|
Construct bipartite graph $G_{1}$ with available sets on the left side and the numbers on the right side. We put an edge from a set to all the numbers contained in it. By Hall's theorem it follows from "the union of any k sets contains no less than k distinct numbers (for every positive integer k)" that there exists perfect matching of all the elements in the bipartite graph (in fact the theorem states that there exists matching including all set vertices, but as the numbers are also restricted by n, this means that there exists perfect matching$. After this observation we find whichever perfect matching in $G_{1, }$let's denote it by $M = {(u_{i}, v_{i})}$. Now we construct second oriented graph $G_{2}$ with vertices corresponding to the available sets and edges ($u_{i} \rightarrow u_{j}$) for each edge ($u_{i}, v_{j}$) from $G_{1}$ that do not occur in $M$ (Note that the matching sets the indices of v's and thus we consider them, not the values of the corresponding numbers). Now for every suitable collection of size k there should be no outgoing edge to other set in $G_{2}$ (otherwise the numbers included in the sets of the collection will be k plus the additional few numbers from the corresponding outgoing edges and the collection will not be suitable - more numbers than sets). Thus our problem has been transformed to the following equivalent: in an oriented graph with weight of vertices find subset S of the vertices with minimum sum of weights and without outgoing edge with other end not in S. This problem is known to be equivalent to finding minimum cut (I wasn't able to prove the equivalence, didn't know it by heart either, but I found it even easier to prove if I consider the task as just max flow). Assign to the edges of $G_{2}$ infinite weights, add additional vertices $s$ and $t$,. Now for every set $u_{i}$ with weight $w$ add edge $u_{i} \rightarrow t$ with weight $w$ iff $w > 0$ and edge $s \rightarrow u_{i}$ with weight $- w$ iff $w < 0$. The part of the minimum cut of s and t in the constructed graph that contains s is the sought optimal collection (in fact what I did was sum the outgoing weights from s after computing max flow in the graph; I was able to prove this is the required number)
|
[
"flows",
"graph matchings"
] | 2,900
| null |
104
|
A
|
Blackjack
|
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of $52$ cards is used to play blackjack. The pack contains cards of $13$ values: $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$, $10$, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from $2$ to $10$ points, correspondingly. An ace can either earn $1$ or $11$, whatever the player wishes. The picture cards (king, queen and jack) earn $10$ points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals $n$, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals $n$.
|
Obviously, suits are not change the answer. Look at all possible situations: [0 - 10] - zero ways. [11] - four ways using aces. [12 - 19] - four ways using cards from 2 to 9. [20] - 15 ways, they are described in statement. [21] - four ways using aces. [22 - 25] - zero ways. Complexity is $O(1)$.
|
[
"implementation"
] | 800
| null |
105
|
A
|
Transmigration
|
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills.
Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration.
Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life.
As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the $k$ coefficient (if the skill level was equal to $x$, then after transmigration it becomes equal to $[kx]$, where $[y]$ is the integral part of $y$). If some skill's levels are \textbf{strictly less} than $100$, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to $0$.
Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible.
You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?
|
In this problem you should do just that is written in the statement. At the first you should read all skills and multiply all levels of them by koefficient $k$. Next you should drop all skills which have level less than 100. After that you should add all new skills from the second list but only those thah are not present in the second list. At the end you should sort all skills by thier names and output them.
|
[
"implementation"
] | 1,700
| null |
105
|
B
|
Dark Assembly
|
Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.
The Dark Assembly consists of $n$ senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to $10%$.
Senators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If \textbf{strictly more} than half of the senators take a positive decision, the player's proposal is approved.
If the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to $A / (A + B)$, where $A$ is the sum of levels of all player's characters and $B$ is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved.
Senators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by $10%$. It's worth to mention that loyalty cannot exceed $100%$. The player can take no more than $k$ sweets to the courtroom. Candies should be given to the senators \textbf{before} the start of voting.
Determine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way.
|
Solution of this problem is search maximum for all cases of sweets' distribution. Common count of the distributions is $C_{k + n - 1}^{n - 1}$, thah id always no mare than 6435. Let us define as current some distribution and calculate values $z_{i} = min(l_{i} + c_{i} \times 0.1, 1.0)$, where $z_{i}$ is probability that $i$-th senator vote "yes", $l_{i}$ is loyality of senator and $c_{i}$ is number of candies that we should give $i$-th senator. Now you can calculate propability of success in $O(2^{n}n)$. You should iterate ovel all masks of length $n$. 1-bits mean that corresponding senators vote "yes", 0-bits means that ones vote "no". Probability that this mask happen is $m_{mask} = \Pi (z_{i} \times [i - thsenatorvote"yes"] + (1 - z_{i}) \times [i - thsenatorvote"no"])$, where [true] = 1 and [false] = 0. Now for every mask you should find propability that player's proposal will be approved. It is $s_{mask} = 1$ if number of votes "yes" more than half of $n$ and $s_{mask} = A / (A + B)$ it other case, where $B$ is the sum of levels of senators that voted "no". So, propability for current distribution is $\sum_{m a s k}s_{m a s k}\times p_{m a s k}$. Solution has complexity $O(C_{k + n - 1}^{n - 1}2^{n}n)$.
|
[
"brute force",
"probabilities"
] | 1,800
| null |
105
|
C
|
Item World
|
Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res).
Each item belongs to one class. In this problem we will only consider three of such classes: weapon, armor, orb.
Besides, there's a whole new world hidden inside each item. We can increase an item's level travelling to its world. We can also capture the so-called residents in the Item World
Residents are the creatures that live inside items. Each resident gives some bonus to the item in which it is currently located. We will only consider residents of types: gladiator (who improves the item's atk), sentry (who improves def) and physician (who improves res).
Each item has the size parameter. The parameter limits the maximum number of residents that can live inside an item. We can move residents between items. Within one moment of time we can take some resident from an item and move it to some other item if it has a free place for a new resident. We cannot remove a resident from the items and leave outside — any of them should be inside of some item at any moment of time.
Laharl has a certain number of items. He wants to move the residents between items so as to equip himself with weapon, armor and a defensive orb. The weapon's atk should be largest possible in the end. Among all equipping patterns containing weapon's maximum atk parameter we should choose the ones where the armor’s def parameter is the largest possible. Among all such equipment patterns we should choose the one where the defensive orb would have the largest possible res parameter. Values of the parameters def and res of weapon, atk and res of armor and atk and def of orb are indifferent for Laharl.
Find the optimal equipment pattern Laharl can get.
|
There you can see that if at least one item has empty slots then you can redistribute the residents in any order. This assertion can be easily proved. In other case you cannot move residents. Yet another thing that you can see here. In the optimal equipment all items have maximal possible paremeters. Moreover this items with thier residents do not affect each other. So, you can split all items and all residents by thier classes and types and three times solve same problem for groups (weapon, gladiators), (armor, senrties), (orbs, physicians). So, there are 2 cases: you cannot move residents and you can move ones. 1. For every item you should find its paremeter considering residents that are living inside it. After thah you should choose item that have maximal parameter. 2. Here you should sort all residents by desreasing its bonuses. Next you should iterate over all items, try put maximal count of strongest residents and calculate resulting value of parameter. Now you shouls choose item that have maxumal parameter. In the second case some catch exists. In the three choosen items you can have more empty slots than you had at the beginning of moving. It is impossible because you cannot drop residents. Therefore you should, for example, put as most as posiible unused residents into empty slots of three choosen items.
|
[
"brute force",
"implementation",
"sortings"
] | 2,200
| null |
105
|
D
|
Entertaining Geodetics
|
The maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color.
Besides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent color). Each Geo Symbol is located on one Geo Panel, and each Geo Panel may contain no more than one Geo Symbol.
Geo Symbols can be eliminated. To understand better what happens when a Geo Symbol is eliminated, let us introduce some queue to which we will put the recently eliminated Geo Symbols.
Let's put at the head of the queue a Geo Symbol that was eliminated just now. Next, we will repeat the following operation:
Extract the Geo Symbol from the queue. Look at the color of the panel containing the given Geo Symbol. If it \textbf{differs from transparent} and differs from the color of the Geo Symbol, then all Geo Panels of this color are repainted in the color of the given Geo Symbol (transparent Geo Symbols repaint the Geo Panels transparent). Repainting is executed in an infinite spiral strictly in the following order starting from the panel, which contained the Geo Symbol:
In other words, we select all the panels that need to be repainted and find their numbers in the infinite spiral whose center is placed in the position of the given Geo Symbol. After that, we repaint them in the order of the number's increasing.
If a panel contains another Geo Symbol and this panel is being repainted, then the Geo Symbol is removed from the field and placed at the tail of the queue.
After repainting the Geo Symbol is completely eliminated and the next Geo Symbol is taken from the head of the queue (if there is any) and the process repeats. The process ends if the queue is empty.
See the sample analysis for better understanding.
You know the colors of all the Geo Panels and the location of all the Geo Symbols. Determine the number of repaintings, which will occur if you destroy one of the Geo Symbols.
|
This problem can be solved by data structure like disjoint set union (dsu) with compression paths heuristic. Every vertex of dsu is geo-panel and every connected component is the set of one-colored geo-panels. All important information stores in the leader of component. It is size of group (count of geo-panels in it), its color and list of geo-symbols in this group that not destroyed. You should create queue that described in the statement. There you should store geo-symbols. Every symbol is color and position of map where this symbol was placed. Also yoy should create associative array (like std::map in c++), that returns leader of group in dsu by color of this group. At last you should create array with size $2n \times 2m$ and store in it path of infinite spiral. This array you can use for easily sorting geo-symbols before putting its into queue. This system of data structures allows fast emulate all process. So, let put the first geo-symbol into queue, generate spiral array and set dsu and associative array into initial state. Now you can do following operations while queue is not empty: You should remove geo-symbol from front of queue. Let call it current geo-symbol. By its coordinates using dsu you can find group in which current geo-symbol is placed. Next you should compare colors of group and geo-symbol and understand this group should be repainted or not. If group should be repainted you should add size of its group to global answer. After that you should sort all geo-symbols in this group using spiral array. In this order you should insert these geo-symbols into back of queue and clear list of qeo-symbols in the group. Now you should repaint group and replace associative array. You can see that some situation can happen. Now you can have two groups with equal colors (you can fast know it using associative array). These groups chould by united. You should set parent of group that you this moment repainted the second group and increase size of the second group by size of first group. You can prove that this algorithm works in $O(nmlognm)$.
|
[
"brute force",
"dsu",
"implementation"
] | 2,700
| null |
105
|
E
|
Lift and Throw
|
You are given a straight half-line divided into segments of unit length, which we will call positions. The positions are numbered by positive integers that start with $1$ from the end of half-line, i. e. $1$, $2$, $3$ and so on. The distance between the positions is the absolute difference between the respective numbers.
Laharl, Etna and Flonne occupy some positions on the half-line and they want to get to the position with the largest possible number. They are originally placed in different positions.
Each of the characters can perform each of the following actions \textbf{no more than once}:
- Move a certain distance.
- Grab another character and lift him above the head.
- Throw the lifted character a certain distance.
Each character has a movement range parameter. They can only move to free positions, assuming that distance between those positions doesn't exceed the movement range.
One character can lift another character if the distance between the two characters equals $1$, and no one already holds that another character. We can assume that the lifted character moves to the same position as the person who has lifted him, and the position in which he stood before becomes free. A lifted character cannot perform any actions and the character that holds him cannot walk.
Also, each character has a throwing range parameter. It is the distance at which this character can throw the one lifted above his head. He can only throw a character to a free position, and only when there is a lifted character.
We accept the situation when one person grabs another one who in his turn has the third character in his hands. This forms a "column" of three characters. For example, Laharl can hold Etna while Etna holds Flonne. In this case, Etna and the Flonne cannot perform any actions, and Laharl can only throw Etna (together with Flonne) at some distance.
Laharl, Etna and Flonne perform actions in any order. They perform actions in turns, that is no two of them can do actions at the same time.
Determine the maximum number of position at least one of the characters can reach. That is, such maximal number $x$ so that one of the characters can reach position $x$.
|
At the beginning you should estimate maximal answer what you can get. It equals 42. This answer you can get from following obvious maximal test: 8 10 10 9 10 10 10 10 10 Common number of states in which character can be without regard to position is 8. 2 for moved/not-moved multiply to 4 for nobody-lifted/lifted-A/lifted-B/already-threw. Total number of states is $(8 * 42)^{3} = 37933056$. This count of states can be easily stored in memory. Solution is DFS or BFS from initial state. Maximal position in reached states is answer.. Why it fits into time limits? In fact you can do about 60 moves from every state. Point is that most of states will be not reached. For example, following heuristics confirm it: 1. If one character is lifted by another one, thier positions are equal. 2. States where one characher lifted by both anothers are incorrect. 3. In positions with big numbers no more than 2 characters can be. In positions with very big numbers no more than 1 character can be. Also from more states possible little number of moves. They are states in which some characrers already moved or already threw somebody. You can find exact number of moves only after writing solution. Run on the maxtest shows that number of moves about $2 \times 10^{8}$. So, this solution fits into time limits. You should just accuracy write it.
|
[
"brute force"
] | 2,500
| null |
106
|
A
|
Card Game
|
There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly — you can find them later yourselves if you want.
To play durak you need a pack of $36$ cards. Each card has a suit ("S", "H", "D" and "C") and a rank (in the increasing order "6", "7", "8", "9", "T", "J", "Q", "K" and "A"). At the beginning of the game one suit is arbitrarily chosen as trump.
The players move like that: one player puts one or several of his cards on the table and the other one should beat each of them with his cards.
A card beats another one if both cards have similar suits and the first card has a higher rank then the second one. Besides, a trump card can beat any non-trump card whatever the cards’ ranks are. In all other cases you can not beat the second card with the first one.
You are given the trump suit and two different cards. Determine whether the first one beats the second one or not.
|
Solution of this problem is written in the fourth paragraph of the statements. You should carefully read and implement it. Only one difficult part is how to to determine which card has higher rank. You can for every card iterate over array [ '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ] and determine numbers of ranks in this array. Finally, just compare them.
|
[
"implementation"
] | 1,000
| null |
106
|
B
|
Choosing Laptop
|
Vasya is choosing a laptop. The shop has $n$ laptops to all tastes.
Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.
If all three properties of a laptop are \textbf{strictly less} than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.
There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.
|
You can create array for all laptops where true for outdated laptop and false otherwise. Value of every cell of this array you can determine by iterating over all laptops and comparing all their parameters. At the end you should itarate over all laptops once again and choose cheapest one that is not outdated.
|
[
"brute force",
"implementation"
] | 1,000
| null |
106
|
C
|
Buns
|
Lavrenty, a baker, is going to make several buns with stuffings and sell them.
Lavrenty has $n$ grams of dough as well as $m$ different stuffing types. The stuffing types are numerated from 1 to $m$. Lavrenty knows that he has $a_{i}$ grams left of the $i$-th stuffing. It takes exactly $b_{i}$ grams of stuffing $i$ and $c_{i}$ grams of dough to cook a bun with the $i$-th stuffing. Such bun can be sold for $d_{i}$ tugriks.
Also he can make buns without stuffings. Each of such buns requires $c_{0}$ grams of dough and it can be sold for $d_{0}$ tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking.
Find the maximum number of tugriks Lavrenty can earn.
|
Let create array dp by size n x m. dp[i][j] means maximum number of tugriks that the baker can earn if he used i grams of dough and cook buns with stuffings of types 1..j. Initially dp[i][0] is 0 for all i. You can easily calculate this dp: dp[i][j] = max{ dp[i-c[j]*k][j-1] + d[j]*k } for every k from 0 to a[j]/b[j], for which i-c[j]*k>=0 The answer will be max{ dp[k][m] + ((n-k)/c0)*d0 } for every k from 0 to n. Of course, all divisions in editorial of this problem are integer. Solution works in O(nma), where a is maximum a_i.
|
[
"dp"
] | 1,700
| null |
106
|
D
|
Treasure Island
|
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.
The treasure map can be represented as a rectangle $n × m$ in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.
Besides, the map also has a set of $k$ instructions. Each instruction is in the following form:
"Walk $n$ miles in the $y$ direction"
The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried.
Unfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.
The captain wants to know which sights are worth checking. He asks you to help him with that.
|
Solution is simulation of all insrtuctions from all of local sights. But naive solution doesn't fit into time limit. You should speed up this solution and do every instruction in O(1). You can use one of following things. 1. For every position and every direction you can precalculate nearest position of sea. Now before than you do an instruction you should check that nearest position of sea further than position whereto you move after doing the instruction. 2. Let sea cells have 1 and all other ones have 0. For every cell (i,j) you can calculate sum of all cells in the rectangle with angles in (1,1) and (i,j). It can be done by the operations like: sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + smth where smth is 0 or 1 according to type of according cell (i,j). Now you can determine sum of numbers for all rectangles of the map. Before you do instruction you should chech that sum of rectangle on which you will go has sum 0. Solution has complexity O(nm + kz), where z is number of local sights (this number no more than 26).
|
[
"brute force",
"implementation"
] | 1,700
| null |
106
|
E
|
Space Rescuers
|
The Galaxy contains $n$ planets, there are many different living creatures inhabiting each planet. And each creature can get into troubles! Space rescuers know it perfectly well and they are always ready to help anyone who really needs help. All you need to do is call for them.
Now the space rescuers plan to build the largest in the history of the Galaxy rescue station; however, the rescue station's location is yet to be determined. As some cases are real emergencies, the rescuers want to find such a point in the Galaxy from which it would be possible to get to the remotest planet in the minimum possible time. In other words, the rescuers need such point in the space that the distance between it and the planet remotest from it was minimal (if we compare this point with all other possible points in the space). Unfortunately, the rescuers can't sole this problem.
As the planets are quite remote from each other, they can be considered as points in Euclidean three-dimensional space. The distance between points $(x_{i}, y_{i}, z_{i})$ and $(x_{j}, y_{j}, z_{j})$ can be calculated by the formula $p={\sqrt{(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}+(z_{i}-z_{j})^{2}}}$. The rescue station can be positioned in any point in the space. It can also coincide with some planet.
Galaxy is in danger! Save the space rescuers and find the required point for them.
|
Author's solution is three ternary search for every demension that are nested within each other. It works because the function is convex. Maximum of convex functions also convex function. Author not very well imagine convex function in 3 dimrnsions, therefore you can read following proof that algorithm is correct: Let consider some straight line. Function of distance between points on this line and planet position will be convex (you can imagine it). If you get maximum of such functions it will be convex function too. Let's call this function f1. Now let's consider flat plane and choose one straight line in it. Set for every point of this line a minumum of function f1 of line that passes through this point and is perpendicular to choosen line. Let's call function on this choosen line f2. f2 is convex. It can be easily proved by contrary. If f2 is not convex, we can find at least two local minimums. Let's choose two neighbour of them. We can find this two minimums on the plane and drawn through them new line. f1 on this line will be not convex (you also can imagine it). Contradiction. Now let's consider all space. Choose one line in it and define function f3 on it. Values of f3 will be minimums of functions f2 of planes that passes through the line and is perpendicular to it. f3 also is convex. Proof of it is analogically to that is written in the previous paragraph. [] Now you can see that minimum can ge found by three ternary search over functions fi. You can add to these functions returning of value in which they reach a minimum. Also there are solutions that uses idea of Gradient descent or Hill climbing. Author was unable to write this solution (not enough precision), but some participants got AC with such solutions. There is exact solution O(n^4) (more exactly O(C_n^4)). This solution uses Helly's theorem and Jung's theorem that follows from the first one: http://en.wikipedia.org/wiki/Helly's_theorem In this solution you should itarate over all pairs, triples and fours of points and for every of them build minimal ball that cover them. Answer is center of ball with maximum radius. Also you can google something like that http://www.inf.ethz.ch/personal/gaertner/miniball.html There are code and article, but the author of contest is not particularly delved into them))
|
[
"geometry",
"ternary search"
] | 2,100
| null |
107
|
A
|
Dorm Water Supply
|
The German University in Cairo (GUC) dorm houses are numbered from $1$ to $n$. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.
In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
|
The problem describes a graph of houses as nodes and one-way pipes as edges. The problem states that the graph will contain $1$ or more chains of nodes. The required is to find the start and end of every chain (consisting of more than $1$ node, which caused many hacks). The other requirement was to find the weakest edge in each of the chains. This can be done by traversing (using Depth-First Search (DFS) for example) the graph from each un-visited node with no incoming edges. These nodes are the $start$ of a chain. By keeping track of the $minimum$ $diameter$ so far, whenever the DFS reaches a node with no outgoing edges, it means that this node is the $end$ of the current chain. After storing, in a list or vector, the tuples $(start, end, minimum$ $diameter)$, we sort these tuples by start index and print.
|
[
"dfs and similar",
"graphs"
] | 1,400
| null |
107
|
B
|
Basketball Team
|
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).
A team is to be formed of $n$ players, all of which are GUC students. However, the team might have players belonging to different departments. There are $m$ departments in GUC, numbered from $1$ to $m$. Herr Wafa's department has number $h$. For each department $i$, Herr Wafa knows number $s_{i}$ — how many students who play basketball belong to this department.
Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department.
Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.
|
This problem is asking for the probability. Consider two sets of teams: the set of teams where Herr Wafa is the only student from his major and the set where at least one other student from Herr Wafa's major is present. These two sets don't intersect, so once we can compute the number of teams in the first set, A, and the number of teams in the second set, $B$, the answer would be $B / (A + B)$. The number of teams in the first set is A = $C((\sum s[i],i\neq h),n-1)$. We subtract one as Herr Wafa is guaranteed the spot, and the other $(n - 1)$ spots are to be taken by the remaining $(\sum s[i],i\neq h)$ students. Now let's count the number of teams having exactly $k$ students from Herr Wafa's major apart from him. This number would be $F(k)=C(s[h]-1,k)*C((\sum s[i],i\neq h),n-(k+1))$. Much like for the first set, $(n - (k + 1))$ students from the other majors should he selected, and none of them should be from Herr Wafa's major. The total number of teams where at least one other student is from Herr Wafa's major is therefore $B=\textstyle\sum_{k=1}^{s(h)-1}F(k)$. The statements above describe the mathematical solution. It can be implemented in various ways.
|
[
"combinatorics",
"dp",
"math",
"probabilities"
] | 1,600
| null |
107
|
C
|
Arrangement
|
In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.
The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.
Traditionally GUC has $n$ professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from $1$ to $n$, with $1$ being the most senior professor and $n$ being the most junior professor.
The ceremonial hall has $n$ seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, $m$ pairs of seats are in "senior-junior" relation, and the tradition requires that for all $m$ pairs of seats $(a_{i}, b_{i})$ the professor seated in "senior" position $a_{i}$ should be more senior than the professor seated in "junior" position $b_{i}$.
GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that:
- The seating of the professors changes every year.
- Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall.
- Each consecutive year lexicographically next arrangement of the professors is used.
The arrangement of the professors is the list of $n$ integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.
Given $n$, the number of professors, $y$, the current year and $m$ pairs of restrictions, output the arrangement of the professors for this year.
|
The problem asks for finding the lexicographically $n$-th permutation satisfying the input constraints. The trick which confused many contestants, as well as a few authors and testers, is that instead of having the restrictions formulated in a way $position[a[i]] < position[b[i]]$ the restrictions were element at position[a[i]] < element at position[b[i]]. As in most problems where one has to output lexicographically $n$-th answer, the idea which can result in the solution which is passing the systests is to learn how to compute the number of solutions satisfying certain constraints. We will speak about how to compute the number of solutions in a bit, but first let's understand how having such function would lead to a solution. The very first observation is: if the total number of possible solutions is less than $y - 2000$, then the answer is "The times have changed". Once we have ensured that the solution exists it can be found using some of search. A simple approach would be the following: fix the first element of the resulting permutation to be $1$ and count the number of possible solutions. If we do have enough to reach year $y$, then the first element must be $1$, because there exists enough permutations with the first element being $1$ to cover the years up to $y$, and any permutation where the first element is not $1$ comes after any permutation where the first element is $1$ in lexicographical order. And if fixing the first element to be $1$ is not giving enough permutations, then we should decrease the "desired" year by the number of solutions with $1$ being fixed as the first element and start looking for the solutions with $2$ as the first element. The intuition is that there are not enough solutions with $1$ being the first element, but once we acknowledge that and start looking for the other solutions --- with $2$ as the first element, we are speaking not about arrangements for years 2001 and onwards but about the years 2001 + number of solutions with first element being one and onwards. Therefore instead of looking for the permutation with index $y - 2001$ with the first element being $1$ we are looking for the permutation with the lower index, y - 2001 - number of solutions with first element being one, with the first element being $2$ or higher. This process should be continued until all the elements are identified. Once the first index is fixed the known prefix would become a two-numbers prefix, and it will grow until all the permutation is constructed. Now to complete the solution we need to be able to compute the number of permutations which satisfy two restrictions: the input constraints and the added "permutation has prefix P" constraint. This problem can be solved using DP. For a given prefix P of length m, (n-m) other elements should be placed. Assume first that we are going to be iterating over all possible permutations with the given prefix using the brute force, but, instead of trying each possible value for the element at the next empty position i, we would be trying each possible position for the next not-yet-placed element i. This approach would work, but in $O((n - m)!)$ time, which is obviously unfeasible. We need to find some way to reduce the state space and make it run faster. The key observation is the following: the state of the partially solved problem can be completely described by the bitmask of the currently occupied positions. This statement is nontrivial, as, from the first glance, it seems that apart from the unused positions mask, the information about the order, in which the already-placed elements are placed, is important. However it's not. Recall that all the constraints have the form of "element at position $a_{i}$ is less than the element at position $b_{i}$". Provided the elements are placed in increasing order, in order to satisfy each constraint it's enough to confirm that, if the element to be placed is being put into position i, there is no such constraint in the input, that the element at position i should be less than the element at position j, while the element at position j has already been placed. This approach results in the DP with $2^{n - m}$ states. Note that the next element to be placed can always be determined by the number of bits set in the mask and the prefix elements. The implementation of the above algorithm requires nontrivial coding, as the elements, belonging to the prefix, have to be treated differently compared to the elements which were placed by the DP. This is because the DP is enforcing that the elements are always added in the increasing order, which does not have to be the case for the elements conducting the prefix.
|
[
"bitmasks",
"dp"
] | 2,400
| null |
107
|
D
|
Crime Management
|
Zeyad wants to commit $n$ crimes in Egypt and not be punished at the end. There are several types of crimes. For example, bribery is a crime but is not considered such when repeated twice. Therefore, bribery is not considered a crime when repeated an even number of times. Speeding is a crime, but is not considered such when repeated a number of times which is a multiple of five.
More specifically, $c$ conditions on crime repetitions are known. Each condition describes the crime type $t_{i}$ and its multiplicity $m_{i}$. If the number of times Zeyad committed the crime $t_{i}$ is a multiple of $m_{i}$, Zeyad will not be punished for crime $t_{i}$. Some crimes may be listed more than once. In this case fulfilling at least one condition for this crime is enough to not be punished for it. Of course, if for certain crime the number of times Zeyad committed it is zero, he is innocent with respect to this crime.
Now Zeyad is interested in a number of ways he can commit exactly $n$ crimes without any punishment.
The order of commiting the crimes matters. More formally, two ways, sequences $w1$ and $w2$, of committing $n$ crimes are equal if $w1_{i} = w2_{i}$, for all $1 ≤ i ≤ n$.
|
At the first glance the upper limit for $n$ being $10^{18}$ looks huge. But in fact, combined with the fact, that the answer should be output modulo $12345$, it's should not scare you but rather hint that the problem has a DP approach. Like all DP problems the way to approach it is to split the problem into sub-problems and figure out what extra information should be carried between the sub-problems in order to combine them into the solution to the whole problem. Say, $n$ is $11$ and we solved the problem for the first $10$ crimes. Clearly, just the number of ways to commit the first $10$ crimes is not enough to solve the full problem with $n = 11$. The extra information to be carried along with the number of ways to commit n crimes and be innocent is the following: the number of ways to commit the first $n$ crimes and have remaining multiplicities $d_{1}, d_{2}, ...d_{26}$ respectively. The fact that the product of the multiplicities does not exceed $123$ makes this a solvable task, as the set of all possible remainders contains not more elements than the product of multiplicities. To illustrate the idea from the first paragraph consider the first example case. It has two constraints, A with multiplicity $1$ and B with multiplicity $2$. The remainder of the number of crimes of type A is always zero, and committing crimes of type A may not yield any punishment. The remainder of the number of crimes of type B is zero or one. Therefore, while solving the sub-problems for the first $n2 < = n$ crimes, it's enough to keep track of only two numbers: "number of ways to commit $n2$ crimes and be completely innocent" and "number of ways to commit $n2$ crimes and have committed one 'extra' crime of type B". The key step to solve the problem now is to notice that each transition from the solution for the first $k$ crimes to the solution for the first $(k + 1)$ crimes can be seen as multiplying the vector of the current state by the transition matrix. Once all possible transitions are converted to the matrix form, the problem can be solved by raising the matrix into n-th power. Raising the matrix into large power can be done efficiently using matrix exponentiation: on some steps instead of computing $A_{i + 1} = A_{i} \cdot A_{0}$ one can compute $A_{2i} = A_{i} \cdot A_{i}$. The last trick of this problem is to deal with multiple allowed multiplicities. If they were not allowed, the remainders per each crime type could have been kept with the modulo being equal to the multiplicity for this crime type. Moreover, if no crime type is listed more than once, the only valid final state is the state where the remainders are zero across all the crime types. With multiple allowed multiplicities, for each crime type the remainder modulo the product of the multiplicities of crimes for this type should be kept. (Strictly speaking, LCM is enough, but the constraints allow to use the plain product instead). Then, at the stage of printing the output, instead of treating the counter for the state with zero remainders as the only contributor to the output, one would have to iterate through all possible states and verify if each set of remainders conducts a valid final state.
|
[
"dp",
"graphs",
"matrices"
] | 2,400
| null |
107
|
E
|
Darts
|
The night after the graduation ceremony graduate students of German University in Cairo (GUC) are playing darts. As there's no real dart board available, the photographs of members of the GUC upper management are being used.
So, $n$ rectangular photos are placed on the wall. They can overlap arbitrary and even coincide. The photos are not necessarily placed horizontally or vertically, they could also be rotated before being pinned to the wall.
The score of one dart throw is simply the number of photos the dart went through.
Fatma has made a throw but her score was not recorded. She only remembers that she did make it into at least one photo.
Assuming that the probability distribution of the throw is equal across the whole wall, what would be the expectation of Fatma's score?
|
Before doing the coding let's do some math. The answer to this problem can be computed as the total area of all input rectangles / the area of the union of all input rectangles. One of the easy ways to understand it is the following. First notice that if all the rectangles are the same, the answer is always the number of rectangles. Now forget that the input figures are rectangles, assume any shape is allowed, and then try to construct the example case given the union area $s$ and the resulting expected score $e$. Notice that you can start with any shape constructed of non-intersecting figures with the total area $s$, and then add more figures on top of these, such that the contour of the union is the same as the contour of the first original figure of area $s$. Specifically, you'd need to add some figures of the total sum of $t = s \cdot (e - 1)$, but the number doesn't matter here. The key is that the placement of these added figures doesn't change the result, and therefore the answer will always depend only on the total area of the input figures and the area of their union. Now back to the rectangles. Computing the sum of the ares of the rectangles is easy. The hard part is to compute the area of their union in better than $O(n^{3})$. Note that the union may have multiple disjoins components, it does not have to be convex, it may have holes and, in short, does not have to be easy to describe. One of the relatively-easy-to-implement solutions is the following. We will be computing the are of the union of the rectangles using the trapezoid method. Note that for the trapezoid method the order, in which the segments of the figure are provided, doesn't matter. Therefore, in order to use the trapezoid method, we "only" need to find all non-vertical directed segments which are the part of the contour of the union. Let me elaborate a bit more on the previous paragraph. We don't need vertical segments, because their contribution to the resulting area is zero in the trapezoid method of computing the area. The direction of the segment is the important part though. It's not enough to know that the segment $(x1, x2) - (y1, y2)$ belongs to the contour of the union. It's important to know whether the area of the union if the part of the plane above it or below it. Imagine the test case where the union of all the rectangles is a big rectangle with a hole inside it. In this case we need to know that the segments, describing the outer part of the union, should contribute to the area with the "plus" sign, while the segments describing the inner hole should be considered with the "minus" sign. Specifically, for the trapezoid method, the sign of $x2 - x1$ would be describing the direction of this segment: for example, if $x1 < x2$ than the segment is "positive" and if $x1 < x2$ it's "negative". To find all such segments let's consider all distinct non-vertical lines. There are at most $4n$ such lines in the input. Each segment of the final contour of the union should lay on one of those lines, so it's enough to focus on the lines only, consider them independently from each other (but make sure to process each distinct line only once!) and for each line construct a set of the positive and negative segments. Let's formulate the rules under which a part of the line would be a positive or negative segment. They turn out to be very simple: 1) If some segment $(x1, y1) - (x2, y2)$ is part of the border of one of the input rectangles, then it's a "positive" segment if this input rectangle lays below this segment and a "negative" segment if this rectangle lays above this segment. 2) If some segment $(x1, y1) - (x2, y2)$ belongs to the intersection of the borders of two different input rectangles, with one being a "positive" one and one being a "negative" one, then this segment does not belong to the contour. 3) If some segment $(x1, y1) - (x2, y2)$ is being covered by another rectangle, then it does not belong to the contour. "Covered" means laying completely inside some other rectangle, the border cases are covered above. The easy way of constructing all the segments could look as the following pseudo-code: for each distinct non-vertical line create the array of markers. the marker holds the x coordinate and one of four events: { start union area below, end union area below, start union area above, end union area above }. iterate through all the input rectangles if this rectangle has one segment laying on the line under consideration add two markers: one for start and one for end. whether the markers are above or below is determined by the position of this rectangle with respect to this line else if this rectangle intersects this line find the intersection points and add four markers: { start area below } and { start area above } for the left intersection point and { end area below } and { end area above } for the right intersection point sort the array of markers by the x coordinate of the events traverse the array of markers. if some segment $(x1..x2)$ is being reported as having the union area only above it or only below it, it becomes the negative or positive segment of the union respectively. At this point one could run some sort of DFS to merge the segments into the connected loops, but this is actually unnecessary to compute the area using the trapezoid method. Just summing up $(x2 - x1) \cdot (y1 + y2) / 2$ for all the segments does the trick, and it would automatically ensure that the outer contours are taken with the positive sign and the inner contours are taken with the negative sign. The solution described above runs in $O(n^{2} \cdot logn)$ : for each of $O(n)$ lines we have at most $O(n)$ intersections, which should be sorted in $O(n \cdot logn)$ inside the loop over all the lines.
|
[
"geometry",
"probabilities"
] | 2,700
| null |
108
|
A
|
Palindromic Times
|
\underline{Tattah is asleep if and only if Tattah is attending a lecture.} This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.
In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.
However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.
|
In this problem it was required to find next palindrome on a digital clock. Since the lowest unit of time used $1$ minute, and there are only $24 * 60$ minutes in a day, one could simply go through each minute starting from the time given in the input plus $1$ minute, until finding a palindrome. If no palindrome is found till the end of the day $23: 59$, the output should then be $00: 00$.
|
[
"implementation",
"strings"
] | 1,000
| null |
108
|
B
|
Datatypes
|
Tattah's youngest brother, Tuftuf, is new to programming.
Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava.
Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has $n$ unsigned integer datatypes of sizes (in bits) $a_{1}, a_{2}, ... a_{n}$. The $i$-th datatype have size $a_{i}$ bits, so it can represent every integer between $0$ and $2^{ai} - 1$ inclusive.
Tuftuf is thinking of learning a better programming language. If there exists an integer $x$, such that $x$ fits in some type $i$ (in $a_{i}$ bits) and $x·x$ does not fit in some other type $j$ (in $a_{j}$ bits) where $a_{i} < a_{j}$, then Tuftuf will stop using Gava.
Your task is to determine Tuftuf's destiny.
|
Let us call a pair of datatypes $(a, b)$, where $a < b$, BAD if and only if there exists a number $x$ where $x$ fits in $a$ bits but $x * x$ does not fit in $b$ bits. The following observation helps in finding a solution to the problem. The best candidate for the number $x$ is the largest number fitting in $a$ bits, which is $x = 2^{a} - 1$. So for each $a_{i}$ it is enough to check that the smallest $a_{j}$ > $a_{i}$ has enough bits to contain $x * x = (2^{a} - 1) * (2^{a} - 1)$, which has at most $2 * a$ bits. Sorting the numbers first was needed to traverse the list of datatypes once and ensuring the condition above.
|
[
"math",
"sortings"
] | 1,400
| null |
109
|
A
|
Lucky Sum of Digits
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
Petya wonders eagerly what minimum lucky number has the sum of digits equal to $n$. Help him cope with the task.
|
Let result number contains $a$ digits $4$ and $b$ digits $7$. Obviously, that $a * 4 + b * 7 = n$. Loop through all values of $b$. If we know $b$, we can calculate $a$, $a={\frac{n-b x7}{4}}$. Among all pairs $(a;b)$ we need to choose one with $a + b$ minimum. Among all that pairs we need to choose one with $b$ minimum. Output will be an integer $444...444777...777$, here number of digits $4$ equal to $a$, number of digits $7$ equal to $b$.
|
[
"brute force",
"implementation"
] | 1,000
| null |
109
|
B
|
Lucky Probability
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer $p$ from the interval $[p_{l}, p_{r}]$ and Vasya chooses an integer $v$ from the interval $[v_{l}, v_{r}]$ (also randomly). Both players choose their integers equiprobably. Find the probability that the interval $[min(v, p), max(v, p)]$ contains exactly $k$ lucky numbers.
|
Let $L[i]$ - $i$-th lucky number, starting from 1 ($L[0] = 0$, $L[1] = 4$, $L[2] = 7$...). At first choose first $k$ lucky number, then second $k$ numbers and so on. For each of that group lets find answer, result will be a sum of each of this probabilities. Let index of current first number if $i$, last - $j$ ($j = i + k - 1$). Then we need to find intersection of intervals $[p_{l};p_{r}]$ and $(L[i - 1];L[i]]$, and also $[v_{l};v_{r}]$ and $[L[j];L[j + 1])$, product of that values will be a number of ways in which $p < v$, similarly for $p > v$. Sum of all that values for each group will be a total number of ways, then result = total number of ways / $((p_{r} - p_{l} + 1) * (v_{r} - v_{l} + 1))$.
|
[
"brute force",
"probabilities"
] | 1,900
| null |
109
|
C
|
Lucky Tree
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
One day Petya encountered a tree with $n$ vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a \underline{tree with $n$ vertexes} is an undirected connected graph that has exactly $n - 1$ edges.
Petya wondered how many vertex triples $(i, j, k)$ exists that on the way from $i$ to $j$, as well as on the way from $i$ to $k$ there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple $(1, 2, 3)$ is not equal to the triple $(2, 1, 3)$ and is not equal to the triple $(1, 3, 2)$.
Find how many such triples of vertexes exist.
|
Solve this problem using dynamic programming. Consider that root of a tree is vertex with number 1. Let $F(x)$ - number of vertex in subtree of vertex $x$ for which there is a path containing lucky edge. We will calculate $F(x)$ using recursion. If $x$ is a leaf, than $F(x) = 0$. Else, if there is an edge from $x$ that leads to $y$ and this edge is lucky, then to $F(x)$ we need to add $C(y)$, otherwise we add $F(y)$, here $C(y)$ - number of vertex in subtree of $y$, including $y$. But, to solve this problem we need to know also $F'(x)$ - number of vertex which are not in subtree of $x$ and there exits a path from $x$ to that vertex that contains lucky edge. For a root of tree, $F'(x)$ equals to $0$. We should go recursive from root, and if we are in vertex $x$ now, we suppose that $F'(x)$ is already calculated. If from $x$ we can directly go to $y$ and that edge is lucky, then $F'(y) = C(0) - C(y)$, otherwise $F'(y) = F'(x) + F(x) - F(y)$. After that, result equals to $\textstyle{\sum_{i=1}^{n}F(i)*(F(i)-1)+F^{\prime}(i)*(F^{\prime}(i)-1)+2*F(i)*F^{\prime}(i)}$.
|
[
"dp",
"dsu",
"trees"
] | 1,900
| null |
109
|
D
|
Lucky Sorting
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
Petya got an array consisting of $n$ numbers, it is the gift for his birthday. Now he wants to sort it in the non-decreasing order. However, a usual sorting is boring to perform, that's why Petya invented the following limitation: one can swap any two numbers but only if at least one of them is lucky. Your task is to sort the array according to the specified limitation. Find any possible sequence of the swaps (the number of operations in the sequence should not exceed $2n$).
|
At first, if our array is already sorted, just return $0$. Otherwise, if there is no lucky number in $A$, then output $- 1$. Otherwise, let $B$ is sorted $A$ (array from input). Now, for all numbers in $A$ we know a final position in $B$. Let $k$ is an index of minimal lucky number in $A$. If we want to place integer from position $i$ to $j$, we need $A[j]$ to be lucky number. If is not so, we just $Swap(A[j], A[k])$, then $A[j]$ contains lucky number. After that we can $Swap(A[i], A[j])$ and number $A[i]$ is on position $j$. So, to place one number to it's position in $B$, we need at most two operations and total number that replacements will be not more than $n$, so answer'll contain at most $2n$ operations.
|
[
"constructive algorithms",
"sortings"
] | 2,000
| null |
109
|
E
|
Lucky Interval
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
One day Petya came across an interval of numbers $[a, a + l - 1]$. Let $F(x)$ be the number of lucky digits of number $x$. Find the minimum $b$ $(a < b)$ such, that $F(a)$ = $F(b)$, $F(a + 1)$ = $F(b + 1)$, ..., $F(a + l - 1)$ = $F(b + l - 1)$.
|
That is only onw variation of solution, there are diffrent other, which uses same thinking. With constraints for $a$ and $b$ to $10^{7}$ problem can be solved using KMP algorithm: consider a string $F(1)F(2)F(3)F(4)...F(3 * 10^{7})$. We need to find first occurrence after index $a$ of string $F(a)F(a + 1)F(a + 2)...F(a + l - 1)$. Complexity of that algorithm is $O(a + l)$, obviously, that fails on time and memory. Lets try to optimize this algorithm using some facts from "Lucky numbers theory". Split all number interval on block with sizes $100$: $[0;99]$, $[100;199]$ and so on. Introduce a concept "class of block". Class number of a block equals to $F(i / 100)$, where $i$ - any number from that block. There are $8$ different block classes. There are at most $6$ consecutive blocks with same class. All that can be seen using brute force. Note #1: if $l \ge 1000$, then $(b-a)\mod100=0$. Proof: consider a string $F(100 * k)F(100 * k + 1)...F(100 * k + 99)$. Number of different that strings is equal to number of different classes. For example, for first class that string looks like this: $00001001000000100100000010010000001001001111211211000010010000001001001111211211$ 00001001000000100100 for second: $11112112111111211211111121121111112112112222322322111121121111112112112222322322$ 11112112111111211211 and so on. According to the structure of that strings, different block (by classes) can't intersect (there'll be no match). Hence, any sequence of of consecutive blocks which contain at least two blocks of different classes will match only with the same sequence, so shift will be multiple of $100$. Since there is no more than $6$ consecutive blocks with the same classes, if $l \ge 1000$ then, obviously, this interval will contain at least two blocks with different classes. So, problem with $l \ge 1000$ can be solved using KMP with complexity $O((a + l) / C)$, where $C$ equals $100$, let function that do that is named $Solve(l, r)$. Now we need to solve problem for $l < 1000$. At first, let $a'$ is minimal number that $F(a') = F(a)$, $F(a' + 1) = F(a + 1)$, ..., $F(a' + l - 1) = F(a + l - 1)$, $a' / 100 = a / 100$, that can be done using brute force. Then result is the minimum of next numbers: - $r = Solve(a', a' + l - 1)$; - Minimum $r'$, for which $r - r' < = 1000$, $r' > a$, $F(r') = F(a)$, $F(r' + 1) = F(a + 1)$, ..., $F(r' + l - 1) = F(a + l - 1)$. - Minimum $a''$ for which $a'' > a$, $a'' - a \le 1000$ and $F(a'') = F(a)$, $F(a'' + 1) = F(a + 1)$, ..., $F(a'' + l - 1) = F(a + l - 1)$. That solves the problem of some non-100-multiple shifts, but that may be a doubt. Consider input interval is in just one block with class $C$. Then, probably, it is better to go to block with class $C + 1$, for example $(397;1) \rightarrow (400;1)$. Actually, second point solves that problem, because if block with class $C + 1$ is before $C$ (and only in that case we will choose $C + 1$), then next block after current have class $C + 1$. To proof this we can use this note (which can be proofed using brute forces): Note #2: if there is two consecutive block, then absolute difference between they classes is not more then $1$. Hence, if after block $C$ (in which input interval is) goes block with class $C - 1$, then we will go to block $C$ before $C + 1$, otherwise we will choose it ($C$ or $C + 1$). Thus, problems solves by accurate analysis all moments. Complexity of solution is $O((A + L) / 100)$, my solution works $1.5$ sec. and use $250$ mega bytes of memory. There are also solution which decompose of blocks with sizes depentding on $l$, that one work faster.
|
[
"brute force",
"math"
] | 2,700
| null |
110
|
A
|
Nearly Lucky Number
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
Unfortunately, not all numbers are lucky. Petya calls a number \underline{nearly lucky} if the number of lucky digits in it is a lucky number. He wonders whether number $n$ is a nearly lucky number.
|
In this problem you just need to find a number of lucky digits in $n$ and output $YES$ if it number is equal to $4$ or $7$, $NO$ otherwise.
|
[
"implementation"
] | 800
| null |
110
|
B
|
Lucky String
|
\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.}
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in $26$ lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two \textbf{adjacent} numbers is a lucky number.
For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are:
- b: $2$
- c: $3, 10$
- d: $4, 8$
- e: $6$
- f: $7$
- z: $1, 5, 9$
- Lists of positions of letters a, g, h, ..., y are empty.
This string is lucky as all differences are lucky numbers. For letters z: $5 - 1 = 4$, $9 - 5 = 4$, for letters c: $10 - 3 = 7$, for letters d: $8 - 4 = 4$.
Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.
Find the lexicographically minimal lucky string whose length equals $n$.
|
To solve this problem you need to notice that result is a prefix of string $abcdabcdabcd...abcd$ and output first $n$ characters of this string.
|
[
"constructive algorithms",
"strings"
] | 1,100
| null |
111
|
A
|
Petya and Inequiations
|
Little Petya loves inequations. Help him find $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$, such that the following two conditions are satisfied:
- $a_{1}^{2} + a_{2}^{2} + ... + a_{n}^{2} ≥ x$
- $a_{1} + a_{2} + ... + a_{n} ≤ y$
|
It is easy to see that in order to maximize the sum of squares, one should make all numbers except the first one equal to 1 and maximize the first number. Keeping this in mind we only need to check whether the given value of y is large enough to satisfy a restriction that all n numbers are positive. If y is not to small, then all we need is to ensure that $x \le 1 + 1 + \dots + (y - (n - 1))^{2}$
|
[
"greedy"
] | 1,400
| null |
111
|
B
|
Petya and Divisors
|
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:
You are given $n$ queries in the form "$x_{i}$ $y_{i}$". For each query Petya should count how many divisors of number $x_{i}$ divide none of the numbers $x_{i - yi}, x_{i - yi + 1}, ..., x_{i - 1}$. Help him.
|
Let's create an array used[], j-th element of which will be the index of the last number from the input, which is divisible by j. Then for each query we'll iterate over all divisors of xi and for each k, which divides xi we'll check whether it is "unique". After that we'll update used[k].
|
[
"binary search",
"data structures",
"number theory"
] | 1,900
| null |
111
|
C
|
Petya and Spiders
|
Little Petya loves training spiders. Petya has a board $n × m$ in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to some of the four side-neighboring cells (that is, one command for each of the four possible directions). Petya gives the commands so that no spider leaves the field. It is allowed for spiders to pass through each other when they crawl towards each other in opposite directions. All spiders crawl simultaneously and several spiders may end up in one cell. Petya wants to know the maximum possible number of spider-free cells after one second.
|
This problem has many different approaches. One of them uses the fact that the overall number of possible inputs is small and it is possible to compute the answer manually for all of them. One could also write a brute-force with a few optimizations, which works even without a precalc. However, the major part of all solutions involved dynamic programming with bitmasks. The solution below was described by Zlobober. Instead of counting the maximal number of free cells, we'll count the minimal number of occupied cells. We'll assume that the number of rows is not greater than 6 (otherwise we can rotate the board). Let D[k][pmask][mask] be the minimal number of occupied cells in the first k columns with the restrictions that the k-th column is described by pmask (ones correspond to occupied cells and zeroes correspond to free cells) and k+1-st column is described by mask. To make a transition from D[k-1][*][*] we can iterate over all possible masks for the k-1-st column, check whether we can distribute spiders in kth column knowing the masks for k+1-st and k-1-st columns and find the minimal value of D[k-1][*][pmask] for all such masks. The overall complexity is O(n*23m), n > m.
|
[
"bitmasks",
"dp",
"dsu"
] | 2,100
| null |
111
|
D
|
Petya and Coloring
|
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size $n × m$ ($n$ rows, $m$ columns) in $k$ colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
|
One can notice that if $m = 1$ then the answer is kn, because all colorings are possible. Now we'll assume that m > 1. Let's look on the first column of the board (i.e. the vertical cut will be made right next to the first column). Suppose there are x distinct colors in this column. Then in the rest of the board there are also x colors. If we move the vertical line by one unit to the right, the number of different colors to the left of it will not decrease and the number of colors to the right of it won't increase. It means that the number of different colors in both parts of the board will be also x. We can repeat this process until the line reaches the rightmost column, which means that the number of distinct colors in it is also x. It is easy to see that we can only use colors which belong to the intersection of sets of colors in the leftmost and rightmost columns in the rest of the board. Let's iterate over all values of x and y, where x is the number of colors in the leftmost column and y is the number of elements in intersection of sets of colors in the rightmost and leftmost columns. It is easy to see that x is limited by the number of rows in the board and y can't be greater than x. Let's find the answer for all such pairs of x and y and at the end we'll add them up together. Suppose x and y are fixed. We first need to choose (2x - y) colors from the given k colors, which we will use, which means that the answer for will be multiplied by C(k, 2x - y). After that we'll choose (x-y) unique colors which will be used in the first column, which means that the answer will be also multiplied by C(2x-y, x-y). Then we'll choose x-y colors for the rightmost column and multiply the answer by C(x, x-y). Now all we need to know is how many ways of coloring n cells into x colors are there. We'll use a dynamic programming approach to solve this sub-problem. Let d[i][j] be the number of ways to color a rectangle of unit width and length i into colors, numerated from 1 to j with the following restriction: if a < b then the first appearence of color a in the rectangle will be before the first appearence of color b. Then we can calculate this function using the following recurrence: d[i][j] = j * d[i - 1][j] + d[i - 1][j - 1]. After we finish calculating d[i][j], we need to multiply the answer by d[n][x]2 (to color the first and the last columns). Now we need to notice that we can reorder all colors in the first and the last columns in arbitrary way, which means that the answer should be multiplied by (x!)2. Finally, we need to multiply the answer by yn(m-2), which correspond to coloring the rest of our board. Some contestants had problems with time limit, because of calculation of C(N,K). One can notice that we won't need more than 2000 colors, which reduces the time significantly. Author's solution worked less than 200ms with the time-limit of 5s.
|
[
"combinatorics",
"dp"
] | 2,300
| null |
111
|
E
|
Petya and Rectangle
|
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells $n × m$ in size (containing $n$ rows, $m$ columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a \underline{simple path} between those two cells as a sequence of distinct cells $a_{1}, a_{2}, ..., a_{k}$, where $a_{1}$ and $a_{k}$ are the two marked cells. Besides, $a_{i}$ and $a_{i + 1}$ are side-neighboring cells of the path ($1 ≤ i < k$). Let's denote the path length as number $k$ (the sequence length).
Petya's task is to find the longest simple path's length and to print the path. Help him.
|
Let the length of the maximal path be S. First, we'll estimate the value of S without specifying the longest path itself. Let's color our board into a chess-coloring. Obviously, each two neighboring cells in the path will have different color. Keeping this in mind we can make some estimation on the value of S. For example, if there are 4 white cells and 5 black cells on the board and we know that both starting and ending cells are white, than the length of the path can't be greater than 7, because white and black cells must alternate in the path. It appears that for the constraints mentioned in the statement, this theoretical bound for S is always achievable. All we need is to find the path of the length S. Author solution divides the board into 5 pieces and solves the problem for each piece separately. Let's divide the board into 5 parts as it was shown on the first picture. We'll assume that the relative location of the starting and ending cells is the same as on the picture. In each part we'll try to build a longest path which completely belongs to it. For the first part we'll try to build a path from the upper-right corner to the upper-left corner. Similar rules will hold for all other parts (see the picture above for further clarification). Paths can be different for different boards, but they will have similar structure. One can notice that there are only two types of paths (with respect to rotations of the board): the one which starts at the upper-left corner and ends at the bottom-right corner and the one which starts at the upper-left corner and ends at the upper-right corner. Now we can write down an algorithm: 1) Divide the board into 5 parts. 2) Find the longest path in each of the parts. 3) Check if the total length is equal to S. 4) If the above is false, then rotate or reflect the board and continue to the step 1. In order to find the longest path in a particular part, one can either consequently move through all rows of the part or through all its columns. This solution gives correct answers for all $4 \le n, m \le 20$. All possible cases of parity of each part are feasible within those constraints, which means that the solution will work for all boards, including ones with n > 20 or m > 20. The overall complexity of described algorithm is O(N*M).
|
[] | 2,900
| null |
112
|
A
|
Petya and Strings
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings \underline{lexicographically}. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
|
In this problem one could transform all letters in both strings to lower case and then compare the strings lexicographically.
|
[
"implementation",
"strings"
] | 800
| null |
112
|
B
|
Petya and Square
|
Little Petya loves playing with squares. Mum bought him a square $2n × 2n$ in size. Petya marked a cell inside the square and now he is solving the following task.
The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal \textbf{up to rotation}.
Petya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him.
|
One can notice that if we want to divide a square into two equal parts, then the cutting line should pass through the center of our square. Thus, if the marked cell contains the center of the square, then we can't make a cut, otherwise we can.
|
[
"implementation",
"math"
] | 1,200
| null |
113
|
A
|
Grammar Lessons
|
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
- There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
- There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
- Masculine adjectives end with -lios, and feminine adjectives end with -liala.
- Masculine nouns end with -etr, and feminime nouns end with -etra.
- Masculine verbs end with -initis, and feminime verbs end with -inites.
- Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
- It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
- There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
- A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
- Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
- All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
|
This task is an example of task that requires accurate realization. After reading the statement one can understand that we have to check whether the text from input represents exactly one correct sentence or no. If yes, therefore the text can be either a single word from our language or a following structure: {zero or non-zero count of adjectives} -> {a single noun} -> {zero or non-zero count of verbs}, and moreover, all these words should have equal gender. So, to check these facts, one can do the following: We count number of words. If this number is equal to 1, we check this word for being a valid word from our language. Otherwise, we can get gender of the first word, and iterate through the rest of the words validating existing of only one noun and order of these words. Also, while iterating we check the gender of each word for being equal to the gender of the first word.
|
[
"implementation",
"strings"
] | 1,600
| null |
113
|
B
|
Petr#
|
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the $s_{begin}$ and ending with the $s_{end}$ (it is possible $s_{begin} = s_{end}$), the given string $t$ has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!
|
Let's find all occurrences of begin and end. Then we'll map the whole string to number 0. After this we will simply add one symbol per iteration to already seen sub-strings and map new strings to some non-negative integers. One can notice that we will never reach a situation when more then 2000 different strings exist, so we can map them easily. Now, as per we know all the ends and beginnings of strings and different string of equal length are mapped to different numbers ( and equal strings are mapped equally), we can simply count the number of necessary sub-strings of certain length. So, we have time complexity $O(N^{2}LogN)$, since we are making $N$ iterations and each is done in O($NLogN$) time.
|
[
"brute force",
"data structures",
"hashing",
"strings"
] | 2,000
| null |
113
|
C
|
Double Happiness
|
On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number $t$ is his lucky number, if it can be represented as:
\[
t = a^{2} + b^{2},
\]
where $a, b$ are arbitrary positive integers.Now, the boys decided to find out how many days of the interval $[l, r]$ ($l ≤ r$) are suitable for pair programming. They decided that the day $i$ ($l ≤ i ≤ r$) is suitable for pair programming if and only if the number $i$ is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days.
|
In this task one have to find quantity of prime numbers that can be reproduced as sum of two perfect squares. Obviously, that $4k + 3$ prime numbers are not suitable as sum of two perfect squares can not be equal to 3 (of course, modulo 4). So, we can prove or use the well-known fact ( also known as Fermat theorem), that every odd $4k + 1$ prime number is a sum of two perfect squares. Also, we have not to forget about 2, as $2 = 1^{2} + 1^{2}$. Now, how can we get this task accepted? Simply using the sieve will exceed memory limit, but we can use block sieve, that works in the same time ($O(N\log\log N)$), but uses $O({\sqrt{N}})$ of memory. Also, we can use precalc for intervals of length equal to 100000. Also, Romka used the fact, that using bitset compress memory up to 8 times, and it will enough to suite the ML. Also, it would be nice to count only odd numbers while buliding the sieve.
|
[
"brute force",
"math",
"number theory"
] | 2,200
| null |
113
|
D
|
Museum
|
One day as Petya and his friend Vasya were having one of their numerous trips, they decided to visit a museum castle. The museum has a specific shape: it consists of $n$ rooms connected with $m$ corridors so that one can access any room from any other one.
After the two friends had a little walk around the museum, they decided to split and watch the pieces of art each of them found interesting. They agreed to meet in one of the rooms at six p.m. However, they forgot one quite essential thing: they didn't specify the place to meet and when the time came, they started to rush about the museum looking for each other (they couldn't call each other as roaming made a call's cost skyrocket).
Yet, even despite the whole rush, they couldn't get enough of the pieces of art, that's why each of them has the following strategy: each minute he make a decision where to go — with probability $p_{i}$ he doesn't move to any other place during this minute (i.e. he stays in the room). With probability $1 - p_{i}$ he equiprobably choose one of the adjacent rooms and went there along the corridor. Here $i$ is the ordinal number of the current room. Building was expensive in ancient times, that's why each corridor connected two different rooms, and any two rooms had no more than one corridor between them.
The boys act simultaneously. As the corridors are dark, it is impossible to meet there; however, one can walk along the corridors in both directions (besides, the two boys can be going through the same corridor simultaneously without meeting). The boys act like that until they meet each other. More formally, the two friends meet when at some moment of time both of them decided to appear in the same room.
For each room find the probability that the boys will meet there considering that at 6 p.m. they are positioned in rooms $a$ and $b$ correspondingly.
|
Let's consider a pair (i, j) as a state - this means that now Petya is in room i, and Vasya is in room j. Therefore, their meeting is state (i, i) for some i. So, it's quite easy to build transition matrix - this means that for each state (i, j) we will know probability of reaching state (x, y) in one step, where $1 \le i, j, x, y \le n$. Also, from meeting state we can reach only the same state. Let's try to solve such a problem - what is the probability of meeting in the first room? We build system of linear algebraic equations: $p_{(i,j)}=\sum_{o v e r\ a l l\;t h e\ r e a c h a b l e\ s t a t e s\ (x,y)}a_{(i,j),(x,y)}p_{(x,y)}$, where $a_{(i, j), (x, y)} -$ probability of transition from state (i,j) to state (x,y). One can notice that $p_{(1, 1)} = 1$, and $p_{(i, i)} = 0$ when $i \neq 1$, and the answer will be $p_{(a, b)}$. This system can be easily solved using Gauss method. Similarly we can solve such a problem for every room (considering that we will meet in certain room), but we have complexity O($n^{7}$), that will not pass time limit. But, after some observations, we now see that each time we are solving system $Ax = b$ (and the only thing that is changing $-$ is vector b). So, we can solve matrix equation $Ax = b$, where b is a matrix with dimensions $n^{2} * n$, and the answer will be in the row that corresponds to state (a, b) . With this approach we have time complexity O($n^{6}$), that will pass time limit.
|
[
"math",
"matrices",
"probabilities"
] | 2,700
| null |
113
|
E
|
Sleeping
|
One day Vasya was lying in bed watching his electronic clock to fall asleep quicker.
Vasya lives in a strange country, where days have $h$ hours, and every hour has $m$ minutes. Clock shows time in decimal number system, in format H:M, where the string H always has a fixed length equal to the number of digits in the decimal representation of number $h - 1$. To achieve this, leading zeros are added if necessary. The string M has a similar format, and its length is always equal to the number of digits in the decimal representation of number $m - 1$. For example, if $h = 17$, $m = 1000$, then time equal to 13 hours and 75 minutes will be displayed as "13:075".
Vasya had been watching the clock from $h_{1}$ hours $m_{1}$ minutes to $h_{2}$ hours $m_{2}$ minutes inclusive, and then he fell asleep. Now he asks you to count how many times he saw the moment at which at least $k$ digits changed on the clock simultaneously.
For example, when switching 04:19 $ → $ 04:20 two digits change. When switching 23:59 $ → $ 00:00, four digits change.
Consider that Vasya has been watching the clock for strictly less than one day. Note that the last time Vasya saw on the clock before falling asleep was "h2:m2". That is, Vasya \textbf{didn't see} the moment at which time "h2:m2" switched to the next value.
|
Let's consider function $F(x)$ (where $x$ is some moment of time) $-$ amount of moments from 0..00:00..00 up to $x$ (and $x$ doesn't switch to next moment ) when n $k$ or more digits will be changed . The answer will be $F(h2: m2) - F(h1: m1)$, also it's necessary not to forget that if $h2: m2 < h1: m1$, then $F(h2: m2)$ will be enlarged by a day. Now we will learn how to calculate $F(x)$. To start with, let's count amount of such numbers when hour will remain the same. As hour is not changing, then $k$ or more digits have to be changed in minutes, but in this case we need our number of minutes to be of the following form: $a..a99...9$, where $a$ means any digit,and at the end we have $k - 1$ nines. So k digits are changing every moment that is divisible by $10^{k - 1}$. So, the total amount of such moments (without changing an hour) is $J_{l.T}\ *\left[\frac{m-1}{10^{k-1}}\right]\ +\left[\frac{m.c-1}{10^{k-1}}\right]$, where$hx$ and $mx$ are numbers of hour and minute in time moment $x$, and [] is integer part. Now let's deal with such moments when hour is changing. If this happens, then minute turns from $m - 1$ to 0, and we have $y$ different digits, where $y$ is amount of non-zero digits of number $m - 1$. Therefore we have to count for hours ( in similar way) amount of moments, when $k - y$ or more digits will be changed. $k - y$ digits are changing every moment that is divisible by $10^{max(0, k - y - 1)}$, this means that total amount of such moments is $[\frac{hx-1}{10^{max(0, k-y-1}}]$. And the final value of $F$ is $F(x)=h x*[\frac{m-1}{10^{k-1}}]+[\frac{m x-1}{10^{k-1}}]+[\frac{h x-1}{10^{m a x(0,k-1)}}]$.
|
[
"combinatorics",
"implementation",
"math"
] | 2,700
| null |
114
|
A
|
Cifera
|
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.
Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number $k$. Moreover, petricium la petricium stands for number $k^{2}$, petricium la petricium la petricium stands for $k^{3}$ and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.
Petya's invention brought on a challenge that needed to be solved quickly: does some number $l$ belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.
|
To solve this task, let's describe what is needed more formally. We should answer whether is number $l$ some positive degree of number $k$ or no. To answer this question we can proceed in 2 ways: 1) Using 64 bit data type, we can find minimal degree $h$ of number $k$, such that $k^{h} \ge l$. If $k^{h} = l$, then the answer is $YES$, and number of articles is equal to $h - 1$. Otherwise, the answer is $NO$. 2) We will divide $l$ by $k$, until $k$ divides $l$ and $l \neq 1$. If $l = 1$, then the answer - $YES$ and number of articles is equal to $numberOfDivisions - 1$, and the answer is $NO$ otherwise.
|
[
"math"
] | 1,000
| null |
114
|
B
|
PFAST Inc.
|
When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.
To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.
|
We can reformulate the statement more formally. In this case, we have a undirected graph, and we have to find some maximal clique in it. If we have a look to constraint $n \le 16$, then there can be noticed that we can iterate over all possbile subsets of vertices and find the answer. To do this, one can use bit masks and iterate from 0 to $2^{16}$, checking current subgraph for being a clique. Also, it's necessary not to forget about sorting the names while printing the answer.
|
[
"bitmasks",
"brute force",
"graphs"
] | 1,500
| null |
115
|
A
|
Party
|
A company has $n$ employees numbered from $1$ to $n$. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee $A$ is said to be the \underline{superior} of another employee $B$ if at least one of the following is true:
- Employee $A$ is the immediate manager of employee $B$
- Employee $B$ has an immediate manager employee $C$ such that employee $A$ is the superior of employee $C$.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all $n$ employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees $A$ and $B$ such that $A$ is the superior of $B$.
What is the minimum number of groups that must be formed?
|
We let an employee without a manager called as root. There's an edge from a manager to an employee that he/she manages. First notice that the graph is a collection of directed trees. Hence, we can assign a depth label to each node - denoting the number of nodes on the simple path from the root to it. The answer is then the maximum depth a node has. Why? First, the answer is bounded below by this number because any pair of employees in this path cannot be in the same group. Second, since the graph is a tree, each node in the graph has a unique depth label assigned to it. Simply put all nodes with the same depth in the same group. It's fairly easy to see that no one will be the superior of another within a group, for otherwise their depths will not be equal.
|
[
"dfs and similar",
"graphs",
"trees"
] | 900
| null |
115
|
B
|
Lawnmower
|
You have a garden consisting entirely of grass and weeds. Your garden is described by an $n × m$ grid, with rows numbered $1$ to $n$ from top to bottom, and columns $1$ to $m$ from left to right. Each cell is identified by a pair $(r, c)$ which means that the cell is located at row $r$ and column $c$. Each cell may contain either grass or weeds. For example, a $4 × 5$ garden may look as follows (empty cells denote grass):
You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell $(1, 1)$. At any moment of time you are facing a certain direction — either left or right. And initially, you face right.
In one move you can do either one of these:
1) Move one cell in the direction that you are facing.
- if you are facing right: move from cell $(r, c)$ to cell $(r, c + 1)$
- if you are facing left: move from cell $(r, c)$ to cell $(r, c - 1)$
2) Move one cell down (that is, from cell $(r, c)$ to cell $(r + 1, c)$), and change your direction to the opposite one.
- if you were facing right previously, you will face left
- if you were facing left previously, you will face right
You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.
What is the minimum number of moves required to mow all the weeds?
|
First, let's observe a particular strategy that turns out to be optimal at the end of our discussion. Suppose we're on a row, facing right. This strategy say that we need to move to the right as long as there is a weed to the right of us either on this row or on the row directly below us. The idea is that we need to mow that weed, hence, we need to move there. If it's in the same row as us, it's fairly obvious we have to mow that before going down. If it's at the row directly below us, since we can't move to the right in the row below us (since we'll be facing left there) we need to move there before going down. The strategy then says that if we no longer need to move right, we go down, and face left. Repeat this until all weeds are mowed (replacing left and right in the discussion above) - and we have our strategy. This strategy is optimal. Proof is using induction - but it's not particularly interesting, so the idea is given instead. Suppose we're on a row, facing right, again. If there exist a weed to the right in this row or below us, then any solution will necessarily move right as far as our strategy goes (for the reason we discussed above). Some solution however choose to go further right despite having no weed in this row or the row directly below us. This solution is not optimal if we need to go left directly after going down, for we can just simply go down instead of going right-down-left. On the other case, if we don't need to go left directly after going down, then it means that we go down twice-in-a-row! Hence, instead of moving right in this row, we go down twice, then move right there. And then the induction can continue and the proof can follow.
|
[
"greedy",
"sortings"
] | 1,500
| null |
115
|
C
|
Plumber
|
Little John aspires to become a plumber! Today he has drawn a grid consisting of $n$ rows and $m$ columns, consisting of $n × m$ square cells.
In each cell he will draw a pipe segment. He can only draw four types of segments numbered from $1$ to $4$, illustrated as follows:
Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment $1$ has ends at top and left side of it.
Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size $1 × 2$.
Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling \textbf{all} of the empty cells with pipe segments. Print this number modulo $1000003$ ($10^{6} + 3$).
Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
|
To solve this problem, let's imagine that the left and top sides of the grid also determines whether the pipe adjacent to that side has an end connecting it to the side or not. There are 2^(N+M) ways to pick them. We claim that if we fix them (i.e., pick one of the possible 2^(N+M) ways, then the entire grid's pipes are fixed). To see this, notice that each pipe segment will have either one vertical end (it either have end on the top or end on the bottom) and one horizontal end (left or right). We can pick any 4 combinations of them. Suppose we pick a row, and determine whether the leftmost pipe should have an end to the left of it, or not. Suppose it doesn't have an opening to the left. It means that the leftmost pipe should have an opening to the right, the next pipe should have an opening to the left, the next pipe to the right, and so on. Continuing this way, we have fixed the horizontal ends for an entire row - and only that. Hence, if we pick one of the possible 2^(N+M) ways to pick the ends, then the horizontal ends of each row and vertical ends of each column is fixed. Since there is exactly one pipe segment that has a particular configuration of ends, there is exactly one possible completed grid for each of the 2^(N+M) ways to pick the ends. Hence, the solution works by first checking if a solution exists. Any pre-assigned pipe simply sets whether or not its corresponding row and column has an end at the left and top side. We need to check that no two pipes sets this value contradictorily. If any of them are contradictory, then we return the answer as 0. Otherwise, we return 2^(number of rows without preassigned cell + number of columns without preassigned cell).
|
[
"math"
] | 2,200
| null |
115
|
D
|
Unambiguous Arithmetic Expression
|
Let's define an unambiguous arithmetic expression (UAE) as follows.
- All non-negative integers are UAE's. Integers may have leading zeroes (for example, $0000$ and $0010$ are considered valid integers).
- If $X$ and $Y$ are two UAE's, then "$(X) + (Y)$", "$(X) - (Y)$", "$(X) * (Y)$", and "$(X) / (Y)$" (all without the double quotes) are UAE's.
- If $X$ is an UAE, then "$ - (X)$" and "$ + (X)$" (both without the double quotes) are UAE's.You are given a string consisting only of digits ("0" - "9") and characters "-", "+", "*", and "/". Your task is to compute the number of different possible unambiguous arithmetic expressions such that if all brackets (characters "(" and ")") of that unambiguous arithmetic expression are removed, it becomes the input string. Since the answer may be very large, print it modulo $1000003$ ($10^{6} + 3$).
|
This problem is solved using Dynamic Programming. The somewhat straightforward dynamic programming is to represent the state as {start_pos, end_pos}, which represents the number of unambiguous arithmetic expression on the substring of the input starting at start_pos and ending at end_pos. This however has a complexity of O(N^3) and is not suitable for our problem. The solution uses the state {pos, braces}. This state is somewhat tricky to explain. This means that we have read the first pos characters in the input. We're expected to read a single unambiguous arithmetic expression, close it with some number of brackets that we don't care (to be explained below), and then, if braces is zero, that's it. Otherwise, we're then expected to read a binary operator (either + - * or /), then open a bracket, then move the state to {pos + some_value, braces-1}. That is, braces keeps track on the number of second operands of binary expression that we need to make. For an example how this works, let's try to solve a particular test case: "++0*+1" Let's denote with quotes the part of the input that we haven't processed. We're going to create the unambiguous arithmetic expression by scanning it left to right and making some choices. There are three choices: 1) Create a unary expression. In the example above, "++0*+1" -> +("+0*+1" We don't really care about where the closing bracket is yet. 2) Create a binary expression. In the example above, +("+0*+1" -> +(("+0*+1" How does this tells that we will need to create a binary expression? The second open bracket does not have any operator preceeding it. The only thing that can makes this a proper prefix of an unambiguous arithmetic expression is that if this bracket belongs to the first operand of a binary expression. For our example, we suppose we read another unary expression +(("+0*+1" -> +((+("0*+1" 3a) Read an integer. In our example above, +((+("0*+1" -> +((+(0))*("+1" There are two questions. a) how do we know the number of closing brackets we have to make? This is actually easy - for every open bracket we have, if it's for a unary expression, we simply close and repeat. Otherwise it's a closing bracket for possibly the first operand to a binary expression, so we close it, and we read a binary operator (* in the example above), and try to read the second operand of the binary expression. Finally: +((+(0))*("+1" -> +((+(0))*(+("1" 3b) We try to read an integer again and we have no open brackets that belongs to the first operand of a binary expression, and we have ourself a possible answer. +((+(0))*(+("1" -> +((+(0))*(+(1))) So, in the state {pos, braces}, pos determines the starting location of the remaining unprocessed input. braces indicates the number of open brackets that belongs to a binary expression. So, in the examples above: 1) "++0*+1" -> +("+0*+1" is represented by {0, 0} -> {1, 0} More specifically, for unary expressions, {pos, braces} -> {pos+1, braces} 2) +("+0*+1" -> +(("+0*+1" is represented by {1, 0} -> {1, 1} More specifically, for binary expressions, {pos, braces} -> {pos, braces+1} 3a) +((+("0*+1" -> +((+(0))*("+1" {2, 1} -> {4, 0} More specifically, {pos, braces} -> {pos + length_of_integer + 1, braces-1} 3b) +((+(0))*(+("1" -> +((+(0))*(+(1))) {5, 0} -> Done More specifically, {pos, braces} -> done if braces is zero and the remaining input forms a single integer.
|
[
"dp",
"expression parsing"
] | 2,600
| null |
115
|
E
|
Linear Kingdom Races
|
You are a car race organizer and would like to arrange some races in Linear Kingdom.
Linear Kingdom has $n$ consecutive roads spanning from left to right. The roads are numbered from $1$ to $n$ from left to right, thus the roads follow in the order of their numbers' increasing. There will be several races that may be held on these roads. Each race will use a \textbf{consecutive} subset of these roads. Also, each race will pay some amount of money to you if this race is held. No races overlap in time, so some roads can be used in several races.
Unfortunately, some of the roads are in a bad condition and they need repair. Each road has repair costs associated with it, you are required to pay this cost to repair the road. A race can only take place if all the roads used in the race are renovated. Your task is to repair such roads (possibly all or none) that will maximize your profit. Your profit is defined as the total money you get from the races that are held minus the total money you spent to repair the roads. Note that you may decide not to repair any road and gain zero profit.
Print the maximum profit you can gain.
|
We process the roads one by one. Associated with each road is the races whose UBi is that road (i.e., races that 'ends' at that road). We will discuss the Dynamic Programming solution first, then improve it with a data structure into the optimal solution. Let's say we're going to process a road. Our state is this : DP[X] is the maximum possible profit such that the last X roads before this road are fixed and the X+1-th road before this road is NOT fixed. We are going to compute the value of DP for the next iteration, let's call this FUTURE. FUTURE[0] is obtained if we don't fix this road, FUTURE[0] = maximum amongst the value of DP. Otherwise, if we decide to fix this road, then for each of DP[X], FUTURE[X+1] >?= DP[X] - cost to fix the road + all races' profit that ends at this road and whose starting point is not before X roads from current road (i.e., all the races that is contained and ends at this road). This should work in N^2 + N * M. It can be improved to N^2 + M The data structure approach is slightly different. We will use a segment tree that allows finding a maximum value in a subset and modifying the values of a range, all of which should work in either O(1) or O(log N). The segment tree will consist of N+1 leaves. However, not all the leaves are active at the start of the algorithm. At the start, only one leaf is active and it corresponds to the initial value of DP[0]. Next, we can compute the maximum value amongst all active leaves in O(log N). Then, we create a new active leaf that corresponds to FUTURE[0]. This will be located in the same tree however, the values represented by the leaves will be shifted one to the right - this is done implicitly (for example, we use the last node as DP[0] for the first iteration, but treat it as DP[1] for the next, and so on). These shifted values will correspond to FUTURE[X], since we notice that FUTURE[X] = DP[X-1] - cost to fix the road + races that this series contains and ends at this current road (i.e., it's value directly depends on the leaf BEFORE it was shifted). Next, we decrement the value of all these new leaves (except FUTURE[0]) by the cost to fix the road (in O(log N)). Finally, for each race that ends at this road, we increment the value of the leaves that contains this race. This will be continuous, i.e., FUTURE[X] for X in [race_len, INFINITY]. This can also be done in O(log N). Since a race ends at at most one road, the total complexity this will contribute is M log N. The answer will then simply the maximum value amongst all members of the tree.
|
[
"data structures",
"dp"
] | 2,400
| null |
116
|
A
|
Tram
|
Linear Kingdom has exactly one tram line. It has $n$ stops, numbered from $1$ to $n$ in the order of tram's movement. At the $i$-th stop $a_{i}$ passengers exit the tram, while $b_{i}$ passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.
Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit \textbf{before} any entering passenger enters the tram.
|
If we know the number of people inside the tram at all possible time, then the answer is the maximum of such. We observe that the number of people inside the tram changes only at tram stops. The conclusion is that the answer will be the maximum of the number of people inside the tram directly before arriving at a particular stop and directly after leaving a particular stop (the more observant readers can notice that using only one of these is sufficient). It's sufficiently easy to calculate the number of people inside the tram directly before and after leaving a tram stop.
|
[
"implementation"
] | 800
| null |
116
|
B
|
Little Pigs and Wolves
|
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size $n × m$. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.
They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.
What is the maximum number of little pigs that may be eaten by the wolves?
|
No... not maximum matching ;) So, an equivalent less-evil rewording of the problem would be: "Return the number of wolves that are adjacent to at least one pig". To see this, since each pig has at most one wolf adjacent to it (the constraints impose that) we don't need to worry at a single pig may get eaten by two different wolves. Hence, each wolf can eat any of the pig adjacent to it.
|
[
"greedy",
"implementation"
] | 1,100
| null |
117
|
A
|
Elevator
|
And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All $n$ participants who have made it to the finals found themselves in a huge $m$-floored $10^{8}$-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".
The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time $0$) the elevator is located on the $1$-st floor, then it moves to the $2$-nd floor, then — to the $3$-rd floor and so on until it reaches the $m$-th floor. After that the elevator moves to floor $m - 1$, then to floor $m - 2$, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.
For each of the $n$ participant you are given $s_{i}$, which represents the floor where the $i$-th participant starts, $f_{i}$, which represents the floor the $i$-th participant wants to reach, and $t_{i}$, which represents the time when the $i$-th participant starts on the floor $s_{i}$.
For each participant print the minimum time of his/her arrival to the floor $f_{i}$.
If the elevator stops on the floor $s_{i}$ at the time $t_{i}$, then the $i$-th participant can enter the elevator immediately. If the participant starts on the floor $s_{i}$ and that's the floor he wanted to reach initially ($s_{i} = f_{i}$), then the time of arrival to the floor $f_{i}$ for this participant is considered equal to $t_{i}$.
|
Consider three cases. $s = f$, $ans = t$. $s < f$, we must find the smallest non-negative $k$ such, that $t \le (s - 1) + 2(m - 1)k$. $ans = s - 1 + 2(m - 1)k + (f - s)$. $s > f$, similarly, we must find the smallest non-negative $k$ such, that $t \le 2(m - 1) - (s - 1) + 2(m - 1)k$. $ans = 2(m - 1) - (s - 1) + 2(m - 1)k + (s - f)$. We can find $k$ in any reasonable manner, for example, by using formulas of integer division.
|
[
"implementation",
"math"
] | 1,300
| null |
117
|
B
|
Very Interesting Game
|
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string $s_{1}$, consisting of exactly nine digits and representing a number that does not exceed $a$. After that second player looks at $s_{1}$ and writes a string $s_{2}$, consisting of exactly nine digits and representing a number that does not exceed $b$. Here $a$ and $b$ are some given constants, $s_{1}$ and $s_{2}$ are chosen by the players. The strings are allowed to contain leading zeroes.
If a number obtained by the concatenation (joining together) of strings $s_{1}$ and $s_{2}$ is divisible by $mod$, then the second player wins. Otherwise the first player wins. You are given numbers $a$, $b$, $mod$. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move.
|
Suppose, that the first player made a move $x \le a$, then consider the remainder $rem = x \cdot 10^{9}%mod$. Obviously, if $(mod - rem)%mod \le b$, then the second player can win. Thus, we must iterate through all relevant values of $x$ (we don't need iterate through more than $mod$ values) and check whether the second player to win. If there exist a losing move for second player, then won the first, else second. Since we iterate through all relevant moves of the first player, then we can easily determine his winning move (if such move exist).
|
[
"brute force",
"number theory"
] | 1,800
| null |
117
|
C
|
Cycle
|
A \underline{tournament} is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes $u$ and $v$ ($u ≠ v$) exists either an edge going from $u$ to $v$, or an edge from $v$ to $u$.
You are given a tournament consisting of $n$ vertexes. Your task is to find there a cycle of length three.
|
If the tournament has at least one cycle, then there exist a cycle of length three. A constructive proof. Find any cycle in the tournament by using any standard algorithm, such as depth-first search. If there is no cycle, then output -1, else choose any three consecutive vertices of the cycle $v_{1}$ $v_{2}$ $v_{3}$ ($A_{v1, v2} = A_{v2, v3} = 1$). Since given graph is a tournament, then there is an edge ($v_{3}$, $v_{1}$), or there is an edge ($v_{1}$, $v_{3}$). The first of these two cases, we find immediately the cycle of length three of the vertices $v_{1}$ $v_{2}$ $v_{3}$, the second, we can reduce the length of the loop (erase vertex $v_{2}$). We can reduce the length of the cycle until we find a cycle of length three.
|
[
"dfs and similar",
"graphs"
] | 2,000
| null |
117
|
D
|
Not Quick Transformation
|
Let $a$ be an array consisting of $n$ numbers. The array's elements are numbered from $1$ to $n$, $even$ is an array consisting of the numerals whose numbers are even in $a$ ($even_{i} = a_{2i}$, $1 ≤ 2i ≤ n$), $odd$ is an array consisting of the numberals whose numbers are odd in $а$ ($odd_{i} = a_{2i - 1}$, $1 ≤ 2i - 1 ≤ n$). Then let's define the transformation of array $F(a)$ in the following manner:
- if $n > 1$, $F(a) = F(odd) + F(even)$, where operation "$ + $" stands for the arrays' concatenation (joining together)
- if $n = 1$, $F(a) = a$
Let $a$ be an array consisting of $n$ numbers $1, 2, 3, ..., n$. Then $b$ is the result of applying the transformation to the array $a$ (so $b = F(a)$). You are given $m$ queries $(l, r, u, v)$. Your task is to find for each query the sum of numbers $b_{i}$, such that $l ≤ i ≤ r$ and $u ≤ b_{i} ≤ v$. You should print the query results modulo $mod$.
|
Imagine a recursion tree our transformation $F$. This tree is binary. We write on the edges leading into the left subtree, zero, and on the edges, leading to the right, one. Now consider the path of some number $a$ (hereafter, we assume that we substracted one from all numbers in the array over which we make the conversion). This path start in the root of the tree and end in some leaf, and numbers written on the edges of the path is exactly bit representation of $a$ in order from least significant bit to the most significant bit. Construct the recursive function which solve our problem, similar to how we carry out a query to the segment tree. Here is the prototype of this function. $solve(idx, tl, tr, l, r, u, v)$ This function returns the answer to the query $(l, r, u, v)$, if we consider only subtree with positions $[tl, tr]$, while on the path from the root to the subtree is written bit representation of $idx$. If $l \le tl \le tr \le r$, then we calculate answer by formulae, else we divide our segment of positions and return sum of answers from left and right part. As described above, the answer to the whole subtree is a formula. Here you need to use the fact that all the numbers in the subtree have the form $k \cdot 2^{depth} + idx$, where $depth$ - depth of subtree. We must find $k$ such, that $u \le k \cdot 2^{depth} + idx \le v$ and then calculate the sum of appropriate numbers. Asymptotics of this solution $O(m \cdot log(n) \cdot (formulae - for - whole - subtree))$. We can calculate formulae for whole subtree in $O(logn)$.
|
[
"divide and conquer",
"math"
] | 2,500
| null |
117
|
E
|
Tree or not Tree
|
You are given an undirected connected graph $G$ consisting of $n$ vertexes and $n$ edges. $G$ contains no self-loops or multiple edges. Let each edge has two states: on and off. Initially all edges are switched off.
You are also given $m$ queries represented as $(v, u)$ — change the state of all edges on the shortest path from vertex $v$ to vertex $u$ in graph $G$. If there are several such paths, the lexicographically minimal one is chosen. More formally, let us consider all shortest paths from vertex $v$ to vertex $u$ as the sequences of vertexes $v, v_{1}, v_{2}, ..., u$. Among such sequences we choose the lexicographically minimal one.
After each query you should tell how many connected components has the graph whose vertexes coincide with the vertexes of graph $G$ and edges coincide with the switched on edges of graph $G$.
|
In this problem, suggested a solution using heavy light decomposition. Graph, given in problem statement, is a cycle, on which are suspended trees. For each tree construct the data structure (heavy light + segment tree), which can perform $change$ on the path from some vertex to any parent, and to maintain the amount of ones. The same structure we use for the cycle. Suppose, that we have no cycle, i.e. there is just a bunch of trees (forest). Then the amount of switched-on edges uniquely determines the number of connected components (each switched-on edge decrease the amount of components by one). Suppose, that we have only the cycle. Then, similarly, the amount of switched-on edges uniquely determines the number of connected components. We will maintain the amount of switched-on edges in the cycle and in the all trees. So, the answer to the problem $Comps_{cicle} + Comps_{trees} - Cnt_{Cicle}$, where $Comps_{cicle}$ - the amount of connected components in cycle, $Comps_{trees}$ - the amount of connected components in all trees, $Cnt_{Cicle}$ - the amount of vertexes in cycle.
|
[
"data structures",
"divide and conquer",
"graphs",
"implementation",
"trees"
] | 2,900
| null |
118
|
A
|
String Task
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels,
- inserts a character "." before each consonant,
- replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
|
First problem only is realization. In need read input string, delete all uppercase and lowercase vowels letter and print answer.
|
[
"implementation",
"strings"
] | 1,000
| null |
118
|
B
|
Present from Lena
|
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from $0$ to $n$ as the pattern. The digits will form a rhombus. The largest digit $n$ should be located in the centre. The digits should decrease as they approach the edges. For example, for $n = 5$ the handkerchief pattern should look like that:
\begin{verbatim}
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 3 4 3 2 1 0
0 1 2 3 4 5 4 3 2 1 0
0 1 2 3 4 3 2 1 0
0 1 2 3 2 1 0
0 1 2 1 0
0 1 0
0
\end{verbatim}
Your task is to determine the way the handkerchief will look like by the given $n$.
|
Second problem is realization too. Good solution to calc count space in beginning of string. In handkerchief pattern there is 2 * n + 1 rows. In rows form 0 to N number of space is 2 * n - i. In rown number from N + 1 to 2 * N number of space is (I - N) * 2.
|
[
"constructive algorithms",
"implementation"
] | 1,000
| null |
118
|
C
|
Fancy Number
|
A car number in Berland consists of exactly $n$ digits. A number is called beautiful if it has at least $k$ equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of $n$ digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.
Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.
|
In this task it need to find a minimal sum that to find a beautiful number of car. So, there are only 10 available digits. Let us try the minimum cost to have one of those digits repeat at least K times and the lexicographically minimum string that has such cost. Then we pick the best result among all digits. Therefore, we divide the task into subtasks and solve it for each digit separately. To spend the least amount of money and make the maximum number of substitutions for each digit it need replace all the numbers are different from her first modulo 1, then modulo 2, then modulo 3 and etc to increase the module, in this and only this if typed in the sum will be minimal. Of course, if produced the right number of substitutions of K, then the algorithm should stop. However, to get the lexicographically smallest string with K digit C, then the replacement should be performed as follows. Suppose that this step of the algorithm need to change all the numbers that are different from the numbers with modulo I, first time it need replace all digits C + I for digit C from begin to end of string. Second time it need replace all digits C - I for C for end to begin of string, because in need to lexicographically minimum one. After choosing the best answer will be 10 rows. Thus, the asymptotic complexity of the algorithm is 10 * 10 * n.
|
[
"brute force",
"greedy",
"sortings",
"strings"
] | 1,900
| null |
118
|
D
|
Caesar's Legions
|
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had $n_{1}$ footmen and $n_{2}$ horsemen. Caesar thought that an arrangement is \textbf{not} beautiful if somewhere in the line there are strictly more that $k_{1}$ footmen standing successively one after another, or there are strictly more than $k_{2}$ horsemen standing successively one after another. Find the number of \underline{beautiful} arrangements of the soldiers.
Note that all $n_{1} + n_{2}$ warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.
|
The problem is solved lazy dynamics. Let z[n1] [n2] [2] - a number of ways to place troops in a legion of Caesar. Indicate the following parameters, n1 - is a number of footmen, n2 - is a number of horseman, the third parameter indicates what troops put Caesar in the beginning of the line. If Caesar wants to put the footmen, the state dynamics of the z [n1] [n2] [0] go to the state z [n1] [n2 - i] [0], where 0 <= I <= min (k2, n2) . If Caesar wants to put the riders, the state dynamics of the z [n1] [n2] [1] go to the state z [n1] [n2 - i] [1], where 0 <= I <= min (k2, n2) .
|
[
"dp"
] | 1,700
| null |
118
|
E
|
Bertown roads
|
Bertown has $n$ junctions and $m$ bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
|
We are given an undirected connected graph, it is necessary to orient its arc so as to obtain a strongly connected directed graph. There is theorem (on a theoretical basis for a written task) that a graph admits an orientation to a strongly connected digraph if and only if every edge is part of what a cycle. To test this, simply run the bfs to the depth of any vertex and orient the edges in the direction of the bfs. The result of this procedure is an orientation of the graph. To make sure that in the original graph has no bridges, it need to take the orientation of the resulting graph, change the direction of arcs in it, and check that there remains a strong connection. This may be check by dfs too.
|
[
"dfs and similar",
"graphs"
] | 2,000
| null |
119
|
A
|
Epic Game
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number $a$ and Antisimon receives number $b$. They also have a heap of $n$ stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has \underline{strictly} less stones left than one needs to take).
Your task is to determine by the given $a$, $b$ and $n$ who wins the game.
|
It's enough just to model the described game to solve this problem. You can search a greatest common divisor in any reasonable way.
|
[
"implementation"
] | 800
|
#include <iostream>
using namespace std;
int gcd(int x, int y)
{
return (x==0)? y : gcd(y % x, x);
}
int main()
{
int a, b, n;
cin >> a >> b >> n;
int k = 0;
while (n >= 0)
{
++k;
n -= gcd((k & 1) ? a : b, n);
}
if (k & 1) cout << 1; else cout << 0;
}
|
119
|
B
|
Before Exam
|
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...
To prepare for the exam, one has to study proofs of $n$ theorems. It is known that there will be $k$ examination cards on the exam and each card contains $\left\lfloor{\frac{22}{k}}\right\rfloor$ distinct theorems. Besides, no theorem is mentioned in more than one card (that is, $n-k\cdot\lfloor{\frac{n}{k}}\rfloor$ theorems won't be mentioned in any card). During the exam several students may get the same card.
We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his \underline{level of proficiency in the $i$-th theorem} by some number $a_{i}$. \underline{The level of proficiency in some card} is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.
|
Let's consider solution of the task for maximum level of profience (for minimum level solution is similar). It's clear that maximum level can be reached either in a card that has fallen one somebody's lot already or in a card about that we know nothing. In the first case we can just calculate levels of profiency for all cards from input and choose maximal level. The second case is more tricky. Let's sort all the theorems that weren't mentioned in cards from input in order of non-increasing of profiency's level. It's obvious that sought-for card consists of first $\left\lfloor{\frac{22}{k}}\right\rfloor$ theorems in sorted list. This case is possible if the number of different cards mentioned in input is stictly less than k. For example, in the test 3 2 1 2 3 2 1 2 we can't consider a card containing third theorem because both examination cards are already known.
|
[
"constructive algorithms",
"implementation",
"sortings"
] | 1,900
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int n, k, a[100], q, ans_mx = -1, ans_mn = 1E9, nmb;
bool used[100];
vector<int> rem;
int main()
{
cin >> n >> k; nmb = n / k;
for (int i = 0; i < n; ++i) cin >> a[i];
int f = 0;
cin >> q;
for (int i = 0; i < q; ++i)
{
bool yes = false;
int cur, sum = 0;
for (int j = 0; j < nmb; ++j)
{
cin >> cur; --cur;
if (!used[cur] && !yes)
{
yes = true;
++f;
}
used[cur] = true;
sum += a[cur];
}
ans_mx = max(ans_mx, sum);
ans_mn = min(ans_mn, sum);
}
for (int i = 0; i < n; ++i)
if (!used[i]) rem.push_back(a[i]);
sort(rem.begin(), rem.end());
if (rem.size() >= nmb && f < k)
{
int sum1 = 0,sum2 = 0;
for (int i = 0; i < nmb; ++i) { sum1 += rem[i]; sum2 += rem[rem.size() - 1 - i]; }
ans_mx = max(ans_mx, sum2);
ans_mn = min(ans_mn, sum1);
}
printf("%.10lf %.10lf", ans_mn * 1.0 / nmb, ans_mx * 1.0 / nmb);
return 0;
}
|
119
|
C
|
Education Reform
|
Yet another education system reform has been carried out in Berland recently. The innovations are as follows:
An academic year now consists of $n$ days. Each day pupils study exactly one of $m$ subjects, besides, each subject is studied for no more than one day. After the lessons of the $i$-th subject pupils get the home task that contains no less than $a_{i}$ and no more than $b_{i}$ exercises. Besides, each subject has a special attribute, the complexity ($c_{i}$). A school can make its own timetable, considering the following conditions are satisfied:
- the timetable should contain the subjects in the order of the complexity's strict increasing;
- each day, except for the first one, the task should contain either $k$ times more exercises, or more by $k$ compared to the previous day (more formally: let's call the number of home task exercises in the $i$-th day as $x_{i}$, then for each $i$ ($1 < i ≤ n$): either $x_{i} = k + x_{i - 1}$ or $x_{i} = k·x_{i - 1}$ must be true);
- the total number of exercises in all home tasks should be maximal possible.
All limitations are separately set for each school.
It turned out that in many cases $a_{i}$ and $b_{i}$ reach $10^{16}$ (however, as the Berland Minister of Education is famous for his love to half-measures, the value of $b_{i} - a_{i}$ doesn't exceed $100$). That also happened in the Berland School №256. Nevertheless, you as the school's principal still have to work out the timetable for the next academic year...
|
This problem can be solved by dynamic programming. Let's sort all subjects in order of complexity's non-increasing. Let $d < / span > [ < spanstyle = "" > i < / span > ][ < spanstyle = "" > j < / span > ][ < spanstyle = "" > z < / span > ]$ is the greatest summary number of exercises, that can be given, if timetable contains exactly $z$ subjects from among of first $i$ subjects (in order of sort), involves $i$th subject and number of exercises in $i$th subject is equal to $a_{i} + j$. Recurrent correlations are based on search of subject that will occupy ($< spanstyle = "" > z < / span > - 1$)th day in timetable. For restoration of answer you should save source numbers of subjects. Asymptotic complexity is $O(m^{2} \cdot n \cdot max(b_{i} - a_{i}))$.
|
[
"dp"
] | 2,000
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct TSubject
{
__int64 a, b;
int nmb, c;
} sb[100];
bool operator < (const TSubject &x, const TSubject &y)
{
return x.c < y.c;
}
int n, m, k, cur = 0;
__int64 d[50][101][51];
pair<int, int> p[50][101][51], state;
int main()
{
cin >> n >> m >> k;
for (int i = 0; i < m; ++i)
{
cin >> sb[i].a >> sb[i].b >> sb[i].c;
sb[i].nmb = i + 1;
}
sort(sb, sb + m);
state = make_pair(0, 0);
for (int i = 0; i < m; ++i)
for (int j = 0; j <= sb[i].b - sb[i].a; ++j)
{
d[i][j][1] = sb[i].a + j;
for (int z = 2; z <= n; ++z)
{
d[i][j][z] = -1;
for (int last = i - 1; last >= 0; --last)
if (sb[last].c < sb[i].c)
for (int t = 0; t <= 1; ++t)
{
__int64 temp = sb[i].a + j;
bool yes = (t == 0) ? temp % k == 0 : temp >= k;
temp = (t == 0) ? temp / k : temp - k;
temp -= sb[last].a;
if (!yes) continue;
if (temp >= 0 && temp <= sb[last].b - sb[last].a
&& d[last][temp][z - 1] != -1
&& d[last][temp][z - 1] + sb[i].a + j > d[i][j][z])
{
d[i][j][z] = d[last][temp][z - 1] + sb[i].a + j;
p[i][j][z] = make_pair(last, temp);
}
}
}
if (d[i][j][n] > d[state.first][state.second][n])
state = make_pair(i, j);
}
if (d[state.first][state.second][n] == -1)
{
cout << "NO";
return 0;
}
vector<pair<int, __int64> > ans;
for (int i = n; i >= 1; --i)
{
ans.push_back(make_pair(sb[state.first].nmb, sb[state.first].a + state.second));
state = p[state.first][state.second][i];
}
cout << "YES" << endl;
for (int i = n - 1; i >= 0; --i)
cout << ans[i].first << ' ' << ans[i].second << endl;
return 0;
}
|
119
|
D
|
String Transformation
|
Let $s$ be a string whose length equals $n$. Its characters are numbered from 0 to $n - 1$, $i$ and $j$ are integers, $0 ≤ i < j < n$. Let's define function $f$ as follows:
$f(s, i, j) = s[i + 1... j - 1] + r(s[j... n - 1]) + r(s[0... i])$.
Here $s[p... q]$ is a substring of string $s$, that starts in position $p$ and ends in position $q$ (inclusive); "+" is the string concatenation operator; $r(x)$ is a string resulting from writing the characters of the $x$ string in the reverse order. If $j = i + 1$, then the substring $s[i + 1... j - 1]$ is considered empty.
You are given two strings $a$ and $b$. Find such values of $i$ and $j$, that $f(a, i, j) = b$. Number $i$ should be maximally possible. If for this $i$ there exists several valid values of $j$, choose the minimal $j$.
|
If lengths of input strings aren't equal, we can at once output "-1 -1" and complete execution of a program. Otherwise let number $n$ is equal to the length of input strings. Let's iterate through the number $i$. We should find (in $O(1)$) the such smallest number $j$, that substing $b[0... n - i - 1]$ can be represented as $a[i + 1... j - 1] + r(a[j... n - 1]$). In order to do that, let's calculate the prefix function ($p[i]$) for string $s_{1} = r(a) + ' 0' + b$ and z-function ($z[i]$) for string $s_{2} = b + ' 0' + a$. It's clear that for fixed $i$ value of $j$ is equal to $n - p[2n - i - 1]$, and substrings $a[i + 1... j - 1]$, $b[0... j - i]$ must coincide at that (1). The last condition can be easily verified through using of calculated z-function. You can also trivial prove the next statement: if the property (1) is not satisfied by fixed $i$ for the chosen $j$, then it will not meet for bigger $j$. Asymptotic complexity is $O(n)$.
|
[
"hashing",
"strings"
] | 2,500
|
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string a, b, s1, s2;
int main()
{
getline(cin, a);
getline(cin, b);
if (a.length() != b.length())
{
cout << "-1 -1";
return 0;
}
int n = a.length();
s1 = a; reverse(s1.begin(),s1.end()); s1 += ' ' + b;
s2 = b + ' ' + a;
int *p = new int[2 * n + 1];
p[0] = 0;
for (int i = 1; i < 2 * n + 1; ++i)
{
p[i] = p[i - 1];
while (p[i] > 0 && s1[p[i]] != s1[i])
p[i] = p[p[i] - 1];
if (s1[p[i]] == s1[i])
++p[i];
}
int *z = new int[2 * n + 1];
z[0] = 0;
for (int i = 1, l = 0, r = 0; i < 2 * n + 1; ++i)
{
z[i] = 0;
if (i <= r)
z[i] = min(z[i - l], r - i + 1);
while (i + z[i] < 2 * n + 1 && s2[z[i]] == s2[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
{
l = i;
r = i + z[i] - 1;
}
}
int ans_i = -1, ans_j = -1;
for (int i = 0; i < n - 1; ++i)
{
if (a[i] != b[n - i - 1]) break;
int len = p[2 * n - i - 1];
if (z[n + i + 2] >= n - i - len - 1)
{
ans_i = i;
ans_j = n - len;
}
}
cout << ans_i << ' ' << ans_j << endl;
return 0;
}
|
120
|
A
|
Elevator
|
A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand.
One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.
|
You can either check all four cases or notice, that if we consider front/back equal to 0/1 (b) and decrease a by 1, then a XOR b became the answer (0/1). Time and memory consumption - $O(1)$.
|
[
"brute force",
"implementation",
"math"
] | 1,000
| null |
120
|
B
|
Quiz League
|
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number $k$.
|
Just write one loop: while $k$th question has already been asked, increase $k$ by one and if $k > n$ let $k = 1$. Time and memory consumpiton - $O(n)$.
|
[
"implementation"
] | 1,100
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.