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
255
A
Greg's Workout
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was $n$ integers $a_{1}, a_{2}, ..., a_{n}$. These numbers mean that Greg needs to do exactly $n$ exercises today. Besides, Greg should repeat the $i$-th in order exercise $a_{i}$ times. Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the $n$-th exercise. Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
It is not hard problem. We must calculate sums of numbers for each group and print group with maximum count.
[ "implementation" ]
800
null
255
B
Code Parsing
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string $s$, consisting of characters "x" and "y", and uses two following operations at runtime: - Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. - Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string $s$, and the algorithm works as follows: - If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. - If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string $s$.
Not hard to see that after few operations of first type string will become: x..xy..y. After fer operations of second type, there will be only letters of one type, count of this letters will be: |count(x) - count(y)|
[ "implementation" ]
1,200
null
255
D
Mr. Bender and Square
Mr. Bender has a digital table of size $n × n$, each cell can be switched on or off. He wants the field to have at least $c$ switched on squares. When this condition is fulfilled, Mr Bender will be happy. We'll consider the table rows numbered from top to bottom from 1 to $n$, and the columns — numbered from left to right from 1 to $n$. Initially there is exactly one switched on cell with coordinates $(x, y)$ ($x$ is the row number, $y$ is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on. For a cell with coordinates $(x, y)$ the side-adjacent cells are cells with coordinates $(x - 1, y)$, $(x + 1, y)$, $(x, y - 1)$, $(x, y + 1)$. In how many seconds will Mr. Bender get happy?
Solution - binary search for answer. Next we have to calculate the area of a truncated square set at 45 degrees. This can be done as follows: Calculate its total area. Subtract area that cuts off the top line. Similarly, for the lower, left and right line. Add parts that are cutted by corners. You can write a function that finds the length of the truncation desired area, for that would not write a lot of code.
[ "binary search", "implementation", "math" ]
1,800
null
255
E
Furlo and Rublo and Game
Furlo and Rublo play a game. The table has $n$ piles of coins lying on it, the $i$-th pile has $a_{i}$ coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to: - choose some pile, let's denote the current number of coins in it as $x$; - choose some integer $y$ $(0 ≤ y < x; x^{1 / 4} ≤ y ≤ x^{1 / 2})$ and decrease the number of coins in this pile to $y$. In other words, after the described move the pile will have $y$ coins left. The player who can't make a move, loses. Your task is to find out, who wins in the given game if both Furlo and Rublo play optimally well.
Note that after the first move any pile turns into a pile no larger than 1000000. We assume Grundy function for numbers less than 1 million. Grundy function is very small, you can start on the partial sums for each type of function that would quickly tell what function is in the interval, and which are not present. Knowing the answer is not difficult to find small response for all piles.
[ "games", "implementation", "math" ]
2,200
null
256
D
Liars and Serge
There are $n$ people, sitting in a line at the table. For each person we know that he always tells either the truth or lies. Little Serge asked them: how many of you always tell the truth? Each of the people at the table knows everything (who is an honest person and who is a liar) about all the people at the table. The honest people are going to say the correct answer, the liars are going to say any integer from 1 to $n$, which is not the correct answer. Every liar chooses his answer, regardless of the other liars, so two distinct liars may give distinct answer. Serge does not know any information about the people besides their answers to his question. He took a piece of paper and wrote $n$ integers $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the answer of the $i$-th person in the row. Given this sequence, Serge determined that exactly $k$ people sitting at the table \textbf{apparently lie}. Serge wonders, how many variants of people's answers (sequences of answers $a$ of length $n$) there are where one can say that exactly $k$ people sitting at the table apparently lie. As there can be rather many described variants of answers, count the remainder of dividing the number of the variants by $777777777$.
If person say number x, and at all x was said by x persons, then we cannot tell anything about fixed person. Now we understand which sequence are good for us. We will calculate their count wuth dynamic programming dp[n][m][k], n - which persons answers we set to the sequence right now, m - how mant persons gived theis answers, k - how many persons from them are liers. Transfer: dp[n][m][k]*cnk[N-m][n] -> dp[n+1][m+n][k] dp[n][m][k]*cnk[N-m][p] -> dp[n+1][m+p][k+p] p = 1 .. N, p != n. We assume, that N - total number of the persons. This solution get TLE, becouse complexity if O(N^4). We need to use precalc. It will not be so big, as N is power of 2.
[ "dp" ]
2,700
null
256
E
Lucky Arrays
Little Maxim loves interesting problems. He decided to share one such problem with you. Initially there is an array $a$, consisting of $n$ zeroes. The elements of the array are indexed, starting from 1. Then follow queries to change array $a$. Each query is characterized by two integers $v_{i}, t_{i}$. In the answer to the query we should make the $v_{i}$-th array element equal $t_{i}$ $(a_{vi} = t_{i}; 1 ≤ v_{i} ≤ n)$. Maxim thinks that some pairs of integers $(x, y)$ are good and some are not. Maxim thinks that array $a$, consisting of $n$ integers, is lucky, if for all integer $i$, $(1 ≤ i ≤ n - 1)$ the pair of integers $(a_{i}, a_{i + 1})$ — is good. Note that the order of numbers in the pairs is important, that is, specifically, $(1, 2) ≠ (2, 1)$. After each query to change array $a$ Maxim wants to know, how many ways there are to replace all zeroes in array $a$ with integers from one to three so as to make the resulting array (without zeroes) lucky. Of course, distinct zeroes can be replaced by distinct integers. Maxim told you the sequence of queries and all pairs of integers he considers lucky. Help Maxim, solve this problem for him.
Solution is - interval tree. We will save dynamic programming f[i,j] in each vertex, this dp means: in how many ways we can change all 0 to some numbers on interval, such that it will be valid and first element will be i and last will be j. With normal implementation its easy to pass system tests.
[ "data structures" ]
2,400
null
258
A
Little Elephant and Bits
The Little Elephant has an integer $a$, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number $a$ fits on the piece of paper, the Little Elephant \textbf{ought} to delete exactly one any digit from number $a$ in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes). The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
It's pretty easy to notice that you need to delete the first (from the left) 0-digit. The only catchy case is 111...111 - here you need to delete any of 1-digits.
[ "greedy", "math" ]
1,100
null
258
B
Little Elephant and Elections
There have recently been elections in the zoo. Overall there were $7$ main political parties: one of them is the Little Elephant Political Party, $6$ other parties have less catchy names. Political parties find their number in the ballot highly important. Overall there are $m$ possible numbers: $1, 2, ..., m$. Each of these $7$ parties is going to be assigned in some way to exactly one number, at that, two distinct parties cannot receive the same number. The Little Elephant Political Party members believe in the lucky digits $4$ and $7$. They want to evaluate their chances in the elections. For that, they need to find out, how many correct assignments are there, such that the number of lucky digits in the Little Elephant Political Party ballot number is strictly larger than the total number of lucky digits in the ballot numbers of 6 other parties. Help the Little Elephant Political Party, calculate this number. As the answer can be rather large, print the remainder from dividing it by $1000000007$ $(10^{9} + 7)$.
First of all, lets think about the problem of finding array $c_{i}$ - the number of integers from 1 to $m$ such, that the number of lucky digits is equal to $i$. It's pretty standart dynamic programminc problem, which can be solved with state [position][less][count]. It can be solved directly using DP, but to simplify a bit you can use brute force (recursion) to brute all possible assignments of numbers of lucky digits in for all paries (up to 9 digits). Now you can divide all parties in several indepentent groups, each of which should contain the same number of lucky digits. Consider that the party of Litte Elephant is with number 1. Than assignment for the first position should have more digits than the sum of the rest (because of the statement). Since all groups are indepented (because there is no number that can have different number of lucky digits, obviously) you can find the number of resulting assignments for each group and find the final result by multiplying these all numbers and taking modulo $10^{9} + 7$. Consider that you have group of size $t$, each number of which should contain $l$ lucky digits. That it's pretty easy to understand that the number of assignment is equal to $(c_{l}) * (c_{l} - 1) * (c_{l} - 2) * ... * (c_{l} - t + 1)$.
[ "brute force", "combinatorics", "dp" ]
1,900
null
258
C
Little Elephant and LCM
The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of $k$ positive integers $x_{1}, x_{2}, ..., x_{k}$ is the minimum positive integer that is divisible by each of numbers $x_{i}$. Let's assume that there is a sequence of integers $b_{1}, b_{2}, ..., b_{n}$. Let's denote their LCMs as $lcm(b_{1}, b_{2}, ..., b_{n})$ and the maximum of them as $max(b_{1}, b_{2}, ..., b_{n})$. The Little Elephant considers a sequence $b$ good, if $lcm(b_{1}, b_{2}, ..., b_{n}) = max(b_{1}, b_{2}, ..., b_{n})$. The Little Elephant has a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Help him find the number of good sequences of integers $b_{1}, b_{2}, ..., b_{n}$, such that for all $i$ $(1 ≤ i ≤ n)$ the following condition fulfills: $1 ≤ b_{i} ≤ a_{i}$. As the answer can be rather large, print the remainder from dividing it by $1000000007$ $(10^{9} + 7)$.
The complexity of the possible solution is $O(n * sqrt(n) * log(n))$. You can see that statement $lcm(b_{1}, b_{2}, ..., b_{n}) = max(b_{1}, b_{2}, ..., b_{n})$ is equal to statement "All the numbers $b_{1}, b_{2}, ..., b_{n}$ must divide $max(b_{1}, b_{2}, ..., b_{n})$". You can iterate that $max(b_{1}, b_{2}, ..., b_{n})$, let it be equal to $m$. Find all divisors of $m$ and sort them - $p_{1}, p_{2}, ..., p_{k}$. For each $i$ between 1 and $k$ you can find (using simple DP) the number of numbers $a_{j}$ that $p_{i} \le a_{j} < p_{i + 1}$ (if $i = k$ than $p_{i + 1} = max(a_{1}, a_{2}, ..., a_{n}) + 1$), denote it as $q_{i}$. Then the reuslt is equal to $1^{q1} * 2^{q2} * 3^{q3} * ... * p^{qp}$, because for each of the $q_{1}$ numbers there is $1$ way to assign, for each of $q_{2}$ numbers there is $2$ ways of assignments, and so on. But you should notice that if doing this problem in such way, you need to garantee that there is some $i$ such $b_{i} = m$. Hance you need from the last multiplier $(p^{qp})$ subtract $(p - 1)^{qp}$ - all the ways that there is no number equal to $m$.
[ "binary search", "combinatorics", "dp", "math" ]
2,000
null
258
E
Little Elephant and Tree
The Little Elephant loves trees very much, he especially loves root trees. He's got a tree consisting of $n$ nodes (the nodes are numbered from 1 to $n$), with root at node number $1$. Each node of the tree contains some list of numbers which initially is empty. The Little Elephant wants to apply $m$ operations. On the $i$-th operation $(1 ≤ i ≤ m)$ he first adds number $i$ to lists of all nodes of a subtree with the root in node number $a_{i}$, and then he adds number $i$ to lists of all nodes of the subtree with root in node $b_{i}$. After applying all operations the Little Elephant wants to count for each node $i$ number $c_{i}$ — the number of integers $j$ $(1 ≤ j ≤ n; j ≠ i)$, such that the lists of the $i$-th and the $j$-th nodes contain at least one common number. Help the Little Elephant, count numbers $c_{i}$ for him.
Very useful thing in this problem is ordering all vertices in DFS order (preorped). After that any subtree can be represented as a some sequence of continuous vertices. Consider that we have some fixed vertex $v$. Which vertices should be included in $c_{v}$? Obviously, if in the path from the root to $v$ is some non-empty vertex (i. e. such that has at least one integer in its list) than each vertex from substree $v$ should be included in $c_{i}$, but since we now working with preorder traversal of the tree, we consider that every vertex from some segment $[l_{v}, r_{v}]$ must be included to $c_{i}$. More generally, let for each vertex keep some set of segments ($l_{k};r_{k}$). If on the $i$-th operation we have two vertices $a$ and $b$, we add segment $(l_{b};r_{b})$ to vertex $a$, and $(l_{a};r_{a})$ to vertex $b$. Also for each vertex $i$ ($i = 1..n$) we add segment $(l_{i};r_{i})$, where $(l_{i};r_{i})$ is a segment in our preored traversal for subtree $i$. After that, you can see that, if we unite all segments from all vertices on the path from the root to some vertex $v$, we find the result for $v$, which will be the size of the resulting set. So now we need some data structure that would support three operations: add(l, r), subtract(l, r), count(). The first one should add 1 to all positions from $l$ to $r$, inclusive. The second should subtract 1 from all positions from $l$ to $r$, inclusive. The last should count the number of non-zero element. This all can be done either with segment tree or sqrt-decomposition.
[ "data structures", "dfs and similar", "trees" ]
2,400
null
259
A
Little Elephant and Chess
The Little Elephant loves chess very much. One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an $8 × 8$ checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation \textbf{multiple times} (or not run it at all). For example, if the first line of the board looks like that "BBBBBBWW" (the white cells of the line are marked with character "W", the black cells are marked with character "B"), then after one cyclic shift it will look like that "WBBBBBBW". Help the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.
Obviously, the only correct rows are rows WBWBWBWB and BWBWBWBW. Only thing you need to do is to check whether each string is one of these. If yes then print YES, else print NO.
[ "brute force", "strings" ]
1,000
null
259
B
Little Elephant and Magic Square
Little Elephant loves magic squares very much. A magic square is a $3 × 3$ table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15. The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed $10^{5}$. Help the Little Elephant, restore the original magic square, given the Elephant's notes.
Since each number is less than or equal to $10^{5}$, you can loop all possible $a_{1, 1}$ values, the rest of cells can be calculated from this.
[ "brute force", "implementation" ]
1,100
null
260
A
Adding Digits
Vasya has got two number: $a$ and $b$. However, Vasya finds number $a$ too short. So he decided to repeat the operation of lengthening number $a$ $n$ times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number $b$. If it is impossible to obtain the number which is divisible by $b$, then the lengthening operation cannot be performed. Your task is to help Vasya and print the number he can get after applying the lengthening operation to number $a n$ times.
At first try to add to the right one digit from $0$ to $9$. If it is impossible write -1. In other case, the remaining $n-1$ digits can be $0$ because divisibility doesn't change.
[ "implementation", "math" ]
1,400
null
260
B
Ancient Prophesy
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "{00\textbf{12-10-2012}-10-2012}", second time as "{0012-10-20\textbf{12-10-2012}}"). The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date. A date is correct if the year lies in the range from $2013$ to $2015$, the month is from $1$ to $12$, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it. Notice, that any year between 2013 and 2015 is not a leap year.
In this problem you have to consider every date from $2013$ to $2015$ year (there is no leap years in this interval), count occurrences of this date and find maximum. In one year there is $365$ days, so the complexity of the solution $(3 \cdot 365 \cdot N)$.
[ "brute force", "implementation", "strings" ]
1,600
null
260
C
Balls and Boxes
Little Vasya had $n$ boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to $n$ from left to right. Once Vasya chose one of the boxes, let's assume that its number is $i$, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers $i + 1$, $i + 2$, $i + 3$ and so on. If Vasya puts a ball into the box number $n$, then the next ball goes to box $1$, the next one goes to box $2$ and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number $i$. If $i = n$, Vasya puts the first ball into the box number $1$, then the next ball goes to box $2$ and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had $3$ balls, the second one had $2$, the third one had $5$ and the fourth one had $4$ balls. Then, if $i = 3$, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: $4, 1, 2, 3, 4$. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are $4$ balls, $3$ in the second one, $1$ in the third one and $6$ in the fourth one. At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number $x$ — the number of the box, where he put the last of the taken out balls. He asks you to help to find the initial arrangement of the balls in the boxes.
Firstly describe simple solution. We will get by one ball from boxes (we begin from box $x$) from right to left (action back). At some moment there will be $0$ balls in current box. This box is the first box in our initial problem (from which we took all balls and begun to put). In this box we put all balls, which we get from all boxes. But we can't solve the problem in such a way, because it is too long. Note, that before we meet the situation when in some box will be $0$ balls, we will go through every element of array several times and subtract $1$. So we can make our solution faster. We can subtract from every element of array $minv - 1$, where $minv$ - minimum in array. After that you should do $O(N)$ operations, that were mentioned above.
[ "constructive algorithms", "greedy", "implementation" ]
1,700
null
260
D
Black and White Tree
The board has got a painted tree graph, consisting of $n$ nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles. Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer. A bad boy Vasya came up to the board and wrote number $s_{v}$ near each node $v$ — the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board. Your task is to restore the original tree by the node colors and numbers $s_{v}$.
The problem can be solved constructively maintaining the following invariant (rule) - the sum of the white vertices equals to the sum of the black vertices. The tree is a bipartite graph, so we build bipartite graph with no cycles, which will satisfy the conditions of the problem. Parts of graph will be black and white vertices. On each step we will choose vertex $v$ with minimum sum from white and black vertices. Then find any vertex of opposite color $u$ and add edge $(u, v)$ with weight $s[v]$, and subtract from sum of $u$ sum of $v$, that is $s[u] = s[u]-s[v]$. After each step one vertex is deleted. That's why there will be no cycles in constructed graph. When we delete last vertex of one of colors, all other vertices can be joined in any correct way with edges of weight $0$.
[ "constructive algorithms", "dsu", "graphs", "greedy", "trees" ]
2,100
null
260
E
Dividing Kingdom
A country called Flatland is an infinite two-dimensional plane. Flatland has $n$ cities, each of them is a point on the plane. Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four \textbf{distinct} straight lines, such that two of them are parallel to the $Ox$ axis, and two others are parallel to the $Oy$ axis. At that, no straight line can go through any city. Thus, Flatland will be divided into 9 parts, and each son will be given exactly one of these parts. Circle IV thought a little, evaluated his sons' obedience and decided that the $i$-th son should get the part of Flatland that has exactly $a_{i}$ cities. Help Circle find such four straight lines that if we divide Flatland into 9 parts by these lines, the resulting parts can be given to the sons so that son number $i$ got the part of Flatland which contains $a_{i}$ cities.
Consider $9!$ variants of location of integers $a[i]$ on $9$ areas. When we consider some location (some grid), we can easily find amount of cities to the left of the left vertical line, to the right of the right vertical line, below the lower horizontal line and above the upper horizontal line. All these numbers is sum of three values $a[i]$. We assume that the lines of the answer are always in half-integer coordinates. Then, knowing the above $4$ numbers, we can uniquely determine separately for $x$ and $y$ how to accommodate all the $4$ lines. It remains only to check that in all areas there is desired number of points. For each of four zones (to the left of the left vertical line, to the right of the right vertical line, below the lower horizontal line and above the upper horizontal line) separately check, that all three areas have correct number of cities. It can be done offline using scan-line and segment-tree, which can find sum on interval and change value in some point. You should put all queries in some array, sort them and process from left to right. Note, when you check $8$ from $9$ areas for every $9!$ variants of location, the last area (central) could not be checked, it will be correct automatically.
[ "binary search", "brute force", "data structures" ]
2,500
null
261
A
Maxim and Discounts
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are $m$ types of discounts. We assume that the discounts are indexed from 1 to $m$. To use the discount number $i$, the customer takes a special basket, where he puts exactly $q_{i}$ items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the $q_{i}$ items in the cart. Maxim now needs to buy $n$ items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well. Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
Ofcourse the most optimal way is to use discount with minimal q_i. We will sort our numbers and will go from the end to begin of the array. We will by use our discount as soon as it will be possible. It's not hard to see that we will buy all the items with numbers I (zero-numeration from the end of the sorted array) such, that I%(q+2)<q.
[ "greedy", "sortings" ]
1,400
null
261
B
Maxim and Restaurant
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is $p$ meters. Maxim has got a dinner party tonight, $n$ guests will come to him. Let's index the guests of Maxim's restaurant from 1 to $n$. Maxim knows the sizes of all guests that are going to come to him. The $i$-th guest's size ($a_{i}$) represents the number of meters the guest is going to take up if he sits at the restaurant table. Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than $p$. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table. Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible $n!$ orders of guests in the queue. Help Maxim, calculate this number.
If all people can come, we will return answer as n. If it is impossible, there will be finded some person that will be the last to come. We will brtueforce this value. Then we will detrminate dp[i,j,s] in how many ways j persons from the first i with total length s can be in the resturant. It is easy to calculate. Then we will add to the answer values dp[n][i][s]*i!*(n-1-i)! for all i,s such that s+p[h]>P. Where P - total length of the table, p[h] - length of the fixed person.
[ "dp", "math", "probabilities" ]
1,900
null
261
C
Maxim and Matrix
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size $(m + 1) × (m + 1)$: Maxim asks you to count, how many numbers $m$ $(1 ≤ m ≤ n)$ are there, such that the sum of values in the cells in the row number $m + 1$ of the resulting matrix equals $t$. Expression ($x$ $xor$ $y$) means applying the operation of bitwise excluding "OR" to numbers $x$ and $y$. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal — by "xor".
For fixed m, the sum in the last row will be 2^(bit_count(m+1)-1). So now if T is not power of 2, answer is 0. Else we can find number of bits that we need. And know we have stndart problem. How many numbers form 2 to n+1 have exactly P bits in binary presentation of the number. It is well known problem can be done using binomial cooficients. We will count number of numebers smaller then out number with fixed prefix.
[ "constructive algorithms", "dp", "math" ]
2,000
null
261
D
Maxim and Increasing Subsequence
Maxim loves sequences, especially those that strictly increase. He is wondering, what is the length of the longest increasing subsequence of the given sequence $a$? Sequence $a$ is given as follows: - the length of the sequence equals $n × t$; - $a_{i}=b_{((i-1)}\;\;\mathrm{mod}\;n)+1$ $(1 ≤ i ≤ n × t)$, where operation $(x\ {\mathrm{~mod~}}y)$ means taking the remainder after dividing number $x$ by number $y$. Sequence $s_{1}, s_{2}, ..., s_{r}$ of length $r$ is a subsequence of sequence $a_{1}, a_{2}, ..., a_{n}$, if there is such increasing sequence of indexes $i_{1}, i_{2}, ..., i_{r}$ $(1 ≤ i_{1} < i_{2} < ... < i_{r} ≤ n)$, that $a_{ij} = s_{j}$. In other words, the subsequence can be obtained from the sequence by crossing out some elements. Sequence $s_{1}, s_{2}, ..., s_{r}$ is increasing, if the following inequality holds: $s_{1} < s_{2} < ... < s_{r}$. Maxim have $k$ variants of the sequence $a$. Help Maxim to determine for each sequence the length of the longest increasing subsequence.
This problem can be done using dp[i,j] where we can end our increasing sequence with length i and last number j. Its not hard to understand that number of states will be n*b. To make a tranfer we need to know array first[j] - first position of the number j in the sequence b, next[i][j] - first position of the number j in the sequence b after position i. Now its easy to calculate all values.
[ "dp" ]
2,600
null
262
A
Roma and Lucky Numbers
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not. Roma's got $n$ positive integers. He wonders, how many of those integers have not more than $k$ lucky digits? Help him, write the program that solves the problem.
This problem just need to simulate everithing that was given in statment.
[ "implementation" ]
800
null
262
B
Roma and Changing Signs
Roma works in a company that sells TVs. Now he has to prepare a report for the last year. Roma has got a list of the company's incomes. The list is a sequence that consists of $n$ integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly $k$ changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times. The operation of changing a number's sign is the operation of multiplying this number by -$1$. Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform \textbf{exactly} $k$ changes.
We will "reverse" numbers from the begining to the end while numebrers are negative and we did't spend all k operations. In the end there can leave some operetions, and we will "reverse" only one numeber, with minimal value k(that remains) times.
[ "greedy" ]
1,200
null
263
A
Beautiful Matrix
You've got a $5 × 5$ matrix, consisting of $24$ zeroes and a single number one. Let's index the matrix rows by numbers from $1$ to $5$ from top to bottom, let's index the matrix columns by numbers from $1$ to $5$ from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: - Swap two neighboring matrix rows, that is, rows with indexes $i$ and $i + 1$ for some integer $i$ $(1 ≤ i < 5)$. - Swap two neighboring matrix columns, that is, columns with indexes $j$ and $j + 1$ for some integer $j$ $(1 ≤ j < 5)$. You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
If the single $1$ is located on the intersection of the $r$-th row and the $c$-th column (1-based numeration), then the answer is $|3 - r| + |3 - c|$.
[ "implementation" ]
800
null
263
B
Squares
Vasya has found a piece of paper with a coordinate system written on it. There are $n$ distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to $n$. It turned out that points with coordinates $(0, 0)$ and $(a_{i}, a_{i})$ are the opposite corners of the $i$-th square. Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly $k$ drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits.
If $k > n$, then the answer doesn't exist. Otherwise let's sort the squares by descending of their sizes. Now you can print any point that belongs to the $k$-th square and doesn't belong to the $k + 1$-th square. One of the possible answers is $(a_{k}, 0)$.
[ "greedy", "implementation", "sortings" ]
900
null
263
C
Circle of Numbers
One day Vasya came up to the blackboard and wrote out $n$ distinct integers from $1$ to $n$ in some order in a circle. Then he drew arcs to join the pairs of integers $(a, b)$ $(a ≠ b)$, that are either each other's immediate neighbors in the circle, or there is number $c$, such that $a$ and $с$ are immediate neighbors, and $b$ and $c$ are immediate neighbors. As you can easily deduce, in the end Vasya drew $2·n$ arcs. For example, if the numbers are written in the circle in the order $1, 2, 3, 4, 5$ (in the clockwise direction), then the arcs will join pairs of integers $(1, 2)$, $(2, 3)$, $(3, 4)$, $(4, 5)$, $(5, 1)$, $(1, 3)$, $(2, 4)$, $(3, 5)$, $(4, 1)$ and $(5, 2)$. Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with $2·n$ written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs.
First of all, we have to check that each number occurs in the input exactly 4 times. If it's not true, then the answer definitely doesn't exist. Otherwise, let's try to restore the circle. As cyclic shift of circle doesn't matter, let $1$ to be the first number. As the second and the third number must be connected to each other and to $1$, there are only few possibilities. So let's try them all. And when we know first three numbers, the rest of the circle could be easily and unambiguously restored in $O(n)$. Just find a number, which is not included in the circle yet, and is connected to the last two numbers of the circle. Add this number to the resulting circle (as new last number), and repeat the procedure while possible. If we succeeded to add all the numbers to the circle, than the resulting circle is the answer.
[ "brute force", "dfs and similar", "implementation" ]
2,000
null
263
D
Cycle in Graph
You've got a undirected graph $G$, consisting of $n$ nodes. We will consider the nodes of the graph indexed by integers from 1 to $n$. We know that each node of graph $G$ is connected by edges with at least $k$ other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least $k + 1$. A simple cycle of length $d$ $(d > 1)$ in graph $G$ is a sequence of distinct graph nodes $v_{1}, v_{2}, ..., v_{d}$ such, that nodes $v_{1}$ and $v_{d}$ are connected by an edge of the graph, also for any integer $i$ $(1 ≤ i < d)$ nodes $v_{i}$ and $v_{i + 1}$ are connected by an edge of the graph.
Consider any simple path $v_{1}, v_{2}, ..., v_{r}$ which cannot be increased immediately (by adding a node to it's end, $v_{r}$). In other words, all the neighbours of $v_{r}$ are already included in the path. Let's find the first node of the path (say, $v_{l}$), which is connected to $v_{r}$. It is clear that $v_{l}, v_{l + 1}, ..., v_{r}$ is a cycle and it contains all the neighbours of $v_{r}$. But according to the problem's statement, each node has at least $k$ neighbours. So length of the cycle is at least $k + 1$ ($+ 1$ is for node $v_{r}$ itself).
[ "dfs and similar", "graphs" ]
1,800
null
263
E
Rhombus
You've got a table of size $n × m$. On the intersection of the $i$-th row ($1 ≤ i ≤ n$) and the $j$-th column ($1 ≤ j ≤ m$) there is a non-negative integer $a_{i, j}$. Besides, you've got a non-negative integer $k$. Your task is to find such pair of integers $(a, b)$ that meets these conditions: - $k ≤ a ≤ n - k + 1$; - $k ≤ b ≤ m - k + 1$; - let's denote the maximum of the function $f(x,y)=\sum_{i=1}^{n}\sum_{j=1}^{m}a_{i,j}\cdot m a x(0,k-\vert i-x\vert-\vert j-y\vert)$ among all integers $x$ and $y$, that satisfy the inequalities $k ≤ x ≤ n - k + 1$ and $k ≤ y ≤ m - k + 1$, as $mval$; for the required pair of numbers the following equation must hold $f(a, b) = mval$.
Divide the rhombus of size $k$ into 4 right-angled triangles as shown on a picture below. One of them has size $k$, two - size $k - 1$, and another one - size $k - 2$. Let's solve the problem separately for each triangle. The most convenient way to do that is to rotate the input 4 times and run the same solving function 4 times. The result of this function will be a 2D array. Cell $(x, y)$ indicates the answer we get if the right-angled vertex of triangle is located at cell $(x, y)$. So it will be easy to combine 4 such arrays (just rotating and shifting properly) to get the actual answer for rhombus. The main idea of the solution for triangle is the following. If we know the answer for a cell, we can easily move our triangle by one cell in any direction (right, down, left, or up) and recalculate the answer for that new cell in constant time. In fact, we need only 2 directions: right and down. And the values for top left corner should be calculated with straightforward cycles in $O(k^{2})$ time. More precisely, let's define 5 functions: The sum on diagonal segment of $k$ elements: $d i a g o n a l(x,y)=\sum_{i=0}^{k-1}a_{x-i,y+i}$ The sum on vertical segment of $k$ elements: $v e c t i c a l(x,y)=\sum_{i=0}^{k-1}a_{x-i,y}$ The weighted sum on vertical segment of $k$ elements: $v e r t i c a l W e i g h t e d(x,y)=\sum_{i=0}^{k-1}a_{x-i,y}\cdot(k-i)$ The sum on a triangle: $t r i a n g l e(x,y)=\sum_{i=0}^{k-1}\sum_{j=0}^{k-1}a_{x-i,y-j}$ The weighted sum on a triangle: $t r i a n g l e W e i g h t e d(x,y)=\sum_{i=0}^{k-1}\sum_{i=0}^{k-1-i}a_{x-i,y-j}\cdot(k-i-j)$ Calculating the first 3 functions in $O(nm)$ in total is quite obvious. Formulas for the others are following: $triangle(x, y + 1) = triangle(x, y) - diagonal(x, y - k + 1) + vertical(x, y + 1)$ $triangleWeighted(x, y + 1) = triangleWeighted(x, y) - triangle(x, y) + verticalWeighted(x, y + 1)$ Formulas for moving in other directions are similar.
[ "brute force", "data structures", "dp" ]
2,500
null
264
A
Escape from Stones
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval $[0, 1]$. Next, $n$ stones will fall and Liss will escape from the stones. The stones are numbered from 1 to $n$ in order. The stones always fall to the center of Liss's interval. When Liss occupies the interval $[k - d, k + d]$ and a stone falls to $k$, she will escape to the left or to the right. If she escapes to the left, her new interval will be $[k - d, k]$. If she escapes to the right, her new interval will be $[k, k + d]$. You are given a string $s$ of length $n$. If the $i$-th character of $s$ is "l" or "r", when the $i$-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the $n$ stones falls.
In this problem, there are many simple algorithms which works in $O(n)$. One of them (which I intended) is following: You should prepare 2 vectors. If $s[i] = 'l'$, you should push i to the first vector, and if $s[i] = 'r'$, you should push i to the second vector. Finally, you should print the integers in the second vector by default order, after that, you should print the integers in the first vector in the reverse order. This algorithm works because if Liss divides an interval into two intervals $A$ and $B$ and she enters $A$, she will never enter $B$.
[ "constructive algorithms", "data structures", "implementation", "two pointers" ]
1,200
null
264
B
Good Sequences
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks $n$ integers $a_{1}, a_{2}, ..., a_{n}$ are good. Now she is interested in good sequences. A sequence $x_{1}, x_{2}, ..., x_{k}$ is called good if it satisfies the following three conditions: - The sequence is strictly increasing, i.e. $x_{i} < x_{i + 1}$ for each $i$ $(1 ≤ i ≤ k - 1)$. - No two adjacent elements are coprime, i.e. $gcd(x_{i}, x_{i + 1}) > 1$ for each $i$ $(1 ≤ i ≤ k - 1)$ (where $gcd(p, q)$ denotes the greatest common divisor of the integers $p$ and $q$). - All elements of the sequence are good integers. Find the length of the longest good sequence.
The main idea is DP. Let's define $dp[x]$ as the maximal value of the length of the good sequence whose last element is $x$, and define $d[i]$ as the (maximal value of $dp[x]$ where $x$ is divisible by $i$). You should calculate $dp[x]$ in the increasing order of x. The value of $dp[x]$ is (maximal value of $d[i]$ where $i$ is a divisor of $x$) + 1. After you calculate $dp[x]$, for each divisor $i$ of $x$, you should update $d[i]$ too. This algorithm works in $O(nlogn)$ because the sum of the number of the divisor from 1 to $n$ is $O(nlogn)$. Note that there is a corner case. When the set is ${1}$, you should output 1.
[ "dp", "number theory" ]
1,500
null
264
C
Choosing Balls
There are $n$ balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the $i$-th ball is $c_{i}$ and the value of the $i$-th ball is $v_{i}$. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where $a$ and $b$ are given constants): - If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) $ × $ $a$. - Otherwise, add (the value of the ball) $ × $ $b$. You are given $q$ queries. Each query contains two integers $a_{i}$ and $b_{i}$. For each query find the maximal value of the sequence she can make when $a = a_{i}$ and $b = b_{i}$. Note that the new sequence can be \textbf{empty}, and the value of an empty sequence is defined as zero.
There are many $O(Q * N * logN)$ solutions using segment trees or other data structures, but probably they will get time limit exceeded. We can solve each query independently. First, let's consider the following DP algorithm. $dp[c]$ := the maximal value of a sequence whose last ball's color is $c$ For each ball $i$, we want to update the array. Let the $i$-th ball's color be $col[i]$, the $i$-th ball's value be $val[i]$, and the maximal value of dp array other than $dp[col[i]]$ be $otherMAX$. We can update the value of $dp[col[i]]$ to $dp[col[i]] + val[i] \times a$ or $otherMAX + val[i] \times b$. Here, we only need to know $dp[col[i]]$ and $otherMAX$. If we remember the biggest two values of $dp$ array in that time and their indexes in the array, $otherMAX$ can be calculated using the biggest two values, which always include maximal values of dp array other than any particular color. Since the values of dp array don't decrease, we can update the biggest two values in $O(1)$. Finally, the answer for the query is the maximal value of $dp$ array. The complexity of the described algorithm is $O(QN)$.
[ "dp" ]
2,000
null
264
D
Colorful Stones
There are two sequences of colorful stones. The color of each stone is one of red, green, or blue. You are given two strings $s$ and $t$. The $i$-th (1-based) character of $s$ represents the color of the $i$-th stone of the first sequence. Similarly, the $i$-th (1-based) character of $t$ represents the color of the $i$-th stone of the second sequence. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially Squirrel Liss is standing on the first stone of the first sequence and Cat Vasya is standing on the first stone of the second sequence. You can perform the following instructions zero or more times. Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction $c$, the animals standing on stones whose colors are $c$ will move one stone forward. For example, if you perform an instruction «RED», the animals standing on red stones will move one stone forward. You are not allowed to perform instructions that lead some animals out of the sequences. In other words, if some animals are standing on the last stones, you can't perform the instructions of the colors of those stones. A pair of positions (position of Liss, position of Vasya) is called a state. A state is called reachable if the state is reachable by performing instructions zero or more times from the initial state (1, 1). Calculate the number of distinct reachable states.
First, let's consider a simpler version of the problem: You are given a start state and a goal state. Check whether the goal state is reachable from the start state. Define $A$, $B$, $C$, and $D$ as in the picture below, and let $I$ be the string of your instructions. $A$ and $B$ are substrings of $s$, and $C$ and $D$ are substrings of $t$. It is possible to reach the goal state from the start state if there exists an instruction $I$ such that: 1 $A$ is a subsequence of $I$. 2 $B$ is not a subsequence of $I$. 3 $C$ is a subsequence of $I$. 4 $D$ is not a subsequence of $I$. So we want to check if such string $I$ exists. (string $s1$ is called a subsequence of $s2$ if it is possible to get $s2$ by removing some characters of $s1$) There are some obvious "NO" cases. When $D$ is a subsequence of $A$, it is impossible to satisfy both conditions 1 and 4. Similarly, $B$ must not be a subsequence of $C$. Are these sufficient conditions? Let's try to prove this hypothesis. To simplify the description we will introduce some new variables. Let $A'$, $B'$, $C'$, and $D'$ be strings that can be obtained by removing the first characters of $A$, $B$, $C$, and $D$. Let $c1$ and $c2$ be the first characters of $A$ and $C$. Suppose that currently the conditions are satisfied (i.e. $D$ is not a subsequence of $A$ and $B$ is not a subsequence of $C$). If $c1 = c2$, you should perform the instruction $c1 = c2$. The new quatruplet will be $(A', B', C', D')$ and this also satisies the conditions. If $c1 \neq c2$ and $B'$ is not a subsequnce of $C$, you should perform the instruction $c1$. The new quatruplet will be $(A', B', C, D)$ and this also satisies the conditions. If $c1 \neq c2$ and $D'$ is not a subsequnce of $A$, you should perform the instruction $c2$. The new quatruplet will be $(A, B, C', D')$ and this also satisies the conditions. What happens if all of the above three conditions don't hold? In this case $A$ and $C$ have the same length and $A = c1c2c1c2...$, $B = c2c1c2c1$. In particular the last two characters of $A$ and $B$ are swapped: there are different characters $x$ and $y$ and $A = ...xy$, $B = ...yx$. Now you found a new necessary condition! Generally, if $A$ and $B$ are of the form $A = ...xy$ and $B = ...yx$, the goal state is unreachable. If the last instruction is $x$, Vasya must be in the goal before the last instruction, but then Vasya will go further after the last instruction. If the last instruction is $y$, we will also get a contradiction. Finally we have a solution. The goal state is reachable from the start state if and only if $D$ is not a subsequence of $A$, $B$ is not a subsequnce of $C$, and $A$ and $C$ are not of the form $A = ...xy$, $C = ...yx$. The remaining part is relatively easy, so I'll leave it as an exercise for readers.
[ "dp", "two pointers" ]
2,500
null
264
E
Roadside Trees
Squirrel Liss loves nuts. Liss asks you to plant some nut trees. There are $n$ positions (numbered 1 to $n$ from west to east) to plant a tree along a street. Trees grow one meter per month. At the beginning of each month you should process one query. The query is one of the following types: - Plant a tree of height $h$ at position $p$. - Cut down the $x$-th existent (not cut) tree from the west (where $x$ is 1-indexed). When we cut the tree it drops down and takes all the available place at the position where it has stood. So no tree can be planted at this position anymore. After processing each query, you should print the length of the longest increasing subsequence. A subset of existent trees is called an increasing subsequence if the height of the trees in the set is strictly increasing from west to east (for example, the westmost tree in the set must be the shortest in the set). The length of the increasing subsequence is the number of trees in it. Note that Liss don't like the trees with the same heights, so it is guaranteed that at any time no two trees have the exactly same heights.
When you want to plant a tree with height h at time t, you should plant a tree with height h-t instead. Then you can ignore the growth of the trees. And plot trees on a x-y plane: x-coordinate is the position and y-coordinate is the modified height (h-t). like this picture then..... LIS is the longest sequence of points P_1, P_2, ... such that x(P_1) < x(P_2) < ... y(P_1) < y(P_2) < ... At each point write the length of the longest increasing sequence that starts from the point. The value written on point p = (the maximal value written in the rectangle whoselower-left corner is p) + 1. How should we process queries? Planting query -> plot a new point The new point will be one of the ten points that have the smallest y-coordinate. To process this query, erase all values written below the new point first and rewrite the values to those points from top to bottom. Cutting query -> remove a point Similarly the removed point will be one of the ten points that have the smallest x-coordinate. So you can erase all values written on those points and rewrite correct values from right to left. What data structures do we need? 2D segtree? -> too slow :( Make two segment trees: let's call them segx and segy. segx : x-directional segtree segy : y-directional segtree For planting queries use segx. For cutting queries use segy. The i-th leaf of segx contains the value written on the point whose x-coordinate is x and non-leaf nodes of the segment trees have the maximum of children of the node. Define segy similarly. Time Complexity O(N * 10 * log N)
[ "data structures", "dp" ]
3,000
null
265
A
Colorful Stones (Simplified Edition)
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string $s$. The $i$-th (1-based) character of $s$ represents the color of the $i$-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times. Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction $c$, if Liss is standing on a stone whose colors is $c$, Liss will move one stone forward, else she will not move. You are given a string $t$. The number of instructions is equal to the length of $t$, and the $i$-th character of $t$ represents the $i$-th instruction. Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence.
In this problem you just need to implement what is written in the statement. Make a variable that holds the position of Liss, and simulate the instructions one by one.
[ "implementation" ]
800
null
265
B
Roadside Trees (Simplified Edition)
Squirrel Liss loves nuts. There are $n$ trees (numbered $1$ to $n$ from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree $i$ is $h_{i}$. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number $1$. In one second Liss can perform one of the following actions: - Walk up or down one unit on a tree. - Eat a nut on the top of the current tree. - Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height $h$ of the tree $i$ ($1 ≤ i ≤ n - 1$), she jumps to height $h$ of the tree $i + 1$. This action can't be performed if $h > h_{i + 1}$. Compute the minimal time (in seconds) required to eat all nuts.
The optimal path of Liss is as follows: First she starts from the root of tree 1. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_{1}, h_{2})$. Jump to the tree 2. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_{2}, h_{3})$, $...$ and so on.
[ "greedy", "implementation" ]
1,000
null
266
A
Stones on the Table
There are $n$ stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
In this problem you should count number of consecutive pairs of equal letters. It can be done using one cycle and $O(N)$ time.
[ "implementation" ]
800
null
266
B
Queue at the School
During the break the schoolchildren, boys and girls, formed a queue of $n$ people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second. Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from $1$ to $n$, at that the person in the position number $1$ is served first. Then, if at time $x$ a boy stands on the $i$-th position and a girl stands on the $(i + 1)$-th position, then at time $x + 1$ the $i$-th position will have a girl and the $(i + 1)$-th position will have a boy. The time is given in seconds. You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after $t$ seconds.
In this you should realize the given process. You should $t$ times swap elements $i$ and $i + 1$ if on the place $i$ was a girl and on the place $i + 1$ was a boy. You should not push some girl to the left multiple times at once. The solution can be written using $O(N \cdot T)$ time.
[ "constructive algorithms", "graph matchings", "implementation", "shortest paths" ]
800
null
266
C
Below the Diagonal
You are given a square matrix consisting of $n$ rows and $n$ columns. We assume that the rows are numbered from $1$ to $n$ from top to bottom and the columns are numbered from $1$ to $n$ from left to right. Some cells ($n - 1$ cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: - Swap $i$-th and $j$-th rows of the matrix; - Swap $i$-th and $j$-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the $i$-th row and of the $j$-th column, lies below the main diagonal if $i > j$.
This problem can be solved using constructive algorithm. We will use inductive approach. At first, we have matrix of size $n$ and $n - 1$ ones in it. Therefore, there is a column with no ones in it. So, we put this column to $n$-th place. In this case, the lower right element will be $0$. Then find any row with at least one integer one and put it to the $n$-th place. After these operations the element in cell $(n, n)$ equals to $0$ and the last row has at least one integer one. Therefore, we can reduce the dimension of our problem, that is $n: = n - 1$. In our new problem we have no more than $n - 2$ ones. So, we can solve this problem using the same algorithm. When $n$ equals to $1$ you should finish algorithm, because there is no ones left. This algorithm uses $O(N)$ swap operations, no more than two for every $n$.
[ "constructive algorithms", "greedy", "math" ]
2,100
null
266
D
BerDonalds
BerDonalds, a well-known fast food restaurant, is going to open a cafe in Bertown. The important thing is to choose the new restaurant's location so that it would be easy to get there. The Bertown road system is represented by $n$ junctions, connected by $m$ bidirectional roads. For each road we know its length. We also know that we can get from any junction to any other one, moving along the roads. Your task is to find such location of the restaurant, that the shortest distance along the roads from the cafe to the farthest junction would be minimum. Note that the restaurant can be located not only on the junction, but at any point of any road.
I'll tell a few ideas how to solve this problem. Firstly, describe the solution with time $O(N^{4})$. Consider every edge $(u, v)$ of length $len$ where could be the answer point. Let this point lie at a distance $x$ from vertex $u$. So, the distance from this point to vertex $i$ would be $min(x + d[u][i], len-x + d[v][i])$, where $d[x][y]$ - distance between vertices $x$ and $y$. Equate these values and get the critical value $x$ for vertex $i$, $x = (len + d[v][i]-d[u][i]) / 2$. It follows that the answer to the problem is half-integer. So, for every edge and every other vertex we get set of critical points. We should check them all include the vertices of the graph (ends of the segments). This solution may probably pass with some optimizations. Another solution with complexity $O(N^{3} \cdot log^{2})$. Multiply all weights by $2$. Consider every edge where should be the answer and make binary search for the answer (in integers). To check some current value you should consider every vertex $i$ and assume that the answer is achieved in this vertex. In this case, the answer point must lie on this edge <= some value $l[i]$ or >= some value $r[i]$. This subproblem is solved using offline algorithm using sorting events and maintaining the balance. Also, you can use ternary search on every edge of the graph. But you should divide every edge on several segments and find the answer on every segment, because the ternary search is incorrect in this problem. The last two solutions can provide accepted, if you realize them carefully. Also note, that there is the solution with complexity $O(N^{3})$ by the author RAD.
[ "graphs", "math", "shortest paths" ]
2,400
null
266
E
More Queries to Array...
You've got an array, consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Your task is to quickly run the queries of two types: - Assign value $x$ to all elements from $l$ to $r$ inclusive. After such query the values of the elements of array $a_{l}, a_{l + 1}, ..., a_{r}$ become equal to $x$. - Calculate and print sum $\textstyle\sum_{i=l}^{r}a_{i}\cdot(i-l+1)^{k}$, where $k$ doesn't exceed $5$. As the value of the sum can be rather large, you should print it modulo $1000000007 (10^{9} + 7)$.
This problem can be solved using data structure. We would use segment tree, we will support $k$ segment trees for every power. At every vertex we will calculate weighted sum of the appropriate power, also we will save some number that indicates the color of the whole segment, if any. User Egor in comments to the post and user mexmans in comments to the tutorial tell their formula to get the answer. I try to describe how to get them by yourself. Firstly, you should write what value your segment tree gives. The tree can calculate the sum $\textstyle\sum_{i=1}^{r}a_{i}\cdot i^{j}$. You need to calculate the sum $\sum_{i=l}^{r}a_{i}\cdot(i-l+1)^{j}$, you can write it also as $\textstyle\sum_{i=l}^{r}a_{i}\cdot(i+(1-l))^{j}$. Then you should write the last sum for some first powers (at least three) (at piece of paper) and subtract the second sum (what you need) from the first sum (what your tree can calculate). You get an expression that describes what should be subtracted to get the answer from the value what you tree can calculate. This is just the Newton binomial without the highest power. So, the answer for power $j$ is expressed as the subtraction of the value of query to your segment tree and the Newton binomial, with all powers that are less than $j$ (these values can also calculated using your segment tree). Partial sum of the powers and binomial coefficients can be precalced. The solution has the complexity $O(N \cdot K \cdot log(N))$.
[ "data structures", "math" ]
2,500
null
268
A
Games
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different. There are $n$ teams taking part in the national championship. The championship consists of $n·(n - 1)$ games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number. You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
With only 30 teams, the simplest solution is simulating all the matches: An O(N + M) solution is also possible, where M is the length of colors' range (i.e. 100 under the given constraints). First, you need to count for each color i the number of teams cntH[i] which have the home uniform of color i and the number of teams cntA[i] which have the away uniform of color i. The answer is the sum of products of these quantities for each color, i.e. sum of cntH[i] * cntA[i] over all i.
[ "brute force" ]
800
null
268
B
Buttons
Manao is trying to open a rather challenging lock. The lock has $n$ buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens. Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock. Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.
Let us first detect the worst case scenario. It is more or less apparent that when Manao tries to guess the i-th (1 <= i <= n) button in order, he will make n-i mistakes in the worst case. After that the correct button is evident. Now let's count the total number of presses Manao might need before he guesses the whole sequence. When he is guessing the first button he makes n-1 mistakes, but the "mistake cost", i.e. the number of presses before the mistake is made, is equal to 1. When Manao goes for the second button, the mistake cost becomes 2, because each time Manao needs to press the first (already guessed) button. Continuing like this, we obtain that when Manao tries to guess the i-th button in order, he will perform (n-i) * i button presses. After Manao guessed the correct sequence, he needs to enter it once, which is another n presses. So we already have an O(n) algorithm: sum up (n-i)*i for i=1, ..., n-1 and add n to the sum obtained. When n is anything that fits in 32-bit integer type, the task is solvable in O(1)*. The sum (n-i)*i is two separate sums: the sum of n*i and the sum of i*i. The first sum is n*(1+...+n-1), which can be computed with the sum of arithmetic progression. The second sum is the sum of squares from 1 to n-1, which can be evaluated with a polynom of degree 3: http://pirate.shu.edu/~wachsmut/ira/infinity/answers/sm_sq_cb.html *The only problem is that the answer for large n-s does not fit even in 64-bit integer type, but at least we can compute its remainder from division by anything.
[ "implementation", "math" ]
1,000
null
268
C
Beautiful Sets of Points
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: - The coordinates of each point in the set are integers. - For any two points from the set, the distance between them is a non-integer. Consider all points $(x, y)$ which satisfy the inequations: $0 ≤ x ≤ n$; $0 ≤ y ≤ m$; $x + y > 0$. Choose their subset of maximum size such that it is also a beautiful set of points.
Obviously, if a set contains a point (x', y'), it can not contain any other point with x=x' or y=y', because these two points would be an integer distance apart. There are only n+1 distinct x-coordinates and m+1 distinct y-coordinates. Therefore, the size of the set sought can not exceed min(n, m) + 1. If the constraint x+y>0 was not present, the set of points (i, i) (0 <= i <= min(n, m)) would do nicely. The distance between two points (i, i) and (j, j) is equal to |i-j|*sqrt(2) and can only be integer when i=j. On the other hand, there are min(n, m) + 1 points and we already know that we can't take more than that. Since point (0, 0) is restricted, we can take the other "diagonal", i.e. use points (i, min(n, m) - i).
[ "constructive algorithms", "implementation" ]
1,500
null
268
D
Wall Bars
Manao is working for a construction company. Recently, an order came to build wall bars in a children's park. Manao was commissioned to develop a plan of construction, which will enable the company to save the most money. After reviewing the formal specifications for the wall bars, Manao discovered a number of controversial requirements and decided to treat them to the company's advantage. His resulting design can be described as follows: - Let's introduce some unit of length. The construction center is a pole of height $n$. - At heights $1, 2, ..., n$ exactly one horizontal bar sticks out from the pole. Each bar sticks in one of four pre-fixed directions. - A child can move from one bar to another if the distance between them does not exceed $h$ and they stick in the same direction. If a child is on the ground, he can climb onto any of the bars at height between $1$ and $h$. In Manao's construction a child should be able to reach at least one of the bars at heights $n - h + 1, n - h + 2, ..., n$ if he begins at the ground. \begin{center} {\scriptsize The figure to the left shows what a common set of wall bars looks like. The figure to the right shows Manao's construction} \end{center} Manao is wondering how many distinct construction designs that satisfy his requirements exist. As this number can be rather large, print the remainder after dividing it by $1000000009 (10^{9} + 9)$. Two designs are considered distinct if there is such height $i$, that the bars on the height $i$ in these designs don't stick out in the same direction.
Those who are well experienced at dynamic programming can scroll down to "Overall solution" right away. Those who have some experience in DPs can read my attempt to explain how you can come up with that solution. Those with no experience probably shouldn't read this at all :) Imagine a solution which considers all possible designs, adding the bar-steps one by one. Consider any sequence, like 2123412413. There are 4 ways to continue this sequence by appending '1', '2', '3' or '4' to it. For each of the 4^n wall bars / strings we need to check that for at least one of {'1', '2', '3', '4'} character the following is true: its first entry in the string is at position no more than h, each next one differs from the previous by no more than h and the last one is beyond position n-h. Surely, such a solution won't work for large n-s in any reasonable time, but we can start from it in the search of a better approach. First, let's note that we can check the feasibility of the string after each character addition: if somewhere in the middle of string we noticed that for each of the characters the necessary conditions are broken, there is no reason to complete the string. Also, note that we don't need the whole prefix to check the validity of the conditions after each character addition. All we need to know is when each of the '1', '2', '3' and '4' characters occured last, and whether the conditions for each of the characters have been fulfilled up to this point. It turns out that two prefixes in which [each of the characters last occured at the same position] and [the validity of the conditions for each character are equal], are absolutely equivalent for the brute force algorithm's further operation. That is, for example for h=4 these two prefixes can be completed (up to length n) in the same number of ways: The last time each of the characters have occured at the same positions, characters '1' and '3' are already "lost" (the conditions are already broken for them), characters '2' and '4' can still turn the string into a valid one. With the help of the observations made, we can already build a polynomial-time algorithm based on dynamic programming principle. Let ways[curN][i][j][k][l][ii][jj][kk][ll] be the number of designs of height curN, where the last step in direction 1 was at height i, the last step in direction 2 - at height j and so on; ii, jj, kk, ll are boolean parameters which indicate whether the conditions are valid in the corresponding direction. When we choose the direction for the step at height curN+1, we obtain a design with curN+1 steps, the last step in the direction we chose is now at height curN+1 and rest stay where they were. Conditions validity can also be reassessed. Since curN is always one of {i, j, k, l}, we can obtain a O(n^4) algorithm. However, this is still too slow. Another observation: if we are looking at a bar at height curN and the last step in this direction was earlier than curN-h steps ago, we don't really care which height was it exactly at, since this direction is not valid any more. Therefore, the number of states in our algorithm can be only O(n*h^3). Moreover, those ii,jj,kk,ll parameters correlate with the heights of the latest steps in the corresponding directions, so we can (almost) get rid of them, thus reducing the number of states in a number of times. On the base of these observations we can probably build different solutions. I will tell mine. We will keep a 5-dimensional DP :) Let ways[curN][alive][last1][last2][last3] be the number of designs where: There are exactly curN steps. If the direction of the latest step if still "alive", then alive = 1, otherwise it's equal to 0. A direction is alive if its first step was not higher than h and each subsequent one was higher than the previous by at most distance h. last1, last2 and last3 keep the information about the other directions in any order. lasti can be zero in two cases: if there were no steps in the corresponding direction, or if the latest one was earlier than h steps before. Otherwise, lasti is the number of steps between the current step and the latest step in the corresponding direction. We can optimize by keeping last1<=last2<=last3, which reduces the number of states in roughly 6 times. However, this complicates the code and doesn't have a significant effect (since the transitions processing becomes costly). Thus I will not consider it at all. What transitions can be made from state [curN][alive][last1][last2][last3]? We shall process the states in order from curN=1 to curN=N-1. ways[1][1][0][0][0] (i.e. a single step) is equal to 4 as a base case. So we have: If we add a step in the same direction as the latest (i.e. the one at height curN), then we obtain state [curN+1][alive][last1+1][last2+1][last3+1] (roughly): curN has increased by 1; the "livingness" of the direction of the last step could not change; all the lasti-s have increased by 1. However, note that for lasti=0 it should not be incremented (the corresponding step either does not exist at all, or is way below). Also, for lasti=h-1 it turns to zero (the last step is now too low). If we put the step in the same direction as the one which was at height last1, we obtain state [curN+1][last1 > 0 || curN < h][alive][last2+1][last3+1]. This decyphers in the following way: if last1>0, then this condition is alive. last1 could also be 0, but the number of already built steps less than h - in which case this is the first step and the direction becomes alive by putting it. The direction denoted by last1 has been replaced (in the state parameters) by the one in which the curN-th step was sticked out. Therefore, it was 1 step ago and we should write [1] there. On the other hand, that direction could already be dead and we would need to write [0]. It turns out that the value coincides with value of alive. last2 and last3 change in the same way as in the previous case. Directions last2 and last3 are treated in the same way as last1. When we process a transition, the number of designs corresponding to the new state increments by ways[curN][alive][last1][last2][last3]. So the overall answer is sum of all [n][1][a][b][c], where 0<=a,b,c<h plus sum of all [n][0][a][b][c], where at least one of a, b, c is non-zero. So we have an algorithm of O(n*h^3) complexity which needs asymptotically the same amount of memory. Its implementation could catch ML (especially on Java). This can be handled through the following observation: since we only need values [i-1][][][][] to compute [i][][][][]-s, only O(h^3) states need to be kept at any given moment.
[ "dp" ]
2,300
#include <cstdio> #include <cstring> #include <algorithm> #define FOR(i,s,e) for (int i=(s); i<(e); i++) #define FOE(i,s,e) for (int i=(s); i<=(e); i++) #define FOD(i,s,e) for (int i=(s)-1; i>=(e); i--) #define CLR(a,x) memset(a, x, sizeof(a)) #define EXP(i,l) for (int i=(l); i; i=qn[i]) #define LLD long long using namespace std; int n, m; LLD dp[2][32][32][32][2], t, j3, ret; LLD MOD = 1000000009; int main(){ scanf("%d%d", &n, &m); dp[0][0][0][0][1] = 1; FOR(i,0,n){ FOE(j0,0,m) FOE(j1,0,m) FOE(j2,0,m) FOR(k,0,2){ t = dp[i&1][j0][j1][j2][k]; if (!t) continue; dp[i&1][j0][j1][j2][k] = 0; t %= MOD; if (k) j3 = 1; else j3 = m; // put j0 dp[i&1^1][min(m, j1+1)][min(m, j2+1)][j3][j0 < m] += t; // put j1 dp[i&1^1][min(m, j0+1)][min(m, j2+1)][j3][j1 < m] += t; // put j2 dp[i&1^1][min(m, j0+1)][min(m, j1+1)][j3][j2 < m] += t; // put k dp[i&1^1][min(m, j0+1)][min(m, j1+1)][min(m, j2+1)][k] += t; } } FOE(j0,0,m) FOE(j1,0,m) FOE(j2,0,m) FOR(k,0,2) if (j0 < m || j1 < m || j2 < m || k) ret = (ret + dp[n&1][j0][j1][j2][k]) % MOD; printf("%I64d ", ret); return 0; }
268
E
Playlist
Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs. Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist: - If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song. - If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song. For example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following: - Manao listens to A, he likes it, he remembers it. - Manao listens to B, he does not like it, so he listens to A, again. - Manao listens to C, he likes the song and he remembers it, too. - Manao listens to D, but does not enjoy it and re-listens to songs A and C. That is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening. Manao has received $n$ songs: the $i$-th of them is $l_{i}$ seconds long and Manao may like it with a probability of $p_{i}$ percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist.
Let us first find the answer for a fixed sequence of songs. Consider any two songs which are at positions i and j (i < j) in the playlist. If Manao liked song i and disliked song j, then song i will be listened to again. Therefore, with probability p[i]*(1-p[j]) the process length will increase by L[i]. The sum of L[i]*p[i]*(1-p[j]) over all pairs (plus the length of all songs since Manao listens to them at least once) is the expected length for the fixed sequence. So we have that if there are two songs (l1, p1) and (l2, p2), the first one should be placed earlier in the playlist if l1*p1*(1-p2)>l2*p2*(1-p1) and later otherwise. This is obviously true if there are only two songs. But suppose that we have more and you ask, why can't there be another song (l3, p3) such that the above inequality rules out that the first song should be after this one and the second song should be before it? Then it's unclear which of the orders results in the maximum expected value. Consider this case in details: (this is not quite true if any pi is equal to 0 or 1, but that's not important here) We have a contradicting system of inequations, so such a case is impossible. Next, let's consider some order of songs (l[1], p[1]), ..., (l[n], p[n]), in which there is a pair of neighbouring songs i and i+1, for which the condition l[i] * p[i] * (1 - p[i + 1]) >= l[i + 1] * p[i + 1] * (1 - p[i]) does not hold, and assume that this order is optimal. Evidently, if we interchange songs i and i+1, the answer will only change by the value contributed by this pair (i.e. l[i] * p[i] * (1 - p[i + 1])). The rest of the songs keep their order towards song i and song i+1. But l[i] * p[i] * (1 - p[i + 1]) < l[i + 1] * p[i + 1] * (1 - p[i]), therefore if we put song i+1 before song i, we obtain a larger value. So we have a contradiction - the order chosen is not optimal. So it turns out that the permutation with maximum possible expected value is obtained when sorting the songs in decreasing order of l[i]*p[i]/(1-p[i]). But we still have a problem of computing the answer for a fixed permutation: we only learned how to do this in O(n^2), which is too slow with n=50000. We can use an idea which is probably a yet another dynamic programming example. Suppose we have fixed j and are counting the contribution of song j towards the answer if Manao dislikes it. This value is (l1*p1 + l2*p2 + ... + l[j-1]*p[j-1]). For j+1, the corresponding value will be (l1*p1+...+l[j-1]*p[j-1]+l[j]*p[j]). It turns out that these values differ in only a single summand, so we can compute each of them in O(1) if we consider j-th one by one in increasing order. This idea can be expressed as follows:
[ "math", "probabilities", "sortings" ]
2,100
null
269
A
Magical Boxes
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to $2^{k}$ ($k$ is an integer, $k ≥ 0$) units. A magical box $v$ can be put inside a magical box $u$, if side length of $v$ is strictly less than the side length of $u$. In particular, Emuskald can put 4 boxes of side length $2^{k - 1}$ into one box of side length $2^{k}$, or as in the following figure: Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.
Suppose we can put all the squares inside a square with side length $2^{p}$. Then we can insert each $k_{i}$ type squares independently along the grid as shown in the picture. No two squares will overlap, since $2^{x}$ divides $2^{y}$, if $x < y$. That means that we can find the smallest square that can hold all the given squares with side length $2^{ki}$ for each $k_{i}$ separately. The answer will be the side length of the largest such square. To be able to put $a_{i}$ squares with side length $2^{ki}$ inside a square with side length $2^{s}$, the following should hold: $(2^{s})^{2} \ge (2^{ki})^{2} \cdot a_{i}$ $4^{s} \ge 4^{ki} \cdot a_{i}$ $4^{s - ki} \ge a_{i}$We can then find the minimum $s$: $s-k_{i}=\lceil\log_{4}a_{i}\rceil$ $s=k_{i}+\lceil\log_{4}a_{i}\rceil$In a special case, if we obtain $s = k_{i}$, $s$ should be increased by 1. Time: $O(n\cdot\log\operatorname*{max}a)$. Memory: $O(1)$.
[ "greedy", "math" ]
1,600
#include<cstdio> #include<algorithm> using namespace std; int main() { int n; scanf("%d", &n); int p = 0, maxk = 0; for(int i = 0; i < n; i++) { int k, a; scanf("%d %d", &k, &a); maxk = max(k, maxk); int m = 0, s = 1; while(s < a) { s *= 4; m++; } p = max(p, k+m); } if(p == maxk) { p++; } printf("%d ", p); }
269
B
Greenhouse Effect
Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length. Over the years Emuskald has cultivated $n$ plants in his greenhouse, of $m$ different plant species numbered from 1 to $m$. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange $m - 1$ borders that would divide the greenhouse into $m$ sections numbered from 1 to $m$ from left to right with each section housing a single species. He is free to place the borders, but in the end all of the $i$-th species plants must reside in $i$-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at \textbf{any} real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.
First, observe that the coordinates don't matter: only the order of the points is important. Let there be some number of points we can replace to achieve the good arrangement. Then all the other points remain in their positions, so their values must be in increasing order from left to right. Then we must find the maximum number of points that can remain in their positions, which is the longest non-decreasing subsequence of types in the input. If it is of length $l$, the answer is $n - l$. In this problem it was enough to implement a quadratic solution. We count $dp[i][j]$ - the length of the longest non-decreasing subsequence on prefix $[1;i]$, with element of type $j$ being the last in subsequence. The transition is as follows: $d p[i][j]=\left\{{1+\operatorname*{max}_{k=1}^{j}d p}_{\mathrm{ap}[i-1][k],\ \ \mathrm{~if~\type}[i]=j}_{\mathrm{otherwise}}\right\}$For easy implementation, we can maintain only array $dp[j]$, and skip the second case. Time: $O(n^{2})$ / $O(n \log n)$. Memory: $O(n^{2})$ / $O(n)$.
[ "dp" ]
1,700
#include<cstdio> #include<algorithm> #include<iostream> using namespace std; #define MAXN 5005 int n, m, type[MAXN], dp[MAXN]; int main() { scanf("%d %d", &n, &m); for(int i = 1; i <= n; i++) { double x; scanf("%d %lf", type+i, &x); } for(int i = 1; i <= n; i++) { int j = type[i]; for(int k = j; k >= 1; k--) { dp[j] = max(dp[j], 1+dp[k]); } } int ans = 0; for(int i = 1; i <= n; i++) { ans = max(ans, dp[i]); } printf("%d ", n-ans); }
269
C
Flawed Flow
Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of $n$ vertices and $m$ edges. Vertices are numbered from 1 to $n$. Vertices $1$ and $n$ being the source and the sink respectively. However, his max-flow algorithm seems to have a little flaw — it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow. More formally. You are given an undirected graph. For each it's undirected edge ($a_{i}$, $b_{i}$) you are given the flow volume $c_{i}$. You should direct all edges in such way that the following conditions hold: - for each vertex $v$ $(1 < v < n)$, sum of $c_{i}$ of incoming edges is equal to the sum of $c_{i}$ of outcoming edges; - vertex with number $1$ has no incoming edges; - the obtained directed graph \textbf{does not have cycles}.
The key element to solving the task is the following observation: if we know all the incoming edges of a vertex, all the remaining edges must be outgoing. The source has no incoming edges, so we already know that all its edges are outgoing. For all other vertices except the sink the amount of incoming and outcoming flow is the same, and is equal to half of the sum of the flow along its incident edges. The algorithm then is to repeatedly direct all the flow from the vertices for which all the incoming edges are known. This can be done with a single BFS: for all v from 2 to n-1 f[v] := sum(flow(v,u))/2; put source in queue while queue is not empty v := pop(queue) for all edges (v, u) if (v, u) is not directed yet direct v -> u f[u] = f[u] - flow(v,u) if u not sink and f[u] = 0 push(queue, u)As the flow contains no cycles, we can sort the vertices topologically. Then we can be sure that, until all edge directions are known, we can put at least the first vertex with unknown edges in the queue, as all of its incoming edges will be from vertices with lower indices, but we took the first vertex with unknown edges. Time: $O(n + m)$ Memory: $O(n + m)$
[ "constructive algorithms", "flows", "graphs", "greedy" ]
2,100
#include <cstdio> #include <vector> #include <queue> #include <cstring> #include <iostream> using namespace std; #define MAXN 200005 #define pb push_back struct edge { int v, c, i, d; edge(int v, int c, int i, int d) : v(v), c(c), i(i), d(d) {} }; typedef vector<vector<edge> > graph; int n, m, d[MAXN], f[MAXN]; graph g; int main() { scanf("%d %d", &n, &m); g = graph(n); for(int i = 0; i < m; i++) { int a, b, c; scanf("%d %d %d", &a, &b, &c); a--; b--; g[a].pb(edge(b,c,i,0)); g[b].pb(edge(a,c,i,1)); f[a] += c; f[b] += c; } for(int i = 0; i < n; i++) { f[i] /= 2; } memset(d, -1, sizeof(d)); queue<int> Q; Q.push(0); while(!Q.empty()) { int u = Q.front(); Q.pop(); for(size_t i = 0; i < g[u].size(); i++) { int id = g[u][i].i; if(d[id] == -1) { d[id] = g[u][i].d; int v = g[u][i].v; f[v] -= g[u][i].c; if(v != n-1 && f[v] == 0) { Q.push(v); } } } } for(int i = 0; i < m; i++) { printf("%d ", d[i]); } }
269
D
Maximum Waterfall
Emuskald was hired to design an artificial waterfall according to the latest trends in landscape architecture. A modern artificial waterfall consists of multiple horizontal panels affixed to a wide flat wall. The water flows down the top of the wall from panel to panel until it reaches the bottom of the wall. The wall has height $t$ and has $n$ panels on the wall. Each panel is a horizontal segment at height $h_{i}$ which begins at $l_{i}$ and ends at $r_{i}$. The $i$-th panel connects the points $(l_{i}, h_{i})$ and $(r_{i}, h_{i})$ of the plane. The top of the wall can be considered a panel connecting the points $( - 10^{9}, t)$ and $(10^{9}, t)$. Similarly, the bottom of the wall can be considered a panel connecting the points $( - 10^{9}, 0)$ and $(10^{9}, 0)$. No two panels share a common point. Emuskald knows that for the waterfall to be aesthetically pleasing, it can flow from panel $i$ to panel $j$ ($i\rightarrow j\,$) only if the following conditions hold: - $max(l_{i}, l_{j}) < min(r_{i}, r_{j})$ (horizontal projections of the panels overlap); - $h_{j} < h_{i}$ (panel $j$ is below panel $i$); - there is no such panel $k$ $(h_{j} < h_{k} < h_{i})$ that the first two conditions hold for the pairs $(i, k)$ and $(k, j)$. Then the \textbf{flow} for $i\rightarrow j\,$ is equal to $min(r_{i}, r_{j}) - max(l_{i}, l_{j})$, the length of their horizontal projection overlap. Emuskald has decided that in his waterfall the water will flow in a single path from top to bottom. If water flows to a panel (except the bottom of the wall), the water will fall further to \textbf{exactly one} lower panel. The total amount of water flow in the waterfall is then defined as the minimum horizontal projection overlap between two consecutive panels in the path of the waterfall. Formally: - the waterfall consists of a single path of panels $t o p\to p_{1}\to p_{2}\to\dots\cdots b o t t o m$; - the flow of the waterfall is the minimum flow in the path $t o p\to p_{1}\to p_{2}\to\dots\cdots b o t t o m$. To make a truly great waterfall Emuskald must maximize this water flow, but there are too many panels and he is having a hard time planning his creation. Below is an example of a waterfall Emuskald wants: Help Emuskald maintain his reputation and find the value of the maximum possible water flow.
We will use a sweepline algorithm to solve this task. This horizontal sweepline runs from bottom to top, and holds the parts of the segments that are visible from the line this sweepline is currently at. Each part also holds the reference to its original segment. The sweepline itself is implemented with a binary search tree. The events of the sweep are the segments. When a new segment is found, we want to find all the lower segments that we can direct the flow onto from this segment. These can be only the original segments of the parts currently in the sweepline whose projections overlap with this segment. Then we iterate over all such parts $p$ (finding the first such part is an $O(\log n)$ operation). How do we know that we can direct the flow onto $p$? Observe that if there is some segment that prevents this, there should be also a part $q$ in the sweepline that also can be seen from the current segment. And since the projections of all three segments overlap, this part can only be directly to the left or to the right of $p$ in the binary search tree. So we just check whether the original segments of the two parts next to $p$ prevent the flow from the current segment to the original segment of $p$. Afterwards, we remove all such parts from the sweepline, and insert a new part corresponding to the new segment. If the new segment only partially covered an existing part, we reinsert the remaining portion of that part. There are at most two such portions - one on each side of the segment. Thus each segment inserts at most 3 new parts and the size of the sweepline is $O(n)$. Each part is handled just once before removal, so the total time of such operations is $O(n \log n)$. Once we know we can direct the flow through $a\rightarrow b$ we can immediately update the maximum downwards flow of $a$: $f_{a} = max(f_{a}, min(f_{b}, min(r_{a}, r_{b}) - max(l_{a}, l_{b})))$When we reach the top, $f_{top}$ will be the answer. Time: $O(n \log n)$ Memory: $O(n)$
[ "data structures", "dp", "graphs", "sortings" ]
2,600
#include <cstdio> #include <vector> #include <iostream> #include <set> #include <algorithm> using namespace std; #define MAXN 100005 int inf = 2000000000; struct segment { int h, l, r; segment(){} segment(int h, int l, int r) : h(h), l(l), r(r) {} bool operator < (const segment &s) const { return h < s.h; } }; struct part { int l, r, f; segment s; part(int l, int r, int f, segment s) : l(l), r(r), f(f), s(s) {} bool operator < (const part &p) const { return l < p.l; } }; set<part> sweep; segment s[MAXN]; int main() { int n, t; scanf("%d %d", &n, &t); for(int i = 0; i < n; i++) { int h, l, r; scanf("%d %d %d", &h, &l, &r); s[i] = segment(h, l, r); } s[n] = segment(t, -inf, inf); sort(s, s+n); part bottom(-inf, inf, inf, segment(0, -inf, inf)); part left(-inf-1, -inf, 0, segment(0, -inf-1, -inf)); part right(inf, inf+1, 0, segment(0, inf, inf+1)); sweep.insert(bottom); sweep.insert(left); sweep.insert(right); for(int i = 0; i <= n; i++) { int h = s[i].h, l = s[i].l, r = s[i].r; part p(l, r, 0, s[i]); set<part>::iterator it = sweep.upper_bound(p), jt, kt; it--; jt = it; set<part>::iterator lt = jt, rt = jt; lt--; rt++; while(jt->l < r) { if(!(lt->s.r > max(jt->s.l, l) && jt->s.h < lt->s.h && lt->s.h < h) && !(rt->s.l < min(jt->s.r, r) && jt->s.h < rt->s.h && rt->s.h < h)) { p.f = max(p.f, min(jt->f, min(jt->s.r, r)-max(jt->s.l, l))); } lt++; jt++; rt++; } kt = jt; kt--; part start = *it, end = *kt; sweep.erase(it, jt); if(start.l<l) { sweep.insert(part(start.l, l, start.f, start.s)); } if(end.r>r) { sweep.insert(part(r, end.r, end.f, end.s)); } sweep.insert(p); } set<part>::iterator it = sweep.begin(); it++; printf("%d ", it->f); }
269
E
String Theory
Emuskald is an innovative musician and always tries to push the boundaries of music production. Now he has come up with an idea for a revolutionary musical instrument — a rectangular harp. A rectangular harp is a rectangle $n × m$ consisting of $n$ rows and $m$ columns. The rows are numbered 1 to $n$ from top to bottom. Similarly the columns are numbered 1 to $m$ from left to right. String pins are spaced evenly across every side, one per unit. Thus there are $n$ pins on the left and right sides of the harp and $m$ pins on its top and bottom. The harp has exactly $n + m$ different strings, each string connecting two different pins, each on a different side of the harp. Emuskald has ordered his apprentice to construct the first ever rectangular harp. However, he didn't mention that no two strings can cross, otherwise it would be impossible to play the harp. Two strings cross if the segments connecting their pins intersect. To fix the harp, Emuskald can perform operations of two types: - pick two different columns and swap their pins on each side of the harp, not changing the pins that connect each string; - pick two different rows and swap their pins on each side of the harp, not changing the pins that connect each string; In the following example, he can fix the harp by swapping two columns: Help Emuskald complete his creation and find the permutations how the rows and columns of the harp need to be rearranged, or tell that it is impossible to do so. He can detach and reattach each string to its pins, so the physical layout of the strings doesn't matter.
There are overall 6 types of segments that connect the sides: left-top; top-right; right-bottom; bottom-left; left-right; top-bottom; If there are both left-right and top-bottom segments, there is no solution. Otherwise there remain only 5 types of segments. Without loss of generality suppose there are no left-right segments. Let's take a closer look at what should the end picture of the rectangle be: All left-top segments should be at the left top corner connecting positions (L,i) and (T,i), otherwise they surely would cross some other segment. Similarly must be positioned top-right, right-bottom, bottom-left segments. Finally, all top-bottom segments should be parallel. We also observe that the number of left-top segments must be equal to the number of right-bottom segments and the number of top-right segments should be equal to the number of bottom-right segments. Thus the important observation: the picture of the end arrangement is unique and can be determined from the input simply by counting the number of segments of each type. Next we define a cycle to be the sequence of segments, where the second midpoint of some segment in the cycle is equal to the first midpoint in the next segment in the cycle. In the given example there are two such cycles (but the direction of each cycle actually matters): Then we observe that the set of the cycles does not change with any permutation by the definition of the cycle. We can make a sketch of the solution: we should find the cycle sets in the given arrangement and in the end arrangement, and compare them for equality. At this point we actually find all the cycles in both arrangements. There are only two types of cycles: (left-top) $\to$ (top-right) $\to$ (right-bottom) $\to$ (bottom-left); other cycles. We can easily check whether the sets of first type cycles match, since the length of such cycles is 4. If they match, we rearrange the columns and rows involved to match the end arrangement. How to compare the remaining cycles. Consider a following example: Let the difference in the number of left-top and left-bottom segments be $i$, and this number plus the number of top-bottom segments $s$. If we enumerate the midpoints as in the figure, we can see that each top midpoint $k$ is connected to the bottom midpoint $k\mod s+1$ (top-right segments continue as corresponding left-bottom segments). Thus we can describe it as a permutation $\binom{1}{i+1}\begin{array}{c c c}{{2}}&{{\ddots\ }}\\ {{i+1}}&{{i+2}}&{{\ldots\ }}\end{array}$Our cycles correspond to the cycles in this permutation, with top-right segment continuation to left-bottom segment corresponding to the case where permutation cycle element decreases. It is known that the number of such permutations is $\operatorname*{gcd}(s,i)$ and their length is $\frac{}{\sqrt{\operatorname{cd}(s,i)}}$. So all these cycles have the same length. Denote the remaining segment types as some letters (in picture A, B, C). Then not only the length, but the strings describing the cycles are also the same, but can be shifted cyclically (here the direction of the cycles also is important). Besides, we know this string from the correct arrangement cycle. Thus we need to compare all the remaining given arrangement cycle strings to this string, considering cyclic shifts as invariant transformations. For each string this can be done in linear time, for example, using the Knuth-Morris-Pratt algorithm. When we find a cyclical shift for each cycle, we can position its relevant columns and rows according to the end arrangement. Time: $O(n + m)$. Memory: $O(n + m)$.
[ "geometry", "math", "strings" ]
3,100
#include<cstdio> #include<iostream> #include<vector> #include<cstring> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<int,int> pii; #define MAXN 1000005 int n, m, cnt[4][4], id[128], GS[4][MAXN], GC[4][MAXN], IS[4][MAXN], IC[4][MAXN], colp[MAXN], rowp[MAXN], vis[4][MAXN], code[4][4], memC[MAXN], pi[3*MAXN], done[4][MAXN]; string small, large, cycle, text; int findShift(string &s, string &t) { if(s.size() != t.size()) return -1; text = s + "#" + t + t; int sz = s.size(); int l = text.length(); pi[0] = 0; for (int i = 1; i < l; i++) { int j = pi[i-1]; while(j > 0 && text[i] != text[j]) { j = pi[j-1]; } if(text[i] == text[j]) { j++; } pi[i] = j; } for(int i = 2*sz; i < l; i++) { if(pi[i] == sz) { return i-2*sz; } } return -1; } int main() { freopen("input.in", "r", stdin); int L = id['L'] = 0; int T = id['T'] = 1; int R = id['R'] = 2; int B = id['B'] = 3; scanf("%d %d ", &n, &m); for(int i = 0; i < n+m; i++) { char a, b; int p, q; scanf("%c %c %d %d ", &a, &b, &p, &q); a = id[a]; b = id[b]; cnt[a][b]++; cnt[b][a]++; GS[a][p] = b; GC[a][p] = q; GS[b][q] = a; GC[b][q] = p; } if((cnt[T][B] && cnt[L][R]) || (cnt[L][T] != cnt[B][R])) { printf("No solution "); return 0; } int smallPtr[4]; int d = min(cnt[L][T], cnt[L][B]); for(int x = 1; x <= cnt[L][T]; x++) { IS[L][x] = T; IS[T][x] = L; IC[L][x] = x; IC[T][x] = x; smallPtr[L] = 1; } for(int x = 1; x <= cnt[T][R]; x++) { IS[T][m-x+1] = R; IS[R][x] = T; IC[T][m-x+1] = x; IC[R][x] = m-x+1; smallPtr[T] = m-d+1; } for(int x = 1; x <= cnt[R][B]; x++) { IS[R][n-x+1] = B; IS[B][m-x+1] = R; IC[R][n-x+1] = m-x+1; IC[B][m-x+1] = n-x+1; smallPtr[R] = n-d+1; } for(int x = 1; x <= cnt[B][L]; x++) { IS[B][x] = L; IS[L][n-x+1] = B; IC[B][x] = n-x+1; IC[L][n-x+1] = x; smallPtr[B] = 1; } for(int x = cnt[L][T]+1, y = cnt[T][R]+1; x <= cnt[L][T]+cnt[L][R]; x++, y++) { IS[L][x] = R; IS[R][y] = L; IC[L][x] = y; IC[R][y] = x; } for(int x = cnt[L][T]+1, y = cnt[L][B]+1; x <= cnt[L][T]+cnt[T][B]; x++, y++) { IS[T][x] = B; IS[B][y] = T; IC[T][x] = y; IC[B][y] = x; } char cd = 'A'; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { code[i][j] = cd++; } } int startS = -1, startC = d+1; if(cnt[L][R]) { startS = L; } else if(cnt[T][B]) { startS = T; } else if(cnt[L][T] != cnt[L][B]) { startS = L; } if(startS != -1) { int currS = startS, currC = startC; while(1) { int nextS = IS[currS][currC]; int nextC = IC[currS][currC]; large += code[currS][nextS]; currS = (nextS+2)%4; currC = nextC; if(currS==startS && currC==startC) { break; } } } if(startS == -1) { startS = 0; } for(int i = 0; i < 4; i++) { int nextS = (startS+1)%4; small += code[startS][nextS]; startS = (nextS+2)%4; } if(d > 0) { int smallCnt = 0; for(int x = 1; x <= (startS%2==0?n:m); x++) { if(!vis[startS][x] && code[startS][GS[startS][x]] == small[0]) { cycle = string(); int currS = startS, currC = x; for(int i = 0; ; i++) { vis[currS][currC] = true; memC[i] = currC; int nextS = GS[currS][currC]; int nextC = GC[currS][currC]; cycle += code[currS][nextS]; currS = (nextS+2)%4; currC = nextC; if(currS==startS && currC==x) { break; } } if(cycle.length() == small.length()) { int p = findShift(small, cycle); if(p != -1) { smallCnt++; currS = startS; currC = smallPtr[startS]++; for(int j = p, k = 0; k < 4; j=(j+1)%4, k++) { if(currS%2==0) { rowp[currC] = memC[j]; } else { colp[currC] = memC[j]; } done[currS][memC[j]] = 1; int nextS = IS[currS][currC]; int nextC = IC[currS][currC]; currS = (nextS+2)%4; currC = nextC; } } } } } if(smallCnt != d) { printf("No solution "); return 0; } } d = large.size()?(n+m-4*d)/large.size():0; if(d > 0) { int largeCnt = 0; memset(vis, 0, sizeof(vis)); for(int x = 1; x <= (startS%2==0?n:m); x++) { if(!vis[startS][x] && !done[startS][x] && code[startS][GS[startS][x]] == large[0]) { cycle = string(); int currS = startS, currC = x; for(int i = 0; ; i++) { vis[currS][currC] = true; memC[i] = currC; int nextS = GS[currS][currC]; int nextC = GC[currS][currC]; cycle += code[currS][nextS]; currS = (nextS+2)%4; currC = nextC; if(currS==startS && currC==x) { break; } } if(cycle.length() == large.length()) { int p = findShift(large, cycle); if(p != -1) { largeCnt++; currS = startS; currC = startC++; int sz = large.size(); for(int j = p, k = 0; k < sz; j=(j+1)%sz, k++) { if(currS%2==0) { rowp[currC] = memC[j]; } else { colp[currC] = memC[j]; } int nextS = IS[currS][currC]; int nextC = IC[currS][currC]; currS = (nextS+2)%4; currC = nextC; } } } } } if(largeCnt != d) { printf("No solution "); return 0; } } for(int i = 1; i <= n; i++) { printf("%d ", rowp[i]); } printf(" "); for(int i = 1; i <= m; i++) { printf("%d ", colp[i]); } printf(" "); }
270
A
Fancy Fence
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle $a$. Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to $a$?
Consider all supplementary angles of the regular $n$-polygon with angle $a$, which are equal to $180^\circ - a$. Their sum is equal to $360^{\circ}$, because the polygon is convex. Then the following equality holds: $n \cdot (180 - a) = 360$, which means that there is an answer if and only if $360{\mathrm{~~mod~}}(180-a)\equiv0$. Time: $O(t)$. Memory: $O(1)$.
[ "geometry", "implementation", "math" ]
1,100
#include<iostream> #include<cstdio> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int a; cin >> a; cout << (360 % (180-a) == 0 ? "YES" : "NO") << endl; } }
270
B
Multithreading
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of $n$ different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time. Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the $i$-th place in the list there is a thread that was at the $a_{i}$-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages. Help Emuskald find out the number of threads that \textbf{surely} have new messages. A thread $x$ surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: - thread $x$ is not updated (it has no new messages); - the list order 1, 2, ..., $n$ changes to $a_{1}$, $a_{2}$, ..., $a_{n}$.
If some $a_{i}$ is greater than $a_{i + 1}$, it is clear that $a_{i}$ definitely contains a new message because the order of these two elements has changed. Let the last such element be $a_{k}$. Then all of the elements $a_{k + 1}$, $a_{k + 2}$, $...$, $a_{n}$ can contain no new messages, since their order has not changed. The answer to the problem is $n - k$. If there is no such $a_{k}$ the order hasn't changed at all and there may be no new messages. Time: $O(n)$. Memory: $O(n) / O(1)$.
[ "data structures", "greedy", "implementation" ]
1,400
#include<iostream> using namespace std; int a[100005]; int main() { int n; cin >> n; for(int i = 0; i < n; i++) { cin >> a[i]; } int i = n-1; while(i > 0 && a[i-1] < a[i]) { i--; } cout << i << endl; }
271
A
Beautiful Year
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
This is a very straight forward problem. Just add 1 to a year number while it still has equal digits.
[ "brute force" ]
800
null
271
B
Prime Matrix
You've got an $n × m$ matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by $1$. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: - the matrix has a row with prime numbers only; - the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
Precalculate the next prime for every integer from $1$ to $10^{5}$. You can do that in any way. The main thing is to test all the divisors up to square root when you are checking if a number is prime. Now for each $a_{ij}$ (element of the given matrix) we can easily calculate $add_{ij}$ - how many do we have to add in order to make $a_{ij}$ prime. After that all we need to do is to find row or column with minimal sum in this new matrix.
[ "binary search", "brute force", "math", "number theory" ]
1,300
null
271
C
Secret
The Greatest Secret Ever consists of $n$ words, indexed by positive integers from $1$ to $n$. The secret needs dividing between $k$ Keepers (let's index them by positive integers from $1$ to $k$), the $i$-th Keeper gets a \textbf{non-empty} set of words with numbers from the set $U_{i} = (u_{i, 1}, u_{i, 2}, ..., u_{i, |Ui|})$. Here and below we'll presuppose that the set elements are written in the increasing order. We'll say that the secret is safe if the following conditions are hold: - for any two indexes $i, j$ ($1 ≤ i < j ≤ k$) the intersection of sets $U_{i}$ and $U_{j}$ is an empty set; - the union of sets $U_{1}, U_{2}, ..., U_{k}$ is set $(1, 2, ..., n)$; - in each set $U_{i}$, its elements $u_{i, 1}, u_{i, 2}, ..., u_{i, |Ui|}$ \textbf{do not form} an arithmetic progression (in particular, $|U_{i}| ≥ 3$ should hold). Let us remind you that the elements of set $(u_{1}, u_{2}, ..., u_{s})$ form an arithmetic progression if there is such number $d$, that for all $i$ ($1 ≤ i < s$) fulfills $u_{i} + d = u_{i + 1}$. For example, the elements of sets $(5)$, $(1, 10)$ and $(1, 5, 9)$ form arithmetic progressions and the elements of sets $(1, 2, 4)$ and $(3, 6, 8)$ don't. Your task is to find any partition of the set of words into subsets $U_{1}, U_{2}, ..., U_{k}$ so that the secret is safe. Otherwise indicate that there's no such partition.
If $3k > n$ there is no solution (because each of the $k$ sets must have at least 3 elements). Otherwise we can divide first $3k$ words in the following way: 1 1 2 2 3 3 ... k k 1 2 3 ... k For each of the $k$ sets, the difference between the first and the second elements will be $1$. And the difference between the second and the third elements is definitely not $1$ (more precisely, it is $2k - i - 1$ for the $i$-th set). So each set doesn't form an arithmetic progression for sure. For this solution it doesn't matter how we divide the rest $n - 3k$ words.
[ "constructive algorithms", "implementation" ]
1,500
null
271
D
Good Substrings
You've got string $s$, consisting of small English letters. Some of the English letters are good, the rest are bad. A substring $s[l...r]$ ($1 ≤ l ≤ r ≤ |s|$) of string $s = s_{1}s_{2}...s_{|s|}$ (where $|s|$ is the length of string $s$) is string $ s_{l}s_{l + 1}...s_{r}$. The substring $s[l...r]$ is good, if among the letters $ s_{l}, s_{l + 1}, ..., s_{r}$ there are \textbf{at most} $k$ \textbf{bad} ones (look at the sample's explanation to understand it more clear). Your task is to find the number of distinct good substrings of the given string $s$. Two substrings $s[x...y]$ and $s[p...q]$ are considered distinct if their content is different, i.e. $s[x...y] ≠ s[p...q]$.
At first, build a trie containing all suffixes of given string (this structure is also called explicit suffix tree). Let's iterate over all substrings in order of indexes' increasing, i. e. first $[1...1],$ then $[1...2], [1...3], ..., [1...n], [2...2], [2...3], ..., [2...n], ...$ Note, that moving from a substring to the next one is just adding a single character to the end. So we can easily maintain the number of bad characters, and also the "current" node in the trie. If the number of bad characters doesn't exceed $k$, then the substring is good. And we need to mark the corresponding node of trie, if we never did this before. The answer will be the number of marked nodes in the trie. There is also an easier solution, where instead of trie we use Rabin-Karp rolling hash to count substrings that differ by content. Just sort the hashes of all good substrings and find the number of unique hashes (equal hashes will be on adjacent positions after sort). But these hashes are unreliable in general, so it's always better to use precise algorithm.
[ "data structures", "strings" ]
1,800
null
271
E
Three Horses
There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with $a$ on the top and $b$ in the bottom as $(a, b)$. Each of the three horses can paint the special cards. If you show an $(a, b)$ card to the gray horse, then the horse can paint a new $(a + 1, b + 1)$ card. If you show an $(a, b)$ card, such that $a$ and $b$ are even integers, to the white horse, then the horse can paint a new $\textstyle{{\binom{a}{2}},{\frac{b}{2}}}$ card. If you show two cards $(a, b)$ and $(b, c)$ to the gray-and-white horse, then he can paint a new $(a, c)$ card. Polycarpus really wants to get $n$ special cards $(1, a_{1})$, $(1, a_{2})$, $...$, $(1, a_{n})$. For that he is going to the horse land. He can take exactly one $(x, y)$ card to the horse land, such that $1 ≤ x < y ≤ m$. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards? Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires.
It could be proved, that a card $(x, y)$ $(x < y)$ can be transformed to any card $(1, 1 + k \cdot d)$, where $d$ is the maximal odd divisor of $y - x$, and $k$ is just any positive integer. So every $(a_{i} - 1)$ must be divisible by $d$, i. e. $d$ is a divisor of $gcd(a_{1} - 1, ..., a_{n} - 1)$, and we can just iterate over all possible divisors. Let's take a look at all the initial cards $(x, y)$, which have have $d$ as their maximal odd divisor: these are cards with $y - x$ equal to $d$, or $2d$, or $4d$, $8d$, $16d$, ... Don't forget that the numbers $x$ and $y$ must not exceed $m$. It means that the total number of cards with some fixed difference $t = y - x$ is exactly $m - t$. The resulting solution: sum up $(m - 2^{l}d)$, where $d$ is any odd divisor of $gcd(a_{1} - 1, ..., a_{n} - 1)$, and $l$ is such, that $2^{l}d \le m$.
[ "constructive algorithms", "math", "number theory" ]
2,200
null
272
A
Dima and Friends
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment. For example, if Dima and one of his friends played hide and seek, and $7$ fingers were shown during the counting-out, then Dima would clean the place. If there were $2$ or say, $8$ fingers shown, then his friend would clean the place. Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
We will bruteforce number of fingers that will be show Dima, then if total sum of fingers = 1 modulo (n+1), Dima will clean the room. So we should increase answer if the remaining part after division by (n+1) is not 1.
[ "implementation", "math" ]
1,000
null
272
B
Dima and Sequence
Dima got into number sequences. Now he's got sequence $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Also, Dima has got a function $f(x)$, which can be defined with the following recurrence: - $f(0) = 0$; - $f(2·x) = f(x)$; - $f(2·x + 1) = f(x) + 1$. Dima wonders, how many pairs of indexes $(i, j)$ $(1 ≤ i < j ≤ n)$ are there, such that $f(a_{i}) = f(a_{j})$. Help him, count the number of such pairs.
First of all - f(i) is number of ones in binary presentation of number. We will repair all numbers to functions of them. Now we have to find number of pairs of equal numbers. Lets Q[i] - number of numbers with i bits, the answer will be sum of values Q[i]*(Q[i]-1)/2 for all i.
[ "implementation", "math" ]
1,400
null
272
C
Dima and Staircase
Dima's got a staircase that consists of $n$ stairs. The first stair is at height $a_{1}$, the second one is at $a_{2}$, the last one is at $a_{n}$ ($1 ≤ a_{1} ≤ a_{2} ≤ ... ≤ a_{n}$). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The $i$-th box has width $w_{i}$ and height $h_{i}$. Dima throws each box vertically down on the first $w_{i}$ stairs of the staircase, that is, the box covers stairs with numbers $1, 2, ..., w_{i}$. Each thrown box flies vertically down until at least one of the two following events happen: - the bottom of the box touches the top of a stair; - the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width $w_{i}$ cannot touch the stair number $w_{i} + 1$. You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.
Lets L will be the answer after last block, last block was (w1, h1), next block is (w2, h2). Next answer will be max(L+h1, A[w2]), where A - given array. At the beggining we can suppose that L = 0, w1 = 0, h1 = 0.
[ "data structures", "implementation" ]
1,500
null
272
D
Dima and Two Sequences
Little Dima has two sequences of points with integer coordinates: sequence $(a_{1}, 1), (a_{2}, 2), ..., (a_{n}, n)$ and sequence $(b_{1}, 1), (b_{2}, 2), ..., (b_{n}, n)$. Now Dima wants to count the number of distinct sequences of points of length $2·n$ that can be assembled from these sequences, such that the $x$-coordinates of points in the assembled sequence will \textbf{not decrease}. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence. Dima considers two assembled sequences $(p_{1}, q_{1}), (p_{2}, q_{2}), ..., (p_{2·n}, q_{2·n})$ and $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{2·n}, y_{2·n})$ distinct, if there is such $i$ $(1 ≤ i ≤ 2·n)$, that $(p_{i}, q_{i}) ≠ (x_{i}, y_{i})$. As the answer can be rather large, print the remainder from dividing the answer by number $m$.
Not hard to understand that answer will be (number of numbers with first coordinate = 1)! * (number of numbers with first coordinate = 2)! * ... * (number of numbers with first coordinate = 10^9)!/(2^(number of such i = 1..n, that Ai=Bi)). The only problem was to divide number with non prime modulo, it can be easely done if we will count number of prime mulpiplies=2 in all factorials. Then we can simply substract number that we need and multiply answer for some power of 2.
[ "combinatorics", "math", "sortings" ]
1,600
null
272
E
Dima and Horses
Dima came to the horse land. There are $n$ horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3. Right now the horse land is going through an election campaign. So the horses trusted Dima to split them into two parts. At that the horses want the following condition to hold: a horse shouldn't have more than one enemy in its party. Help Dima split the horses into parties. Note that one of the parties can turn out to be empty.
Not hard to understand that we have undirected graph. Lets color all vetexes in one color. Then we will find some vertex that is incorrect. We will change color of this vertex, and repeat our search, while it is possible. After every move number of bad edges will be decrease by 1 or 2, so our cycle will end in not more then M operations. So solutions always exists and we need to change some vertex not more then M times, so we will take queue of bad vertexes and simply make all operations of changes.
[ "combinatorics", "constructive algorithms", "graphs" ]
2,200
null
273
D
Dima and Figure
Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures. A piece of squared paper of size $n × m$ is represented by a table, consisting of $n$ rows and $m$ columns. All squares are white on blank squared paper. Dima defines a picture as an image on a blank piece of paper, obtained by painting some squares black. The picture portrays one of Dima's favorite figures, if the following conditions hold: - The picture contains at least one painted cell; - All painted cells form a connected set, that is, you can get from any painted cell to any other one (you can move from one cell to a side-adjacent one); - The minimum number of moves needed to go from the painted cell at coordinates $(x_{1}, y_{1})$ to the painted cell at coordinates $(x_{2}, y_{2})$, moving only through the colored cells, equals $|x_{1} - x_{2}| + |y_{1} - y_{2}|$. Now Dima is wondering: how many paintings are on an $n × m$ piece of paper, that depict one of his favorite figures? Count this number modulo $1000000007 (10^{9} + 7)$.
Good picture is connected figure that saticfy next condition: most left coordinates in every row of figure vere we have some cells will be almost-ternary, we have the same situation with right side, but here we have another sign. So it is not hard to write dp[i][j1][j2][m1][m2] numbr of figures printed of field size i*m, where last row contain all cells from j1 to j2, the most left coordinate will be m1, the most right coordinate will be m2. But it is not enough. We have to rewrite it in way that m1 will mean - was there some rows j and j+1 that most left coordinate if row j is bigger then most left coordinate in j+1. So now it is not hard to write solution with coplexity O(n*m*m*m*m). But we should optimize transfer to O(1), is can be done using precalculations of sums on some rectangels.
[ "dp" ]
2,400
null
274
A
k-Multiple Free Set
A $k$-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by $k$. That is, there are no two integers $x$ and $y$ $(x < y)$ from the set, such that $y = x·k$. You're given a set of $n$ distinct positive integers. Your task is to find the size of it's largest $k$-multiple free subset.
Consider an integer $x$ which is divisible by $k$. At most one of the integers $x$ and $x / k$ can appear in the maximum $k$-multiple free subset. Also for any integer $y$ at most one of the numbers $y$ and $yk$ appears in the answer. If you look like this you can see the input as chains of numbers so that for each chain no two adjacent elements can appear in the output. For example, If $k = 2$ then $6, 12, 24, 48, 96$ forms a chain. It's easy to see that from a chain of length $l$ we can choose at most $(l + 1) / 2$ elements in the answer. So the solution would be to compute the lengths of the chains and pick as much numbers as we can from each chain. You can sort all the numbers and do binary search or similar things to find the length of chains. Here's a cute greedy solution which picks numbers greedily from the chains: First sort all the numbers. Also consider an empty set of integers $S$, which represents the output. For each integer $x$ in the sequence, If it's not divisible by $k$, just pick it and insert it into $S$. Otherwise if it's divisible by $k$ check if $x / k$ is in $S$ or not. If it's not in $S$ insert $x$ into $S$ otherwise skip $x$. I'd also like to note that this problem comes from an old problem in UVa Online Judge, with the same the name.
[ "binary search", "greedy", "sortings" ]
1,500
null
274
B
Zero Tree
A tree is a graph with $n$ vertices and exactly $n - 1$ edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree $T$ is a tree with both vertices and edges as subsets of vertices and edges of $T$. You're given a tree with $n$ vertices. Consider its vertices numbered with integers from 1 to $n$. Additionally an integer is written on every vertex of this tree. Initially the integer written on the $i$-th vertex is equal to $v_{i}$. In one move you can apply the following operation: - Select the subtree of the given tree that includes the vertex with number 1. - Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
In the problem statement vertex $1$ is not mentioned as root of the tree. But it seems if we make it the root of the tree we can figure out the solution easier. For the leaves of the tree we can see the least number of steps needed to make each of them equal to zero. Consider a vertex which all its children are leaves. The minimum number of times that we should increase this vertex is at least as the maximum times one of the children of this vertex is increased. Also the minimum number of times this vertex is decreased is at least as maximum times one of the children of this vertex is decreased. Now we know some necessary plus or minus steps that this vertex is included in them. So after all of the children of this vertex reached zero, this vertex itself has some new value. If the current value of the vertex is positive we should decrease this vertex certain times otherwise we should decrease it. So we can find the minimum number of times this vertex should be decreased and the minimum number of times this vertex should be increased. As we showed above if we know these pair of numbers for each child of a vertex then we can calculate these numbers for that vertex too. This can be implemented using a simple DFS on the rooted tree. And the answer to the problem would be the sum of increments and decrements of vertex $1$. The time complexity of the solution is $O(n)$.
[ "dfs and similar", "dp", "greedy", "trees" ]
1,800
null
274
C
The Last Hole!
Luyi has $n$ circles on the plane. The $i$-th circle is centered at $(x_{i}, y_{i})$. At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time $t (t > 0)$ is equal to $t$. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consists of several black and white regions. Note that the circles may overlap while growing. We define a \underline{hole} as a closed, connected white region. For instance, the figure contains two holes shown by red border. During growing some holes may be created and it is easy to see that each created hole will disappear eventually. Luyi asks you to find moment of time such that the last hole disappears. In other words, you should find the first moment such that no hole can be seen after that.
In the solution we will try to find the position of all points which are the last moments in holes. Here we claim that each minimal potential hole is one of these two forms: For each three centers that form an acute triangle it's obvious that they form a potential hole. The last point in this hole would be the in triangle's circumcenter. For each four centers which are sides of a square it's also obvious there's a potential hole with last point being the square's center. For each potential hole we should check if the last point is not covered with any other circle in the last moment. The solution would be the hole with maximum distance from the centers which won't be covered by anything else. Let's remind some geometry facts. We know that circumcenter of a triangle is the point where the three perpendicular bisectors of the triangle meet. Also the circumcenter of the triangle lies inside the triangle if and only if the triangle is acute. Circumcenter is the point which has equal distance from each vertex of the triangle. Using above information it's easy to prove that three circles make a hole if and only if the triangle they form is acute. Now what remains is to prove that in the last moment which the hole is disappearing there are 3 triangles or four forming a square enclosing the hole. I'm not going into details but the proof would be like this. Consider the last point of a hole. There are some circles which form the border of the hole in the last moment. These centers have the same distance from the last point. We need to prove that only three of the centers or four of them which form a square do the same job. And all others can be ignored. Consider the circle which these centers lie on its perimeter. Here's a way to pick at most four of these points which make that hole. As long as there are three consecutive points which form make a obtuse triangle delete the middle point (why?). It's easy to see what will remain at the end is either a square or an acute triangle. The implementation can be done in $O(n^{4})$ with iterating through all triangles in $O(n^{3})$ and checking them in $O(n)$. Also there are at most $O(n^{3})$ squares, because once you've picked three of its vertices the fourth will be unique.
[ "brute force", "geometry" ]
2,600
null
274
D
Lovely Matrix
Lenny had an $n × m$ matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers.
The naive solution for this problem would be to make a graph were each vertex represents a column of the grid. Then for each two not erased integers $x$ and $y$ in the same row where $x < y$ we can add an edge from the column of $x$ to the column of $y$ in our graph. Then topological sorting on the built graph would give us the sought order of the rows. But there can be as much as O(m^2) edges in our graph and thus a $O(nm^{2})$ solution won't pass the time limit. But still the idea to solve this problem is to implement topological sort in a such way that the graph we make has less edges or to make less processing to find the topological sort. Here I present two solutions which use topological sorting. One implements topological sorting explicitly in a graph of columns as its vertices with some extra vertices but fewer edges. The other one does some kind of topological sorting without building the graph and by deciding which column can come as the first column of our ordering, and doing the same thing until all columns come in order. The first solution relies on decreasing the number of edges we used in the graph of our naive solution. Consider the numbers of a row sorted. We insert an extra vertex between each pair of adjacent different numbers. Then each column gets connected to the next extra vertex and each extra vertex gets connected to the columns before the next extra vertex. In this way the sorted order of this row would be preserved in topological sorting. We do the same thing for each row, so topological sort on the final graph would give us the sought ordering of columns. This can be implemented in $O(nmlgm)$. In the second solution for each row we color all the minimum not erased elements of that row. The first column in the output permutation should be a column where all of its non erased elements are colored. So we put this column as the first column. Now the rest of the columns can be ordered by the same way. If at some point we can't find a suitable column then there's no solution. This also can be implemented in $O(nmlgm)$.
[ "dfs and similar", "graphs", "greedy", "sortings" ]
2,200
null
274
E
Mirror Room
Imagine an $n × m$ grid with some blocked cells. The top left cell in the grid has coordinates $(1, 1)$ and the bottom right cell has coordinates $(n, m)$. There are $k$ blocked cells in the grid and others are empty. You flash a laser beam from the center of an empty cell $(x_{s}, y_{s})$ in one of the diagonal directions (i.e. north-east, north-west, south-east or south-west). If the beam hits a blocked cell or the border of the grid it will reflect. The behavior of the beam reflection in different situations is depicted in the figure below. After a while the beam enters an infinite cycle. Count the number of empty cells that the beam goes through at least once. We consider that the beam goes through cell if it goes through its center.
The blocked cells can make lots of complicated patterns. So it's obvious that the solution in includes simulating the path the laser beam goes. But the dimensions of the gird are large and the beam might travel a long path before entering a loop. So naive simulation will surely time out (See note!). It's kind of obvious that the beam finally comes back to its initial position and direction. Here were going to prove that the maximum number of times the beam might reflect until it reaches its first state is $O(n + m + k)$. Consider an empty grid, It has $O(n + m)$ maximal empty diagonal segments. When we block a cell, the two diagonal segments which pass this cell split. So the number of maximal empty diagonal segments increases by two. There for there are $O(n + m + k)$ of these segments. Also If you look at the behavior of the beam it passes some of the segments one after another. So if you simulate the beam, it reflects $O(n + m + k)$ times. Instead of naive simulation we can find the next position the beam reflects. Now we're going to prove that no cell will be visited twice. A cell gets visited twice in the cycle if we pass it in both NE-SW direction and NW-SE direction. Consider the grid colored in black and white like a chessboard. There are two types of diagonal segments the NE-SW ones and NW-SE ones (property 1). At each reflection we alternate between these two. Also there are two types of segments in another way, black segments and white segments (property 2). As you can see each time one of the properties changes the other one also changes. As a result we'll never pass a black cell in both directions, and the same is for a white cell. So this problem can be solved with simulation in $O((n + m + k)lgk)$.
[ "data structures", "implementation" ]
3,000
null
275
A
Lights Out
Lenny is playing a game on a $3 × 3$ grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on. Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
For each light you should count the number of times it's been toggled. Consider a light is toggled $k$ times. If $k$ is even then the final state of the light is 'on' otherwise it's 'off'. The implementation would be easy. You may look at the accepted solutions as reference.
[ "implementation" ]
900
null
275
B
Convex Shape
Consider an $n × m$ grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid \underline{convex} if one can walk from \textbf{any} black cell to \textbf{any another} black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Consider a pair of black cells. There exist at most two different valid paths we can take between these two cells. The naive solution would be to check the existence of at least one of these paths for each pair of black cells. There are $O(n^{2}m^{2})$ such pairs and each pair can be checked in $O(n + m)$. So the time complexity will be $O(n^{2}m^{2}(n + m))$ which is enough to get accepted. But there exists a $O(nm)$ approach. It's obvious that each row of the grid either doesn't have any black cell or the black cells are a consecutive part of the row. The same holds for every column. For every non-empty row consider the interval of its black cells. The intersection of intervals of all non-empty rows should be non-empty. If the same holds for all columns then our grid is convex. The proof of this solution is not hard and is left for the reader.
[ "constructive algorithms", "implementation" ]
1,700
null
276
A
Lunch Rush
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly $k$ time units for the lunch break. The Rabbits have a list of $n$ restaurants to lunch in: the $i$-th restaurant is characterized by two integers $f_{i}$ and $t_{i}$. Value $t_{i}$ shows the time the Rabbits need to lunch in the $i$-th restaurant. If time $t_{i}$ exceeds the time $k$ that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal $f_{i} - (t_{i} - k)$. Otherwise, the Rabbits get exactly $f_{i}$ units of joy. Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose \textbf{exactly} one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.
Let's look at all restraunts, where Rabbits can have their lunch. Let's calculate the answer for all restraunts and choose the maximulm value among of them. We need to use formula descrbed in problem statement to calculate the answer for some particular restraunt. Time complexity of this solution is $O(N)$.
[ "implementation" ]
900
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <queue> #include <algorithm> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <memory.h> #include <ctime> using namespace std; #define ABS(a) ((a>0)?a:-(a)) #define MIN(a,b) ((a<b)?(a):(b)) #define MAX(a,b) ((a<b)?(b):(a)) #define FOR(i,a,n) for (int i=(a);i<(n);++i) #define FI(i,n) for (int i=0; i<(n); ++i) #define pnt pair <int, int> #define mp make_pair #define PI 3.14159265358979 #define MEMS(a,b) memset(a,b,sizeof(a)) #define LL long long #define U unsigned int main() { #ifdef Fcdkbear freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); double beg=clock(); #endif int res=-2000000000; int n,T; scanf("%d%d",&n,&T); FOR(i,0,n) { int f,t; scanf("%d%d",&f,&t); int cur=f; if (t>T) cur-=(t-T); res=MAX(res,cur); } cout<<res<<endl; #ifdef Fcdkbear double end=clock(); fprintf(stderr,"*** Total time = %.3lf *** ",(end-beg)/CLOCKS_PER_SEC); #endif return 0; }
276
B
Little Girl and Game
The Little Girl loves problems on games very much. Here's one of them. Two players have got a string $s$, consisting of lowercase English letters. They play a game that is described by the following rules: - The players move in turns; In one move the player can remove an arbitrary letter from string $s$. - If the player before his turn can reorder the letters in string $s$ so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Let's calculate the number of letters with odd number of occurrences in $s$. Let this value be equal to $k$. If $k = 0$, then first player can win immediately: he can easily build palindrome, placing equal letters in different sides of resulting string (he always can do it, because total number of all letters is even). If $k = 1$ then first player can win immediately again; at first he builds palindrome from letters with even number of occurrences in $s$; after that he inserts the rest of the letters in the middle of built in previous step string. Let's proof very useful statement. If $k > 1$ our problem has the following solution: if $k$ is even, than second player is winner; otherwise, first player is winner. Let $k = 2$. At the beginning of the game first player can make move of two types. Using move of first type first player can decrease $k$ to $1$ by erasing one appearance of letter with odd number of occurrences. But this move leads him to defeat, because after this move second player can build palindrome. Using move of second type first player can increase $k$ to $3$ by erasing one appearance of letter with even number of occurrences. In this case second player can make similar move - he will erase the same letter. Since the number of moves of this type is finite, sooner or later first player will have to make a move of first type. After this move he loses immediately. So, if $k = 2$, than second player is a winner. Let $k = 3$. First player can decrease $k$ to $2$ by erasing the letter with odd number of occurrences. If second player will try to increase $k$ to $3$ again by erasing the similar letter, first player can decrease $k$ to $2$ again (he erases the same letter again). It's easy to see that the last move in this sequence of moves will be the move of first player. So, first player always can change the game in such a way that $k = 2$. This position is losing position for second player and winning position for first player. Now we can easily proof our statement for any $k$ using mathematical induction. So, we have quite easy solution with time complexity $O(|S|)$.
[ "games", "greedy" ]
1,300
#include <iostream> #include <string> #include <string.h> using namespace std; string s; int cnt[30]; int main() { cin>>s; for (int i=0; i<s.size(); ++i) cnt[s[i]-'a']++; int odd=0; for (int i=0; i<26; ++i) if (cnt[i]&1) odd++; if ((odd==0) || (odd&1)) cout<<"First"<<endl; else cout<<"Second"<<endl; return 0; }
276
C
Little Girl and Maximum Sum
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)$. You need to find for each query the sum of elements of the array with indexes from $l_i$ to $r_i$, inclusive. The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
Lets calculate for each cell of the initial array the number of queries that cover this cell. It's claimed, that we should associate the cell with bigger value to the cell with bigger value in initial array. More formally: suppose $b$ is an array, in $i - th$ cell of which is written the number of queries that cover $i - th$ cell. Suppose $a$ is an initial array. Let's sort those arrays. It's claimed, that the answer in this case can be calculated with following formula: $\textstyle\sum_{i=1}^{n}a[i]\cdot b[i]$ Let's proof this statements. We will take a look at some indexes $i < j$, and at elements, corresponding to shis indexes $a[i]$, $a[j]$ , $b[i]$, $b[j]$ $(a[i] \le a[j], b[i] \le b[j])$. Those elements add to the answer the following value: $a[i] \cdot b[i] + a[j] \cdot b[j]$. Let's swap $a[i]$ and $a[j]$. Now those elements elements add to the answer the following value $a[i] \cdot b[j] + a[j] \cdot b[i]$. Let's take a look at the following difference: $a[i] \cdot b[j] + a[j] \cdot b[i] - a[i] \cdot b[i] - a[j] \cdot b[j] = b[j] \cdot (a[i] - a[j]) + b[i] \cdot (a[j] - a[i]) = (b[j] - b[i]) \cdot (a[i] - a[j]) \le 0$. So, swapping of two elements leads us to nonincreasing of the total result. This means, that our arrangement is optimal. Now we need to calculate array $b$ fast enough. For this purpose one can use different data structures, which support segment modifications (segment tree, Cartesian tree and so on). But there exists much easier method. Let's create some array $d$. When we have query $l_{i}$, $r_{i}$, we should increase value $d[l_{i}]$ by $1$ and decrease value $d[r_{i} + 1]$ by $1$. In such a tricky way we increase all elements in segment $[l_{i};r_{i}]$ by $1$ After processing all of the queries we need to make a loop, which visit every element of array $d$. In this loop we can easily calculate all elements of array $b$. Now we are ready to get the final answer. The complexity of author's solution is $O(NlogN + Q)$
[ "data structures", "greedy", "implementation", "sortings" ]
1,500
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <queue> #include <algorithm> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <memory.h> #include <ctime> using namespace std; #define ABS(a) ((a>0)?a:-(a)) #define MIN(a,b) ((a<b)?(a):(b)) #define MAX(a,b) ((a<b)?(b):(a)) #define FOR(i,a,n) for (int i=(a);i<(n);++i) #define FI(i,n) for (int i=0; i<(n); ++i) #define pnt pair <int, int> #define mp make_pair #define PI 3.14159265358979 #define MEMS(a,b) memset(a,b,sizeof(a)) #define LL long long #define U unsigned int a[200100]; int val[200100]; int b[200100]; int main() { int n,q; scanf("%d%d",&n,&q); FOR(i,0,n) scanf("%d",&a[i]); sort(a,a+n); FOR(i,0,q) { int l,r; scanf("%d%d",&l,&r); l--; r--; val[l]++; if (r<n-1) val[r+1]--; } int v=0; FOR(i,0,n) { v+=val[i]; b[i]=v; } sort(b,b+n); LL res=0; FOR(i,0,n) res+=(b[i]*1ll*a[i]); cout<<res<<endl; return 0; }
276
D
Little Girl and Maximum XOR
A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers $l$ and $r$. Let's consider the values of $a\oplus b$ for all pairs of integers $a$ and $b$ $(l ≤ a ≤ b ≤ r)$. Your task is to find the maximum value among all considered ones. Expression $x\oplus y$ means applying bitwise excluding or operation to integers $x$ and $y$. The given operation exists in all modern programming languages, for example, in languages $C$++ and $Java$ it is represented as "^", in $Pascal$ — as "xor".
To be honest, I am surprised that problem D had so many accepted solution during the contest. The author's solution uses dynamic programming. In this editorial I'll explain this solution. First of all we should convert $L$ and $R$ to the binary numeral system. Now we can solve our problem with dynamic programming, using the following state $d[p][fl1][fr1][fl2][fr2]$, where $p$ is current position in binary representation of our numbers $a$ and $b$ (this parameter is in range from $0$ to number of bits in $R$), $fl$ ($0$ or $1$) is a variable, which shows if current value of $a$ is strictly greater than $L$, $fr1$ (from $0$ to $1$) is a variable, which shows if current value of $a$ is strictly less then $R$, $fl2$, $fr2$ are variables, which show the similar things for $b$. Let's use recursion with memorization for our solution. Let's define the base of recursion. If we have looked through all the bits, we should return $0$. Let's define a recursive transition. We need to know, which bits we can place into binary representation of number $a$ in $p$-th position. We can place $0$ if the following condition is true: $p$-th bit of $L$ is equal to $0$, or $p$-th bit of $L$ is equal to $1$ and variable $fl1$ shows that current value of $a$ is strictly greater then $L$. Similarly, we can place $1$ if the following condition is true: $p$-th bit of $R$ is equal to $1$, or $p$-th bit of $R$ is equal to $0$ and variable $fr1$ shows that current value of $a$ is strictly less then $R$. Similarly, we can obtain, which bits we can place into binary representation of number $b$ in $p$-th position. Let's iterate through all possible bits' values and check the result of xor operation. If it is equal to $1$, we should add to the answer corresponding power of $2$. We also need carefully recalculate values of variables $fl1$, $fr1$, $fl2$, $fr2$. We should choose maximum answer from all valid options. Initial state for our recursion is ($P$,$0$,$0$,$0$,$0$), where $P$ is number of bits in $R$. I hope, my code will clarify all the obscure points. I also want to say, that this approach is in some sense universal and can be applied to many similar problems, like this one The complexity of algorithm is $O(logR)$
[ "bitmasks", "dp", "greedy", "implementation", "math" ]
1,700
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <queue> #include <algorithm> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <memory.h> #include <ctime> using namespace std; #define ABS(a) ((a>0)?a:-(a)) #define MIN(a,b) ((a<b)?(a):(b)) #define MAX(a,b) ((a<b)?(b):(a)) #define FOR(i,a,n) for (int i=(a);i<(n);++i) #define FI(i,n) for (int i=0; i<(n); ++i) #define pnt pair <int, int> #define mp make_pair #define PI 3.14159265358979 #define MEMS(a,b) memset(a,b,sizeof(a)) #define LL long long #define U unsigned LL solveStupid(LL l, LL r) { LL res=0; for (LL i=l; i<=r; ++i) for (LL j=i; j<=r; ++j) res=max(res,i^j); return res; } string s1,s2; LL dp[70][2][2][2][2]; LL rec(int p, int fl1, int fl2, int fr1, int fr2) { if (p==s1.size()) return 0; if (dp[p][fl1][fl2][fr1][fr2]!=-1) return dp[p][fl1][fl2][fr1][fr2]; int min1=0,max1=1; if ((fl1==0) && (s1[p]=='1')) min1=1; if ((fl2==0) && (s2[p]=='0')) max1=0; int min2=0,max2=1; if ((fr1==0) && (s1[p]=='1')) min2=1; if ((fr2==0) && (s2[p]=='0')) max2=0; LL res=0; FOR(i,min1,max1+1) FOR(j,min2,max2+1) { int v=(i^j); LL toadd=0; if (v==1) { int step=s1.size()-p-1; toadd=(1ll<<step); } int nfl1=fl1,nfl2=fl2,nfr1=fr1,nfr2=fr2; if (i>s1[p]-'0') nfl1=1; if (i<s2[p]-'0') nfl2=1; if (j>s1[p]-'0') nfr1=1; if (j<s2[p]-'0') nfr2=1; res=max(res,toadd+rec(p+1,nfl1,nfl2,nfr1,nfr2)); } return dp[p][fl1][fl2][fr1][fr2]=res; } string getbin(LL num) { string res=""; while (num) { res+=((num&1)+'0'); num/=2; } reverse(res.begin(),res.end()); return res; } LL solveSmart(LL l, LL r) { s1=getbin(l); s2=getbin(r); while (s1.size()<s2.size()) s1="0"+s1; MEMS(dp,-1); LL res=rec(0,0,0,0,0); return res; } int main() { #ifdef Fcdkbear freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); double beg=clock(); #endif LL l,r; cin>>l>>r; cout<<solveSmart(l,r)<<endl; #ifdef Fcdkbear double end=clock(); fprintf(stderr,"*** Total time = %.3lf *** ",(end-beg)/CLOCKS_PER_SEC); #endif return 0; }
276
E
Little Girl and Problem on Trees
A little girl loves problems on trees very much. Here's one of them. A tree is an undirected connected graph, not containing cycles. The degree of node $x$ in the tree is the number of nodes $y$ of the tree, such that each of them is connected with node $x$ by some edge of the tree. Let's consider a tree that consists of $n$ nodes. We'll consider the tree's nodes indexed from 1 to $n$. The cosidered tree has the following property: each node except for node number 1 has the degree of at most 2. Initially, each node of the tree contains number 0. Your task is to quickly process the requests of two types: - Request of form: $0$ $v$ $x$ $d$. In reply to the request you should add $x$ to all numbers that are written in the nodes that are located at the distance of at most $d$ from node $v$. The distance between two nodes is the number of edges on the shortest path between them. - Request of form: $1$ $v$. In reply to the request you should print the current number that is written in node $v$.
One can see, that our tree is a set of chains, each of which starts in the root. First of all we need to decompose our tree in chains using, for example, depth first search. For each vertex we should find out it's depth and number of chain, which contain this vertex. For each chain we'll use some data structure, which can fast enough change it's elements and fast enough answer to the range sum query. For example, we canuse Binary Indexed Tree (BIT). We also need to create one BIT for root. This BIT is global: it's information is actual for all the chains Let's remember problem $C$. In that problem we used array $d$ for processing all the queries. We need to know values of elements of array $b$ in that problem after processing all the queries. In this problem queries are online. That's why we need to use BIT; it allows to change element and answer range sum query in $O(logN)$ time. Let's learn, how to process queries, which require modification and queries, which require finding the element, using BIT. BIT can make two types of operations: $add(x, y)$ - add value $y$ to element with index $x$ $find(x)$ - finds sum in range from $1$ to $x$ Let's consider, that we need to add value $val$ to all elements in range from $l$ to $r$ . Than we should just make operations $add(l, val)$ and $add(r + 1, - val)$. Let's consider, that we have query which require printing the value of element with index $v$. Then we should just make operation $find(v)$. Now let's go back to the initial problem. During the processing query of type $0$ we should check, if it affects the root. If query affects the root, we should carefully process this query in our chain and make necessary changes in root's BIT. Otherwise we just process query in our chain. During the processing query of type $1$ we should just find corresponding sums in root's BIT and in BIT for our chain. We should print the sum of this values. Time complexity of this solution is $O(N + QlogN)$
[ "data structures", "graphs", "trees" ]
2,100
#include <iostream> #include <string> #include <string.h> #include <cstdlib> #include <set> #include <map> #include <vector> #include <algorithm> #include <iomanip> #include <sstream> #include <memory.h> #include <stdio.h> #include <ctime> #include <cmath> using namespace std; char ch_ch_ch[1<<20]; inline int gi() {int a; scanf("%d",&a); return a;} inline string gs() {scanf("%s",ch_ch_ch); return string(ch_ch_ch);} inline string gl() {gets(ch_ch_ch); return string(ch_ch_ch);} const int inf = 2000000000; #define LL long long #define U unsigned #define pnt pair<int,int> #define FOR(i,a,b) for (int i=(a); i<(b); ++i) #define MEMS(a,b) memset((a),(b),sizeof(a)) #define MAX(a,b) ((a)>(b)?(a):(b)) #define MIN(a,b) ((a)<(b)?(a):(b)) #define ABS(a) (((a)>=(0))?(a):(-(a))) #define mp make_pair #define pb push_back #define ALL(a) a.begin(),a.end() #define FI(i,b) FOR(i,0,b) #define V(t) vector < t > #define sz size() vector<vector<int> > g; int inTree[100100]; int depth[100100]; vector<vector<int> > t; void dfs(int v, int d, int num, int p) { inTree[v]=num; depth[v]=d; t[num].push_back(0); FOR(i,0,g[v].size()) { int to=g[v][i]; if (to==p) continue; dfs(g[v][i],d+1,num,v); } } void add(int p, int v, int num) { for (int i=p; i<t[num].size(); i+=(i&(-i))) t[num][i]+=v; } int find(int p, int num) { int res=0; for (int i=p; i>0; i-=(i&(-i))) res+=t[num][i]; return res; } int main() { #ifdef Fcdkbear double beg=clock(); freopen("in.txt","r",stdin); #endif int n,q; scanf("%d%d",&n,&q); g.resize(n); FOR(i,0,n-1) { int v1,v2; scanf("%d%d",&v1,&v2); v1--; v2--; g[v1].push_back(v2); g[v2].push_back(v1); } t.resize(g[0].size()+1); int inRoot=0; FOR(i,0,g[0].size()) { t[i].push_back(0); dfs(g[0][i],1,i,0); } t[t.size()-1].resize(n+10); FOR(i,0,q) { int ty; scanf("%d",&ty); if (ty==0) { int v,val,dist; scanf("%d%d%d",&v,&val,&dist); v--; if (v==0) { inRoot+=val; add(1,val,t.size()-1); add(dist+1,-val,t.size()-1); } else { if (dist>=depth[v]) { int left=dist-depth[v]; inRoot+=val; add(1,val,t.size()-1); add(left+1,-val,t.size()-1); add(left+1,val,inTree[v]); add(depth[v]+dist+1,-val,inTree[v]); } else { add(depth[v]-dist,val,inTree[v]); add(depth[v]+dist+1,-val,inTree[v]); } } } else { int v; scanf("%d",&v); v--; if (v==0) printf("%d ",inRoot); else { int res=find(depth[v],inTree[v])+find(depth[v],t.size()-1); printf("%d ",res); } } } #ifdef Fcdkbear double end=clock(); fprintf(stderr,"*** Time = %.3lf *** ",(end-beg)/CLOCKS_PER_SEC); #endif return 0; }
277
A
Learning Languages
The "BerCorp" company has got $n$ employees. These employees can use $m$ approved official languages for the formal correspondence. The languages are numbered with integers from $1$ to $m$. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs $1$ berdollar. Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Build bipartite graph with $n$ nodes for employees and $m$ nodes for languages. If an employee initially knows a language, than there will be an edge between corresponding nodes. Now the problem is simple: add the minimal number of edges in such a way, that all the $n$ employees will be in the same connected component. Obviously, this number equals to the number of initially connected components, containing at least one employee, minus one. But there is one exception (pretest #4): if initially everyone knows no languages, we'll have to add $n$ edges, because we can't add the edges between employees (remember that the graph is bipartite).
[ "dfs and similar", "dsu" ]
1,400
null
277
B
Set of Points
Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of $n$ points with the convexity of exactly $m$. Your set of points should not contain three points that lie on a straight line.
For $m = 3, n = 5$ and $m = 3, n = 6$ there is no solution. Let's learn how to construct the solution for $n = 2m$, where $m \ge 5$ and is odd. Set up $m$ points on a circle of sufficiently large radius. This will be the inner polygon. The outer polygon will be the inner polygon multiplied by 2. More precisely ($1 \le i \le m$): $x_{i}=r o u n d(10^{7}*c o s(\frac{2\pi}{m}i))$ $y_{i}=r o u n d(10^{7}*s i n({\frac{2\pi}{m}}i))$ $x_{i+m}=2\cdot r o u n d(10^{7}*c o s(\frac{2\pi}{m}i))$ $y_{i+m}=2\cdot r o u n d(10^{7}*s i n({\frac{2\pi}{m}}i))$ If $m$ is even, construct the solution for $m + 1$ and then delete one point from each polygon. If $n < 2m$, delete $2m - n$ points from the inner polygon. Unfortunately, this solution doesn't work for $m = 4, n = 7$ and $m = 4, n = 8$. Another approach is to set up $m$ points on a convex function (for example, $y = x^{2} + 10^{7}$), and set up the rest $n - m$ points on a concave function (for example, $y = - x^{2} - 10^{7}$).
[ "constructive algorithms", "geometry" ]
2,300
null
277
C
Game
Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid line (not necessarily from border to border). The part of the paper, that touches the knife at least once, is considered cut. There is one limit not to turn the game into an infinite cycle: each move has to cut the paper, that is the knife has to touch the part of the paper that is not cut before. Obviously, the game ends when the entire sheet is cut into $1 × 1$ blocks. During the game, the pieces of the sheet are not allowed to move. It is also prohibited to cut along the border. The coordinates of the ends of each cut must be integers. You are given an $n × m$ piece of paper, somebody has already made $k$ cuts there. Your task is to determine who will win if the players start to play on this sheet. You can consider that both players play optimally well. If the first player wins, you also need to find the winning first move.
At first, notice that horizontal and vertical cuts are independent. Consider a single horizontal line. It contains $m$ unit segments. And in any game state it's always possible to decrease the number of uncut units as the player wants. Imagine, that she starts growing a segment from a border, increasing it's length by 1 at a time. Each time the total uncut length decreases by either 0 or 1. In the end it obviously reaches 0. The same holds for vertical lines as well. So if there are no initial cuts, the game is a nim with $n - 1$ piles of $m$ stones and $m - 1$ piles of $n$ stones. Could be solved with simple formula. Initial $k$ cuts should be just a technical difficulty. For any vertical/horizontal line, which contains at least one of the cuts, it's pile size should be decreased by the total length of all segments on this line. How to make a first move in nim: let $res$ is the result of state (grundy function), and $a_{i}$ is the size of the $i$-th pile. Then the result of the game without $i$-th pile is $res \oplus a_i$. We want to replace $a_{i}$ with some $x$, so that $r e s\oplus a_{i}\oplus x=0$. Obviously, the only possible $x=r e s\oplus a_{i}$. The resulting solution: find a pile for which $(r e s\oplus a_{i})<a_{i}$, and decrease it downto $res \oplus a_i$.
[ "games", "implementation" ]
2,400
null
277
D
Google Code Jam
Many of you must be familiar with the Google Code Jam round rules. Let us remind you of some key moments that are crucial to solving this problem. During the round, the participants are suggested to solve several problems, each divided into two subproblems: an easy one with small limits (Small input), and a hard one with large limits (Large input). You can submit a solution for Large input only after you've solved the Small input for this problem. There are no other restrictions on the order of solving inputs. In particular, the participant can first solve the Small input, then switch to another problem, and then return to the Large input. Solving each input gives the participant some number of points (usually different for each problem). This takes into account only complete solutions that work correctly on all tests of the input. The participant gets the test result of a Small input right after he submits it, but the test result of a Large input are out only after the round's over. In the final results table the participants are sorted by non-increasing of received points. If the points are equal, the participants are sorted by ascending of time penalty. By the Google Code Jam rules the time penalty is the \textbf{time when the last correct solution was submitted}. Vasya decided to check out a new tactics on another round. As soon as the round begins, the boy quickly read all the problems and accurately evaluated the time it takes to solve them. Specifically, for each one of the $n$ problems Vasya knows five values: - Solving the Small input of the $i$-th problem gives to the participant $scoreSmall_{i}$ points, and solving the Large input gives $scoreLarge_{i}$ more points. That is, the maximum number of points you can get for the $i$-th problem equals $scoreSmall_{i} + scoreLarge_{i}$. - Writing the solution for the Small input of the $i$-th problem takes exactly $timeSmall_{i}$ minutes for Vasya. Improving this code and turning it into the solution of the Large input takes another $timeLarge_{i}$ minutes. - Vasya's had much practice, so he solves all Small inputs from the first attempt. But it's not so easy with the Large input: there is the $probFail_{i}$ probability that the solution to the Large input will turn out to be wrong at the end of the round. Please keep in mind that these solutions do not affect the participants' points and the time penalty. A round lasts for $t$ minutes. The time for reading problems and submitting solutions can be considered to equal zero. Vasya is allowed to submit a solution exactly at the moment when the round ends. Vasya wants to choose a set of inputs and the order of their solution so as to make the expectation of the total received points maximum possible. If there are multiple ways to do this, he needs to minimize the expectation of the time penalty. Help Vasya to cope with this problem.
Suppose we have fixed set of inputs that we have to solve. Let's learn how to determine the optimal order. Obviously, Small inputs (and Large inputs with $probFail = 0$) won't fail in any case. It means that our penalty time is no less than submission time of last such ``safe'' inputs. So we will solve such inputs before all the others. Inputs with $probFail = 1$ are just a waste of time, we won't solve such inputs. Now we have only inputs with $0 < probFail < 1$. Let $i$ and $j$ be two problems that we are going to solve consecutively at some moment. Let's check, if it is optimal to solve them in order $i$, $j$, or in reversed order. We can discard all the other inputs, because they don't affect on the relative order of these two. $(timeLarge_{i} + timeLarge_{j})(1 - probFail_{j}) + timeLarge_{i}(1 - probFail_{i})probFail_{j} < (timeLarge_{i} + timeLarge_{j})(1 - probFail_{i}) + timeLarge_{j}(1 - probFail_{j})probFail_{i}$ $- probFail_{j} \cdot timeLarge_{j} - timeLarge_{i} \cdot probFail_{j} \cdot probFail_{i} < - probFail_{i} \cdot timeLarge_{i} - timeLarge_{j} \cdot probFail_{i} \cdot probFail_{j}$ $timeLarge_{i} \cdot probFail_{i}(1 - probFail_{j}) < timeLarge_{j} \cdot probFail_{j}(1 - probFail_{i})$ $timeLarge_{i} \cdot probFail_{i} / (1 - probFail_{i}) < timeLarge_{j} \cdot probFail_{j} / (1 - probFail_{j})$ Now we've got a comparator for sort, which will give us the optimal order. Note, that inputs with $probFail = 0, 1$ will be sorted by the comparator correctly as well, so it's not a corner case. Let's return to the initial problem. First of all, sort problems with the optimal comparator (it's clear that any other order won't be optimal by time, and the score doesn't depend on the order). Calculate the DP: $z[i][j]$ = pair of maximal expected total score and minimal expected penalty time with this score, if we've already decided what to do with the first $i$ problems, and we've spent $j$ real minutes from the contest's start. There are 3 options for the $i$-the problem: skip: update $z[i + 1][j]$ with the same expected values solve the Small input: update $z[i + 1][j + timeSmall_{i}]$, the expected total score increases by $scoreSmall_{i}$, and the expected penalty time increases by $timeSmall_{i}$ (we assume that this input is solved in the very beggining of the contest) solve both inputs: update $z[i + 1][j + timeSmall_{i} + timeLarge_{i}]$, the expected total score increases by $scoreSmall_{i} + (1 - probFail_{i})scoreLarge_{i}$, and the expected penalty time becomes $timeSmall_{i} + (1 - probFail_{i})(j + timeLarge_{i}) + probFail_{i} \cdot penaltyTime(z[i][j])$, where $penaltyTime(z[i][j])$ is the expected penalty time from DP The resulting answer is the best of $z[n][i], (0 \le i \le t)$. The expected total score could be a number around $10^{12}$ with 6 digits after decimal point. So it can't be precisely stored in double. And any (even small) error in calculating score may lead to completely wrong expected time (pretest #7). For example, you can multiply all the probabilities by $10^{6}$ and store the expected score as integer number to avoid this error.
[ "dp", "probabilities" ]
2,800
null
277
E
Binary Tree on Plane
A root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node. A root tree is binary if each node has at most two outgoing arcs. When a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from $u$ to $v$ must meet the condition $y_{u} > y_{v}$. You've been given the coordinates of all tree nodes. Your task is to connect these nodes by arcs so as to get the binary root tree and make the total length of the arcs minimum. All arcs of the built tree must be directed from top to bottom.
If there is no "binary" restriction, the solution is simple greedy. Each node of the tree (except the root) must have exactly 1 parent, and each node could be parent for any number of nodes. Let's assign for each node $i$ (except the root) such a node $p_{i}$ as a parent, so that $y_{pi} > y_{i}$ and distance between $i$ and $p_{i}$ is minimal possible. Renumerate all the nodes in order of non-increasing of $y$. Now it's clear that $p_{i} < i$ ($2 \le i \le n$). So we've just built a directed tree with all the arcs going downwards. And it has minimal possible length. Let's recall the "binary" restriction. And realize that it doesn't really change anything: greedy transforms to min-cost-max-flow on the same distance matrix as edge's costs, but each node must have no more than 2 incoming flow units.
[ "flows", "trees" ]
2,400
null
278
B
New Problem
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title \underline{original} if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of $n$ last problems — the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string. A substring $s[l... r]$ $(1 ≤ l ≤ r ≤ |s|)$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is string $s_{l}s_{l + 1}... s_{r}$. String $x = x_{1}x_{2}... x_{p}$ is lexicographically smaller than string $y = y_{1}y_{2}... y_{q}$, if either $p < q$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{p} = y_{p}$, or there exists such number $r$ $(r < p, r < q)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} < y_{r + 1}$. The string characters are compared by their ASCII codes.
The total number of different strings of 2 letters is $26^{2} = 676$, but the total length of the input strings is no more than $600$. It means that the length of answer is no more than 2. So just check all the strings of length 1 and 2.
[ "brute force", "strings" ]
1,500
null
279
A
Point on Spiral
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: \textbf{$[(0, 0), (1, 0)]$, $[(1, 0), (1, 1)]$, $[(1, 1), ( - 1, 1)]$, $[( - 1, 1), ( - 1, - 1)]$, $[( - 1, - 1), (2, - 1)]$, $[(2, - 1), (2, 2)]$} and so on. Thus, this infinite spiral passes through each integer point of the plane. Valera the horse lives on the plane at coordinates $(0, 0)$. He wants to walk along the spiral to point $(x, y)$. Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point $(0, 0)$ to point $(x, y)$.
Since constraints are small, you can just simulate the whole process, but I'll explain an $O(1)$ solution. Let's look at the path Now it's easy to see that the plane can be divided into four parts And then we can calculate answer for each part separately, just be careful with borders. For example, for the right part the answer is $4x - 3$.
[ "brute force", "geometry", "implementation" ]
1,400
#include "bits/stdc++.h" using namespace std; int main() { int x, y; cin >> x >> y; if (x == 0 && y == 0) { cout << 0 << '\n'; } else if (-x + 1 < y && y <= x) { cout << 1 + (x - 1) * 4 << '\n'; } else if (-y <= x && x < y) { cout << 2 + (y - 1) * 4 << '\n'; } else if (x <= y && y < -x) { cout << 3 + (-x - 1) * 4 << '\n'; } else { cout << 4 + (-y - 1) * 4 << '\n'; } return 0; }
279
B
Books
When Valera has got some free time, he goes to the library to read some books. Today he's got $t$ free minutes to read. That's why Valera took $n$ books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to $n$. Valera needs $a_{i}$ minutes to read the $i$-th book. Valera decided to choose an arbitrary book with number $i$ and read the books one by one, starting from this book. In other words, he will first read book number $i$, then book number $i + 1$, then book number $i + 2$ and so on. He continues the process until he either runs out of the free time or finishes reading the $n$-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.
The problem can be written in the following way: for each index $i$ denote $r_i$ as the largest index such that $a_i + \ldots + a_{r_i} \leqslant t$. The problem is to find $max(r_i - i + 1)$. One can see that $r_i$ are nondecreasing, so the problem can be solved with two pointers: iterate over $i$ and keep a pointer to corresponding $r_i$.
[ "binary search", "brute force", "implementation", "two pointers" ]
1,400
#include "bits/stdc++.h" using namespace std; int main() { int n, t; cin >> n >> t; vector<int> a(n); for (int& k : a) cin >> k; int r = 0; int sm = 0; int ans = 0; for (int i = 0; i < n; ++i) { while (r < n && sm + a[r] <= t) { sm += a[r]; ++r; } ans = max(ans, r - i); sm -= a[i]; } cout << ans << '\n'; return 0; }
279
C
Ladder
You've got an array, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Also, you've got $m$ queries, the $i$-th query is described by two integers $l_{i}, r_{i}$. Numbers $l_{i}, r_{i}$ define a subsegment of the original array, that is, the sequence of numbers $a_{li}, a_{li + 1}, a_{li + 2}, ..., a_{ri}$. For each query you should check whether the corresponding segment is a ladder. A ladder is a sequence of integers $b_{1}, b_{2}, ..., b_{k}$, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer $x$ $(1 ≤ x ≤ k)$, that the following inequation fulfills: $b_{1} ≤ b_{2} ≤ ... ≤ b_{x} ≥ b_{x + 1} ≥ b_{x + 2}... ≥ b_{k}$. Note that the non-decreasing and the non-increasing sequences are also considered ladders.
Let's calculate two arrays before answering queries. $tol[i]$ is the smallest index such that $[b_{tol[i]},\, \ldots,\, b_{i}]$ is nonincreasing, and $tor[i]$ is the largest index such that $[b_{i},\, \ldots,\, b_{tor[i]}]$ is nondecreasing. Then for each query we can take $tor[l]$ and $tol[r]$ and compare them. The answer is "Yes" iff $tor[l] \geqslant tol[r]$. In other words, we are checking if the largest nondecreasing segment from $l$ and largest nonincreasing segment from $r$ are intersecting. To calculate $tol[i]$, go over $i$ from $1$ to $n$ and maintain largest nonincreasing suffix. For $tor$ do the same in reverse.
[ "dp", "implementation", "two pointers" ]
1,700
#include "bits/stdc++.h" using namespace std; int main() { int n, m; cin >> n >> m; vector<int> a(n); for (int& k : a) cin >> k; vector<int> tor(n), tol(n); iota(tol.begin(), tol.end(), 0); iota(tor.begin(), tor.end(), 0); tol[0] = 0; for (int i = 1; i < n; ++i) if (a[i - 1] >= a[i]) tol[i] = tol[i - 1]; tor[n - 1] = n - 1; for (int i = n - 2; i >= 0; --i) if (a[i] <= a[i + 1]) tor[i] = tor[i + 1]; while (m--) { int l, r; cin >> l >> r; --l; --r; cout << (tol[r] <= tor[l] ? "Yes" : "No") << '\n'; } return 0; }
279
D
The Minimum Number of Variables
You've got a positive integer sequence $a_{1}, a_{2}, ..., a_{n}$. All numbers in the sequence are distinct. Let's fix the set of variables $b_{1}, b_{2}, ..., b_{m}$. Initially each variable $b_{i}$ $(1 ≤ i ≤ m)$ contains the value of zero. Consider the following sequence, consisting of $n$ operations. The first operation is assigning the value of $a_{1}$ to some variable $b_{x}$ $(1 ≤ x ≤ m)$. Each of the following $n - 1$ operations is assigning to some variable $b_{y}$ the value that is equal to the sum of values that are stored in the variables $b_{i}$ and $b_{j}$ $(1 ≤ i, j, y ≤ m)$. At that, the value that is assigned on the $t$-th operation, must equal $a_{t}$. For each operation numbers $y, i, j$ are chosen anew. Your task is to find the minimum number of variables $m$, such that those variables can help you perform the described sequence of operations.
You can notice that when we want to perform some operation, we are only interested in a subset of current values of variables (including zeros). So let's create $dp[i][mask] = bool$, which is $1$ if we can perform first $i$ operations and end up with the values from $mask$. Here $k$-bit in the mask corresponds to the value $vals[k]$, where array $vals$ stores all numbers in $a$ and a zero, and $k$-th bit is set iff the value of one of the variables is $vals[k]$. To make transition from $dp[i][mask]$ to $dp[i + 1][new\_mask]$, let's look at the operation. We have to find two values in the $mask$ such that their sum is $a[i + 1]$. Then to calculate $new\_mask$ we have to set $k$-th bit in the $mask$, where $k$ is such that $vals[k] = a[i + 1]$. Also, while writing new variable we can overwrite any existing variable, so we have an option to disable any bit in the $mask$. Now it looks like we have $O(2^nn)$ states and $n$ transitions from each state (disabling each bit). But actually if we only make transition from $dp[i][mask] = 1$, the complexity will be $O(2^nn)$, because for each $i$ there are at most $2^{i+1}$ masks that we can achieve, since there are only $i$ distinct numbers on the current prefix plus an additional zero. And $\sum_{i=1}^n 2^{i+1}\cdot n = O(2^nn)$. The only problem left is to check if we can build some number $y$ from $vals$ using numbers from $mask$. This can be precomputed in $O(2^nn)$: let's calculate array $possible[mask] = x$, where $i$-th bit in $x$ is set iff we can get number $vals[i]$ from mask on the next step. To calculate it, first for each $mask$ with at most $2$ bits just calculate all possible $x$ with any straightforward approach, since there are only $O(n^2)$ such masks. For any other mask notice that we can get $y$ iff sum of some two values equals to $y$. So we can iterate over all submasks such that they differ from $mask$ in exactly one bit and update $possible[mask]$ with $possible[submask]$. And since $mask$ has at least $3$ bits, if there is a pair which sums up to $y$, this pair will be included into at least one of the submasks. One can even notice that we only need any $3$ such submasks to cover every pair of bits. The answer is minimum number of bits over all masks such that $dp[n][mask] = 1$.
[ "bitmasks", "dp" ]
2,200
#include "bits/stdc++.h" using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int& k : a) cin >> k; auto vals = a; vals.push_back(0); sort(vals.begin(), vals.end()); vals.erase(unique(vals.begin(), vals.end()), vals.end()); vector<int> pos(n); for (int i = 0; i < n; ++i) { pos[i] = lower_bound(vals.begin(), vals.end(), a[i]) - vals.begin(); } vector<int> possible(1 << vals.size(), 0); for (int i = 1; i < possible.size(); ++i) { int k = 0; for (int j = 0; j < vals.size() && k < 3; ++j) { if ((i >> j) & 1) { possible[i] |= possible[i ^ (1 << j)]; ++k; } } if (__builtin_popcount(i) <= 2) { for (int j = 0; j < vals.size(); ++j) { if (!((i >> j) & 1)) continue; for (int k = 0; k < vals.size(); ++k) { if (!((i >> k) & 1)) continue; int val = vals[j] + vals[k]; int ind = lower_bound(vals.begin(), vals.end(), val) - vals.begin(); if (ind < vals.size() && vals[ind] == val) possible[i] |= (1 << ind); } } } } vector<char> dp_cur(1 << vals.size(), 0); dp_cur[1 << pos[0]] = 1; dp_cur[(1 << pos[0]) | (1 << 0)] = 1; auto can_sum = [&](int mask, int pos) { return (possible[mask] >> pos) & 1; }; vector<char> dp_next; for (int i = 1; i < n; ++i) { dp_next.assign(dp_cur.size(), false); for (int j = 0; j < dp_cur.size(); ++j) { if (dp_cur[j] && can_sum(j, pos[i])) { int mask = j; mask |= (1 << pos[i]); dp_next[mask] = 1; for (int k = 0; k < vals.size(); ++k) if (((mask >> k) & 1) && vals[k] != a[i]) dp_next[mask ^ (1 << k)] = 1; } } swap(dp_cur, dp_next); } int ans = -1; for (int i = 0; i < dp_cur.size(); ++i) { if (!dp_cur[i]) continue; int sz = __builtin_popcount(i); if (ans == -1 || ans > sz) ans = sz; } cout << ans << '\n'; return 0; }
279
E
Beautiful Decomposition
Valera considers a number beautiful, if it equals $2^{k}$ or -$2^{k}$ for some integer $k$ $(k ≥ 0)$. Recently, the math teacher asked Valera to represent number $n$ as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number $n$ into beautiful summands, you need to find the size of the decomposition which has the fewest summands.
First of all it's easy to notice that we will use each power of $2$ at most once. Let's look at the highest bit in the current number, suppose it's $2^k$. Since the sum of all powers of $2$ below $k$ is less than $2^k$, we will have to add at least one power of two $2^x$ with $x \geqslant k$. One can see that adding $2^{k+2}$ is not optimal, since then we will have to subtract at least $2^{k+1}$ and $2^{k+2} - 2^{k+1}$ can be replaced with $2^{k+1}$. So the only choices are $2^k$ or $2^{k+1}$. If we add $2^k$, we have to solve a problem for remaining number, which is a suffix or our current binary string. Otherwise, $2^{k+1}$ is larger than our current number, so we just need the answer for $m = 2^{k+1} - n$. Let's call such $m$ a complement for a number $n$ (notice that we don't need $k$ in the definition because $k$ is defined as largest bit in $n$) Now let's look at $m$. To calculate it, we have to flip all bits in $n$ and add $1$ to the result. Now it's easy to see that if $m$ is a complement for $n$, then for any suffix of $n$ (in binary form), the corresponding suffix of $m$ is a complement for it. Also, $n$ is a complement for $m$. So during our calculations we will only deal with $n$, $m$, suffixes of $n$ and suffixes of $m$. And this leads to a following dp solution: let $v[1] = n$, $v[2] = m$. Then $dp[ind][suf]$ is the smallest answer for a binary number represented by a suffix of number $v[ind]$ starting from index $suf$. We can calculate this $dp$ starting from $dp[\ldots][n]$ and the answer will be $dp[1][1]$.
[ "dp", "games", "greedy", "number theory" ]
1,900
#include "bits/stdc++.h" using namespace std; int main() { string n; cin >> n; string m = n; { for (char& c : m) { c ^= '1' ^ '0'; } int ind = m.size() - 1; while (ind >= 0 && m[ind] == '1') { m[ind] = '0'; --ind; } if (ind == -1) { m.insert(m.begin(), '1'); n.insert(n.begin(), '0'); } else { m[ind] = '1'; } } int sz = n.size(); vector<string> v = {n, m}; vector<array<int, 2>> dp(sz); dp[sz - 1][0] = (v[0].back() == '1'); dp[sz - 1][1] = (v[1].back() == '1'); for (int i = sz - 2; i >= 0; --i) { for (int b = 0; b < 2; ++b) { if (v[b][i] == '0') { dp[i][b] = dp[i + 1][b]; } else { dp[i][b] = min(dp[i + 1][b] + 1, dp[i + 1][b ^ 1] + 1); } } } cout << dp[0][0] << '\n'; return 0; }
280
A
Rectangle Puzzle
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the $Ox$ axis, equals $w$, the length of the side that is parallel to the $Oy$ axis, equals $h$. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle $α$. Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.
It may always be a good idea to try a simplified version before the situation gets into complicated. In this problem, a simplified version you might to be noticed is the square case. So here it is. you can easily see the area can be calculated by $$S - 4 \times T$$ Here S is the area of the large square, and T is the area of those ambient triangles. In the rectangle situation, however, things will turn out to be more complex. But if you come back to the problem after draw some pictures, you can found there are only two cases we need to dig them out: The first case is quiet similar to the square which we discussed just now. The second case is rather easy if you consider the parallelogram. And here the key point is come ... Where is the watershed between them? You can calculate $\beta$ by exterior-interior angles, similar triangle, solving a system of linear equations of two unknowns even binary search on the angle or any other way you could imagine. In the end, you'll find $\beta = 2 \arctan \frac{h}{w}$. As long as you can nd the watershed, the greater part of the problem has been finished. Maybe you have noticed, this problem can also be solved by some computational geometry method, such as half-plane intersection or convex-hull.
[ "geometry" ]
2,000
null
280
B
Maximum Xor Secondary
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers $x_{1}, x_{2}, ..., x_{k}$ $(k > 1)$ is such maximum element $x_{j}$, that the following inequality holds: $x_{j}\not\to\operatorname*{m}_{i\geq k}^{k}x_{i}$. The lucky number of the sequence of distinct positive integers $x_{1}, x_{2}, ..., x_{k}$ $(k > 1)$ is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence. You've got a sequence of distinct positive integers $s_{1}, s_{2}, ..., s_{n}$ $(n > 1)$. Let's denote sequence $s_{l}, s_{l + 1}, ..., s_{r}$ as $s[l..r]$ $(1 ≤ l < r ≤ n)$. Your task is to find the maximum number among all lucky numbers of sequences $s[l..r]$. Note that as all numbers in sequence $s$ are distinct, all the given definitions make sence.
The intervals meaning can only be reflected on its maximum element and second maximum element, so apparently, there must be a lot of meaningless interval which we needn't check them at all. But how can we skip them? Maintain a monotone-decreasing-stack can help us. While a new element came into the view, pop the top element in the stack, and check the corresponding interval, until the new element is greater than the top element in the stack. We can easily see it is correct since we wont lost the answer as long as it exists. All the element at most push and pop once, and only been checked when popped. So the time complexity turn to be O(n).
[ "data structures", "implementation", "two pointers" ]
1,800
null
280
C
Game on Tree
Momiji has got a rooted tree, consisting of $n$ nodes. The tree nodes are numbered by integers from $1$ to $n$. The root has number $1$. Momiji decided to play a game on this tree. The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by $v$) and removes all the subtree nodes with the root in node $v$ from the tree. Node $v$ gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number $1$. Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
The answer is $$\sum_{i=1}^n \frac{1}{Depth[i]}$$ Here we denoted the $Depth[root] = 0$. And why it works? Well, let us observe each vertex independently, when one vertex has been removed, you need either to remove it directly, or remove one of its ancestors. All these choices are equiprobable, so the probability of direct removal is $\frac{1}{Depth[i]}$. And the sum of them is our result. This is been known as the Linearity of the Expected Value. This property arises almost every way in those problems related with probability. This method will also work when the objects of the delete operation is under a partial order relation. For example, on a DAG or even a digraph(reduce it into a DAG). Finally It will be reduce to descendant counting. But when the delete option is look like ... remove the node and all its neighbours ... such disordered form, the method can do nothing.
[ "implementation", "math", "probabilities", "trees" ]
2,200
null
280
D
k-Maximum Subsequence Sum
Consider integer sequence $a_{1}, a_{2}, ..., a_{n}$. You should run queries of two types: - The query format is "$0$ $i$ $val$". In reply to this query you should make the following assignment: $a_{i} = val$. - The query format is "$1$ $l$ $r$ $k$". In reply to this query you should print the maximum sum of at most $k$ non-intersecting subsegments of sequence $a_{l}, a_{l + 1}, ..., a_{r}$. Formally, you should choose at most $k$ pairs of integers $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{t}, y_{t})$ $(l ≤ x_{1} ≤ y_{1} < x_{2} ≤ y_{2} < ... < x_{t} ≤ y_{t} ≤ r; t ≤ k)$ such that the sum $a_{x1} + a_{x1 + 1} + ... + a_{y1} + a_{x2} + a_{x2 + 1} + ... + a_{y2} + ... + a_{xt} + a_{xt + 1} + ... + a_{yt}$ is as large as possible. Note that you should choose at most $k$ subsegments. Particularly, you can choose 0 subsegments. In this case the described sum considered equal to zero.
Consider the static problem, Apparently, we can use a dynamic programming to solve it. $f_{0}[i][j]$: the j-MSS in [0, i]. $f_{1}[i][j]$: the quasi-j-MSS in [0, i], which the item ${A_{i}}$ must be selected. The state transition is enumerating whether the $i$th element is selected or not. That's easy for a clever guy such as you. So the brute-force method is doing a dynamic programming for each query. The operation Modify takes $O(1)$ time, and Query takes $O(nk)$ . It's too slow to get Accepted. A simple optimization is using a data structure to speed up Query. The segment tree can be OK. In every node, we store such values in the interval represented by the node: the max sum if choosing $j$ subsegments the max sum if choosing $j$ subsegments with the first element chosen the max sum if choosing $j$ subsegments with the last element chosen the max sum if choosing $j$ subsegments with both first element and last element chosen It's clear that if we know the values of two intervals $A$ and $B$, we can infer the values of the interval which is concatenating $A$ and $B$ by just enumerating how many subsegments can be chosen in $A$ and can be chosen in $B$. The time complexity of concatenating two intervals is $O(k^{2})$. So both operations Modify and Query take $O(k^{2}\log{n})$ running time. The time limit is 5s in order to save Java's life. If you do some optimization, the solution can be Accepted. You can see liouzhou_101's solution for details. It seems hard to be optimized using such idea. Now we are going to use another totally different idea from max-flow problem. We construct a max-cost max-flow model to solve this problem. The source is $S$ and the sink is $T$. There are other $n + 1$ vertices. A bi-directional edge between Vertex $i$ and Vertex $i + 1$ has cost $A_{i}$ and capacity 1. The unidirectional edge from $S$ to Vertex $i$ has cost 0 and capacity 1 and the unidirectional edge from Vertex $i$ to $T$ has cost 0 and capacity 1. It's obvious for correctness. We can use Successive shortest path algorithm to solve the flow problem. But it's as slow as the brute-force method, or even worse. Considering how the flow problem is solved, that is, how Successive shortest path algorithm works. We find the longest path(**max-cost** instead of min-cost ) between $S$ and $T$, and then augment. We can simplify the algorithm due to the special graph. The new algorithm is: find the subsegment with the maximum sum negate the elements in the subsegment repeat the two steps $k$ times the answer is the sum of the sum of the subsegment you found each time. So, the key point is doing these two operations quickly, where segment tree can possibly be used. To find the MSS you need to store the sum of an interval the maximum partial sum from left the maximum partial sum from right the MSS in the interval To negate a subsegment, the minimum elements must be stored. To find the position of MSS, all the positions are supposed to be kept. The complexity of Modify is $O(\log n)$, and the complexity of Query is $O(k\log n)$. It can pass all the test data easily but it has a really large constant.
[ "data structures", "flows", "graphs", "implementation" ]
2,800
/* Author: elfness@UESTC */ #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #include<iostream> #include<vector> #include<string> using namespace std; typedef long long LL; const int MAX = 105000; /** * Segment tree */ struct Seg { int l, r; int maxLeftValue, maxRightValue, minLeftValue, minRightValue, maxSum, minSum, sum; int maxLeftBound, maxRightBound, minLeftBound, minRightBound, maxSumLeft, maxSumRight, minSumLeft, minSumRight; } seg[MAX << 2]; int a[MAX]; void update(int k) { seg[k].sum = seg[k << 1].sum + seg[k << 1 | 1].sum; if (seg[k << 1].maxLeftValue >= seg[k << 1].sum + seg[k << 1 | 1].maxLeftValue) { seg[k].maxLeftValue = seg[k << 1].maxLeftValue; seg[k].maxRightBound = seg[k << 1].maxRightBound; } else { seg[k].maxLeftValue = seg[k << 1].sum + seg[k << 1 | 1].maxLeftValue; seg[k].maxRightBound = seg[k << 1 | 1].maxRightBound; } if (seg[k << 1 | 1].maxRightValue >= seg[k << 1 | 1].sum + seg[k << 1].maxRightValue) { seg[k].maxRightValue = seg[k << 1 | 1].maxRightValue; seg[k].maxLeftBound = seg[k << 1 | 1].maxLeftBound; } else { seg[k].maxRightValue = seg[k << 1 | 1].sum + seg[k << 1].maxRightValue; seg[k].maxLeftBound = seg[k << 1].maxLeftBound; } if (seg[k << 1].minLeftValue <= seg[k << 1].sum + seg[k << 1 | 1].minLeftValue) { seg[k].minLeftValue = seg[k << 1].minLeftValue; seg[k].minRightBound = seg[k << 1].minRightBound; } else { seg[k].minLeftValue = seg[k << 1].sum + seg[k << 1 | 1].minLeftValue; seg[k].minRightBound = seg[k << 1 | 1].minRightBound; } if (seg[k << 1 | 1].minRightValue <= seg[k << 1 | 1].sum + seg[k << 1].minRightValue) { seg[k].minRightValue = seg[k << 1 | 1].minRightValue; seg[k].minLeftBound = seg[k << 1 | 1].minLeftBound; } else { seg[k].minRightValue = seg[k << 1 | 1].sum + seg[k << 1].minRightValue; seg[k].minLeftBound = seg[k << 1].minLeftBound; } if (seg[k << 1].maxSum >= seg[k << 1 | 1].maxSum) { seg[k].maxSum = seg[k << 1].maxSum; seg[k].maxSumLeft = seg[k << 1].maxSumLeft; seg[k].maxSumRight = seg[k << 1].maxSumRight; } else { seg[k].maxSum = seg[k << 1 | 1].maxSum; seg[k].maxSumLeft = seg[k << 1 | 1].maxSumLeft; seg[k].maxSumRight = seg[k << 1 | 1].maxSumRight; } if (seg[k].maxSum < seg[k << 1].maxRightValue + seg[k << 1 | 1].maxLeftValue) { seg[k].maxSum = seg[k << 1].maxRightValue + seg[k << 1 | 1].maxLeftValue; seg[k].maxSumLeft = seg[k << 1].maxLeftBound; seg[k].maxSumRight = seg[k << 1 | 1].maxRightBound; } if (seg[k << 1].minSum <= seg[k << 1 | 1].minSum) { seg[k].minSum = seg[k << 1].minSum; seg[k].minSumLeft = seg[k << 1].minSumLeft; seg[k].minSumRight = seg[k << 1].minSumRight; } else { seg[k].minSum = seg[k << 1 | 1].minSum; seg[k].minSumLeft = seg[k << 1 | 1].minSumLeft; seg[k].minSumRight = seg[k << 1 | 1].minSumRight; } if (seg[k].minSum > seg[k << 1].minRightValue + seg[k << 1 | 1].minLeftValue) { seg[k].minSum = seg[k << 1].minRightValue + seg[k << 1 | 1].minLeftValue; seg[k].minSumLeft = seg[k << 1].minLeftBound; seg[k].minSumRight = seg[k << 1 | 1].minRightBound; } } void init(int k, int l, int r) { seg[k].l = l; seg[k].r = r; if (l == r) { seg[k].sum = seg[k].maxLeftValue = seg[k].maxRightValue = seg[k].minLeftValue = seg[k].minRightValue = seg[k].maxSum = seg[k].minSum = a[l]; seg[k].maxLeftBound = seg[k].minLeftBound = l; seg[k].maxRightBound = seg[k].minRightBound = r; seg[k].maxSumLeft = seg[k].maxSumRight = r; seg[k].minSumLeft = seg[k].minSumRight = r; return; } int mid = l + r >> 1; init(k << 1, l, mid); init(k << 1 | 1, mid + 1, r); update(k); } void Up(int k,int pos,int v) { if(seg[k].l==pos&&seg[k].r==pos) { seg[k].sum = seg[k].maxLeftValue = seg[k].maxRightValue = seg[k].minLeftValue = seg[k].minRightValue = seg[k].maxSum = seg[k].minSum = v; return; } int mid=(seg[k].l+seg[k].r)/2; if(pos<=mid)Up(k << 1, pos, v); else Up(k << 1 | 1, pos, v); update(k); } int findMaxRight(int k, int l, int r, int& ll) { if (seg[k].l == l && seg[k].r == r) { ll = seg[k].maxLeftBound; return seg[k].maxRightValue; } int mid = seg[k].l + seg[k].r >> 1; if (l > mid) { return findMaxRight(k << 1 | 1, l, r, ll); } else { int l1, l2; int retRight = findMaxRight(k << 1 | 1, mid + 1, r, l1); int retLeft = findMaxRight(k << 1, l, mid, l2) + seg[k << 1 | 1].sum; if (retRight >= retLeft) { ll = l1; return retRight; } else { ll = l2; return retLeft; } } } int findMaxLeft(int k, int l, int r, int& rr) { if (seg[k].l == l && seg[k].r == r) { rr = seg[k].maxRightBound; return seg[k].maxLeftValue; } int mid = seg[k].l + seg[k].r >> 1; if (r <= mid) { return findMaxLeft(k << 1, l, r, rr); } else { int r1, r2; int retLeft = findMaxLeft(k << 1, l, mid, r1); int retRight = seg[k << 1].sum + findMaxLeft(k << 1 | 1, mid + 1, r, r2); if (retLeft >= retRight) { rr = r1; return retLeft; } else { rr = r2; return retRight; } } } int findMax(int k, int l, int r, int& ll, int& rr) { if (seg[k].l == l && seg[k].r == r) { ll = seg[k].maxSumLeft; rr = seg[k].maxSumRight; return seg[k].maxSum; } int mid = seg[k].l + seg[k].r >> 1; if (r <= mid) { return findMax(k << 1, l, r, ll, rr); } else if (l > mid) { return findMax(k << 1 | 1, l, r, ll, rr); } else { int l1, r1, l2, r2, l3, r3, ret; int retLeft = findMax(k << 1, l, mid, l1, r1); int retRight = findMax(k << 1 | 1, mid + 1, r, l2, r2); int retMiddle = findMaxRight(k << 1, l, mid, l3) + findMaxLeft(k << 1 | 1, mid + 1, r, r3); if (retLeft >= retRight) { ll = l1; rr = r1; ret = retLeft; } else { ll = l2; rr = r2; ret = retRight; } if (ret < retMiddle) { ll = l3; rr = r3; ret = retMiddle; } return ret; } } int findMinRight(int k, int l, int r, int& ll) { if (seg[k].l == l && seg[k].r == r) { ll = seg[k].minLeftBound; return seg[k].minRightValue; } int mid = seg[k].l + seg[k].r >> 1; if (l > mid) { return findMinRight(k << 1 | 1, l, r, ll); } else { int l1, l2; int retRight = findMinRight(k << 1 | 1, mid + 1, r, l1); int retLeft = findMinRight(k << 1, l, mid, l2) + seg[k << 1 | 1].sum; if (retRight <= retLeft) { ll = l1; return retRight; } else { ll = l2; return retLeft; } } } int findMinLeft(int k, int l, int r, int& rr) { if (seg[k].l == l && seg[k].r == r) { rr = seg[k].minRightBound; return seg[k].minLeftValue; } int mid = seg[k].l + seg[k].r >> 1; if (r <= mid) { return findMinLeft(k << 1, l, r, rr); } else { int r1, r2; int retLeft = findMinLeft(k << 1, l, mid, r1); int retRight = seg[k << 1].sum + findMinLeft(k << 1 | 1, mid + 1, r, r2); if (retLeft <= retRight) { rr = r1; return retLeft; } else { rr = r2; return retRight; } } } int findMin(int k, int l, int r, int& ll, int& rr) { if (seg[k].l == l && seg[k].r == r) { ll = seg[k].minSumLeft; rr = seg[k].minSumRight; return seg[k].minSum; } int mid = seg[k].l + seg[k].r >> 1; if (r <= mid) { return findMin(k << 1, l, r, ll, rr); } else if (l > mid) { return findMin(k << 1 | 1, l, r, ll, rr); } else { int l1, r1, l2, r2, l3, r3, ret; int retLeft = findMin(k << 1, l, mid, l1, r1); int retRight = findMin(k << 1 | 1, mid + 1, r, l2, r2); int retMiddle = findMinRight(k << 1, l, mid, l3) + findMinLeft(k << 1 | 1, mid + 1, r, r3); if (retLeft <= retRight) { ll = l1; rr = r1; ret = retLeft; } else { ll = l2; rr = r2; ret = retRight; } if (ret > retMiddle) { ll = l3; rr = r3; ret = retMiddle; } return ret; } } /** * heap */ struct Node { bool flag; int v, l, r, ll, rr; Node() { } Node(bool flag, int v, int l, int r, int ll, int rr) : flag(flag), v(v), l(l), r(r), ll(ll), rr(rr) { } } h[MAX]; int K; void sink(int k) { while ((k << 1) <= K) { int maxv = max(h[k].v, h[k << 1].v); if ((k << 1 | 1) <= K) { maxv = max(maxv, h[k << 1 | 1].v); } if (maxv == h[k].v) break; else if (maxv == h[k << 1].v) { swap(h[k], h[k << 1]); k = k << 1; } else { swap(h[k], h[k << 1 | 1]); k = k << 1 | 1; } } } void flow(int k) { while (k > 1) { int p = k >> 1; if (h[p].v < h[k].v) { swap(h[p], h[k]); k >>= 1; } else { break; } } } Node getMax() { swap(h[1], h[K]); K--; sink(1); return h[K + 1]; } void add(const Node& node) { h[++K] = node; flow(K); } int main() { int n, m, Q, t; int l, r, L, R; int ret; while (~scanf("%d", &n) ) { for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } init(1, 0, n - 1); scanf("%d",&Q); while(Q--) { int op; scanf("%d",&op); if(op==0) { scanf("%d%d",&l,&r);l--; Up(1,l,r); } else { scanf("%d%d%d",&L,&R,&m);L--;R--; K = 0; ret = 0; t = findMax(1, L, R, l, r); add( Node(true, t, L, R, l, r)); while (m--) { Node u = getMax(); if (u.v <= 0) { break; } ret += u.v; if (!u.flag) { if (u.l != u.ll) { t = findMin(1, u.l, u.ll - 1, l, r); add(Node(false, -t, u.l, u.ll - 1, l, r)); } if (u.r != u.rr) { t = findMin(1, u.rr + 1, u.r, l, r); add(Node(false, -t, u.rr + 1, u.r, l, r)); } t = findMax(1, u.ll, u.rr, l, r); add(Node(true, t, u.ll, u.rr, l, r)); } else { if (u.l != u.ll) { t = findMax(1, u.l, u.ll - 1, l, r); add(Node(true, t, u.l, u.ll - 1, l, r)); } if (u.r != u.rr) { t = findMax(1, u.rr + 1, u.r, l, r); add(Node(true, t, u.rr + 1, u.r, l, r)); } t = findMin(1, u.ll, u.rr, l, r); add(Node(false, -t, u.ll, u.rr, l, r)); } } printf("%d ", ret); } } } return 0; }
280
E
Sequence Transformation
You've got a non-decreasing sequence $x_{1}, x_{2}, ..., x_{n}$ $(1 ≤ x_{1} ≤ x_{2} ≤ ... ≤ x_{n} ≤ q)$. You've also got two integers $a$ and $b$ $(a ≤ b; a·(n - 1) < q)$. Your task is to transform sequence $x_{1}, x_{2}, ..., x_{n}$ into some sequence $y_{1}, y_{2}, ..., y_{n}$ $(1 ≤ y_{i} ≤ q; a ≤ y_{i + 1} - y_{i} ≤ b)$. The transformation price is the following sum: $\sum_{i=1}^{n}(y_{i}-x_{i})^{2}$. Your task is to choose such sequence $y$ that minimizes the described transformation price.
Let $dp[i][j]$=(the minimum transformation price to the moment if $y_{1}... y_{i}$ have been determined and $y_{i} = j$). It's easy to find that: $dp[1][p] = (p - x_{1})^{2}$ $f[i][p] = min(dp[i - 1][q] | p - b \le q \le p - a)$ $dp[i][p] = (p - x_{i})^{2} + f[i][p]$ Solutions using this idea straight can't pass because it needs very huge amount of memory and time(in fact it's infinite). So we should consider the problem more accurately. Here comes the magic: let $dp[i]$ be a function for $p$. First of all, we'll use the monotonicity of its derivative $dp[i]'$ and mathematical induction to prove that $dp[i]$ is a strictly unimodal function. More strongly, we can prove $dp[i]'$ is a strictly increasing function. $dp[1]'(p) = 2(p - x[1])$. Obviously so it is. If we have proved that $dp[i]'$ is a strictly increasing function, and $min dp[i] = dp[i](k)$. In addition, $dp[i]'(k) = 0$. For $f[i + 1]$ at this moment: $\begin{array}{c}{{f[i+1](p)=\left\{d p[i](p-a),\;\;p<k+a}}\\ {{\displaystyle k p[i](p-b),\;\;p>k+a\le p\le k+b}}\\ {{f[i+1]^{\prime}(p-a),\;\;\;p>k+b}}\\ {{f[j-a+b}}\end{array}\right.$Notice that for the derivative, actually what we do is to cut $dp[i]'$ at the place $p = k$, and then the left part ($p \le k$) moves to the right $a$ units while the right part ($p \ge k$) moves to the right $b$ units. After this operation, the gap ($k + a... k + b$) is filled by 0 so that it's still a continuous function. We can find $f[i + 1]'$ is also a increasing function but not strictly. Then $dp[i + 1]'(p) = 2(p - x_{i + 1}) + f[i + 1]'(p)$, now it's absolutely a strictly increasing function. Since we have proved any $dp[i]$ is a strictly unimodal function, we can push $x_{i}$ one by one and calculate the function $dp[i]$ immediately. Let's focus on the operation to $dp[i]'$: Step 1. Determine $k$ for $dp[i]'(k) = 0$. Step 2. Cutting, translation, and filling 0. Step 3. Add a linear function $2(p - x_{i})$. Because of step 2, the derivative is in reality a piecewise function, and any part of this function is a linear function. Besides, there are at most $O(n)$ parts. Finally, We can use a simple array to hold all the endpoints. Since we should maintain at most $O(n)$ endpoints for $n$ times, the time complexity is $O(n^{2})$.
[ "brute force", "data structures", "dp", "implementation", "math" ]
3,000
null
281
A
Word Capitalization
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
As the first problem in the problemset, it intended to be simple so that any one could solve it. Just implement what the problem said under your favorite language.
[ "implementation", "strings" ]
800
null
281
B
Nearest Fraction
You are given three positive integers $x, y, n$. Your task is to find the nearest fraction to fraction $\scriptstyle{\frac{\pi}{y}}$ whose denominator is no more than $n$. Formally, you should find such pair of integers $a, b$ $(1 ≤ b ≤ n; 0 ≤ a)$ that the value $\left|{\frac{x}{y}}-{\frac{a}{b}}\right|$ is as minimal as possible. If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.
This problem can be solved by a straight forward method since we are at Div II, simply enumerate all possible denominator, and calculate the nearest fraction for each denominator. As you would expect, we can do better. Actually this is the limit_denominator() method implemented by the Python fractions module. Since it is written in Python and you can just look at the source code to nd the truth behind it if you are interested. Here Id like to quote the top comment of the snippet: Algorithm notes: For any real number x, define a *best upper approximation* to x to be a rational number p/q such that: (1) p/q >= x, and (2) if p/q > r/s >= x then s > q, for any rational r/s. Define *best lower approximation* similarly. Then it can be proved that a rational number is a best upper or lower approximation to x if, and only if, it is a convergent or semiconvergent of the (unique shortest) continued fraction associated to x. To find a best rational approximation with denominator <= M, we find the best upper and lower approximations with denominator <= M and take whichever of these is closer to x. In the event of a tie, the bound with smaller denominator is chosen. If both denominators are equal (which can happen only when max_denominator == 1 and self is midway between two integers) the lower bound---i.e., the floor of self, is taken.
[ "brute force", "implementation", "two pointers" ]
1,700
null
282
A
Bit++
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called $x$. Also, there are two operations: - Operation ++ increases the value of variable $x$ by 1. - Operation -- decreases the value of variable $x$ by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable $x$. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains. A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains. You're given a programme in language Bit++. The initial value of $x$ is $0$. Execute the programme and find its final value (the value of the variable when this programme is executed).
Just use a simple loop. (Take a look at the Python code)
[ "implementation" ]
800
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <cmath> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <cstdlib> #include <cstring> #include <map> #include <queue> #include <set> #include <queue> #include <stack> #include <deque> #include <assert.h> #include <ctime> #include <bitset> #include <numeric> #include <complex> #include <valarray> using namespace std; #define FOREACH(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define FOR(i, a, n) for (register int i = (a); i < (int)(n); ++i) #define FORE(i, a, n) for (i = (a); i < (int)(n); ++i) #define Size(n) ((int)(n).size()) #define all(n) (n).begin(), (n).end() #define ll long long #define pb push_back #define error(x) cout << #x << " = " << (x) << endl; #define ull unsigned long long #define pii pair<int, int> //#define pii pair<ll, ll> #define pll pair<ll, ll> #define pdd pair<double, double> #define point complex<double> #define X real() #define Y imag() //#define X first //#define Y second #define EPS 1e-10 //#define endl " " #define pdd pair<double, double> #define mk make_pair int main() { int n; cin >> n; vector<string> v(n); FOR(i, 0, n) cin >> v[i]; cout << count(all(v), "++X")+count(all(v), "X++")-count(all(v), "--X")-count(all(v), "X--") << endl; return 0; }
282
B
Painting Eggs
The Bitlandians are quite weird people. They have very peculiar customs. As is customary, Uncle J. wants to have $n$ eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work. The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got $n$ eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals $1000$. Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than $500$. Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.
This one can be solved by a greedy algorithm. Start from the 1st egg and each time give the egg to A if and only if giving it to A doesn't make the difference > 500, otherwise give it to G. To prove the correctness, one can use induction. The base case is trivial. Suppose that we've assigned the first $n - 1$ eggs such that the total money given to A is $S_{a}$ and total money given to G is $S_{g}$. We can assume $S_{a} \ge S_{g}$. Now we must either add $g_{n}$ to $S_{g}$ or add $a_{n}$ to $S_{a}$. If we can't add $g_{n}$ to $S_{g}$, then $S_{g} + g_{n} > S_{a} + 500$, so $- 500 > S_{a} - S_{g} - g_{n}$, adding $1000$ to both sides gives us the inequality $500 > S_{a} + (1000 - g_{n}) - S_{g}$ which is exactly what we need to make sure that we can add $a_{n} = 1000 - g_{n}$ to $S_{a}$.
[ "greedy", "math" ]
1,500
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <cmath> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <cstdlib> #include <cstring> #include <map> #include <queue> #include <set> #include <queue> #include <stack> #include <deque> #include <assert.h> #include <ctime> #include <bitset> #include <numeric> #include <complex> #include <valarray> using namespace std; #define FOREACH(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define FOR(i, a, n) for (register int i = (a); i < (int)(n); ++i) #define FORE(i, a, n) for (i = (a); i < (int)(n); ++i) #define Size(n) ((int)(n).size()) #define all(n) (n).begin(), (n).end() #define ll long long #define pb push_back #define error(x) cout << #x << " = " << (x) << endl; #define ull unsigned long long #define pii pair<int, int> //#define pii pair<ll, ll> #define pll pair<ll, ll> #define pdd pair<double, double> #define point complex<double> #define X real() #define Y imag() //#define X first //#define Y second #define EPS 1e-10 //#define endl " " #define pdd pair<double, double> #define mk make_pair int main() { int n; cin >> n; int tot = 0; FOR(i, 0, n) { int a, b; cin >> a >> b; if (tot+a <= 500) { tot += a; cout << "A"; } else { tot -= b; cout << "G"; } } cout << endl; return 0; }
282
C
XOR and OR
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string. A Bitlandish string is a string made only of characters "0" and "1". BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string $a$, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as $x$ and the other one as $y$. Then he calculates two values $p$ and $q$: $p = x xor y$, $q = x or y$. Then he replaces one of the two taken characters by $p$ and the other one by $q$. The $xor$ operation means the bitwise excluding OR operation. The $or$ operation is the bitwise OR operation. So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string. You've got two Bitlandish strings $a$ and $b$. Your task is to check if it is possible for BitHaval to transform string $a$ to string $b$ in several (possibly zero) described operations.
First of all, check the length of the two strings to be equal. Then with a little try and guess, you can find out that the zero string (00...0) can't be converted to anything else and nothing else can be converted to zero. All other conversions are possible.
[ "constructive algorithms", "implementation", "math" ]
1,500
#include <iostream> #include <string> using namespace std; int main(){ string a,b; cin>>a>>b; bool ans_a = false; bool ans_b = false; if(a.size()==b.size()){ for(int i=0;i<a.size();i++){ if(a[i]=='1'){ ans_a=true; } if(b[i]=='1'){ ans_b=true; } } } if(a.size()==1){ ans_a=false; } if(a==b){ ans_a=true; ans_b=true; } if(ans_a and ans_b) cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }
282
D
Yet Another Number Game
Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games! Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games. BitLGM and BitAryo are playing yet another of their crazy-looking genius-needed Bitlandish games. They've got a sequence of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. The players make moves in turns. BitLGM moves first. Each player can and must do one of the two following actions in his turn: - Take one of the integers (we'll denote it as $a_{i}$). Choose integer $x$ $(1 ≤ x ≤ a_{i})$. And then decrease $a_{i}$ by $x$, that is, apply assignment: $a_{i} = a_{i} - x$. - Choose integer $x$ $(1\leq x\leq\operatorname*{min}_{i=1}a_{i})$. And then decrease all $a_{i}$ by $x$, that is, apply assignment: $a_{i} = a_{i} - x$, for all $i$. The player who cannot make a move loses. You're given the initial sequence $a_{1}, a_{2}, ..., a_{n}$. Determine who wins, if both players plays optimally well and if BitLGM and BitAryo start playing the described game in this sequence.
For n=1, everything is clear. If $a_{1} = 0$ then BitAryo wins, otherwise BitLGM is the winner. For n=2: define win[i][j] = (Whether i,j is a Winning position). It's easy to calculate win[i][j] for all i and j, using a loop (Checking all possible moves). This leads us to an O($n^{3}$) solution. For n=3: Everything is similar to NIM, With the same statement of proof as for NIM, i,j,k is a winning position if and only if (i xor j xor k) $ \neq 0$.[Don't forget the parentheses in code :) ] Complexity: O(1) One can also solve this case using DP. We define lose[i][j]= (Least k, such that i,j,k is a losing position) ,lose2[i][j]=(Least k, such that k,k+i,k+i+j is a losing position) and win[i][j][k] just as the case with n=2. As in the codes below, one can calculate all these values in O($n^{3}$). Using the same DP strategy for n=2 and the O(1) algorithm for n=3 and n=1, leads us to a total complexity of O($n^{2}$) which was not necessary in this contest.
[ "dp", "games" ]
2,100
//In the name of God #include <iostream> #include <algorithm> using namespace std; const int MAXN=310; const int MGO=305; bool wins2[MAXN][MAXN]; void calc2() { for(int i=0;i<MGO;++i) for(int j=max(i,1);j<MGO;++j) { for(int I=0;I<i;++I) if(wins2[I][j]==false) {wins2[i][j]=true; break;} for(int J=0;J<j and wins2[i][j]==false;++J) if(wins2[i][J]==false) {wins2[i][j]=true; break;} for(int K=1;K<=min(i,j) and wins2[i][j]==false;++K) if(wins2[i-K][j-K]==false) {wins2[i][j]=true; break;} wins2[j][i]=wins2[i][j]; } } int main() { int n; cin>>n; if(n==1) { int x; cin>>x; if(x==0) cout<<"BitAryo"<<endl; else cout<<"BitLGM"<<endl; } else if(n==2) { int x,y; cin>>x>>y; if(x>y) swap(x,y); calc2(); if(wins2[x][y]) cout<<"BitLGM"<<endl; else cout<<"BitAryo"<<endl; } else { int x,y,z; cin>>x>>y>>z; if((x^y^z)==0) cout<<"BitAryo"<<endl; else cout<<"BitLGM"<<endl; } return 0; }
282
E
Sausage Maximization
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages! In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the $xor$ operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage. But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces). The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero. Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Can be solved using a trie in O(n log (max{$a_{i}$})). Start with a prefix of size n, and decrease the size of prefix in each step. For each new prefix calculate the XOR of elements in that prefix and add the XOR of the newly available suffix (which does not coincide with the new prefix) to the trie, then query the trie for the best possible match for the XOR of the new prefix. (Try to get 1 as the first digit if possible, otherwise put 0, then do the same thing for the second digit and so on). Get a maximum over all answers you've found, and it's all done. [By digit, I mean binary digit]
[ "bitmasks", "data structures", "trees" ]
2,200
//In the name of God #include <iostream> #include <deque> using namespace std; const int MAXN=1e6+1e3; #define num long long num all[MAXN]; struct node { node *child[2]; node() { child[0]=child[1]=NULL; } }; node *root; deque<short> binary(long long x) { deque<short> ans; while(x) { ans.push_front(x%2); x/=2; } while(ans.size()<50) ans.push_front(0); return ans; } void add(long long x) { deque<short> a=binary(x); node *C=root; while(a.size()) { if(C->child[a[0]]==NULL) C->child[a[0]]=new node; C=C->child[a[0]]; a.pop_front(); } } long long query(long long x) { deque<short> a=binary(x); long long ans=0; node *C=root; while(a.size()) { if(C->child[1-a[0]]!=NULL) { C=C->child[1-a[0]]; ans*=2; ans+=1; } else { C=C->child[a[0]]; ans*=2; } a.pop_front(); } return ans; } int main() { root=new node; int n; cin>>n; num xorall=0; for(int i=1;i<=n;++i) { cin>>all[i]; xorall^=all[i]; } num maxgot=0; int ai=0,bi=0; num total=0; add(total); for(int i=1;i<=n;++i) { total^=all[i]; add(total); maxgot=max(maxgot,query(total^xorall)); } cout<<fixed<<maxgot<<endl; return 0; }
283
A
Cows and Sequence
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform $n$ operations. Each operation is one of the following: - Add the integer $x_{i}$ to the first $a_{i}$ elements of the sequence. - Append an integer $k_{i}$ to the end of the sequence. (And hence the size of the sequence increases by 1) - Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!
Consider the problem with only queries 1 and 2. Then the problem is easy in $O(n)$: keep track of the number of terms and the sum, and you can handle each query in O(1). But with query 3 we need to also be able to find the last term of the sequence at any given time. To do this, we keep track of the sequence $d_{i} = a_{i + 1} - a_{i}$ for $i = 1, 2, ..., s - 1,$ and $a_{s},$ where $s$ is the length of the sequence. Notice that query 2 only modifies one value of $d_{i},$ and queries 1 and 3 are easily processed and able to update this information. This gives us an $O(n)$ algorithm. One can also use a fenwick or segment tree to compute the last element, but it's not nearly as nice :).
[ "constructive algorithms", "data structures", "implementation" ]
1,600
null
283
B
Cow Program
Farmer John has just given the cows a program to play with! The program contains two integer variables, $x$ and $y$, and performs the following operations on a sequence $a_{1}, a_{2}, ..., a_{n}$ of positive integers: - Initially, $x = 1$ and $y = 0$. If, after any step, $x ≤ 0$ or $x > n$, the program immediately terminates. - The program increases both $x$ and $y$ by a value equal to $a_{x}$ simultaneously. - The program now increases $y$ by $a_{x}$ while decreasing $x$ by $a_{x}$. - The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on. The cows are not very good at arithmetic though, and they want to see how the program works. Please help them! You are given the sequence $a_{2}, a_{3}, ..., a_{n}$. Suppose for each $i$ $(1 ≤ i ≤ n - 1)$ we run the program on the sequence $i, a_{2}, a_{3}, ..., a_{n}$. For each such run output the final value of $y$ if the program terminates or -1 if it does not terminate.
First, suppose we only have the sequence $a_{2}, a_{3}, \dots a_{n}.$ We note that the current state is only determined by the location and the direction we are facing, so there are only $2 \cdot (n - 1)$ states total. Then, we can use DFS with memorization to find the distance traveled from each state, or $- 1$ if a cycle is formed, in $O(n)$ time. Now, when we add $a_{1}$ into the sequence, we essentially only need to give the distance traveled starting from each state facing left. The only difference is that if we ever land on $a_{1}$ again, there must be a cycle, as we started on $a_{1}$. Using this, we can solve the problem in $O(n)$ time total.
[ "dfs and similar", "dp", "graphs" ]
1,700
null