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
⌀ |
|---|---|---|---|---|---|---|---|
412
|
B
|
Network Configuration
|
The R1 company wants to hold a web search championship. There were $n$ computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the $i$-th computer it was $a_{i}$ kilobits per second.
There will be $k$ participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.
The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least $k$ of $n$ computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?
|
In this task you should sort array in descending order and print $k$-th element. Due to the weak constraints you could also solve the problem in the following manner. Let's brute $ans$ - the value of answer and calculate how many computers already have Internet's speed not less than $ans$. If there are not less than $k$ such computers then the answer is acceptable. Let's find the maximum among acceptable answers and it will be the sought value.
|
[
"greedy",
"sortings"
] | 900
| null |
412
|
C
|
Pattern
|
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.
In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.
Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given $n$ patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?
|
Let's find the answer symbol-by-symbol. Let's consider $i$-th symbol. If there are two different symbols differ from '?' on $i$-th positions in the given strings then we must place '?' on $i$-th position in the answer. If there are '?' on $i$-th positions in all string then we can write any symbol. Obviously, it is better to write not '?' but any letter, 'x' for example. Lastly we should consider the case when there are only '?' and one the same letter on $i$-th positions. In this case we should find this letter and put it to the answer.
|
[
"implementation",
"strings"
] | 1,200
| null |
412
|
D
|
Giving Awards
|
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.
Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person $x$ to his office for a reward, and then immediately invite person $y$, who has lent some money to person $x$, then they can meet. Of course, in such a situation, the joy of person $x$ from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.
However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.
|
Let's build sought permutation by adding employee one-by-one. Let's we already define the order of the first $k$ employees: $a_{1}, a_{2}, ..., a_{k}$. Let's place $k + 1$-th after $a_{k}$-th. If $a_{k}$-th employee owe money to $k + 1$-th then we will swap their positions (and will get permutation $a_{1}, a_{2}, ..., a_{k - 1}, k + 1, a_{k}$). If $a_{k - 1}$-th employee also owe money to $k + 1$-th then we will also swap their positions and so on. If all first $k$ employees owe money to $k + 1$-th then $k + 1$-th employee will be placed first in permutation. This algorithm has time complexity $O(m)$, where $m$ is the number of the debt relationships.
|
[
"dfs and similar"
] | 2,000
| null |
412
|
E
|
E-mail Addresses
|
One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.
Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.
We assume that valid addresses are only the e-mail addresses which meet the following criteria:
- the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter;
- then must go character '@';
- then must go a non-empty sequence of letters or numbers;
- then must go character '.';
- the address must end with a non-empty sequence of letters.
You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers $l_{1}, l_{1} + 1, l_{1} + 2, ..., r_{1}$ and the other one consisting of the characters of the string with numbers $l_{2}, l_{2} + 1, l_{2} + 2, ..., r_{2}$, are considered distinct if $l_{1} ≠ l_{2}$ or $r_{1} ≠ r_{2}$.
|
Let's consider position $i$ such, that $s_{i} = '@'$. We are going to calculate the number of such substrings that are correct addresses and the symbol '@' in them is $s_{i}$. Let's go to the left from $i$ until we find '@' or '.' - the symbols that aren't allowed to be to the left of '@'. Let's calculate $cnt$ how many letters on the segment we went through. This letters can be the first symbols of the correct addresses. Let's now move to the right of $i$ while considered symbol is letter or digit. If we stopped and the string is over or the following symbol is '@' or '_' then there aren't correct addresses. If the following symbol is '.' then let's go to the right of it while the considered symbols are letters. The correct address can finish in every such position, so we should add $cnt$ to the answer. In the described solution "move" means "brute by cycle for". We can do this because we will go through each symbol not more than 2 times. Total time complexity is $O(n)$.
|
[
"implementation"
] | 1,900
| null |
413
|
A
|
Data Recovery
|
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors.
The testing goes in $n$ steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in R2 is keeping a report record on the work of the processor: he writes down the minimum and the maximum measured temperature in his notebook. His assistant had to write down all temperatures into his notebook, but (for unknown reasons) he recorded only $m$.
The next day, the engineer's assistant filed in a report with all the $m$ temperatures. However, the chief engineer doubts that the assistant wrote down everything correctly (naturally, the chief engineer doesn't doubt his notes). So he asked you to help him. Given numbers $n$, $m$, $min$, $max$ and the list of $m$ temperatures determine whether you can upgrade the set of $m$ temperatures to the set of $n$ temperatures (that is add $n - m$ temperatures), so that the minimum temperature was $min$ and the maximum one was $max$.
|
Count min and max values in given array of length $m$. If the min value is less then given $min$ or the max value is greater the given $max$ the answer is Incorrect. Count value $0 \le need \le 2$, which equals to minimal number of elements which should be added in given array so that the min value will become $min$ and the max value will become $max$. Then answer is Correct if $n - m \ge need$. Otherwise answer is Incorrect.
|
[
"implementation"
] | 1,200
| null |
413
|
B
|
Spyke Chatting
|
The R2 company has $n$ employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.
R2 has $m$ Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the $k$-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.
The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.
|
Process all queries and count some values: for each employee we will count number of messages which weer sent by this employee and for each chat we will count number of messages which were sent to this chat. Then the answer for some employee equals to sum of messages sent to all chats in which he participates minus all messages sent by him to some chats.
|
[
"implementation"
] | 1,300
| null |
413
|
C
|
Jeopardy!
|
'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2.
The finals will have $n$ questions, $m$ of them are auction questions and $n - m$ of them are regular questions. Each question has a price. The price of the $i$-th question is $a_{i}$ points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.
The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.
All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.
|
Firstly choose all not auction questions and answer on them. So we have only auctions. Sort them in non-decreasing order. Consider each size of suffix of auctions and answer them on their initial price and try to answer other questions by multiplying by 2. It could be explained in this way: less than the cost value, the less you need to multiply your balance by 2. Also more than the cost value more profitable to take it for initial value.
|
[
"greedy",
"math"
] | 1,400
| null |
413
|
D
|
2048
|
The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game — $2^{k}$ on a stripe.
Imagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty or contain some number.
Initially, all squares are empty. Then at infinity one of the unit squares number 2 or 4 appears. Then the player presses a button once, and the appeared number begins to move towards the beginning of the stripe. Let's assume that some number $x$ moves to the beginning of the stripe, then it will stop if:
- it either gets in the first square of the stripe;
- or it is in the square that is preceded by a square with number $y$ $(y ≠ x)$. But if number $x$ at some point of time gets to the square with the same number then both numbers add to each other and result in $2x$. The new number $2x$ continues moving to the beginning of the stripe by the same rules.
After the final stop of the number moving process, the infinity gets a new number 2 or 4 and the process repeats. Read the notes to the test samples to better understand the moving strategy.
I guess you've understood that the game progress fully depends on the order in which numbers 2 and 4 appear. Let's look at some sequence of numbers 2 and 4 in the game. We assume that the sequence is winning if it results in at least one square getting the number greater or equal than $2^{k}$.
The goal of the game is to make up a winning sequence of $n$ numbers. But not everything is so simple, some numbers in the sequence are identified beforehand. You are given a sequence consisting of numbers 0, 2, 4. Count how many ways there are to replace each 0 of the sequence with 2 or 4 to get a winning sequence.
|
Consider some state in your game. Note that, we should maintain the maximum suffix if values in descending order. Also, we will maintain only first $k - 1$ powers of two and keep in mind if have already $k$-th power of two or greater. In fact in violation of this order we can not use these numbers because values could only increase. So, we will count dynamic $dp[i][mask][j]$, where $i$ - size of considered elements, $mask$ - mask of first $k - 1$ powers of two in descending order, $j$ - do we have already the $k$-th power of two or greater (0 or 1). There are two possible transitions by 2 or 4. If the current element equals to 0 make both transitions.
|
[
"bitmasks",
"dp"
] | 2,000
| null |
413
|
E
|
Maze 2D
|
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a $2 × n$ maze.
Imagine a maze that looks like a $2 × n$ rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move from an empty cell of the maze to any side-adjacent empty cell. The shortest path problem is formulated as follows. Given two free maze cells, you need to determine the minimum time required to go from one cell to the other.
Unfortunately, the developed algorithm works well for only one request for finding the shortest path, in practice such requests occur quite often. You, as the chief R2 programmer, are commissioned to optimize the algorithm to find the shortest path. Write a program that will effectively respond to multiple requests to find the shortest path in a $2 × n$ maze.
|
We will consider queries one by one. Firstly check if the one cell of the query is reachable from the second. Find all connected components. If the cells are in different connected components, the answer is -1. Otherwise assume that both cells are situated in columns with exactly one obstacle. To find the answer for such cells we should count the length of the path between these columns using array of partial sums. To count this array consider all columns from left to right and store the last type of column with exactly one obstacle (down obstacle or up obstacle). If in column $j$ the type changes set in the cell $j$ of the array value 1, otherwise set value 0. In this case of query the length of the path between cells equals to sum of absolute differences between column indexes and counted partial sum between these columns. If the column with the left cell has no obstacles find the nearest column with exactly one obstacle to the right. If the column with the right cell has no obstacles find the nearest column with exactly one obstacle to the left. So we get the situation considered above. Be careful if there is no columns with exactly one obstacle between given cells.
|
[
"data structures",
"divide and conquer"
] | 2,200
| null |
414
|
A
|
Mashmokh and Numbers
|
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of $n$ distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers $x$ and $y$ from the board, he gets $gcd(x, y)$ points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly $k$ points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$ such that his boss will score exactly $k$ points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most $10^{9}$.
|
In each turn Bimokh will at least get one point so the result is at lease $\frac{n t}{2}$. So if $k\ll{\frac{n}{2}}$ the answer is -1. Let's denote $x=k-\lfloor{\frac{n-2}{2}}\rfloor$. Then you could output $x$ and $2x$ as the first two integers in the sequence then output $\lfloor{\frac{n-2}{2}}\rfloor$ consecutive integers and also one random integer(distinct from the others) if $n$ is odd. Based on the following fact, Bimokh's point will equal to $x+\lfloor{\frac{n-2}{2}}\rfloor$ which is equal to $k$. $\forall a\geq1:g c d(a,a+1)=1$. Also you must consider some corner cases such as when $n = 1$.
|
[
"constructive algorithms",
"number theory"
] | 1,500
| null |
414
|
B
|
Mashmokh and ACM
|
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.
A sequence of $l$ integers $b_{1}, b_{2}, ..., b_{l}$ $(1 ≤ b_{1} ≤ b_{2} ≤ ... ≤ b_{l} ≤ n)$ is called good if each number divides (without a remainder) by the next number in the sequence. More formally $b_{i}\mid b_{i+1}$ for all $i$ $(1 ≤ i ≤ l - 1)$.
Given $n$ and $k$ find the number of good sequences of length $k$. As the answer can be rather large print it modulo $1000000007$ $(10^{9} + 7)$.
|
Lets define $dp[i][j]$ as number of good sequences of length $i$ that ends in $j$. Let's denote divisors of $j$ by $x_{1}, x_{2}, ..., x_{l}$. Then $d p[i][j]=\sum_{r=1}^{l}d p[i-1][x_{r}]$ This yields $O(nk sqrt(n))$ solution which is not fast enough. But one could use the fact that the following loops run in $O(n log(n))$ in order to achieve $O(nk log(n))$ which is fast enough to pass the tests. for (i = 1; i <= n; i++) //loop from 1 to n for (int j = i; j <= n; j += i) //iterating through all multiples of i that are at most n
|
[
"combinatorics",
"dp",
"number theory"
] | 1,400
| null |
414
|
C
|
Mashmokh and Reverse Operation
|
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.
You have an array $a$ of length $2^{n}$ and $m$ queries on it. The $i$-th query is described by an integer $q_{i}$. In order to perform the $i$-th query you must:
- split the array into $2^{n - qi}$ parts, where each part is a subarray consisting of $2^{qi}$ numbers; the $j$-th subarray $(1 ≤ j ≤ 2^{n - qi})$ should contain the elements $a[(j - 1)·2^{qi} + 1], a[(j - 1)·2^{qi} + 2], ..., a[(j - 1)·2^{qi} + 2^{qi}]$;
- reverse each of the subarrays;
- join them into a single array in the same order (this array becomes new array $a$);
- output the number of inversions in the new $a$.
Given initial array $a$ and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
|
Build a complete binary tree with height $n$. So its $i$-th leaf corresponds to $i$-th element of the initial array. For each vertex $v$ lets define its subarray as the subarray containing the elements that have a leaf corresponding to them in subtree rooted at $v$. For each non-leaf vertex $v$, suppose its left child's subarray contains elements $[a..b]$ of the array and its right child contains elements $[b + 1..c]$ of the array. We'll calculate two numbers for this vertex. number of pairs $(i, j)(a \le i \le b \le j \le c)$ that $a_{i} > b_{j}$ and number of pairs $(i, j)(a \le i \le b \le j \le c)$ that $a_{i} < b_{j}$. We'll call the first calculated number, normal number and the other one reverse number. Calculating these numbers can be done using merge-sort algorithm in $O(n * 2^{n})$. We'll Initially write normal number for each vertex on it. We'll define a vertex's type as type of the number that is written on them. Let's define height of a vertex $v$ equal to its distnace to the nearest leaf. Also let's define switching a vertex as switching the number written on it with the other type number(if normal number is written on it change it to reverse number and vise-versa). Initially sum of writed numbers is equal to number of inversions in the initial array. Now when query $h$ is given, by switching all vertices with height at most $h$, the sum of writed numbers will become equal to the number of inversions in the new array. The only question is how to perform such query fast? One can notice that in a height $h$, always all of the vertices has the same type. So we can calculate two numbers for each height $h$. The sum of normal numbers of vertices with height $h$ and the sum of their reverse numbers. Then instead of switching vertices in a height one by one each time, one can just switch the number for that height. The sum of numbers of heights after each query will be the answer for that query. since there are $n$ height each query can be performed in $O(n)$ so the total running time will be $O(nq + n * 2^{n})$.
|
[
"combinatorics",
"divide and conquer"
] | 2,100
| null |
414
|
D
|
Mashmokh and Water Tanks
|
Mashmokh is playing a new game. In the beginning he has $k$ liters of water and $p$ coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of $m$ vertices. Each vertex of the tree contains a water tank that is empty in the beginning.
The game begins with the fact that Mashmokh chooses some (no more than $k$) of these tanks (except the root) and pours into each of them exactly $1$ liter of water. Then the following process is performed until there is no water remained in tanks.
- The process consists of several steps.
- At the beginning of each step Mashmokh opens doors of all tanks. Then Mashmokh closes doors of some tanks (he is not allowed to close door of tank in the root) for the duration of this move. Let's denote the number of liters in some tank with closed door as $w$, Mashmokh pays $w$ coins for the closing of that tank during this move.
- Let's denote by $x_{1}, x_{2}, ..., x_{m}$ as the list of vertices of the tree sorted (nondecreasing) by their depth. The vertices from this list should be considered one by one in the order. Firstly vertex $x_{1}$ (which is the root itself) is emptied. Then for each vertex $x_{i}$ $(i > 1)$, if its door is closed then skip the vertex else move all the water from the tank of vertex $x_{i}$ to the tank of its father (even if the tank of the father is closed).
Suppose $l$ moves were made until the tree became empty. Let's denote the amount of water inside the tank of the root after the $i$-th move by $w_{i}$ then Mashmokh will win $max(w_{1}, w_{2}, ..., w_{l})$ dollars. Mashmokh wanted to know what is the maximum amount of dollars he can win by playing the above game. He asked you to find this value for him.
|
Let's suppose instead of a tank there is a pile at each vertex and instead of water the game is played on tiles. Let's denote distance of each vertex $q$ from the root by $depth(q)$. Also Let's label each tile with number of the vertex it was initially put on. Suppose initially there was a tile at each of vertices $v$ and $u$ and after some move tile $u$ and $v$ are in the same vertex's pile. Then one can prove that there were exactly $|depth(v) - depth(u)|$ moves at which vertex containing the tile at vertex with less depth was closed and the vertex containing the other tile wasn't. Suppose after $i$-th move, there was $x_{i}$ tiles inside the root's pile and $x_{j}$ is the maximum among these numbers. Suppose tiles $a_{1}, a_{2}, ...a_{xj}$ were on the root after $j$-th move. Then the other tiles that we put inside the tree at the beginning have no effect in the final result. Then we can suppose that only these tiles were initially put on tree. So we can assume that all tiles we place at the beginning will reach to the root together. Suppose $h_{i}$ of these tiles were put at a vertex with depth $i$ and $d_{1}$ is the maximum depth that there is at least a tile in that depth. So as to these tiles reach to the root together we must pay $\sum_{i=1}^{d_{1}}\bigl((d_{1}-i)*h_{i}\bigr)$. Then we want to minimize the number of needed coins so at the beginning there must not be two consecutive depth $i$ and $i + 1$ that $i + 1 \le d$ and there is a tile at depth $i$ and an empty vertex at depth $i + 1$. In other words if we denote the minimum depth that initially there is a tile inside it as $d_{0}$ then there must be a tile at each vertex with depth more than $d_{0}$ and less than or equal to $d_{1}$. Let's iterate over $d_{1}$. Then for each $d_{1}$ we can calculate $d_{2}$, the minimum depth that we can pay the needed price if we put a tile at each vertex with depth at least $d_{2}$ and at most $d_{1}$. Let's denote this needed price as $p_{0}$. Then we can also put $\frac{p\!-\!p_{0}}{d_{1}\!-\!d_{2}\!+\!1}$ at depth $d_{2} - 1$. So we can calculate maximum number of tiles that we can put on the tree so that they all reach to root together for a fixed $d_{1}$. So the maximum of these numbers for all possible $d_{1}$ will be the answer. Since by increasing $d_{1}$, $d_{2}$ won't decrease one can use two-pointers to update $d_{2}$ while iterating over $d_{1}$. Let's denote number of the vertices with depth $i$ as $cnt_{i}$. Then we can save and update the following values. $s=\sum_{i=d_{2}}^{d_{1}}c n t_{i}$ $t=\sum_{i=d_{2}}^{d_{1}}(i\ast c n t_{i})$ Then the needed price is equal to $(d_{1} * s) - t$. So as long as $(d_{1} * s) - t > p$ we must increase $d_{2}$. This yields an $O(n)$ solution.
|
[
"binary search",
"data structures",
"greedy",
"trees",
"two pointers"
] | 2,300
| null |
414
|
E
|
Mashmokh's Designed Problem
|
After a lot of trying, Mashmokh designed a problem and it's your job to solve it.
You have a tree $T$ with $n$ vertices. Each vertex has a unique index from 1 to $n$. The root of $T$ has index $1$. For each vertex of this tree $v$, you are given a list of its children in a specific order. You must perform three types of query on this tree:
- find distance (the number of edges in the shortest path) between $u$ and $v$;
- given $v$ and $h$, disconnect $v$ from its father and connect it to its $h$-th ancestor; more formally, let's denote the path from $v$ to the root by $x_{1}, x_{2}, ..., x_{l} (h < l)$, so that $x_{1} = v$ and $x_{l}$ is root; disconnect $v$ from its father ($x_{2}$) and connect it to $x_{h + 1}$; vertex $v$ must be added to the end of the child-list of vertex $x_{h + 1}$;
- in the vertex sequence produced by calling function dfs(root) find the latest vertex that has distance $k$ from the root.
The pseudo-code of function dfs(v):
\begin{verbatim}
// ls[v]: list of children of vertex v
// its i-th element is ls[v][i]
// its size is size(ls[v])
sequence result = empty sequence;
void dfs(vertex now)
{
add now to end of result;
for(int i = 1; i <= size(ls[v]); i = i + 1) //loop from i = 1 to i = size(ls[v])
dfs(ls[v][i]);
}
\end{verbatim}
|
Let's define the dfs-order of a tree as the sequence created by calling function dfs(root). We'll build another sequence from a dfs-order by replacing each vertex in dfs-order by '+1' and inserting a '-1' after the last vertex of its subtree. Note that all vertices of a particular subtree are a continuous part of dfs-order of that tree. Also note that for each vertex $v$ if the +1 corresponding to it is the $i$-th element of sequence, then $v$'s distance from root(which we'll denote by height of $v$) is equal to sum of elements $1..i$. Suppose we can perform the following operations on such sequence: For each $i$, find sum of the elements $1..i$. For each $i$ find the biggest $j(j < i)$ so that sum of elements $1..j$ of the sequence equals $p$. Using these two operations we can find LCA of two vertices $v$ and $u$, so since distance of $u$ and $v$ equals to $height(u) + height(v) - 2 * height(LCA(u, v))$ we can answer the second query. Also the third query can be answered using the second operation described above. As for the first query it cuts a continuous part of sequence and insert it in another place. This operation can be done using implicit treap. Also we can use the treap as a segment tree to store the following values for each vertex $v$. Then using these values the operations described above can be done. All of these operation can be done in $O(logn)$. Sum of the elements in its subtree(each vertex in the treap has a value equal to +1 or -1 since it corresponds to an element of the sequence.) Let's write the values of each vertex in the subtree of $v$ in the order they appear in the sequence. Then lets denote sum of the first $i$ numbers we wrote as $ps[i]$ and call elements of ps, prefix sums of the subtree of $v$. Then we store the maximum number amongst the prefix sums. Also we'll store the minimum number amongst prefix sums.
|
[
"data structures"
] | 3,200
| null |
415
|
A
|
Mashmokh and Lights
|
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from $1$ to $n$. There are $n$ buttons in Mashmokh's room indexed from $1$ to $n$ as well. If Mashmokh pushes button with index $i$, then each light with index not less than $i$ that is still turned on turns off.
Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed $m$ distinct buttons $b_{1}, b_{2}, ..., b_{m}$ (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button $b_{i}$ is actually $b_{i}$, not $i$.
Please, help Mashmokh, print these indices.
|
For this problem for each light $j$ you could just iterate over all pressed buttons and find the first button $b_{i}$ that $b_{i} < j$. Then you could output $b_{i}$ and move to next light.
|
[
"implementation"
] | 900
| null |
415
|
B
|
Mashmokh and Tokens
|
Bimokh is Mashmokh's boss. For the following $n$ days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back $w$ tokens then he'll get $\left\lfloor{\frac{w a}{b}}\right\rfloor$ dollars.
Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has $n$ numbers $x_{1}, x_{2}, ..., x_{n}$. Number $x_{i}$ is the number of tokens given to each worker on the $i$-th day. Help him calculate for each of $n$ days the number of tokens he can save.
|
For this problem you can find the number of tokens you can save if you initally have $k$ tokens in $O(1)$. Then you can calculate the answer for all of numbers in $O(n)$. Suppose $\left\lfloor{\frac{w a}{b}}\right\rfloor$ by $p$. then $p * b \le w * a$. then ${\underline{{\{p_{a}^{b}\}}}}\leq w$. Suppose initially we have $k$ tokens. Let $x=\lfloor{\frac{w a}{b}}\rfloor$ then we need to find such maximum $k_{0}$ that $k-k_{0}\geq\lceil{\frac{x.b}{a}}\rceil$. So $k_{0}$ will be equal to $k-\left\lceil{\frac{x b}{a}}\right\rceil$. so we can calculate $k_{0}$ in $O(1)$.
|
[
"binary search",
"greedy",
"implementation",
"math"
] | 1,500
| null |
416
|
A
|
Guess a number!
|
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.
The rules are simple. The host thinks of an integer $y$ and the participants guess it by asking questions to the host. There are four types of acceptable questions:
- Is it true that $y$ is strictly larger than number $x$?
- Is it true that $y$ is strictly smaller than number $x$?
- Is it true that $y$ is larger than or equal to number $x$?
- Is it true that $y$ is smaller than or equal to number $x$?
On each question the host answers truthfully, "yes" or "no".
Given the sequence of questions and answers, find any integer value of $y$ that meets the criteria of all answers. If there isn't such value, print "Impossible".
|
Let's use the usual Div 2 problem A approach - the naive one. We will track the interval which might contain the number we're guessing. With each of the query we update this interval. If at the end the interval is non-empty then we output any number from it, otherwise the result is "Impossible".
|
[
"greedy",
"implementation",
"two pointers"
] | 1,400
|
#include <iostream>
void minimize(int &a, int b) { a = std::min(a, b); }
void maximize(int &a, int b) { a = std::max(a, b); }
using namespace std;
int main() {
int mx = 2 * 1000 * 1000 * 1000;
int mn = -mx;
int n; cin >> n;
while (n --> 0) {
string s; cin >> s;
int x; cin >> x;
string ans; cin >> ans;
if (ans == "N") {
if (s == ">=") s = "<";
else if (s == "<") s = ">=";
else if (s == "<=") s = ">";
else s = "<=";
}
if (s == ">=") maximize(mn, x);
else if (s == ">") maximize(mn, x + 1);
else if (s == "<=") minimize(mx, x);
else minimize(mx, x - 1);
}
if (mn <= mx) cout << mn;
else cout << "Impossible";
}
|
416
|
B
|
Art Union
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of $n$ painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these $n$ colors. Adding the $j$-th color to the $i$-th picture takes the $j$-th painter $t_{ij}$ units of time.
Order is important everywhere, so the painters' work is ordered by the following rules:
- Each picture is first painted by the first painter, then by the second one, and so on. That is, after the $j$-th painter finishes working on the picture, it must go to the $(j + 1)$-th painter (if $j < n$);
- each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;
- each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;
- as soon as the $j$-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
|
All we need is to iterate over all painters and for each painter to iterate over all pictures. In the inner loop we also remember when the painter finished working on the picture to make sure that the next painter will not start working on it earlier.
|
[
"brute force",
"dp",
"implementation"
] | 1,300
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m; cin >> m;
int n; cin >> n;
int paintingTime[m][n];
for (int i = 0 ; i < m ; i++) {
for (int j = 0 ; j < n ; j++) cin >> paintingTime[i][j];
}
vector<int> finishTime(m);
for (int i = 0 ; i < n ; i++) {
int freeAt = 0;
for (int j = 0 ; j < m ; j++) {
int start = max(freeAt, finishTime[j]);
finishTime[j] = start + paintingTime[j][i];
freeAt = finishTime[j];
}
}
for (auto x : finishTime) cout << x << ' ';
}
|
416
|
C
|
Booking System
|
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!
A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.
There are $n$ booking requests received by now. Each request is characterized by two numbers: $c_{i}$ and $p_{i}$ — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.
We know that for each request, all $c_{i}$ people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.
Unfortunately, there only are $k$ tables in the restaurant. For each table, we know $r_{i}$ — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.
Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.
|
Let's solve this one greedy. All we need to notice is that the optimal solution will be to place first the groups with biggest sum which they are ready to pay. For each such group it will be optimal to allocate the smallest matching table. The input limits allow to do a full search when looking for a table.
|
[
"binary search",
"dp",
"greedy",
"implementation"
] | 1,600
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class group {
public:
int id;
int size;
int income;
};
class table {
public:
int id;
int size;
};
bool byIncomeDescending(const group &g1, const group &g2) {
return g1.income > g2.income;
}
bool bySize(const table &t1, const table &t2) {
return t1.size < t2.size;
}
bool canFit(const table &t, const group &g) {
return t.size < g.size;
}
int main() {
int n; cin >> n;
vector<group> groups(n);
for (int i = 0 ; i < n ; i++) {
groups[i].id = i + 1;
cin >> groups[i].size >> groups[i].income;
}
sort(groups.begin(), groups.end(), byIncomeDescending);
int m; cin >> m;
vector<table> tables(m);
for (int i = 0 ; i < m ; i++) {
tables[i].id = i + 1;
cin >> tables[i].size;
}
sort(tables.begin(), tables.end(), bySize);
int sum = 0;
vector<pair<int, int> > ans;
for (int i = 0 ; i < n ; i++) {
auto group = groups[i];
auto tableToGive = lower_bound(tables.begin(), tables.end(), group, canFit);
if (tableToGive == tables.end()) continue;
sum += group.income;
ans.push_back(make_pair(group.id, tableToGive->id));
tables.erase(tableToGive);
}
cout << ans.size() << ' ' << sum << endl;
for (auto p : ans) cout << p.first << ' ' << p.second << endl;
}
|
416
|
D
|
Population Size
|
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence $a_{1}, a_{2}, ..., a_{n}$, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence $(8, 6, 4, 2, 1, 4, 7, 10, 2)$ can be considered as a sequence of three arithmetic progressions $(8, 6, 4, 2)$, $(1, 4, 7, 10)$ and $(2)$, which are written one after another.
Unfortunately, Polycarpus may not have all the data for the $n$ consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of $a_{i}$ may be unknown. Such values are represented by number -1.
For a given sequence $a = (a_{1}, a_{2}, ..., a_{n})$, which consists of positive integers and values -1, find the minimum number of arithmetic progressions Polycarpus needs to get $a$. To get $a$, the progressions need to be written down one after the other. Values -1 may correspond to an arbitrary positive integer and the values $a_{i} > 0$ must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence $c$ is called an arithmetic progression if the difference $c_{i + 1} - c_{i}$ of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
|
One thing to notice for this problem is that if we cover some interval with a progression then it will better (at least no worse) to include as many elements to the right of it as possible. So the solution is to greedy - find the leftmost number not covered by a progression, start a new progression with that number (the interval covered by that progression will be of size 1) and then try to extend this interval to the right as far as possible. Repeat this step until all the numbers are covered. One thing you should pay attention to is which numbers can be covered by one arithmetic progression, for example: If there are no fixed numbers in the interval then we can cover it with one progression. If there is only one non-fixed number in the interval then we can cover this interval with one progression. If there are more than one non-fixed numbers in the interval then we can calculate the parameters of the progression (start value and difference). All non-fixed numbers should match those parameters. Difference should be integer. If the progression is ascending and there are some non-fixed numbers in the beginning then those numbers should match positive numbers in the progression. Same way if the progression is descending then we can include numbers from the right side only while matching progression term is positive.
|
[
"greedy",
"implementation",
"math"
] | 2,400
|
#include <iostream>
#include <vector>
#define FOR(i, a, b) for(int i = a; i < b ; ++i)
#define FORD(i, a, b) for(int i = a; i >= b; --i)
using namespace std;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
int main() {
int n; cin >> n;
auto a = readVector<long long>(n);
int res = 0;
for (int l = 0 ; l < n ; ) {
res++;
int i1 = l;
while (i1 < n && a[i1] == -1) i1++;
if (i1 == n) break; // there are no more fixed elements
int i2 = i1 + 1;
while (i2 < n && a[i2] == -1) i2++;
if (i2 == n) break; // there is only one fixed element
int dist = i2 - i1;
if ((a[i2] - a[i1]) % dist) {
l = i2;
continue;
}
auto step = (a[i2] - a[i1]) / dist;
if (step > 0 && a[i1] - step * (i1 - l) <= 0) {
l = i2;
continue;
}
int r = i2 + 1;
while (r < n) {
auto expectedValue = a[i2] + step * (r - i2);
if (a[r] != -1 && a[r] != expectedValue) break;
if (expectedValue <= 0) break;
r++;
}
l = r;
}
cout << res;
}
|
416
|
E
|
President's Path
|
Good old Berland has $n$ cities and $m$ roads. Each road connects a pair of distinct cities and is bidirectional. Between any pair of cities, there is at most one road. For each road, we know its length.
We also know that the President will soon ride along the Berland roads from city $s$ to city $t$. Naturally, he will choose one of the shortest paths from $s$ to $t$, but nobody can say for sure which path he will choose.
The Minister for Transport is really afraid that the President might get upset by the state of the roads in the country. That is the reason he is planning to repair the roads in the possible President's path.
Making the budget for such an event is not an easy task. For all possible distinct pairs $s, t$ ($s < t$) find the number of roads that lie on at least one shortest path from $s$ to $t$.
|
Let's look at the graph given to us in the example: We need to count the count of the edges on all the shortest paths between each pair of vertices. Let's do something easier first - instead of counting all the edges we will count only those which have the destination vertex on its side. For example here are the edges belonging to shortest paths from 4 to 2 which are connected to vertex 2: Let's denote this number like this: $inEdges_{source, v}$ - number of edges which go into vertex $v$ on some shortest path from $source$ to $v$. In the given example $inEdges_{4, 2} = 3$. Let's also denote the set $S_{source, dest}$ - it is a set of the vertices which belong to at least one shortest path from $source$ to $dest$. For example $S_{4, 2} = {1, 2, 3, 4}$. With these two variables it can be seen that the answer for vertices $source$ and $dest$ will be: $e d g e s_{s,d}=\sum_{v\in S_{s,d}}i n E d g e s_{s,v}$ In other words the answer for vertices $s$ and $d$ will be equal to the sum of $inEdges_{s, v}$ for all vertices $v$, which belong to any shortest path from $s$ to $d$. So the only thing left is to calculate these $S$ and $inEdges$. Both of them can be easily calculated if you have minimum distances between all pairs of vertices. And these distances can be calculated using the Floyd-Warshall. So the full solution is: Calculate minimum distances between all pairs of vertices using Floyd-Warshall algorithm. Count $inEdges$. Simply iterate over all source vertices and all edges. For each edge check whether any of its ends belong to any shortest path from source. Calculate the answer. Let's have three loops to iterate over the vertices - - $source$, $destination$ and $mid$. First two vertices are those for which we're calculating the answer. Third vertex is the vertex which should belong to any shortest path (basically we're checking whether $v$ belongs to $S_{source, dest}$). If $mid$ belongs to any shortest path from $source$ to $dest$ then we add $inEdges_{source, mid}$ to the answer. Each step has a complexity $O(n^{3})$.
|
[
"dp",
"graphs",
"shortest paths"
] | 2,500
|
#include <iostream>
#include <vector>
int IntMaxVal = (int) 1e20;
#define minimize(a, b) { a = min(a, b); }
using namespace std;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
const int MAXN = 500;
vector<int> allVertices; // helper array to iterate all vertices
int allMinDist[MAXN + 1][MAXN + 1];
class cEdge {
public:
int v1;
int v2;
int len;
};
istream& operator >>(istream& is, cEdge &e) { is >> e.v1 >> e.v2 >> e.len; return is; }
void FloydWarshall(vector<cEdge> &edges) {
for (auto v1 : allVertices) for (auto v2 : allVertices) allMinDist[v1][v2] = IntMaxVal;
for (auto v : allVertices) allMinDist[v][v] = 0;
for (auto &edge : edges) {
allMinDist[edge.v1][edge.v2] = allMinDist[edge.v2][edge.v1] = edge.len;
}
for (auto v3 : allVertices) for (auto v1 : allVertices) for (auto v2 : allVertices) {
if (allMinDist[v1][v3] != IntMaxVal && allMinDist[v3][v2] != IntMaxVal) {
minimize(allMinDist[v1][v2], allMinDist[v1][v3] + allMinDist[v3][v2]);
allMinDist[v2][v1] = allMinDist[v1][v2];
}
}
}
int main() {
int n; cin >> n;
int m; cin >> m;
for (int i = 0 ; i < n ; i++) allVertices.push_back(i + 1);
auto edges = readVector<cEdge>(m);
FloydWarshall(edges);
int inEdges[n + 1][n + 1];
for (auto v1 : allVertices) for (auto v2 : allVertices) inEdges[v1][v2] = 0;
for (auto &edge : edges) {
for (auto v : allVertices) {
if (allMinDist[v][edge.v1] + edge.len == allMinDist[v][edge.v2]) inEdges[v][edge.v2]++;
if (allMinDist[v][edge.v2] + edge.len == allMinDist[v][edge.v1]) inEdges[v][edge.v1]++;
}
}
for (auto source : allVertices) {
for (int j = source + 1 ; j <= n ; j++) {
int count = 0;
for (auto mid : allVertices) {
if (allMinDist[source][mid] + allMinDist[mid][j] == allMinDist[source][j]) count += inEdges[source][mid];
}
cout << count << ' ';
}
}
}
|
417
|
A
|
Elimination
|
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds.
The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of $c$ problems, the winners of the round are the first $n$ people in the rating list. Each of the additional elimination rounds consists of $d$ problems. The winner of the additional round is one person. Besides, $k$ winners of the past finals are invited to the finals without elimination.
As a result of all elimination rounds at least $n·m$ people should go to the finals. You need to organize elimination rounds in such a way, that at least $n·m$ people go to the finals, and the total amount of used problems in all rounds is as small as possible.
|
The first thing, that you need to mention, is that if $k \le n \cdot m$, then the answer is equal to 0. After that you need to take at least $n \cdot m - k$ people. There's three possibilities to do that: Also in this problem it is possible to write the solution, which check every possible combinations of the numbers of main and elimination rounds.
|
[
"dp",
"implementation",
"math"
] | 1,500
| null |
417
|
B
|
Crash
|
During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.
Each participant is identified by some unique positive integer $k$, and each sent solution $A$ is characterized by two numbers: $x$ — the number of different solutions that are sent before the first solution identical to $A$, and $k$ — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same $x$.
It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number $x$ $(x > 0)$ of the participant with number $k$, then the testing system has a solution with number $x - 1$ of the same participant stored somewhere before.
During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.
|
Let us create array $a$ with $10^{5}$ elements, which is filled with $- 1$. In the cell $a[k]$ we will contain the maximal number of the submissions of the participant with identifier $k$. We will process submissions in the given order. Let us process submission $x$ $k$. If $a[k] < x - 1$, then the answer is NO, else we will update array $a$: $a[k] = max(a[k], x)$.
|
[
"implementation"
] | 1,400
| null |
417
|
C
|
Football
|
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into $n$ teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly $k$ times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
|
Let's consider this tournir as graph. Each vertex should have out-degree $k$. Then the graph should contain exactly $nk$ edges. But the full-graph contains $\textstyle{\frac{n(n-1)}{2}}$, because of that if $n < 2k + 1$ then the answer is $- 1$, otherwise we will connect the $i$-th vertex with $i + 1, ..., i + k$, taking modulo $n$ if needed.
|
[
"constructive algorithms",
"graphs",
"implementation"
] | 1,400
| null |
417
|
D
|
Cunning Gena
|
A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his $n$ friends that they will solve the problems for him.
The participants are offered $m$ problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the $i$-th friend asks Gena $x_{i}$ rubles for his help \textbf{in solving all the problems} he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least $k_{i}$ monitors, each monitor costs $b$ rubles.
Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer.
|
Let us sort the friends by the number of the monitors in the increasing order. Afterwards we will calculate the dp on the masks: the minimal amount of money Gena should spend to solve some subset of problems, if we take first $n$ friends. Then the answer we should compare with the answer for first $i$ friends plus the number of the monitors, which the $i$-th friend needs. Is is not hard to see, that if we consider the friends in this order consequently, then we can recalc dp like in the knapsack problem. The running time of this algorithm is $O(nlog(n) + n2^{m})$.
|
[
"bitmasks",
"dp",
"greedy",
"sortings"
] | 1,900
| null |
417
|
E
|
Square Table
|
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size $n × m$, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.
Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed $10^{8}$.
|
Let's build array of the length $n$ for each $n$, that the sum of the squares of its elements is the square: We are given two numbers $n$ and $m$. Let array $a$ corresponds to $n$, and array $b$ corresponds to $m$. The we will build the answer array $c$ as follows $c_{ij} = a_{i} \cdot b_{j}$.
|
[
"constructive algorithms",
"math",
"probabilities"
] | 2,400
| null |
418
|
D
|
Big Problems for Organizers
|
The Finals of the "Russian Code Cup" 2214 will be held in $n$ hotels. Two hotels (let's assume that they are the main hotels), will host all sorts of events, and the remaining hotels will accommodate the participants. The hotels are connected by $n - 1$ roads, you can get from any hotel to any other one.
The organizers wonder what is the minimum time all the participants need to get to the main hotels, if each participant goes to the main hotel that is nearest to him and moving between two hotels connected by a road takes one unit of time.
The hosts consider various options for the location of the main hotels. For each option help the organizers to find minimal time.
|
This problem has two solutions. The first one. Let's hang the tree on some vertex. Afterwards, let us calculate for eah vertex it's height and $3$ most distant vertices in its subtree. Also let's calculate arrays for the lowest common ancestors problem. For each vertex $i$ and the power of two $2^{j}$ we have $p[i][j]$, $up[i][j]$ and $down[i][j]$: And the last part of this solution. Let us be given the query $u$ $v$. Firstly, we find $w = LCA(u, v)$. Afterwards, we need to find vertex $hu$, which is situated on the middle of the path between $u$ and $v$. Really, we need to split the tree by this vertex, count the longest path from $u$ in its tree and count the longest path from $v$ in its tree. If we can imagine in the main tree, we can not delete this vertex, but with our precalculated arrays recalc this two values. First solution: 6396376 The second solution. In a few words. Let's find the diameter of the tree. Precalc the answer for each vertices on the prefix. Then on the query we find two distant vertices on this diameter and the path. Obviously, diameter should contain the middle of the path, when we find it, using precalculated results on the prefixes and suffixes we can obtain the answer.
|
[
"data structures",
"graphs",
"trees"
] | 2,800
| null |
418
|
E
|
Tricky Password
|
In order to ensure confidentiality, the access to the "Russian Code Cup" problems is password protected during the problem development process.
To select a password, the jury can generate a special table that contains $n$ columns and the infinite number of rows. To construct a table, the first row is fixed, and all the others are obtained by the following rule:
In the row $i$ at position $p$ there is a number equal to the number of times $a[i - 1][p]$ occurs on the prefix $a[i - 1][1... p]$.
To ensure the required level of confidentiality, the jury must be able to perform the following operations:
- Replace number $a[1][p]$ by $v$ and rebuild the table.
- Find the number $a[x][y]$, which will be the new password.
Doing all these steps manually is very tedious, so the jury asks you to help him. Write a program that responds to the request of the jury.
|
The key theoretical idea of this problem is that the $2$nd row is exactly the same as the $4$th row, $3$rd row is exactly the same as $5$th row and so on. Because of that we need only to answer queries on the first three rows. Let's move on to the practical part. In the first place we will compress coordinates, that any value will not exceed $2 \cdot 10^{5}$. Afterwards, let's split the array into parts of the length $LEN$. On each part we will calculate the following values: $cnt[k]$ - the number of occurences of the number $k$ on this prefix, also $f[k]$ - the total number of the values, which occur exactly $k$ times on this prefix. Array $f$ we will store in the Fenwick data structure. It is not hard to see, that array $cnt$ contains the answer for the queries to the $2$nd row. To get the answer for the queries to the 3$rd$ row we need to calculate $f[cnt[k]... 10^{5}]$. Also it's quite understandable how to recalc this dp. In summary, we will get $O(\frac{n o g(n)}{L E N}+L E N)$ per query. And we take $L E N={\sqrt{n l o g(n)}}$, then we will get $O({\sqrt{n l o g(n)}})$ per query.
|
[
"data structures"
] | 3,100
| null |
420
|
A
|
Start Up
|
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?
The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.
There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.
|
One should firstly recognize that the required string should be palindrome and each character of the string should be symmetric. All the symmetric characters are - $AHIMOTUVWXY$.
|
[
"implementation"
] | 1,000
| null |
420
|
B
|
Online Meeting
|
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.
You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
|
Firstly lets add to the answer all the persons, that didn't appear in the log messages. Then we should consider two cases: 1) If there is a person (with number $i$), that the first log message with him is in form $- i$. We will call such persons X-persons. Consider all X-persons. Pick the one from them that has the last first occurrence in the sequence of messages. This person can be a leader, all others cannot be. Now we should check if the picked person is a leader or not. For that reason we will use the algorithm that is described below. This algorithm works fine only on special sequences of messages. So, we need to add all the X-persons to the beginning of the our list in the order they appear in input (in the resulting sequence the picked person should be the first). 2) There is no X-persons. That case only the first person from the list can be a leader. Others cannot be. Check that person with the algorithm described below. The Algorithm of check: The algorithm is very simple. Just to iterate throughout the sequence of messages and maintain $set$-structure for the persons that are currently on the meeting. If we consider log-on message, add the person to the set, if we consider log-off message, erase the person from the set. Each time we perform an operation with set, we should check: either the set is empty or the leader is in set. The most tricky cases are 33 and 34. Will look at them, the 33-th test: 4 4 + 2 - 1 - 3 - 2 Here the leader can be only 4-th person. Others cannot be. The 34-th test: 3 3 - 2 + 1 + 2 The answer for that test is only the 3-rd participant.
|
[
"implementation"
] | 1,800
| null |
420
|
C
|
Bug in Code
|
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the $n$ coders on the meeting said: 'I know for sure that either $x$ or $y$ did it!'
The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least $p$ of $n$ coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?
Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.
|
Lets construct an undirected graph, the vertices of the graph are the persons, there is an edge between two persons if there are claim of some person about these two persons. Now we can describe the problem on this graph. We need to find the number of such pairs of vertices that at least $p$ edges are adjacent to them. How to count such pairs. Just for each vertex $v$ to calculate the number of vertices $u$ such that $d[v] + d[u] \ge p$, then we should consider all the adjacent vertices correctly. Iterate through all the edges and subtract such the vertices from the answer. Then iterate through adjacent vertices and add only such of them that is needed to be added. Pay attention to multiple edges, they should be considered very carefully.
|
[
"data structures",
"graphs",
"implementation",
"two pointers"
] | 1,900
| null |
420
|
D
|
Cup Trick
|
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of $n$ plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
- each cup contains a mark — a number from $1$ to $n$; all marks on the cups are distinct;
- the magician shuffles the cups in $m$ operations, each operation looks like that: take a cup marked $x_{i}$, sitting at position $y_{i}$ in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
|
The solution consists of two parts. 1) Find the valid permutation. Let's go through the given queries. Suppose the current query tells us that the number $a$ is placed on $b$-th position. If we already met $a$ then we are going to skip this query. Otherwise let's find the position of $a$ in the sought permutation. Suppose we already know that in the sought permutation the number $a_{1}$ is on position $b_{1}$, $a_{2}$ is on position $b_{2}$, $...$, $a_{k}$ is on position $b_{k}$ $(b_{1} < b_{2} < ... < b_{k})$. After every query the number from that query goes to the begging of the permutation, so all $a_{i}$ $(1 \le i \le k)$ are already placed to the left of $a$ before the current query. But some of these $a_{i}$ stood to the left of $a$ in the sought permutation, and the other stood to the right of $a$, but went forward to the begging. Let's find the number of these numbers. In order to do this we should find such position $p$, that is not occupied by any of $a_{i}$ and $p + x = b$, where $x$ is the number of such $b_{i}$ that $b_{i} > p$. We can do it by using the segment tree in the following manner. Let's store in the vertex of segment tree the number of already occupied positions on the correspond subsegment. Suppose we want to find $p$ in the some subtree. Let's find the minimal position in the right subtree $p_{rg}$ and the number of occupied positions $x_{rg}$ there. So if $p_{rg} + x_{rg} \le b$ then we should continue finding $p$ in the right subtree. Otherwise we should decrease $b$ by $x_{rg}$ and try to find $p$ in the left subtree. When we find $p$ we need to check that $p + x = b$. If this equation isn't correct then the answer is $- 1$. 2) Check that the sequence of the operations is correct. Let's consider $i$-th query. Suppose it tells us that $a$ is placed on position $b$. We should check whether it is correct. If we haven't already seen $a$ in queries then this statement is correct because we checked it in the first part of the solution. Otherwise, let's find the such maximal $j < i$ that it is given the position of $a$ in $j$-th query. After $j$-th query $a$ goes to the begging of the permutation and the other numbers can move it to the right. Let's find the number of such different numbers on the queries' segment $[j + 1, i - 1]$. We should get exactly $b - 1$.
|
[
"data structures"
] | 2,200
| null |
420
|
E
|
Playing the ball
|
A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game.
Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance $d$ from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance $2·d$ from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each $d$ units). All coders in the F company are strong, so the ball flies infinitely far away.
The plane has $n$ circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle $x$ times during the move, the player also gets $x$ points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates.
|
Let's claim that we have ray and the infinite number of balls on it in this problem. The $k$-th ball is placed on the distance $k \cdot d$ from the begging of the ray. Let's note that in the answer must be the ball which is placed on the border of some cirlce. The second observation is the following. Let's consider any circle. The number of angles, on which we can rotate our ray so that any ball will be on the border of this cirlce, doesn't exceed $4 * r / d$. Let's call these angles critical. Let's put all critical angles from each circle to the array $B$ and sort. After that let's consider every cirlce one-by-one. When we consider some cirlce we are going to find all critical angles and sort them. So the number of balls, which will be inside of the cirlce, will be the constant if we rotate our ray on every angle between the two neighbour critical angles. Let's find $k$ - the number of these balls. Let's create array $C$, where $C_{i}$ is the answer value if we rotate the ray on the angle $B_{i}$. So after we find $k$ and the positions of neighbour critical angles in $B$ we need to perform add on the segment query in $C$. After we processed all critical angles of all circles the maximum in the $C$ will be the answer.
|
[
"geometry"
] | 2,600
| null |
421
|
A
|
Pasha and Hamsters
|
Pasha has two hamsters: Arthur and Alexander. Pasha put $n$ apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamsters on his own. He is going to give some apples to Arthur and some apples to Alexander. It doesn't matter how many apples each hamster gets but it is important that each hamster gets only the apples he likes. It is possible that somebody doesn't get any apples.
Help Pasha distribute all the apples between the hamsters. Note that Pasha wants to distribute all the apples, not just some of them.
|
For each apple you just need to determine who like it. If Alexander likes apple, then he should eat it, if Artur likes the apple, then he should eat it. If they both like the apply anyone can eat the apple.
|
[
"constructive algorithms",
"implementation"
] | 800
| null |
424
|
A
|
Squats
|
Pasha has many hamsters and he makes them work out. Today, $n$ hamsters ($n$ is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.
For another exercise, Pasha needs exactly $\frac{n t}{2}$ hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?
|
The problem is to find the number of standing hamsters. If it is less than half, we should make the required number of hamsters standing. Otherwise we should make some hamsters sitting.
|
[
"implementation"
] | 900
| null |
424
|
B
|
Megacity
|
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates ($0$; $0$). The city is surrounded with $n$ other locations, the $i$-th one has coordinates ($x_{i}$, $y_{i}$) with the population of $k_{i}$ people. You can widen the city boundaries to a circle of radius $r$. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius $r$, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
|
We can sort all the cities by their distance to the Tomsk city $d_{i}$. After that we are to find the smallest index $t$ for which the total population $p_{0} + p_{1} + ... + p_{t} > = 10^{6}$. In such case the answer is $d_{t}$. We can sort all cities in $O(NlogN)$ and find the value of $t$ in $O(N)$. Limits for $N$ allow $O(N^{2})$ sorting or any other $O(N^{2})$ solution.
|
[
"binary search",
"greedy",
"implementation",
"sortings"
] | 1,200
| null |
424
|
C
|
Magic Formulas
|
People in the Tomskaya region like magic formulas very much. You can see some of them below.
Imagine you are given a sequence of positive integer numbers $p_{1}$, $p_{2}$, ..., $p_{n}$. Lets write down some magic formulas:
\[
q_{i}=p_{i}\oplus(i\;m o d\;1)\oplus(i\;m o d\;2)\oplus\cdot\cdot\cdot\oplus(i\;m o d\;n);
\]
\[
Q=q_{1}\oplus q_{2}\oplus\ldots\oplus q_{n}.
\]
Here, "mod" means the operation of taking the residue after dividing.
The expression $x\oplus y$ means applying the bitwise $xor$ (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 by "^", in Pascal — by "xor".
People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence $p$, calculate the value of $Q$.
|
Consider the following formulas: $\ell_{i}=p_{i}\varpi\left(1\;\;\mathrm{mod}\;{\dot{\imath}}\right)\varpi\left({\dot{2}}\;\;\mathrm{mod}\;{\dot{\imath}}\right)\varpi\cdot\cdot\cdot\varpi\left(\eta\;\;\mathrm{mod}\;{\dot{\imath}}\right)},$ $Q=\mathbf{c}_{1}\oplus\mathbf{c}_{2}\oplus\cdot\cdot\oplus\mathbf{c}_{n}.$ Let $f_{i}=0\oplus1\oplus\ldots\leftrightarrow i$. Lets compute the following function for each $i$ ($0 \le i \le n$). One can do it in $O(n)$ using $f_{i}=f_{i-1}\oplus i$. Lets transform $c_{i}$: $\begin{array}{c}{{c_{i}=p_{i}\oplus((1~~\mathrm{mod}~i)\oplus(2~\mathrm{mod}~i)\oplus\cdot\cdot\cdot\oplus\left((i-1)~~\mathrm{mod}~i\right)\oplus(i~~\mathrm{mod}~i)\oplus(i~~\mathrm{mod}~i)\right)\oplus(i~~i)\oplus(i~~i)\times\times\oplus(n+1)~~\mathrm{mod}~i)\oplus(i~~i)}}\\ {{\left(\sinh i)}}&{{\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\quad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\quad\quad\langle\phi\times\cdot\cdot\cdot\cdot\cdot\cdot\in\quad(n-1)}\oplus(i)}}\end{array}$ Also: $\begin{array}{c}{{f_{i-1}=\left((i+1)\;\;\mathrm{mod}\;i\right)\oplus\left((i+2)\;\;\mathrm{mod}\;i\right)\oplus\cdot\cdot\hat{\Phi}\left((2\cdot i-1)\;\;\mathrm{mod}\;i\right)\oplus\left(2\cdot i.}}\end{array}$ Thus: $c_{i}=p_{i}\oplus f_{i-1}\oplus f_{i-1}\oplus\ldots\oplus f_{i-1}\oplus f_{n}{\mathrm{~mod~}}i$ That means, if $n / i$ is odd, $c_{i}=p_{i}\oplus f_{i-1}\oplus f_{n}{\mathrm{~mod~}}i$, otherwise - $c_{i}=p_{i}\oplus f_{n{\mathrm{~mod}}}\,i$. $c_{i}$ can be computed in $O(1)$, that's why the complexity of the whole solution - $O(n)$.
|
[
"math"
] | 1,600
| null |
424
|
D
|
Biathlon Track
|
Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.
To construct a biathlon track a plot of land was allocated, which is a rectangle divided into $n × m$ identical squares. Each of the squares has two coordinates: the number of the row (from 1 to $n$), where it is located, the number of the column (from 1 to $m$), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.
The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends $t_{p}$ seconds, an ascent takes $t_{u}$ seconds, a descent takes $t_{d}$ seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to $t$ seconds as possible. In other words, the difference between time $t_{s}$ of passing the selected track and $t$ should be minimum.
For a better understanding you can look at the first sample of the input data. In this sample $n = 6, m = 7$, and the administration wants the track covering time to be as close to $t = 48$ seconds as possible, also, $t_{p} = 3$, $t_{u} = 6$ and $t_{d} = 2$. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly $48$ seconds. The upper left corner of this track is located in the square with the row number $4$, column number $3$ and the lower right corner is at square with row number $6$, column number $7$.
Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.
You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them.
|
Due to the time limit for Java some of $O(N^{4})$ solution got Accepted. The authors solution has complexity $O(N^{3} \cdot logN)$. The main idea is to fix the top-border and bottom-border. Then, using some abstract data type, for each right-border we can find the most suitable left-border in $O(logN)$ time. For example we can use set in C++ and its method lower_bound. For better understanding lets have a look at the following figure: For such rectangle we fix the upper-border as row number $2$ and bottom-border as row number $5$. Also, we fix right-border as column number $6$, and now we are to find some left-border. Now we can split the time value for any rectangle for two summands. One of them depends only on left-border and another one - on the right-border. With the blue color the summand that depends only on the right-border is highlighted. With the red and yellow color - the other summand is highlighted. The red-colored value should be subtracted and the yellow-colored should be added. For any blue right-border's value we are to find the closest red-yellow left-border. That is the problem to be solved with the help of STL Set or any other similar abstract data type.
|
[
"binary search",
"brute force",
"constructive algorithms",
"data structures",
"dp"
] | 2,300
| null |
424
|
E
|
Colored Jenga
|
Cold winter evenings in Tomsk are very boring — nobody wants be on the streets at such a time. Residents of Tomsk while away the time sitting in warm apartments, inventing a lot of different games. One of such games is 'Colored Jenga'.
This game requires wooden blocks of three colors: red, green and blue. A tower of $n$ levels is made from them. Each level consists of three wooden blocks. The blocks in each level can be of arbitrary colors, but they are always located close and parallel to each other. An example of such a tower is shown in the figure.
The game is played by exactly one person. Every minute a player throws a special dice which has six sides. Two sides of the dice are green, two are blue, one is red and one is black. The dice shows each side equiprobably.
If the dice shows red, green or blue, the player must take any block of this color out of the tower at this minute so that the tower doesn't fall. If this is not possible, the player waits until the end of the minute, without touching the tower. He also has to wait until the end of the minute without touching the tower if the dice shows the black side. \textbf{It is not allowed to take blocks from the top level of the tower (whether it is completed or not)}.
Once a player got a block out, he must put it on the top of the tower so as to form a new level or finish the upper level consisting of previously placed blocks. The newly constructed levels should have all the same properties as the initial levels. \textbf{If the upper level is not completed, starting the new level is prohibited}.
For the tower not to fall, in each of the levels except for the top, there should be at least one block. Moreover, if at some of these levels there is exactly one block left and this block is not the middle block, the tower falls.
The game ends at the moment when there is no block in the tower that you can take out so that the tower doesn't fall.
Here is a wonderful game invented by the residents of the city of Tomsk. I wonder for how many minutes can the game last if the player acts optimally well? If a player acts optimally well, then at any moment he tries to choose the block he takes out so as to minimize the expected number of the game duration.
Your task is to write a program that determines the expected number of the desired amount of minutes.
|
A classical DP-problem on finding expected number. Lets define some function $F(S)$ for some state - the expected number of minutes to finish the game from this state. For each color we can compute the probability of showing this color by the simple formula $\frac{C}{6}$, where $c$ - the number of dice's faces of this color. Now we are to find the probability $P_{L}$ to stay in this state for the next minutes. That is the probabilty of showing black color plus the probabilities of showing colors with no blocks of that color to be removed from the tower. Now we can find the value via the following formula: $F(S)={\frac{1+P_{R}\,F_{m i n}(S/R)+P_{G}\!\cdot\!F_{m i n}(S/G)+P_{B}\!\cdot\!F_{m i n}(S/B)}{1-P_{L}}}$ The only problem is to find how to encode the state. To reduce the number of states we can assume that there is only $18$ different type of levels, but not $27$. For better time-performance it is better to use hashing. The solution for this problem requires good understanding of DP and quite good implementing skills.
|
[
"dfs and similar",
"dp",
"probabilities"
] | 2,500
| null |
425
|
A
|
Sereja and Swaps
|
As usual, Sereja has array $a$, its elements are integers: $a[1], a[2], ..., a[n]$. Let's introduce notation:
\[
f(a,l,r)=\sum_{i=l}^{r}a[i];\;m(a)=\operatorname*{max}_{1\leq l\leq r\leq n}f(a,l,r).
\]
A swap operation is the following sequence of actions:
- choose two indexes $i, j$ $(i ≠ j)$;
- perform assignments $tmp = a[i], a[i] = a[j], a[j] = tmp$.
What maximum value of function $m(a)$ can Sereja get if he is allowed to perform at most $k$ swap operations?
|
Lets backtrack interval on which will contain maximal sum. To improve our sum we can swap not more then $k$ minimal elements from the interval to $k$ maximal elements that don't belong to interval. As $n$ isn't big we can do it in any way. Author solution sort all elemets from interval in increasing order and all elements that don't belong to interval by descreasing order. We will swap elements one by one while we haven't done $k$ swaps and we have some unswaped elements in first set and we have some unswaped elemets in second set and swap is optimal(we will optimize the answer after this swap). Author solution works in time $O(n^{3} \cdot log(n))$.
|
[
"brute force",
"sortings"
] | 1,500
| null |
425
|
B
|
Sereja and Table
|
Sereja has an $n × m$ rectangular table $a$, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size $h × w$, then the component must contain exactly $hw$ cells.
A connected component of the same values is a set of cells of the table that meet the following conditions:
- every two cells of the set have the same value;
- the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table);
- it is impossible to add any cell to the set unless we violate the two previous conditions.
Can Sereja change the values of at most $k$ cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?
|
Note, that if we have two arrays $x[1..n], 0 \le x_{i} \le 1$ and $y[1..m], 0 \le y_{i} \le 1$, then described matrix can be showed as next one: $a_{i, j} = x_{i} xor y_{j}$. If $n \le k$, then we can backtrack array $x$ and using greedy find best $y$. Otherwise there will be atleast one $i$, such that we will not change any cell in row number $i$. So we can simply bruteforce some row and use it like $x$. Then we use greedy and find $y$. From all possible rows we choose most optimal. Such row will be as number of mistakes is lower then number of rows, so it isn't possible to have atleast one mistake in each row. Greedy means next algorithm: for every element of $y$ we will look, will it be better to choose it like $0$ or $1$. To find better choise, we will count number of different bits in $x$ and current(lets it be $j$) column. If number of different if lower then count of same cells we will set $y_{j} = 0$, otherwise $y_{j} = 1$.
|
[
"bitmasks",
"greedy"
] | 2,200
| null |
425
|
C
|
Sereja and Two Sequences
|
Sereja has two sequences $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{m}$, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions:
- Choose several (at least one) first elements of sequence $a$ (non-empty prefix of $a$), choose several (at least one) first elements of sequence $b$ (non-empty prefix of $b$); the element of sequence $a$ with the maximum index among the chosen ones must be equal to the element of sequence $b$ with the maximum index among the chosen ones; remove the chosen elements from the sequences.
- Remove all elements of both sequences.
The first action is worth $e$ energy units and adds one dollar to Sereja's electronic account. The second action is worth the number of energy units equal to the number of elements Sereja removed from the sequences before performing this action. After Sereja performed the second action, he gets all the money that he earned on his electronic account during the game.
Initially Sereja has $s$ energy units and no money on his account. What maximum number of money can Sereja get? Note, the amount of Seraja's energy mustn't be negative at any time moment.
|
In thgis problem we will use dynamic programming: $dp_{i, j}$ - minimal pozition of deleted element in second array, such that we have made first operation $j$ times and have deleted not more then $i$ elements from first array. Lets decided how to calculate transfers. Standing in pozition $dp_{i, j}$ we can change nothing and go to pozition $dp_{i + 1, j}$, by other words make transfer $dp_{i + 1, j}: = min(dp_{i + 1, j}, dp_{i, j})$. What happens when we make first operation with fixed prefix(by $i$-th element) in first array? We should find element in second array with number greater $dp_{i, j}$ and value equal to $a_{i}$, lets its pozition is $t$, so we need to make transfer $dp_{i + 1, j + 1}: = min(dp_{i + 1, j + 1}, t)$. How to find required element quickly: lets just do vector of pozition in second array for all different elements that contains in second array. Then we can simply use binary search.
|
[
"data structures",
"dp"
] | 2,300
| null |
425
|
D
|
Sereja and Squares
|
Sereja has painted $n$ distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number.
|
Lets line $x = k$ contain not more then $\sqrt{n}$ points. Then for each pair of points on this line (lets it be $(k, y_{1})$ and $(k, y_{2})$) check: is there squere that contain them as vertexes. So we should check: is there(in input) pair of points $(k - |y_{2} - y_{1}|, y_{1})$ and $(k - |y_{2} - y_{1}|, y_{2})$, or pair $(k + |y_{2} - y_{1}|, y_{1})$ and $(k + |y_{2} - y_{1}|, y_{2})$. Lets delete all watched points, and reverse points about line $x = y$. Then each line $x = k$ will contain not more then $\sqrt{n}$ points. Will solve problem in the same way. Now we should learn: how to check is some pair of points(on one vertical line) in input. Lets write all of this pairs in vectors. Each vector(for every line) will contain pairs that we should check on it. Suppose, that we check it for line number $k$. Lets mark in some array $u$ for all points with x-coordinate equal to $k$ $u_{y} = k$. Now to check is our pair with y-coordinates $(y_{1}, y_{2})$ on line we can simply check following condition: $u_{y1} = u_{y2} = k$.
|
[
"binary search",
"data structures",
"hashing"
] | 2,300
| null |
425
|
E
|
Sereja and Sets
|
Let's assume that set $S$ consists of $m$ distinct intervals $[l_{1}, r_{1}]$, $[l_{2}, r_{2}]$, $...$, $[l_{m}, r_{m}]$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$; $l_{i}, r_{i}$ are integers).
Let's assume that $f(S)$ is the maximum number of intervals that you can choose from the set $S$, such that every two of them do not intersect. We assume that two intervals, $[l_{1}, r_{1}]$ and $[l_{2}, r_{2}]$, intersect if there is an integer $x$, which meets two inequalities: $l_{1} ≤ x ≤ r_{1}$ and $l_{2} ≤ x ≤ r_{2}$.
Sereja wonders, how many sets $S$ are there, such that $f(S) = k$? Count this number modulo $1000000007$ $(10^{9} + 7)$.
|
First, lets look at $F(S)$. First, we sort all intervals by second coordinte and then go by them in sorted order. And if current interval don't intersected with last taken to the optimal set, we get our current to the set. Our solution will be based on this greedy. Solution of the problem is next dynamic: 1). number of position of second coordinte of interval 2). number of intervals in good set 3). second coordinate of last taken interval to the optimal set How should we make transfers? Lets note that when we know $dp_{i, count, last}$ we can change $last$ by $i$, or not change at all. Lets look what happens in every case. In first case $last$ is changed by $i$, so we should take to optimal set atleast one of the inervals: $[last + 1, i]$, $[last + 2, i]$, ..., $[i, i]$, number of such intervals $i - last$, number of ways to get at least one of them is $2^{i - last} - 1$. All other intervals: $[1, i]$, $[2, i]$, ..., $[last, i]$ we could get as we wish, so we have $2^{last}$ ways. So total number of transfers from $dp_{i, count, last}$ to $dp_{i + 1, count + 1, i}$ is $(2^{i - last} - 1) \cdot (2^{last})$. If we count number of transfers from $dp_{i, count, last}$ to $dp_{i + 1, count, last}$, we can simply use number $2^{last}$(as described early). Also we shouldn't forget about trivial case $dp_{i, 0, 0}$. So now we have quite easy solution.
|
[
"dp"
] | 2,500
| null |
426
|
A
|
Sereja and Mugs
|
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and $n$ water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.
As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has $(n - 1)$ friends. Determine if Sereja's friends can play the game so that nobody loses.
|
Lets count the sum of all elements $Sum$ and value of the maximal element $M$. If $Sum - M \le S$ then answer is yes, otherwise - no.
|
[
"implementation"
] | 800
| null |
426
|
B
|
Sereja and Mirroring
|
Let's assume that we are given a matrix $b$ of size $x × y$, let's determine the operation of mirroring matrix $b$. The mirroring of matrix $b$ is a $2x × y$ matrix $c$ which has the following properties:
- the upper half of matrix $c$ (rows with numbers from $1$ to $x$) exactly matches $b$;
- the lower half of matrix $c$ (rows with numbers from $x + 1$ to $2x$) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows $x$ and $x + 1$).
Sereja has an $n × m$ matrix $a$. He wants to find such matrix $b$, that it can be transformed into matrix $a$, if we'll perform on it \textbf{several} (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
|
Lets solve problem from another side. We will try to cut of matix as many times as we can. Cut means operation, reversed to operation described in statement. To check, can we cut matrix we need to check following conditions: 1). $n mod 2 = 0$ 2). $a_{i, j} = a_{n - i + 1, j}$ for all $1 \le i \le n, 1 \le j \le m$.
|
[
"implementation"
] | 1,300
| null |
427
|
A
|
Police Recruits
|
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
|
Maintain a variable, $sum$. Initially $sum$=0, it keeps the number of currently free police officers. With every recruitment operation, add the number of officers recruited at that time to $sum$. When a crime occurs, if $sum > 0$ then decrease the number of free officers by one, otherwise no officers are free so the crime will go untreated.
|
[
"implementation"
] | 800
| null |
427
|
B
|
Prison Transfer
|
The prison of your city has $n$ prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer $c$ of the prisoners to a prison located in another city.
For this reason, he made the $n$ prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.
Then, the mayor told you to choose the $c$ prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,
- The chosen $c$ prisoners has to form a contiguous segment of prisoners.
- Any of the chosen prisoner's crime level should not be greater then $t$. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.
Find the number of ways you can choose the $c$ prisoners.
|
The severity of crimes form an integer sequence. Find all the contiguous sequences without any integer greater than $t$. If the length of any sequence is $L$, then we can choose $c$ prisoners from them in $L - c + 1$ ways.
|
[
"data structures",
"implementation"
] | 1,100
| null |
427
|
C
|
Checkposts
|
Your city has $n$ junctions. There are $m$ \textbf{one-way} roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.
To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction $i$ can protect junction $j$ if either $i = j$ or the police patrol car can go to $j$ from $i$ and then come back to $i$.
Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions.
You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and \textbf{in addition in minimum number of checkposts}. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other.
|
Find the strongly connected components of the graph. From each component we need to choose a node with the lowest cost. If there are more than one nodes with lowest cost, then there are more than one way to choose node from this component.
|
[
"dfs and similar",
"graphs",
"two pointers"
] | 1,700
| null |
427
|
D
|
Match & Catch
|
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings $s_{1}$ and $s_{2}$ from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.
Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.
Given two strings $s_{1}$ and $s_{2}$ consist of lowercase Latin letters, find the smallest (by length) common substring $p$ of both $s_{1}$ and $s_{2}$, where $p$ is a unique substring in $s_{1}$ and also in $s_{2}$. See notes for formal definition of substring and uniqueness.
|
$O(n^{2})$ dynamic programming solution : Calculate the longest common prefix ( LCP ) for each index of $s1$ with each index of $s2$. Then, calculate LCP for each index of $s1$ with all the other indexes of it's own ( $s1$ ). Do the same for $s2$. Now from precalculated values, you can easily check the length of the shortest unique substring starting from any of the indexes of $s1$ or $s2$. Suppose $i$ is an index of $s1$ and $j$ is an index of $s2$. Find the LCP for $i$ and $j$. Now, the minimum of the length of LCP, length of shortest unique substring starting from $i$, length of shortest unique substring starting from $j$ is the answer for $i$,$j$. Now we need to find the minimum answer from all possible $i$,$j$ pair. This problem can also be solved in $O(n\log n)$ by suffix array and in $O(n)$ using suffix automaton.
|
[
"dp",
"string suffix structures",
"strings"
] | 2,200
| null |
427
|
E
|
Police Patrol
|
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the $x$-axis. Currently, there are $n$ criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only \textbf{one} patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most $m$ criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
|
Trying to place the police station on existing criminal locations is the best strategy. Calculate the cost from the leftmost criminal location, then sweep over the next locations. By doing some adjustments on the cost of the previous location will yield the cost of the current location.
|
[
"greedy",
"implementation",
"math",
"ternary search"
] | 2,000
| null |
429
|
A
|
Xor-tree
|
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having $n$ nodes, numbered from $1$ to $n$. Each node $i$ has an initial value $init_{i}$, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node $x$. Right after someone has picked node $x$, the value of node $x$ flips, the values of sons of $x$ remain the same, the values of sons of sons of $x$ flips, the values of sons of sons of sons of $x$ remain the same and so on.
The goal of the game is to get each node $i$ to have value $goal_{i}$, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
|
There is something to learn from "propagating tree" problem, used in round #225. It's how the special operation works. I'll copy paste the explanation from there (with some modification, corresponding to the problem): Let's define level of a node the number of edges in the path from root to the node. Root (node 1) is at level 0, sons of root are at level 1, sons of sons of root are at level 2 and so on. Now suppose you want to do a special operation to a node x. What nodes from subtree of x will be flipped? Obviously, x will be first, being located at level L. Sons of x, located at level L + 1 will not be flipped. Sons of sons, located at level L + 2, will be flipped again. So, nodes from subtree of x located at levels L, L + 2, L + 4, ... will be flipped, and nodes located at levels L + 1, L + 3, L + 5 won't be flipped. Let's take those values of L modulo 2. All nodes having remainder L modulo 2 will be flipped, and nodes having reminder (L + 1) modulo 2 will not. In other words, for a fixed x, at a level L, let y a node from subtree of x, at level L2. If L and L2 have same parity, y will be flipped, otherwise it won't. We'll use this fact later. For now, let's think what should be our first operation. Let's consider some nodes {x1, x2, ..., xk} with property that x1 is son of x2, x2 is son of x3, ... xk-1 is son of xk and parity of levels of these nodes is the same. Suppose by now we fixed {x1, x2, ..., xk-1} (their current value is equal to their goal value), but xk is still not fixed. After some time, we'll have to fix xk. Now, by doing this, all nodes {x1, x2, ..., xk-1} will get flipped and hence unfixed. We've done some useless operations, so our used strategy is not the one that gives minimal number of operations. What we learn from this example? Suppose I want to currently fix a node X. There is no point to fix it now, unless all ancestors Y of X with property level(Y) = level(X) (mod 2) are fixed. But what if an ancestor Y of X is not fixed yet and level(Y) != level(X) (mod 2)? Can I fix node X now? The answer is yes, as future operations done on Y won't affect X. But, by same logic, I can firstly fix Y and then fix X, because again operations done on Y won't affect X. We get a nice property: there is no point to make an operation on a node X unless all ancestors of X are fixed. How can we use this property? What should be the first operation? We know that node 1 is the root, hence it always won't have any ancestor. All other nodes might have sometimes not fixed ancestors, but we know for sure, for beginning, node 1 won't have any unfixed ancestor (because it won't have any). So, for beginning we can start with node 1. More, suppose node 1 is unfixed. The only way to fix it is to make an operation on it. Since it's unfixed and this is the only way to fix it, you'll be obligated to do this operation. This means, in an optimal sequence of operations, you'll be obligated to do this operation, too. So, if node 1 was unfixed, we did an operation on it. If it was already fixed, we're done with it. What are next nodes we know for sure that will have all ancestors fixed? Sons of 1, because they have only one ancestor (node 1), which we know it's fixed. We can only fix them by doing operations of them (doing operations on node 1 / sons of them won't affect them). Since eventually they have to be fixed and only way to be fixed is to do an operation on them, in an optimal sequence of operations, we'll have to make operations on them. Let's move on. What are next nodes that we know for sure all ancestors of them will be fixed? Sons of sons of 1. We can fix them by doing an operation of them, or by doing an operation on 1. But doing an operation on 1 isn't helpful, because even if it fixes this node, it unfixes 1. Then, you'll have to do one more operation on 1, which will unfix current node, so we do two useless operations. It turns out, the only way to fix them is to do an operation on them. Generally, suppose all ancestors of node x are fixed. We get the current value of node x after the operations done on ancestors of x. If the current value is not the expected one, we'll have to do an operation on node x (this is the only way to fix the node x). Now, after node x is fixed, we can process sons of it. This strategy guarantees minimal number of operations, because we do an operation only when we're forced to do it. This leads immediately to an O(N ^ 2) algorithm, by every time we need to do an operation to update it to nodes from its subtree. How to get O(N)? Suppose we are at node x and want to know its current value after operations done for its ancestors. Obviously, it is defined by initial value. If we know number of operations done so far by even levels for its ancestors, number of operations done so far by odd levels and current level, we can determine the current value. Suppose these values are (initial_value, odd_times, even_times, level). We observe that 2 operations cancel each other, so we can take this number modulo 2. If level mod 2 = 0, then only even_times will matter, and current_value = (initial_value + even_times) % 2. Otherwise, current_value = (initial_value + odd_times) % 2. We can send (even_times, odd_times and level) as DFS parameters, so current_value can be calculated in O(1), and overall complexity is O(N).
|
[
"dfs and similar",
"trees"
] | 1,300
| null |
429
|
B
|
Working out
|
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix $a$ with $n$ lines and $m$ columns. Let number $a[i][j]$ represents the calories burned by performing workout at the cell of gym in the $i$-th line and the $j$-th column.
Iahub starts with workout located at line $1$ and column $1$. He needs to finish with workout $a[n][m]$. After finishing workout $a[i][j]$, he can go to workout $a[i + 1][j]$ or $a[i][j + 1]$. Similarly, Iahubina starts with workout $a[n][1]$ and she needs to finish with workout $a[1][m]$. After finishing workout from cell $a[i][j]$, she goes to either $a[i][j + 1]$ or $a[i - 1][j]$.
There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.
If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.
|
The particularity of this problem which makes it different by other problem of this kind is that paths need to cross exactly one cell and Iahub can go only right and down, Iahubina can go only right and up. Let's try to come up with a solution based on these facts. A good start is to analyze configurations possible for meeting cell. Iahub can come either from right or down and Iahubina can come either from right or up. However, if both Iahub and Iahubina come from right, they must have met in other cell as well before (the cell in the left of the meet one). Similarly, if one comes from up and other one from down, their paths will cross either on upper cell, lower cell or right cell. Only 2 possible cases are: Iahub comes from right, Iahubina comes from up or Iahub comes from down, Iahubina comes from right. By drawing some skatches on paper, you'll see next cell visited after meeting one will have the same direction for both of them. More, they will never meet again. So Iahub comes from right, goes to right, Iahubina comes from up, goes to up or Iahub comes from down, goes to down and Iahubina comes from right, goes to right. In the drawing, Iahub's possible visited cells are blue, Iahubina's possible visited cells are red and meeting cell is purple. Denote (X, Y) meeting cell. For first case, Iahub comes from (1, 1) to (X, Y - 1) by going down or right. Next, he goes from (X, Y + 1) to (N, M) by going down or right. Iahubina goes from (M, 1) to (X + 1, Y) by going up or right and then from (X - 1, Y) to (1, M) by going with same directions. In second case, Iahub goes from (1, 1) to (X - 1, Y) and then from (X + 1, Y) to (N, M) and Iahubina goes from (M, 1) to (X, Y - 1) and then from (X, Y + 1) to (1, M). We can precalculate for dynamic programming matrixes and we're done. dp1[i][j] = maximal cost of a path going from (1, 1) to (i, j) only down and right. dp2[i][j] = maximal cost of a path from (i, j) to (1, m) going only up and right. dp3[i][j] = maximal cost of a path from (m, 1) to (i, j) going only up and right. dp4[i][j] = maximal cost of a path from (i, j) to (n, m) going only down or right. And here is my full implementation of recurrences (C++ only): Also, pay attention that meeting points can be cells (i, j) with 1 < i < n and 1 < j < m. (why?)
|
[
"dp"
] | 1,600
| null |
429
|
C
|
Guess the Tree
|
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.
Iahub asks Iahubina: can you build a rooted tree, such that
- each internal node (a node with at least one son) has at least two sons;
- node $i$ has $c_{i}$ nodes in its subtree?
Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. \textbf{The required tree must contain $n$ nodes}.
|
The constrain n <= 24 immediately suggest us an exponential solution. 24 numbers seems to be not too big, but also not too small. What if we can reduce it by half? We can do this, by analyzing problem's restriction more carefully. The problem states that each internal node has at least two sons. After drawing some trees likes these, one may notice there are a lot of leafs in them. For a tree with this property, number of leafs is at least (n + 1) / 2. We'll proof this affirmation by mathematical induction. For n = 1, affirmation is true. Now, suppose our tree has n nodes, and the root of it has sons {s1, s2, ..., sk}. Let's assume subtree of s1 has n1 nodes, subtree of s2 has n2 nodes, ..., subtree of sk has nk nodes. By induction we get that s1 has at least (n1 + 1) / 2 leafs, ..., sk has at least (nk + 1) / 2 leafs. Summing up, we get that our tree has at least (n1 + n2 + ... + nk + k) / 2 leafs. But n1 + n2 + ... + nk = n - 1. So it has at least (n + k - 1) / 2 leafs. But, by hypothesis k >= 2, so our tree has at least (n + 1) / 2 leafs. For n = 24, there will be at least 13 leafs, so at most 11 internal nodes. It looks much better now for an exponential solution! Before presenting it, we need one more observation. Suppose we sorted c[] array decreasing. Now, the father of node i can be only one of nodes {1, 2, ..., i - 1}. Nodes {i + 1, i + 2, ..., n} will have at most as much nodes as node i, so they can't be father of i. By doing this observation we can start algorithm: start with node 1 and assign its sons. Then, move to node 2. If it does not have a father, we won't have one, so current configuration is good. If he has a father (in this case node 1), then tree is connected so far. So we can assign children of node 2. Generally, if a node i does not have a father when it's processed, it won't have in future either. If it has, the tree is connected so far, so we add children of i. Let's introduce the following dynamic programming. Let dp[node][mask][leafs] = is it possible to create a tree if all nodes {1, 2, ..., node} have already a father, exactly leafs nodes don't have one and internal nodes corresponding to 1 in bitmask mask also don't have one? If you never heart about "bitmask" word, this problem is not good for you to start with. I recommend you problem E from round #191, where I explained more how bitmasks work. Back on the problem. If node has 1 in its bit from the mask, then we know for sure the tree can't be built. Otherwise, let's assign sons for node. We take all submasks of mask (number obtained by changing some bits from 1 to 0) and make sum of degrees for corresponding nodes. Denote this number as S. These are the internal nodes. How about the leafs? We need to have available L = c[node] - S - 1 leafs. If L is <= than leafs, we can use them. If L < 0, obviously we can't build the tree. Will remain obviously leafs - L leafs. The new mask will be mask ^ submask. Also, we need to iterate to node + 1. If dp[node+1][mask ^ submask][leafs - L]. One more condition that needs to be considered: node needs to have at least 2 sons. This means L + cnt > 1 (where cnt are number of internal nodes used). When do we stop the dp? When c[nod] = 1. If mask = 0 and leafs = 0, then we can build the tree. Otherwise, we can't. Let's analyze the complexity. There are O(2 ^ (n / 2)) masks, each of them has O(n) leafs, for each O(n) node. This gives O(2 ^ (n / 2) * n ^ 2) states. Apparently, iterating over all submasks gives O(2 ^ (n / 2)) time for each submask, so overall complexity should be O(4 ^ (n / 2) * n ^ 2). But this complexity is over rated. Taking all submasks for all masks takes O(3 ^ (n / 2)) time, instead of O(4 ^ (n / 2)) time. Why? Consider numbers written in base 3: for a mask and a submask we can assign 3 ternary digits to each bit: 0 if bit does not appear in mask 1 if bit appears in mask but not in submask 2 if bit appears in mask and in submask Obviously, there are O(3 ^ (n / 2)) numbers like this and the two problems are equivalent, so this step takes O(3 ^ (n / 2)) and overall complexity is O(3 ^ (n / 2) * n ^ 2).
|
[
"bitmasks",
"constructive algorithms",
"dp",
"greedy",
"trees"
] | 2,300
| null |
429
|
D
|
Tricky Function
|
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task.
You're given an (1-based) array $a$ with $n$ elements. Let's define function $f(i, j)$ $(1 ≤ i, j ≤ n)$ as $(i - j)^{2} + g(i, j)^{2}$. Function g is calculated by the following pseudo-code:
\begin{verbatim}
int g(int i, int j) {
int sum = 0;
for (int k = min(i, j) + 1; k <= max(i, j); k = k + 1)
sum = sum + a[k];
return sum;
}
\end{verbatim}
Find a value $min_{i ≠ j} f(i, j)$.
Probably by now Iahub already figured out the solution to this problem. Can you?
|
Let's define S[i] = a[1] + a[2] + ... + a[i]. Then, f(i, j) = (i - j) ^ 2 + (S[i] - S[j]) ^ 2. Trying to minimize this function seems complicated, so we need to manipulate the formula more. We know from the maths that if f(i, j) is minimized, then also f'(i, j) = sqrt ( (i - j) ^ 2 + (S[i] - S[j]) ^ 2) is also minimized. Does this function look familiar to you? Suppose you get two points in 2D plane: one having coordinates (i, S[i]) and the other one having coordinates (j, S[j]). One can see that f'(i, j) is exactly euclidean distance of those points. So, if f'(i, j) is a distance between two points in plane, when is achieved minimal f'(i, j)? For the closest two points in plane (the points which are located at minimal distance). So, having set of points (i, S[i]), we need to compute closest two points from this plane. There is a classical algorithm that does this in O(n * logn).
|
[
"data structures",
"divide and conquer",
"geometry"
] | 2,200
| null |
429
|
E
|
Points and Segments
|
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw $n$ distinct segments $[l_{i}, r_{i}]$ on the $OX$ axis. He can draw each segment with either red or blue. The drawing is good if and only if the following requirement is met: for each point $x$ of the $OX$ axis consider all the segments that contains point $x$; suppose, that $r_{x}$ red segments and $b_{x}$ blue segments contain point $x$; for each point $x$ inequality $|r_{x} - b_{x}| ≤ 1$ must be satisfied.
A segment $[l, r]$ contains a point $x$ if and only if $l ≤ x ≤ r$.
Iahub gives you the starting and ending points of all the segments. You have to find any good drawing for him.
|
The problem asks you to check the property for an infinity of points. Obviously, we can't do that. However, we can observe that some contiguous ranges on OX axis have the same rx and bx values. Like a sweep line algorithm, a possible change may appear only when a new segment begins or when an old one ends. So let's consider set of points formed by all li reunited with set of points formed by all ri. Sort the values increasing. Suppose the set looks like {x1, x2, ..., xk}. Then ranges [0, x1) [x1, x2) ... [xk-1, xk) [xk, infinity) are the only ones that need to be considered. If we can take an arbitrary point from each range and the property is respected for all points, then the drawing is good. We need to color segments. But each segment is a reunion of ranges like the ones from above. When you color a segment, all ranges from it will be colored too. So, after coloring the segments, for each range, |number of times range was colored with blue - number of times range was colored with red| <= 1. It's time to think creative. We can see ranges as vertexes of a graph and segments as edges. For example, if a segment is formed by ranges {Xi, Xi+1, ..., Xj-1, Xj} we add an undirected edge from i to j + 1. We need to color the edges. We divide the graph into connected components and apply same logic for each component. Next, by graph I'll refer to a connected graph. Let's assume that our graph has all degrees even. Then, it admits an eulerian cycle. Suppose {x1, x2, ..., xk} is the list of nodes from the cycle, such as x1-x2 x2-x3 ... xk-x1 are the edges of it, in this order. We apply a rule: if xi < xi+1, we color edge between xi and xi+1 in red. Otherwise, we color it in blue. What happens for a node? Whenever a "red" edge crosses it (for example edge 1-5 crosses node 4) a "blue" edge will always exist to cross it again (for example edge 6-2 crosses node 4). This is because of property of euler cycle: suppose we started from a node x and gone in "left". We need to return to it, but the only way to do it is an edge which goes to "right". So, when degrees of graph are all even, for every point on OX axis, difference between rx and bx will be always 0. Let's solve the general case now. Some nodes have odd degree. But there will always be an even number of nodes with odd degrees. Why? Suppose the property is respected for some edges added so far and now we add a new one. There are two cases: 1/ the edge connects two nodes with odd degree. in this case, the number of nodes with odd degrees decreases by 2, but its parity does not change. 2/ the edge connects one node with odd degree and one node with even degree. Now, degree of "old" odd one becomes even and degree of "old" even one becomes odd. So number of nodes with odd degrees does not change. So suppose the nodes with odd degrees are X1 X2 ... Xk (k is even). Assume X1 < X2 < ... < Xk. If we add one more edge to each of these nodes, an euler cycle would be possible. However, we can't "add" edges, because edges are segments from the input. But we can imagine them. Of course, this we'll create an imbalance between red and blue edges, but let's see how big it is. What if we add a fictive edge between X1 to X2, between X3 to X4, ..., between X(k - 1) to Xk? In this way, all those nodes will have even degree. So for each Xi (i odd) we add a dummy vertex Yi and some dummy edges from Xi to Yi and from Yi to Xi+1. Now let's see the effect: if the fictive edges existed, the balance would be 0. But they do not exist, so one of rx or bx will decrease. So now |rx - bx| <= 1, good enough for problem's restrictions.
|
[
"graphs"
] | 3,000
| null |
430
|
A
|
Points and Segments (easy)
|
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw $n$ distinct points and $m$ segments on the $OX$ axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment $[l_{i}, r_{i}]$ consider all the red points belong to it ($r_{i}$ points), and all the blue points belong to it ($b_{i}$ points); each segment $i$ should satisfy the inequality $|r_{i} - b_{i}| ≤ 1$.
Iahub thinks that point $x$ belongs to segment $[l, r]$, if inequality $l ≤ x ≤ r$ holds.
Iahub gives to you all coordinates of points and segments. Please, help him to find any good drawing.
|
The problem asks you to output "-1" if there is no solution. A natural question is now: "when there is no solution"? Try to come up with a test like this! After some analysis, you'll see anyhow we draw the points and the lines, there will always be a solution. By manually solving small cases, you might already have found the pattern. But for now, let's assume anyhow we draw points and lines, there will always be a solution. Let's have a fixed set of points. Then, anyhow we draw a line, there should still be a solution. So, we need to find a coloring of points, such as for every line, |number of red points which belong to it - number of blue points which belong to it| <= 1. Suppose anytime you color a point with red you assign it +1 value. Also, anytime you color it with blue you assign it -1 value. Then, for a segment, the drawing is good if S = sum of values assigned to points that belong to segment is between -1 and 1 (in other words |S| <= 1). Let's sort points increasing by abscissa. It's useful because now, for a segment, there will be a contiguous range of points that belong to that segment. For example, suppose my current segment is [3, 7] and the initial set of points was {4, 1, 5, 2, 8, 7}. Initially, points that belong to the segment would be first, third and sixth. Let's sort the points by abscissa. It looks like {1, 2, 4, 5, 7, 8}. You can see now there is a contiguous range of points that belongs to [3, 7] segment: more exactly third, fourth and fifth. We reduced problem to: given an array, assign it either +1 or -1 values such as, for each subarray (contiguous range), the sum S of subarray's elements follows the condition |S| <= 1. Before reading on, try to come up with an example by yourself. My solution uses the pattern: +1 -1 +1 -1 +1 -1 ... Each subarray of it will have sum of its elements either -1, 0 or 1. How to proof it? When dealing with sums of subarrays, a good idea is to use partial sums. Denote sum[i] = x[1] + x[2] + ... + x[i]. Then, sum of a subarray [x, y] is sum[y] - sum[x - 1]. Partial sums for the pattern looks like: 1 0 1 0 1 0 .... Hence, there are 4 possible cases: 1/ sum[x - 1] = 0 and sum[y] = 0. sum[y] - sum[x - 1] = 0 2/ sum[x - 1] = 1 and sum[y] = 1. sum[y] - sum[x - 1] = 0 3/ sum[x - 1] = 0 and sum[y] = 1. sum[y] - sum[x - 1] = 1 4/ sum[x - 1] = 1 and sum[y] = 0. sum[y] - sum[x - 1] = -1 Hence, each subarray sum is either -1, 0 or 1. So, general algorithm looks like: sort points by abscissa, assign them red, blue, red, blue, ... and then sort them back by original order and print the colors.
|
[
"constructive algorithms",
"sortings"
] | 1,600
| null |
430
|
B
|
Balls Game
|
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?
There are $n$ balls put in a row. Each ball is colored in one of $k$ colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color $x$. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.
For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.
Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.
|
This is an implementation problem. There is not so much to explain. Perhaps the trick at implementation problems is to divide code into smaller subproblems, easy to code and then put them together. I don't know if this is the universally truth, but this is how I approach them. Here, there are two main parts: the part when you insert a ball between 2 balls and the part when you see how many balls are destroyed after the move. We can keep an array a[] with initial configuration of balls, then for each insertion create an array b[] with current configuration after the insertion. If my ball is inserted after position pos, b is something like this: b = a[1....pos] + {my_ball} + a[pos+1....n]. For now we have array b[] and we need to know how many balls will disappear. The problem statement gives us an important clue: no 3 balls will initially have the same color. This means, any time, at most one contiguous range of balls of same color will exist with length at least 3. If it exists, we have to remove it. Then, we have to repeat this process. So algorithm is something like bubble sort: while b[] array has changed last step, continue algorithm, otherwise exit it. Now, search an i for which b[i] = b[i + 1] = b[i + 2]. Then, take the maximum j > i for which b[k] = b[i], with i < k <= j. You have to remove from b[] the subarray [i...j] and add j - i + 1 to the destroyed balls. You'll need to return this sum - 1, because the ball you added wasn't there at beginning. Pay attention on case when you can't destroy anything, you need to output 0 instead of -1. There are O(n) positions where you can insert the new ball, for each of them there are maximal O(n) steps when balls are deleted and deleting balls takes maximal O(n) time, so overall complexity is O(n ^ 3). Note: in my solution, I don't actually do deletion. If I have to delete a range [i, j] I create a new array c[] = b[1...i - 1] + b[j+1....n] and then copy c[] into b[] array. This guarantees O(n) time for deletion.
|
[
"brute force",
"two pointers"
] | 1,400
| null |
431
|
A
|
Black Square
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly $a_{i}$ calories on touching the $i$-th strip.
You've got a string $s$, describing the process of the game and numbers $a_{1}, a_{2}, a_{3}, a_{4}$. Calculate how many calories Jury needs to destroy all the squares?
|
To solve this problem, you must only do the process described in statement. Complexity: $O(N)$
|
[
"implementation"
] | 800
|
#include<iostream>
using namespace std;
int main(){
int a[5];
for (int i = 1; i <= 4; i ++)
cin >> a[i];
string s;
cin >> s;
int sum = 0;
for (int i = 0 ;i < s.size(); i ++)
sum += a[s[i]-'0'];
cout << sum << endl;
return 0;
}
|
431
|
B
|
Shower Line
|
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks.
There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory shower door. As soon as the shower opens, the first person from the line enters the shower. After a while the first person leaves the shower and the next person enters the shower. The process continues until everybody in the line has a shower.
Having a shower takes some time, so the students in the line talk as they wait. At each moment of time the students talk in pairs: the $(2i - 1)$-th man in the line (for the current moment) talks with the $(2i)$-th one.
Let's look at this process in more detail. Let's number the people from 1 to 5. Let's assume that the line initially looks as 23154 (person number 2 stands at the beginning of the line). Then, before the shower opens, 2 talks with 3, 1 talks with 5, 4 doesn't talk with anyone. Then 2 enters the shower. While 2 has a shower, 3 and 1 talk, 5 and 4 talk too. Then, 3 enters the shower. While 3 has a shower, 1 and 5 talk, 4 doesn't talk to anyone. Then 1 enters the shower and while he is there, 5 and 4 talk. Then 5 enters the shower, and then 4 enters the shower.
We know that if students $i$ and $j$ talk, then the $i$-th student's happiness increases by $g_{ij}$ and the $j$-th student's happiness increases by $g_{ji}$. Your task is to find such initial order of students in the line that the total happiness of all students will be maximum in the end. Please note that some pair of students may have a talk several times. In the example above students 1 and 5 talk while they wait for the shower to open and while 3 has a shower.
|
In this problem, according to the small limits, we can brute all permutations and choose the best answer of all. The easeast way to do this - use standart C++ function next_permutation, or simply write 5 for. For each permutation we can simulate the process, which was described in a statement, or notice that first with second student, and second with the third will communicate one time, and third with fourth student, and fourth with fifth - will communicate two times. Another pairs of students will never communicate to each other during they stay in queue. Complexity: $O(n!)$
|
[
"brute force",
"implementation"
] | 1,200
|
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
int g[6][6];
int main()
{
int n = 5;
for(int i = 0 ; i < n ; ++i)
for(int j = 0 ; j < n ; ++j)
cin >> g[i][j];
int p[6], pans[6], ans = -1, tmp;
for(int i = 0 ; i < n ; ++i)
p[i] = i;
do
{
//01234
tmp = g[p[0]][p[1]] + g[p[1]][p[0]];
tmp += g[p[2]][p[3]] + g[p[3]][p[2]];
//1234
tmp += g[p[1]][p[2]] + g[p[2]][p[1]];
tmp += g[p[3]][p[4]] + g[p[4]][p[3]];
//234
tmp += g[p[2]][p[3]] + g[p[3]][p[2]];
//34
tmp += g[p[3]][p[4]] + g[p[4]][p[3]];
if(tmp > ans)
{
ans = tmp;
for(int i = 0 ; i < n ; ++i)
pans[i] = p[i];
}
}
while(next_permutation(p, p+n));
cout << ans << "\n";
return 0;
}
|
431
|
C
|
k-Tree
|
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a $k$-tree.
A $k$-tree is an infinite rooted tree where:
- each vertex has exactly $k$ children;
- each edge has some weight;
- if we look at the edges that goes from some vertex to its children (exactly $k$ edges), then their weights will equal $1, 2, 3, ..., k$.
The picture below shows a part of a 3-tree.
As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight $n$ (the sum of all weights of the edges in the path) are there, starting from the root of a $k$-tree and also containing at least one edge of weight at least $d$?".Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo $1000000007$ ($10^{9} + 7$).
|
This problem can be solved by dinamic programming. Let's Dp[n][is] - number of ways with length equals to $n$ in k-tree, where if $is = 1$ - there is exists edge with length at least $d$, $is = 0$ - lengths of all edges less then $d$. Initial state Dp[0][0] = 1. Transition - iterate all edges which can be first on the way in k-tree, then problem transform to the same, but with less length of the way (because subtree of vertex son is the k-tree). Dp[n][0] = Dp[n-1][0] + ... + Dp[n-min(d-1,n)][0] Dp[n][1] = Dp[n-1][1] + ... + Dp[n-min(d-1,n)][1] + (Dp[n-d][0] + Dp[n-d][1]) + ... + (Dp[n-min(n,k)][0] + Dp[n-min(n,k)][1]) See solution for more details. Complexity: $O(nk)$ Notice that this solution can be easy midify to $O(N)$ complexity, only precalc partial sums. But it is not neccesary to solve this problem in such way.
|
[
"dp",
"implementation",
"trees"
] | 1,600
|
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int mod = 1e9 + 7;
int dp[100][2];
void add(int &a, int b)
{
a += b;
if(a >= mod)
a -= mod;
}
int main(int argc, char ** argv)
{
int n, k, d;
cin >> n >> k >> d;
dp[0][0] = 1;
dp[0][1] = 0;
for(int i = 1 ; i <= n ; ++i)
{
dp[i][0] = dp[i][1] = 0;
for(int j = 1 ; j <= k ; ++j)
{
if(i-j < 0) break;
if(j < d)
{
add(dp[i][0], dp[i-j][0]);
add(dp[i][1], dp[i-j][1]);
}
else
{
add(dp[i][1], dp[i-j][0]);
add(dp[i][1], dp[i-j][1]);
}
}
}
cout << dp[n][1] << "\n";
return 0;
}
|
431
|
D
|
Random Task
|
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer $n$, that among numbers $n + 1$, $n + 2$, ..., $2·n$ there are exactly $m$ numbers which binary representation contains exactly $k$ digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed $10^{18}$.
|
We will search $n$ by binary search. Such function is monotone, because the amount of numbers with exactly $k$ 1-bits on a segment $n + 2$ ... $2 \cdot (n + 1)$ more or equal than amount of such numbers on segment $n + 1$ ... $2 \cdot n$. Last statement is correct, because of $n + 1$ and $2 \cdot (n + 1)$ have equals number of 1-bits. To find the amount of numbers on segment $L...R$, which have exactly $k$ 1-bits, it is sufficient to can calculate this number for segment $1...L$, then the answer will be $F(1...R) - F(1..L - 1)$. Let's understand how we can calculate $F(1...X)$. Iterate number of bit will be the first(from biggest to smallest) which is different in X and numbers, which amount we want to calculate. Let the first difference will be in $i$-th bit(it's possible, if in X this bit equals to 1, because we consider all numbers do not exceed X). Then other smallest bits we can choose in any way, but only amount of 1-bits must equals to $k$. We can do this in $C_{i}^{k - cnt}$ ways, where $cnt$ - the number of 1-bits in X, bigger then $i$, and $C_{n}^{k}$ - binomailany factor. Finally, you should not forget about X (if it, of course, has k one bits). Complexity: $O(log^{2}(Ans))$
|
[
"binary search",
"bitmasks",
"combinatorics",
"dp",
"math"
] | 2,100
|
#include<cstdio>
#include<cassert>
using namespace std;
#define linf 2000000000000000000LL
#define bit(mask,i) ((mask>>i)&1)
const int Max_Bit = 63;
long long C[Max_Bit+1][Max_Bit+1];
int bcount(long long x){
int Res = 0;
for (;x;x&=(x-1)) Res++;
return Res;
}
long long Solve(long long x,int k){
long long Answer = (k == bcount(x));
for (int i = Max_Bit; i >= 0 && k>=0; i -- )
if (bit(x,i))
Answer+=C[i][k--];
return Answer;
}
int main()
{
C[0][0] = 1;
for (int i = 1; i <= Max_Bit ;i ++ )
for (int j = 0 ; j <= i ; j ++ )
C[i][j]=C[i-1][j]+((j)?(C[i-1][j-1]):0);
long long count;
int k;
scanf("%lld%d",&count,&k);
long long l = 1 , r = linf/2;
while (l<r)
{
long long m = l + (r-l)/2;
if (Solve(m*2,k)-Solve(m,k)<count) l = m+1;
else
r = m;
}
printf("%I64d\n",l);
return 0;
}
|
431
|
E
|
Chemistry Experiment
|
One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found $n$ test tubes with mercury numbered from $1$ to $n$ and decided to conduct an experiment.
The experiment consists of $q$ steps. On each step, one of the following actions occurs:
- Diana pours all the contents from tube number $p_{i}$ and then pours there exactly $x_{i}$ liters of mercury.
- Let's consider all the ways to add $v_{i}$ liters of water into the tubes; for each way let's count the volume \textbf{of liquid} (water and mercury) in the tube \textbf{with water} with maximum amount of liquid; finally let's find the minimum among counted maximums. That is the number the students want to count. At that, the students don't actually pour the mercury. They perform calculations without changing the contents of the tubes.
Unfortunately, the calculations proved to be too complex and the students asked you to help them. Help them conduct the described experiment.
|
First of all let's understand the statement. We have $n$ tubes. At the beginning of each of them there are a few amount of mercury is poured. We want be able to perform two types of queries: Make the amount of mercury in $p$-th tube equals to $x$. Given the number $v$ - the amount of water that must be optimally pour these tubes. What does it mean optimally? That mean we pour water in some of the tubes in the way, when maximum volume of liquid for all tubes, where we poured water, will be as small, as possible. Well, actually now turn to the solution. Use binary search to find an answer, in particular, will sort out the amount of mercury in a tubes(let it equals to $d$), such that in the tubes with smaller volume of the liquid can be poured all $v$ liters of water and the maximum liquid level does not exceed $d$. Let the number of tubes, with the amount of mercury less than $d$ is equal $t$. Now the problem is reduced to learning how to count the total amount of water that we can to pour into each of $t$ least tubes, such that the level of the liquid in each of them is equal $d$. Let $a[i]$ - the total amount of mercury in the tubes which exactly have $i$ liters mercury and $b[i]$ - number of tubes which the volume of mercury is equal $i$. Then $t = b[0] + ... + b[d - 1]$ and $v_{1} = t * d - (a[0] + a[1] + ... + a[d - 1])$ - the total maximum amount of the water which can be poured. If $v_{1}$ < $v$, then obviously this space is not enough for pour all the water, otherwise quite enough and so the answer will be no more than $d$. When we found the smallest $d$, we can say that the answer is equal $d$ - ($v_{1}$ - $v$) / $t$. To quickly find for $a[0] + a[1] + ... + a[d - 1]$ and $b[0] + ... + b[d - 1]$, and perform queries of the first type, you can use the Fenwick tree. Complexity: $O(qlog^{2}(n))$
|
[
"binary search",
"data structures",
"ternary search"
] | 2,200
|
#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
using namespace std;
const int maxn = 200001;
int h[maxn];
int T[maxn];
int P[maxn];
long long V[maxn];
int X[maxn];
long long max_h;
int n;
long long a[maxn], b[maxn];
int mas[maxn];
void add(long long t[], int i, long long value) {
for (; i < maxn; i += (i + 1) & -(i + 1))
t[i] += value;
}
long long sum(long long t[], int i) {
long long res = 0;
for (; i >= 0; i -= (i + 1) & -(i + 1))
res += t[i];
return res;
}
long long get(int H)
{
long long V;
V = mas[H]*1ll*n;
long long cnt = sum(a, max_h) - sum(a, H);
V -= mas[H]*cnt;
V -= sum(b, H);
return V;
}
int main()
{
ios::sync_with_stdio(0);
int q;
cin >> n >> q;
map<int,int> mp, id;
for(int i = 0 ; i < n ; ++i)
{
cin >> h[i];
mp[h[i]] = 1;
}
for(int i = 0 ; i < q ; ++i)
{
cin >> T[i];
if(T[i] == 1)
{
cin >> P[i] >> X[i];
mp[X[i]] = 1;
}
else
cin >> V[i];
}
int index = 1;
mas[0] = 0;
for(map<int,int> :: iterator it = mp.begin() ; it != mp.end() ; ++it)
{
id[it->first] = index;
mas[index] = it->first;
++index;
}
max_h = index-1;
for(int i = 0 ; i < n ; ++i)
{
add(a, id[h[i]], 1ll);
add(b, id[h[i]], h[i]);
}
int t;
int p, x, cnt;
long long v, H;
for(int i = 0 ; i < q ; ++i)
{
t = T[i];
if(t == 1)
{
p = P[i];
x = X[i];
add(a, id[h[p-1]], -1);
add(b, id[h[p-1]], -h[p-1]);
h[p-1] = x;
add(a, id[h[p-1]], 1);
add(b, id[h[p-1]], h[p-1]);
}
else
{
v = V[i];
H = 0;
for(int i = 20 ; i >= 0 ; --i)
{
if(H + (1<<i) > max_h) continue;
if(get(H + (1<<i)) <= v)
H += (1<<i);
}
cout.precision(5);
cnt = sum(a, max_h) - sum(a, H);
cout << fixed << mas[H] + (v-get(H))/(double)(n-cnt) << "\n";
}
}
return 0;
}
|
432
|
A
|
Choosing Teams
|
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has $n$ students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least $k$ times?
|
In this problem you should count number of students who can participate in ACM, divide it by 3 and round down. It could be done like this:
|
[
"greedy",
"implementation",
"sortings"
] | 800
| null |
432
|
B
|
Football Kit
|
Consider a football tournament where $n$ teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the $i$-th team has color $x_{i}$ and the kit for away games of this team has color $y_{i}$ $(x_{i} ≠ y_{i})$.
In the tournament, each team plays exactly one home game and exactly one away game with each other team ($n(n - 1)$ games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.
Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.
|
Count for every team number of games in home kit. For team $i$ it equals to sum of $n - 1$ games at home and some away games with such teams which home kit color equals away kit color of team $i$. To count number of such away games you could calc array $cnt[j]$ - number of teams with home color kit $j$. The solution could be implemented in this wasy:
|
[
"brute force",
"greedy",
"implementation"
] | 1,200
| null |
432
|
C
|
Prime Swaps
|
You have an array $a[1], a[2], ..., a[n]$, containing distinct integers from $1$ to $n$. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):
- choose two indexes, $i$ and $j$ ($1 ≤ i < j ≤ n$; $(j - i + 1)$ is a prime number);
- swap the elements on positions $i$ and $j$; in other words, you are allowed to apply the following sequence of assignments: $tmp = a[i], a[i] = a[j], a[j] = tmp$ ($tmp$ is a temporary variable).
You do not need to minimize the number of used operations. However, you need to make sure that there are at most $5n$ operations.
|
The solution can be described by pseudo-code: Consider elements of permutation from $1$ to $n$ While current element $i$ is not sutiated on position $i$ Let the position of element $i$ equals $pos$ Find maximum prime integer $p$ which is less or equal than $pos - i + 1 Swap element in positions $pos$ and $pos - p + 1$ It could be proved that such algorithm makes less than $4n$ swaps (for example, by implementing the algorithm) This algorithm should be implemented optimally. You should maintain positions of elements of permutation. Swap function in author's solution:
|
[
"greedy",
"sortings"
] | 1,800
| null |
432
|
D
|
Prefixes and Suffixes
|
You have a string $s = s_{1}s_{2}...s_{|s|}$, where $|s|$ is the length of string $s$, and $s_{i}$ its $i$-th character.
Let's introduce several definitions:
- A substring $s[i..j]$ $(1 ≤ i ≤ j ≤ |s|)$ of string $s$ is string $s_{i}s_{i + 1}...s_{j}$.
- The prefix of string $s$ of length $l$ $(1 ≤ l ≤ |s|)$ is string $s[1..l]$.
- The suffix of string $s$ of length $l$ $(1 ≤ l ≤ |s|)$ is string $s[|s| - l + 1..|s|]$.
Your task is, for any prefix of string $s$ which matches a suffix of string $s$, print the number of times it occurs in string $s$ as a substring.
|
The problem could be solved using different algorithms with z and prefix functions. Let's describe the solution with prefix function $p$ of string $s$. Calc prefix function and create a tree where vertices - integers from $0$ to $|s|$, edges - from $p[i]$ to $i$ for every $i$. The root of the tree is $0$. For every vertex $v$ calc the number of values $p[i] = v$ - that is $cnt[v]$. Then for every $v$ calc the sum all values $cnt[u]$ for every $u$ in to subtree of $v$. The general answer to the problem is: Find all lenghts of the prefixes which matches the suffixes - these values are $|s|$, $p[|s|]$, $p[p[|s|]]$, $p[p[p[|s|]]]$... For every such length $L$ the answer to the problem is $sum[L] + 1$.
|
[
"dp",
"string suffix structures",
"strings",
"two pointers"
] | 2,000
| null |
432
|
E
|
Square Tiling
|
You have an $n × m$ rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally:
- each cell must be painted some color (the colors are marked by uppercase Latin letters);
- we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square.
Given $n$ and $m$, find lexicographically minimum coloring of the table that meets the described properties.
|
The problem could be solved in a standard way - try to fill the table from the first cell to the last and try to put the miminum letter. Consider the first row. Obviously it begins from some letters A (to be exact $min(n, m)$ letters A). When we put some letters A in the first row, we should put several letters A in some next rows to make a square. The next letter could be only B. Describe the solution in general. Assume that we have already considered some rows. Consider row $i$. Some cells in this row could be already painted. Consider unpainted cells from left to the right. For every such cell consider its color from A to Z. Two cases should be considered: Put in this cell the minimum possible letter (neighbours have no such letter) If the previous cell in this row was not painted at the beginning of considering row $i$, now it is already painted. We should try to merge the current cell with the square of the previous cell. Choose the best case from these cases. Try to get the answer on test $n = 13$ $m = 5$ to understand the algorithm better.
|
[
"constructive algorithms",
"greedy"
] | 2,300
| null |
433
|
A
|
Kitahara Haruki's Gift
|
Kitahara Haruki has bought $n$ apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.
But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
|
Denote $G$ as the sum of the weight of the apples. If $G / 100$ is not an even number, then the answer is obviously "NO". Otherwise, we need to check if there is a way of choosing apples, so that the sum of the weight of the chosen apples is exactly $\frac{G}{2}$. A simple $O(n)$ approach would be to enumerate how many 200-gram apples do we choose, and check if we can fill the rest with 100-gram apples. We can also solve this problem using a classic knapsack DP.
|
[
"brute force",
"implementation"
] | 1,100
|
//Template
#include <cstdio>
#include <iostream>
using namespace std;
int n, a = 0, b = 0;
int main(int argc, char *argv[]) {
#ifdef KANARI
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
cin >> n;
for (int i = 1, x; i <= n; ++i) {
cin >> x;
if (x == 100) ++a;
else ++b;
}
int sum = 100 * a + 200 * b;
if (sum % 200 != 0) cout << "NO" << endl;
else {
int half = sum / 2;
bool ans = false;
for (int i = 0; i <= b; ++i)
if (200 * i <= half && half - 200 * i <= a * 100) ans = true;
if (ans) cout << "YES" << endl;
else cout << "NO" << endl;
}
fclose(stdin);
fclose(stdout);
return 0;
}
|
433
|
B
|
Kuriyama Mirai's Stones
|
Kuriyama Mirai has killed many monsters and got many (namely $n$) stones. She numbers the stones from $1$ to $n$. The cost of the $i$-th stone is $v_{i}$. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
- She will tell you two numbers, $l$ and $r (1 ≤ l ≤ r ≤ n)$, and you should tell her $\sum_{i=1}^{r}v_{i}$.
- Let $u_{i}$ be the cost of the $i$-th cheapest stone (the cost that will be on the $i$-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, $l$ and $r (1 ≤ l ≤ r ≤ n)$, and you should tell her $\sum_{i=1}^{r}u_{i}$.
For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
|
Sort sequence $v$ to obtain sequence $u$. Sorting can be done in $O(n\log n)$ using quicksort. Now we are interested in the sum of a interval of a given sequence. This can be done by calculating the prefix sum of the sequence beforehand. That is, let $s v_{i}=\sum_{j=1}^{t}v_{j}$. The sum of numbers in the interval $[l, r]$ would then be $sv_{r} - sv_{l - 1}$. We can deal with sequence $u$ likewise. Preprocessing takes $O(n)$ time, and answering a query is only $O(1)$. The total complexity would be $O(n\log n+q)$.
|
[
"dp",
"implementation",
"sortings"
] | 1,200
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL "%I64d"
const int maxn=100010;
int n,m;
long long y[maxn],z[maxn];
int main()
{
scanf("%d",&n);
for (int a=1;a<=n;a++)
{
int v;
scanf("%d",&v);
y[a]=z[a]=v;
}
sort(y+1,y+n+1);
for (int a=1;a<=n;a++)
z[a]+=z[a-1],y[a]+=y[a-1];
scanf("%d",&m);
for (int a=1;a<=m;a++)
{
int opt,l,r;
scanf("%d%d%d",&opt,&l,&r);
if (opt==1) printf(LL "\n",z[r]-z[l-1]);
else printf(LL "\n",y[r]-y[l-1]);
}
return 0;
}
|
433
|
C
|
Ryouko's Memory Note
|
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.
Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.
Ryouko's notebook consists of $n$ pages, numbered from 1 to $n$. To make life (and this problem) easier, we consider that to turn from page $x$ to page $y$, $|x - y|$ pages should be turned. During analyzing, Ryouko needs $m$ pieces of information, the $i$-th piece of information is on page $a_{i}$. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is $\sum_{i=1}^{m-1}|a_{i+1}-a_{i}|$.
Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page $x$ to page $y$, she would copy all the information on page $x$ to $y (1 ≤ x, y ≤ n)$, and consequently, all elements in sequence $a$ that was $x$ would become $y$. Note that $x$ can be equal to $y$, in which case no changes take place.
Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.
|
Suppose we're merging page $x$ to page $y$. Obviously page $x$ should be an element of sequence $a$, otherwise merging would have no effect. Enumerate all possible values of $x$, and denote sequence $b$ as the elements of $a$ that are adjacent to an element with value $x$. If one element is adjacent to two elements with value $x$, it should appear twice in $b$. However, if one element itself is $x$, it should not appear in $b$. For example, suppose we have $a = {2, 2, 4, 1, 2, 1, 2, 3, 1}$, then sequence $b$ for $x = 2$ would be $b = {4, 1, 1, 1, 3}$, where the 6-th element appears twice. Problem remains for finding a optimum value for $y$. Let $m$ be the length of sequence $b$. When merging $x$ to $y$, the change in answer would be $\sum_{i=1}^{m}|b_{i}-y|-\sum_{i=1}^{m}|b_{i}-x|$ We only care about the left part, as the right part has nothing to do with $y$. We can change our problem to the following: This is, however, a classic problem. We have the following conclusion: Proof: Consider the case where $n$ is odd. Proof is similar for cases where $n$ is even. We choose an arbitary number as $x$. Suppose there are $l$ numbers on the left of $x$, and $r$ numbers on the right of $x$. If $x$ is the median, then $l = r$, so what we're going to prove is that optimal answer cannot be achieved when $l \neq r$. Suppose $l < r$, consider what would happen to the answer if we add $d(d > 0)$ to $x$ (Here we assume that adding $d$ to $x$ does not affect the values of $l$ and $r$). The distance between $x$ and all the numbers on the right would decrease by $d$, while the distance between $x$ and all numbers on the left would increase by $d$. So the answer would decrease by $(r - l)d$, which is a positive value, since $l < r$. So $x$ would keep increasing until $l = r$, when optimal answer can be achieved. Thus $x$ is the median of the $n$ numbers. This brings us to our solution. Simply sort sequence $b$ and find its median, then calculate the answer. The final answer would be the optimal one from all possible values of $x$. The complexity is $O(n\log n)$, as the sum of the length of all $b$ sequences does not exceed $2n$.
|
[
"implementation",
"math",
"sortings"
] | 1,800
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100010;
int n,m,cnt,z[maxn];
pair<int,int> y[maxn<<1];
int main()
{
scanf("%d%d",&n,&m);
for (int a=1;a<=m;a++)
scanf("%d",&z[a]);
long long sum=0;
for (int a=2;a<=m;a++)
{
sum+=abs(z[a]-z[a-1]);
if (z[a]==z[a-1]) continue;
y[++cnt]=make_pair(z[a],z[a-1]);
y[++cnt]=make_pair(z[a-1],z[a]);
}
sort(y+1,y+cnt+1);
long long ans=sum;
for (int a=1;a<=cnt;)
{
int b=a;
while (b<=cnt && y[b].first==y[a].first)
b++;
long long delta=0;
int mid=(a+b-1)>>1;
for (int c=a;c<b;c++)
delta+=abs(y[mid].second-(y[c].second==y[a].first ? y[mid].second : y[c].second))-abs(y[a].first-y[c].second);
ans=min(ans,sum+delta);
a=b;
}
printf("%I64d\n",ans);
return 0;
}
|
433
|
D
|
Nanami's Digital Board
|
Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.
The digital board is $n$ pixels in height and $m$ pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The $j$-th pixel of the $i$-th line is pixel $(i, j)$. The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.
Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel $(i, j)$ belongs to a side of sub-rectangle with $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ as its upper-left and lower-right vertex if and only if it satisfies the logical condition:
\begin{center}
(($i = x_{1}$ or $i = x_{2}$) and ($y_{1} ≤ j ≤ y_{2}$)) or (($j = y_{1}$ or $j = y_{2}$) and ($x_{1} ≤ i ≤ x_{2}$)).
\end{center}
Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them?
|
Consider a similar problem: find the maximum light-block of the whole board. Constraints to this problem are the same as the original problem, but with no further operations. A brute-force idea would be to enumerate all four edges of the block, checking can be done with two-dimensional prefix sums, so the time complexity is $O(n^{4})$. Obviously it would receive a TLE verdict. Why should we enumerate all four edges? Let's enumerate the lower- and upper-edge, and now our problem is only one-dimensional, which can be easily solved in $O(n)$ time. Now our complexity is $O(n^{3})$, still not fast enough. Let's try to enumerate the lower-edge only, and now what we have is an array $up[]$, denoting the maximum "height" of each column. To be specific, suppose the lower-edge is row $x$, then $up[i]$ is the maximum value such that $(x, i), (x - 1, i), ..., (x - up[i] + 1, i)$ are all light. If we choose columns $l$ and $r$ as the left- and right-edge, then the area of the maximum light-block with these three sides fixed would be $\left(r-l+1\right)\left(\operatorname*{min}_{l\leq i\leq r}\left\{u p[i]\right\}\right)$ Let $h=\mathrm{min}_{l\leq i\leq r}\left\{u p[i]\right\}$, what if we enumerate $h$, and find the leftmost $l$ and the rightmost $r$? To be more specific, we enumerate a column $p$, and let the height of this column be the height of the block. Now we want to "stretch" the left and right sides of the block, so we're looking for the leftmost column $l$ such that $operatornameoperatorname*{m i n}_{i\leq i\leq p}\{u p[i]\}=u p[p]$. Similarly look for the rightmost column $r$, then the maximum light block with its lower-edge and a point in the upper-edge fixed would be $(r - l + 1) \cdot up[p]$. This approach can be optimized with disjoint-set unions (abbr. DSU). Imagine that initially the $up[]$ array is empty. Let's add the elements of $up[]$ one by one, from the largest to the smallest. Maintain two DSUs, and denote them as $L$ and $R$.When we add an element $up[i]$, set the father of $i$ as $i + 1$ in $R$, so that $i$ will be "skipped" during the "find" operation of DSU. Similarly set the father of $i$ as $i - 1$ in $L$. Simply find the root of $i$ in $L$ and $R$, and we would have $l$ and $r$. Now this problem can be solved in quasi-quadratic time. We can actually further optimize it to quadratic time using monotonic queues, but we'll not talk about it here. Let's go back to the original problem. Suppose there are no modifications, operations only contain queries. Then we could simply maintain the $up[]$ array of every row, and similarly maintain $down[]$, $left[]$ and $right[]$ arrays. Use the approach described above to achieve quasi-linear time for the answering of a query. Now consider modifications. Modification of a single pixel only changes the values of $O(n + m)$ positions of the arrays. So modifications can be handled in linear time. The total complexity for the algorithm is $O(n^{2} + qn \cdot \alpha (n))$, where $ \alpha (n)$ is the inverse of the Ackermann function, which is often seen in the analysis of the time complexity of DSUs.
|
[
"dsu",
"implementation"
] | 2,000
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<algorithm>
using namespace std;
const int BUF_SIZE = 30;
char buf[BUF_SIZE], *buf_s = buf, *buf_t = buf + 1;
#define PTR_NEXT() \
{ \
buf_s ++; \
if (buf_s == buf_t) \
{ \
buf_s = buf; \
buf_t = buf + fread(buf, 1, BUF_SIZE, stdin); \
} \
}
#define readint(_n_) \
{ \
while (*buf_s != '-' && !isdigit(*buf_s)) \
PTR_NEXT(); \
bool register _nega_ = false; \
if (*buf_s == '-') \
{ \
_nega_ = true; \
PTR_NEXT(); \
} \
int register _x_ = 0; \
while (isdigit(*buf_s)) \
{ \
_x_ = _x_ * 10 + *buf_s - '0'; \
PTR_NEXT(); \
} \
if (_nega_) \
_x_ = -_x_; \
(_n_) = (_x_); \
}
const int maxn=1010;
int n,m,k,z[maxn][maxn],up[maxn][maxn],left[maxn][maxn],right[maxn][maxn],down[maxn][maxn];
int main()
{
readint(n);
readint(m);
readint(k);
for (int a=1;a<=n;a++)
for (int b=1;b<=m;b++)
{
readint(z[a][b]);
if (z[a][b])
{
up[a][b]=up[a-1][b]+1;
left[a][b]=left[a][b-1]+1;
}
}
for (int a=n;a>=1;a--)
for (int b=m;b>=1;b--)
if (z[a][b])
{
right[a][b]=right[a][b+1]+1;
down[a][b]=down[a+1][b]+1;
}
int opt,x,y;
for (int a=1;a<=k;a++)
{
readint(opt);
readint(x);
readint(y);
if (opt==1)
{
z[x][y]^=1;
for (int b=1;b<=n;b++)
if (z[b][y]) up[b][y]=up[b-1][y]+1;
else up[b][y]=0;
for (int b=n;b>=1;b--)
if (z[b][y]) down[b][y]=down[b+1][y]+1;
else down[b][y]=0;
for (int b=1;b<=m;b++)
if (z[x][b]) left[x][b]=left[x][b-1]+1;
else left[x][b]=0;
for (int b=m;b>=1;b--)
if (z[x][b]) right[x][b]=right[x][b+1]+1;
else right[x][b]=0;
}
else
{
int ans=0;
for (int l=y,r=y,v=up[x][y];;)
{
while (l>=1 && up[x][l]>=v)
l--;
l++;
while (r<=m && up[x][r]>=v)
r++;
r--;
ans=max(ans,(r-l+1)*v);
if (l>1)
{
if (r<m)
{
if (up[x][l-1]>=up[x][r+1]) v=up[x][--l];
else v=up[x][++r];
}
else v=up[x][--l];
}
else
{
if (r<m) v=up[x][++r];
else break;
}
}
for (int l=y,r=y,v=down[x][y];;)
{
while (l>=1 && down[x][l]>=v)
l--;
l++;
while (r<=m && down[x][r]>=v)
r++;
r--;
ans=max(ans,(r-l+1)*v);
if (l>1)
{
if (r<m)
{
if (down[x][l-1]>=down[x][r+1]) v=down[x][--l];
else v=down[x][++r];
}
else v=down[x][--l];
}
else
{
if (r<m) v=down[x][++r];
else break;
}
}
for (int l=x,r=x,v=left[x][y];;)
{
while (l>=1 && left[l][y]>=v)
l--;
l++;
while (r<=n && left[r][y]>=v)
r++;
r--;
ans=max(ans,(r-l+1)*v);
if (l>1)
{
if (r<n)
{
if (left[l-1][y]>=left[r+1][y]) v=left[--l][y];
else v=left[++r][y];
}
else v=left[--l][y];
}
else
{
if (r<n) v=left[++r][y];
else break;
}
}
for (int l=x,r=x,v=right[x][y];;)
{
while (l>=1 && right[l][y]>=v)
l--;
l++;
while (r<=n && right[r][y]>=v)
r++;
r--;
ans=max(ans,(r-l+1)*v);
if (l>1)
{
if (r<n)
{
if (right[l-1][y]>=right[r+1][y]) v=right[--l][y];
else v=right[++r][y];
}
else v=right[--l][y];
}
else
{
if (r<n) v=right[++r][y];
else break;
}
}
printf("%d\n",ans);
}
}
return 0;
}
|
433
|
E
|
Tachibana Kanade's Tofu
|
Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.
Each piece of tofu in the canteen is given a $m$-based number, all numbers are in the range $[l, r]$ ($l$ and $r$ being $m$-based numbers), and for every $m$-based integer in the range $[l, r]$, there exists a piece of tofu with that number.
To judge what tofu is Mapo Tofu, Tachibana Kanade chose $n$ $m$-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero.
Tachibana Kanade considers tofu with values no more than $k$ to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu?
|
A straightforward brute-force idea would be to enumerate all numbers in the interval $[l, r]$, and count how many of them have a value greater than $k$. This approach is way too slow, but nevertheless let's try optimizing it first. The enumeration part seems hard to optimize, so let's consider what is the fastest way of calculating the value of a string. This is a classic problem that can be solved using an Aho-Corasick automaton (abbr. ACA). Build an ACA with the given number strings, and simply "walk" in the automaton according to the string to be calculated. Consider a common method when dealing with digits - split the interval $[l, r]$ into two, $[1, r]$ minus $[1, l - 1]$. Then use DP to solve an interval, take $[1, r]$ for instance. Consider filling in the numbers one by one, we need to record in the states of the DP the position in the string, and a flag denoting whether we're "walking on the edge of the upper bound", that is, whether the numbers we've filled are the prefix of the upper-bound $r$. How can we use the approach above in this problem? Can we combine this approach with our ACA? The answer is yes, further record in the states of the DP the ID of the node we're currently "standing on" in the ACA. Consider the transfer of this DP, enumerate which number we're going to fill in, and check using our flag if the current number will be greater than the upper-bound. Appending a number to the end of our string would result in a change of the ID of the node in our ACA, so "walk" along the transferring edge in the ACA. What about the limit of values? Simply record the current value in our DP state, during transfer, add the value stored in the ACA's node to the value stored in our state. The tricky bit is the leading zeros. Numbers can't have leading zeros, but number strings can. How can we distinguish leading zeros from zeros in the middle of the number? We keep another flag, denoting whether we're still dealing with leading zeros. So finally our state looks like $f[len][node][val][upper_bound_flag][leading_zero_flag]$, where $len$, $node$, and $val$ are current length of number, ID of current node in ACA, and current value of number respectively. Let $N$ be the total length of all number string, and $L$ be the length of $r$, the total complexity would be $O(NLkm)$, since the number of states is $O(NLk)$ and transfer takes $O(m)$ time.
|
[
"dp"
] | 2,500
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define inc(a,b) {a+=b;if (a>=mo) a-=mo;}
#define newnode ++wmt
const int maxn=210;
const int maxm=22;
const int maxk=510;
const int maxp=210;
const int mo=1000000007;
int n,m,k,llen,rlen,wmt,root,f[maxn][maxp][maxk][2],l[maxn],r[maxn],s[maxn],q[maxp];
struct node
{
int next[maxm];
int value,fail;
node()
{
memset(next,0,sizeof(next));
value=fail=0;
}
}z[maxp];
void insert(int *s,int l,int v)
{
int p=root;
for (int a=1;a<=l;a++)
{
if (!z[p].next[s[a]]) z[p].next[s[a]]=newnode;
p=z[p].next[s[a]];
}
z[p].value+=v;
}
void build_AC()
{
int front=1,tail=1;
q[1]=root;
for (;front<=tail;)
{
int now=q[front++];
for (int a=0;a<m;a++)
if (z[now].next[a])
{
int p=z[now].fail;
while (p)
{
if (z[p].next[a])
{
z[z[now].next[a]].fail=z[p].next[a];
break;
}
p=z[p].fail;
}
if (!p) z[z[now].next[a]].fail=root;
z[z[now].next[a]].value+=z[z[z[now].next[a]].fail].value;
q[++tail]=z[now].next[a];
}
else
{
z[now].next[a]=z[z[now].fail].next[a];
if (!z[now].next[a]) z[now].next[a]=root;
}
}
}
int solve(int *y,int l)
{
if (!l) return 0;
int ans=0;
for (int a=1;a<l;a++)
for (int b=1;b<=wmt;b++)
for (int c=0;c<=k;c++)
inc(ans,f[a][b][c][0]);
for (int a=l;a>=1;a--)
for (int b=1;b<=wmt;b++)
for (int c=(a==l);c+(a!=1)<=y[a];c++)
{
int p=b,delta=0;
p=z[p].next[c];
delta+=z[p].value;
for (int d=a+1;d<=l;d++)
{
p=z[p].next[y[d]];
delta+=z[p].value;
}
for (int d=0;d<=k-delta;d++)
for (int e=0;e<=1;e++)
inc(ans,f[a-1][b][d][e]);
}
return ans;
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
scanf("%d",&llen);
for (int a=llen;a>=1;a--)
scanf("%d",&l[a]);
scanf("%d",&rlen);
for (int a=rlen;a>=1;a--)
scanf("%d",&r[a]);
root=newnode;
for (int a=1,v;a<=n;a++)
{
int l;
scanf("%d",&l);
for (int b=1;b<=l;b++)
scanf("%d",&s[b]);
reverse(s+1,s+l+1);
scanf("%d",&v);
insert(s,l,v);
}
build_AC();
n=max(llen,rlen);
f[0][root][0][0]=1;
for (int a=0;a<n;a++)
for (int b=1;b<=wmt;b++)
for (int c=0;c<=k;c++)
for (int d=0;d<=1;d++)
if (f[a][b][c][d])
for (int e=0;e<m;e++)
if (c+z[z[b].next[e]].value<=k) inc(f[a+1][z[b].next[e]][c+z[z[b].next[e]].value][e==0],f[a][b][c][d]);
l[1]--;
for (int a=1;a<=llen;a++)
if (l[a]<0) l[a]+=m,l[a+1]--;
else break;
if (!l[llen]) llen--;
printf("%d\n",(solve(r,rlen)-solve(l,llen)+mo)%mo);
return 0;
}
|
434
|
D
|
Nanami's Power Plant
|
Nanami likes playing games, and is also really good at it. This day she was playing a new game which involved operating a power plant. Nanami's job is to control the generators in the plant and produce maximum output.
There are $n$ generators in the plant. Each generator should be set to a generating level. Generating level is an integer (possibly zero or negative), the generating level of the $i$-th generator should be between $l_{i}$ and $r_{i}$ (both inclusive). The output of a generator can be calculated using a certain quadratic function $f(x)$, where $x$ is the generating level of the generator. Each generator has its own function, the function of the $i$-th generator is denoted as $f_{i}(x)$.
However, there are $m$ further restrictions to the generators. Let the generating level of the $i$-th generator be $x_{i}$. Each restriction is of the form $x_{u} ≤ x_{v} + d$, where $u$ and $v$ are IDs of two different generators and $d$ is an integer.
Nanami found the game tedious but giving up is against her creed. So she decided to have a program written to calculate the answer for her (the maximum total output of generators). Somehow, this became your job.
|
We can use a flow network to solve the problem. For each variable $x_{i}$, create $r_{i} - l_{i} + 2$ points, and denote them as $node(i, l_{i} - 1)$ to $node(i, r_{i})$. Edges are as follows: Let $C$ be the value of the minimum cut of this network. If there are no further restrictions, it is obvious that $MAX \cdot n - C$ is the maximum profit. Now consider the restrictions. Suppose a restriction is $x_{u} \le x_{v} + d$, then for each $node(u, x)$, link it to $node(v, x - d)$ (if exists) with a capacity of infinity. If there exists a solution, $MAX \cdot n - C$ will be the optimal profit. We want to prove that the edges with infinite capacity can really restrict our choice of values for variables. Note that a valid solution is correspondent to a cut of the graph. It can be proved that if a restriction is not satisfied, there will be a augmenting path in the graph. You can verify this by drawing the graphs. And because we are looking for the minimum cut, in this case the maximum sum, there can be no valid solution with a greater sum.
|
[
"flows"
] | 2,900
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define node(a,b) (b-l[a]+start[a])
const int maxn=50*201+10;
const int maxm=(60*210+100)*2;
const int INF=0x3f3f3f3f;
int n,m,en,q[maxn],depth[maxn],l[60],r[60],start[60],A[60],B[60],C[60],s,t;
struct edge
{
int e,f;
edge *next,*op;
}*v[maxn],ed[maxm];
void add_edge(int s,int e,int f)
{
en++;
ed[en].next=v[s];v[s]=ed+en;v[s]->e=e;v[s]->f=f;
en++;
ed[en].next=v[e];v[e]=ed+en;v[e]->e=s;v[e]->f=0;
v[s]->op=v[e];v[e]->op=v[s];
}
bool bfs()
{
int front=1,tail=1;
q[1]=s;
memset(depth,0,sizeof(depth));
depth[s]=1;
for (;front<=tail;)
{
int now=q[front++];
for (edge *e=v[now];e;e=e->next)
if (e->f && !depth[e->e])
{
depth[e->e]=depth[now]+1;
if (e->e==t) return true;
q[++tail]=e->e;
}
}
return false;
}
int dfs(int now,int cur_flow)
{
if (now==t) return cur_flow;
int rest=cur_flow;
for (edge *e=v[now];e && rest;e=e->next)
if (e->f && depth[e->e]==depth[now]+1)
{
int new_flow=dfs(e->e,min(e->f,rest));
e->f-=new_flow;
e->op->f+=new_flow;
rest-=new_flow;
}
if (rest==cur_flow) depth[now]=-1;
return cur_flow-rest;
}
int dinic()
{
int ans=0;
while (bfs())
ans+=dfs(s,INF);
return ans;
}
int f(int x,int y)
{
return y*y*A[x]+y*B[x]+C[x];
}
int main()
{
scanf("%d%d",&n, &m);
for (int a=1;a<=n;a++)
scanf("%d%d%d",&A[a],&B[a],&C[a]);
int maxv=-INF;
int tot=0;
for (int a=1;a<=n;a++)
{
scanf("%d%d",&l[a],&r[a]);
start[a]=tot+1;
tot+=r[a]-l[a]+2;
for (int b=l[a];b<=r[a];b++)
maxv=max(maxv,f(a,b));
}
s=0;t=tot+1;
for (int a=1;a<=n;a++)
{
add_edge(s,start[a],INF);
for (int b=l[a];b<=r[a];b++)
add_edge(node(a,b),node(a,b+1),maxv-f(a,b));
add_edge(node(a,r[a]+1),t,INF);
}
for (int a=1;a<=m;a++)
{
int s,e,d;
scanf("%d%d%d",&s,&e,&d);
for (int b=l[s];b<=r[s];b++)
if (b-d>=l[e] && b-d<=r[e]+1) add_edge(node(s,b),node(e,b-d),INF);
}
printf("%d\n",maxv*n-dinic());
return 0;
}
|
434
|
E
|
Furukawa Nagisa's Tree
|
One day, Okazaki Tomoya has bought a tree for Furukawa Nagisa's birthday. The tree is so strange that every node of the tree has a value. The value of the $i$-th node is $v_{i}$. Now Furukawa Nagisa and Okazaki Tomoya want to play a game on the tree.
Let $(s, e)$ be the path from node $s$ to node $e$, we can write down the sequence of the values of nodes on path $(s, e)$, and denote this sequence as $S(s, e)$. We define the value of the sequence $G(S(s, e))$ as follows. Suppose that the sequence is $z_{0}, z_{1}...z_{l - 1}$, where $l$ is the length of the sequence. We define $G(S(s, e)) = z_{0} × k^{0} + z_{1} × k^{1} + ... + z_{l - 1} × k^{l - 1}$. If the path $(s, e)$ satisfies $G(S(s,e))\equiv x({\mathrm{mod~}}y)$, then the path $(s, e)$ belongs to Furukawa Nagisa, otherwise it belongs to Okazaki Tomoya.
Calculating who has more paths is too easy, so they want to play something more difficult. Furukawa Nagisa thinks that if paths $(p_{1}, p_{2})$ and $(p_{2}, p_{3})$ belong to her, then path $(p_{1}, p_{3})$ belongs to her as well. Also, she thinks that if paths $(p_{1}, p_{2})$ and $(p_{2}, p_{3})$ belong to Okazaki Tomoya, then path $(p_{1}, p_{3})$ belongs to Okazaki Tomoya as well. But in fact, this conclusion isn't always right. So now Furukawa Nagisa wants to know how many triplets $(p_{1}, p_{2}, p_{3})$ are correct for the conclusion, and this is your task.
|
In order not to mess things up, we use capital letters $X$, $Y$ and $K$ to denote the values in the original problem. First, we can build a directed graph with $n^{2}$ edges. Let $E(i, j)$ be the edge from node $i$ to node $j$. If path $(i, j)$ is good, the color of $E(i, j)$ is $0$, otherwise it is $1$. We want to calculate the number of triplets $(i, j, k)$ that satisfies $(i, j)$, $(j, k)$ and $(i, k)$ are all good or all not good. It equals the number of directed triangles, the color of whose three edges are the same. (The triangle is like: $i\rightarrow j,j\rightarrow k,i\rightarrow k$) Calculating this is difficult, so let us calculate the number of directed triangles whose three edges are not all the same. Let $in0[i]$ be the number of in-edges of node $i$ whose color is $0$. Similarly define $in1[i]$, $out0[i]$, $out1[i]$. Let $p=\sum_{1\leq i\leq n}\left(2\cdot o u t{\hat{v}}[i]\cdot o u t{\hat{v}}[i]+2\cdot i n0[i]\cdot i n{\hat{v}}|i\right]+i n![i]\cdot o u t{\hat{v}}|i]+i n][i]\cdot o u t{\hat{v}}|i]+i n][i]\cdot o u t{\hat{v}}|i]\cdot e u t{\hat{v}}|i]+i n{\hat{v}}|i\rangle$ We can see that the answer is twice the number of triangles whose three edges are not all the same. So we can see the answer of the original problem is $n^{3} - p / 2$. It's certain that $out0[i] + out1[i] = in0[i] + in1[i] = n$, so we only need to calculate out0 and in0. Let us calculate $out0$ first. We can use the "Divide and Conquer on trees" algorithm to solve this in $O(n\log^{2}n)$ time. Choose a root $i$ and get its subtree, we can get all the values of the paths from a node in the subtree to node $i$. We save the values and the lengths of the paths. For a path from node $j$ with value $v$ and length $l$, we want to find a node $k$ which makes $G(S(j, k)) \equiv X (mod Y)$. Let $H(i, j)$ be the sequence of the value of nodes on $(i, j)$ except node $i$, then $G(S(j, k)) = G(S(j, i)) + G(H(i, k)) \cdot K^{l} = v + G(H(i, k)) \cdot K^{l}$ As $(v + G(H(i, k)) \cdot K^{l}) \equiv X (mod Y)$, so $G(H(i, k)) = (X - v) / K^{l}$. As $Y$ is a prime number, we can get $(x - v) / K^{l}$ easily. Let $z = (x - v) / K^{l}$, then the problem becomes that we need to calculate how many paths from node $i$ to a node in the subtree except node $i$, whose value is $z$, this can be done by doing binary search on a sorted array. So we can get $out0$, and $in0$ likewise. With these two arrays we can calculate the answer. The total complexity is $O(n\log^{2}n)$.
|
[
"binary search",
"divide and conquer",
"sortings",
"trees"
] | 3,000
|
//Template
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <climits>
#include <map>
#include <vector>
using namespace std;
typedef long long ll;
#define N 100000
struct edge {
int next, node;
} e[N << 1 | 1];
int head[N + 1], tot = 0;
inline void addedge(int a, int b) {
e[++tot].next = head[a];
head[a] = tot, e[tot].node = b;
}
int n, mod, k, X, w[N + 1], size[N + 1], ms[N + 1], q[N + 1], cnt, kpow[N + 1], kinv[N + 1];
bool v[N + 1];
inline int pw(int a, int b) {
int r = 1;
while (b > 0) {
if (b & 1) r = (ll)r * a % mod;
a = (ll)a * a % mod;
b >>= 1;
}
return r;
}
void getSize(int x, int f) {
size[x] = 1, ms[x] = 0, q[++cnt] = x;
for (int i = head[x]; i; i = e[i].next) {
int node = e[i].node;
if (v[node] || node == f) continue;
getSize(node, x);
size[x] += size[node];
ms[x] = max(ms[x], size[node]);
}
}
int center(int x) {
cnt = 0, getSize(x, 0);
int val = INT_MAX, p = -1;
for (int i = 1; i <= cnt; ++i) {
int s = max(size[x] - size[q[i]], ms[q[i]]);
if (s < val) val = s, p = q[i];
}
return p;
}
int dep[N + 1], dt[N + 1], df[N + 1], in[N + 1], out[N + 1], target[N + 1];
// depth, value on path to x, value on path from x
void getDist(int x, int f) {
for (int i = head[x]; i; i = e[i].next) {
int node = e[i].node;
if (v[node] || node == f) continue;
dep[node] = dep[x] + 1;
dt[node] = (dt[x] + (ll)w[node] * kpow[dep[node]]) % mod;
df[node] = ((ll)df[x] * k + w[node]) % mod;
getDist(node, x);
}
}
vector <int> child[N + 1];
void color(int x, int f, int c) {
child[c].push_back(x);
for (int i = head[x]; i; i = e[i].next) {
int node = e[i].node;
if (v[node] || node == f) continue;
color(node, x, c);
}
}
map <int, int> from, to;
map <int, int> :: iterator it;
void add(map <int, int> &h, int k, int x) {
it = h.find(k);
if (it == h.end()) h[k] = x;
else it->second += x;
}
int find(map <int, int> &h, int k) {
it = h.find(k);
if (it == h.end()) return 0;
return it->second;
}
void solve() {
from.clear(), to.clear();
for (int i = 1; i <= cnt; ++i) {
int node = q[i];
for (int j = 0; j < child[node].size(); ++j) {
int p = child[node][j];
add(to, dt[p], 1);
}
}
for (int i = 1; i <= cnt; ++i) {
int node = q[i];
for (int j = 0; j < child[node].size(); ++j) {
int p = child[node][j];
add(to, dt[p], -1);
}
for (int j = 0; j < child[node].size(); ++j) {
int p = child[node][j];
out[p] += find(to, target[p]);
in[p] += find(from, dt[p]);
}
for (int j = 0; j < child[node].size(); ++j) {
int p = child[node][j];
add(from, target[p], 1);
}
}
}
void divide(int x) {
x = center(x);
v[x] = true;
dt[x] = df[x] = w[x], dep[x] = 0;
getDist(x, 0);
for (int i = 1; i <= cnt; ++i)
if (q[i] == x) {
if (dt[q[i]] == X) ++out[x], ++in[x];
} else {
if (dt[q[i]] == X) ++out[x], ++in[q[i]];
if (df[q[i]] == X) ++in[x], ++out[q[i]];
}
cnt = 0;
for (int i = head[x]; i; i = e[i].next) {
int node = e[i].node;
if (v[node]) continue;
child[node].clear(), q[++cnt] = node;
color(node, 0, node);
for (int j = 0; j < child[node].size(); ++j) {
int p = child[node][j];
target[p] = ((ll)(X - df[p] + mod) * kinv[dep[p]] + w[x]) % mod;
}
}
// IN on the LEFT and OUT on the RIGHT
solve();
// OUT on the LEFT and IN on the RIGHT
reverse(q + 1, q + cnt + 1);
solve();
for (int i = head[x]; i; i = e[i].next) {
int node = e[i].node;
if (v[node]) continue;
divide(node);
}
}
int main(int argc, char *argv[]) {
#ifdef KANARI
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cin >> n >> mod >> k >> X;
for (int i = 1; i <= n; ++i) cin >> w[i];
for (int i = 1; i < n; ++i) {
int x, y;
cin >> x >> y;
addedge(x, y), addedge(y, x);
}
kpow[0] = 1;
for (int i = 1; i <= n; ++i) {
kpow[i] = (ll)kpow[i - 1] * k % mod;
kinv[i] = pw(kpow[i], mod - 2);
}
divide(1);
ll ans = 0LL;
for (int i = 1; i <= n; ++i) {
ans += (ll)in[i] * (n - in[i]) * 2LL;
ans += (ll)out[i] * (n - out[i]) * 2LL;
ans += (ll)in[i] * (n - out[i]) + (ll)(n - in[i]) * out[i];
}
ans = (ll)n * n * n - ans / 2LL;
cout << ans << endl;
fclose(stdin);
fclose(stdout);
return 0;
}
|
435
|
A
|
Queue on Bus Stop
|
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.
The bus stop queue has $n$ groups of people. The $i$-th group from the beginning has $a_{i}$ people. Every $30$ minutes an empty bus arrives at the bus stop, it can carry at most $m$ people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue.
Your task is to determine how many buses is needed to transport all $n$ groups to the dacha countryside.
|
The problem could be solved in one cycle by groups. The solution could be implemented in this way:
|
[
"implementation"
] | 1,000
| null |
435
|
B
|
Pasha Maximizes
|
Pasha has a positive integer $a$ without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.
Help Pasha count the maximum number he can get if he has the time to make at most $k$ swaps.
|
The problem could solved by greedy algorithm. We will try to pull maximum digits to the beginning. The algorithm could be described in this way: 1) Consider every position in the number from the first, assume that the current position is $i$ 2) Find the nearest maximum digit from the next $k$ digits of the number, assume that this digit is on position $j$ 3) If this maximum digit is greater than current digit on position $i$, then make series of swaps, push this digit to position $i$, also decrease $k$, that is do $k = k - (j - i)$
|
[
"greedy"
] | 1,400
| null |
435
|
C
|
Cardiogram
|
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
\[
(0;0),(a_{1};a_{1}),(a_{1}+a_{2};a_{1}-a_{2}),(a_{1}+a_{2}+a_{3};a_{1}-a_{2}+a_{3}),\ldots,(\sum_{i=1}^{n}a_{i};\sum_{i=1}^{n}(-1)^{i+1}a_{i}).
\]
That is, a cardiogram is fully defined by a sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$.
Your task is to paint a cardiogram by given sequence $a_{i}$.
|
This problem is technical, you should implement what is written in the statement. First, you need to calc coordinates of all points of the polyline. Also create matrix for the answer. Coordinate $y$ could become negative, so it is useful to double the sizes of the matrix and move the picture up to $1000$. In the end you should print the answer without unnecessary empty rows. To paint the cardiogram you should consider every consecutive pair of points of the polyline and set characters in the answer matrix between them. If the polyline goes up then set slash, otherwise set backslash. To understand the solution better please paint the first test case on the paper, mark coordinates of the points and find what values to set in cycles in your program.
|
[
"implementation"
] | 1,600
| null |
435
|
D
|
Special Grid
|
You are given an $n × m$ grid, some of its nodes are black, the others are white. Moreover, it's not an ordinary grid — each unit square of the grid has painted diagonals.
The figure below is an example of such grid of size $3 × 5$. Four nodes of this grid are black, the other $11$ nodes are white.
Your task is to count the number of such triangles on the given grid that:
- the corners match the white nodes, and the area is positive;
- all sides go along the grid lines (horizontal, vertical or diagonal);
- no side contains black nodes.
|
Values $n$ and $m$ are not so large, so the solution with complexity $O(max(n, m)^{3})$ should pass. It means that you should consider all triangles and check all conditions in $O(1)$. To make this check you should precalc arrays of partial sums on all diagonals, rows and columns. After that you could check, that there is no black nodes on the side using one sum-query. Some hints about this problem and the implementation: all correct triangles are isosceles right triangles; either all legs or hypotenuse of the triangle is parallel to the sides of the grid; if you know how to solve the problem for two types of the triangles, you can get the whole solution making 4 rotates of the matrix.
|
[
"brute force",
"dp",
"greedy"
] | 2,000
| null |
435
|
E
|
Special Graph
|
In this problem you will need to deal with an $n × m$ grid graph. The graph's vertices are the nodes of the $n × m$ grid. The graph's edges are all the sides and diagonals of the grid's unit squares.
The figure below shows a $3 × 5$ graph. The black lines are the graph's edges, the colored circles are the graph's vertices. The vertices of the graph are painted on the picture for a reason: the coloring is a correct vertex coloring of the $3 × 5$ graph into four colors. A graph coloring is correct if and only if each vertex is painted and no two vertices connected by an edge are painted the same color.
You are given the size of the grid graph $n × m$ and the colors of some of its vertices. Find any way how to paint the unpainted vertices of the graph in 4 colors to make the final coloring a correct vertex graph coloring. If there is no such correct vertex coloring, say that the answer doesn't exist.
|
To solve this problem you have to paint different correct colorings on the paper. After it you could observe that there are two types of them: vertical and horizontal. Vertical colorings looks like this: acbcbd... bdadac... acbcbd... bdadac... acbcbd... bdadac... ...... In other words, each vertical has only two colors, odd verticals have equal colors, even verticals have two others. The order of the colors on every vertical could be arbitrary. Horizontal colorings are the same, they are rotated by 90 degrees. Of course, there are both vertical and horizontal colorings, but it doesn't change the solution. So, you should consider every type of described colorings and check them. That is, you could choose what colors are on the verticals or what colors are on horizontals and check that obtained coloring matches the given matrix. The solution's complexity is $O(n \times m)$.
|
[] | 2,500
| null |
436
|
A
|
Feed with Candy
|
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.
One day, Om Nom visited his friend Evan. Evan has $n$ candies of two types (fruit drops and caramel drops), the $i$-th candy hangs at the height of $h_{i}$ centimeters above the floor of the house, its mass is $m_{i}$. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most $x$ centimeter high jumps. When Om Nom eats a candy of mass $y$, he gets stronger and the height of his jump increases by $y$ centimeters.
What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?
|
In this problem types of eaten candies must alternate. It means that the type of first eaten candy dictated the types of all the following candies. There are only two possible types so we should consider each type as a type of first eaten candy separatelly and then pick the most optimal. So, what if Om Nom wants to eat a candy of type $t$ and can jump up to $h$? It is obvious that best option is to eat a candy with maximal mass among all the candies he can eat at this time.
|
[
"greedy"
] | 1,500
| null |
436
|
B
|
Om Nom and Spiders
|
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.
The park can be represented as a rectangular $n × m$ field. The park has $k$ spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.
Om Nom isn't yet sure where to start his walk from but he definitely wants:
- to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders);
- to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).
We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.
Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.
|
Let us number columns with integers from $0$ from left to right and rows from $0$ from top to bottom. In the cell $(x, y)$ at the time $t$ only four spiders can be at this cell: Spider, which is moving left and started at $(x, y + t)$. Spider, which is moving right and started at $(x, y - t)$. Spider, which is moving up and started at $(x + t, y)$. Spider, which is moving down and started at $(x - t, y)$. Let iterate through all possible starting positions of Om Nom. Consider that he starts at column $y$. At time $0$ all spiders are on their initial positions and Om Nom is at $(0, y)$. There is no spiders at row $0$, so at time $0$ Om Nom can not meet any spiders. When Om Nom is at cell $(x, y)$, it means that $x$ units of time passed after the start. So to calculate the number of spiders, that Om Nom meets it is enought to check only $4$ cells stated above.
|
[
"implementation",
"math"
] | 1,400
| null |
436
|
C
|
Dungeons and Candies
|
During the loading of the game "Dungeons and Candies" you are required to get descriptions of $k$ levels from the server. Each description is a map of an $n × m$ checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.
When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level $A$:
- You can transmit the whole level $A$. Then you need to transmit $n·m$ bytes via the network.
- You can transmit the difference between level $A$ and some previously transmitted level $B$ (if it exists); this operation requires to transmit $d_{A, B}·w$ bytes, where $d_{A, B}$ is the number of cells of the field that are different for $A$ and $B$, and $w$ is a constant. Note, that you should compare only the corresponding cells of levels $A$ and $B$ to calculate $d_{A, B}$. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other.
Your task is to find a way to transfer all the $k$ levels and minimize the traffic.
|
Let's consider a weighted undirected graph with $k + 1$ vertex. Label the vertices with numbers from $0$ to $k$. Vertices from $1$ to $k$ correspond to levels. For each pair of levels $i$ and $j$ add an edge between vertices $i$ and $j$ with weight equal to the cost of transferring one level as a difference from the other level. For each level $i$ add an edge from vertex $0$ to vertex $i$ with weight equal to $n \cdot m$, i.e. cost of transmitting the whole level. Each way to transmit levels defined an spanning tree of this graph. So to solve the problem, we must find a minimal spanning tree of this graph.
|
[
"dsu",
"graphs",
"greedy",
"trees"
] | 1,800
| null |
436
|
D
|
Pudding Monsters
|
Have you ever played Pudding Monsters? In this task, a simplified one-dimensional model of this game is used.
Imagine an infinite checkered stripe, the cells of which are numbered sequentially with integers. Some cells of the strip have monsters, other cells of the strip are empty. All monsters are made of pudding, so if there are two monsters in the neighboring cells, they stick to each other (literally). Similarly, if several monsters are on consecutive cells, they all stick together in one block of monsters. We will call the stuck together monsters a block of monsters. A detached monster, not stuck to anyone else, is also considered a block.
In one move, the player can take any block of monsters and with a movement of his hand throw it to the left or to the right. The selected monsters will slide on until they hit some other monster (or a block of monsters).
For example, if a strip has three monsters in cells $1$, $4$ and $5$, then there are only four possible moves: to send a monster in cell $1$ to minus infinity, send the block of monsters in cells $4$ and $5$ to plus infinity, throw monster $1$ to the right (it will stop in cell $3$), throw a block of monsters in cells $4$ and $5$ to the left (they will stop in cells $2$ and $3$).
Some cells on the strip are marked with stars. These are the special cells. The goal of the game is to make the largest possible number of special cells have monsters on them.
You are given the numbers of the special cells on a strip as well as the initial position of all monsters. What is the maximum number of special cells that will contain monsters in the optimal game?
|
This problem can be solved using dynamic programming. Let's introduce some designations: $sum(l, r)$ - number of special cells on the segment $[l, r]$, $z_{i}$ - maximal number of covered special cells using only first $i$ monsters, $d_{i}$ - maximal number of covered special cells using only first $i$ monsters and with $i$-th monster not moving. How to calculate $d_{i}$. Let's denote $i$-th monster position as $r$. Let's iterate through all special cells to the left of $i$-th monster. Let's denote current special cell position as $l$. Let's consider the situation when this cell is the leftmost special cell in the block of monsters with $i$-th monster in it. So we need $r - l$ additional monsters to get to this cell from monster $i$. So the value of $d_{i}$ can be updated with $z_{i - (r - l)} + sum(l, r)$. Now, after we computed new value of $d_{i}$, we need to update some values of $z_{j}$. Let's denote $i$-th monster position as $l$. Let's iterate through all special cells to the right of $i$-th monster. Let's denote current special cell position as $r$. Let's consider the situation when this cell is the rightmost special cell in the block of monsters with $i$-th monster in it. So we need $r - l$ additional monsters to get to this cell from monster $i$. So we can update the value $z_{i + (r - l)}$ with $d_{i} + sum(l + 1, r)$. Also, $z_{i}$ should be updated with $z_{i - 1}$. So the solution works in $O(n \cdot m)$ because for each of $n$ monsters we iterate through all $m$ special cells and for a fixed monster-cell pair all computing is done in $O(1)$. There are some details about monsters, that are merged at the initial state, but they are pretty easy to figure out.
|
[
"dp"
] | 2,800
| null |
436
|
E
|
Cardboard Box
|
Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels.
Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: $a_{i}$ — how long it takes to complete the level for one star, $b_{i}$ — how long it takes to complete the level for two stars $(a_{i} < b_{i})$.
You want to open the next box as quickly as possible. So, you need to earn at least $w$ stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels.
|
In this task you have to come with the proper greedy algorithms. Several algorithms will fit, let's describe one of them: From that point we will consider that the levels are sorted by increasing value of $b$. Let's look at some optimal solution (a set of completed levels). From levels that we completed for two stars, select the level $k$ with the largest $b[k]$. It turns out that all levels that stand before $k$ (remember, the levels are sorted) should be completed for at least one star. Otherwise, we could complete some of the previous levels instead of the level $k$. This won't increase the cost. Let's fix a prefix of the first $L$ levels and solve the problem with the assumption that each of the selected levels should be completed. Additionally, we will assume that all levels that are completed for two stars are within this prefix (as was shown before, such prefix of $L$ levels always exists for some optimal solution). As we will surely complete this $L$ levels, we can imagine that we have initially completed all of the for just one star. So, we have $w - L$ more stars to get. We can get these stars either by completing some of the levels that are outside our prefix for one star, or by completing some of the first $L$ levels for two stars instead of one star. It's clear that we just have to choose $w - L$ cheapest options, which correspond to $w - L$ smallest numbers among the following: $b[i] - a[i]$ for $i \le L$ and $a[i]$ for $i > L$. Computing the sum of these smallest values can be done with a data structure like Cartesian tree or BIT. The described solution has time completixy of $O(n log n)$.
|
[
"data structures",
"greedy"
] | 2,600
| null |
436
|
F
|
Banners
|
All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads.
Suppose that a paid version of the app costs $p$ ($p$ is an integer) rubles, and the free version of the application contains $c$ ad banners. Each user can be described by two integers: $a_{i}$ — the number of rubles this user is willing to pay for the paid version of the application, and $b_{i}$ — the number of banners he is willing to tolerate in the free version.
The behavior of each member shall be considered strictly deterministic:
- if for user $i$, value $b_{i}$ is at least $c$, then he uses the free version,
- otherwise, if value $a_{i}$ is at least $p$, then he buys the paid version without advertising,
- otherwise the user simply does not use the application.
Each user of the free version brings the profit of $c × w$ rubles. Each user of the paid version brings the profit of $p$ rubles.
Your task is to help the application developers to select the optimal parameters $p$ and $c$. Namely, knowing all the characteristics of users, for each value of $c$ from $0$ to $(max b_{i}) + 1$ you need to determine the maximum profit from the application and the corresponding parameter $p$.
|
Task F was the hardest one in the problemset. To better understand the solution, let's look at the task from the geometrical point of view. Imagine that people are point in the $Opc$ plane (value of $p$ and $q$ are points' coordinates). Then for each line horizontal $c = i$ we have to find such vertical line $p = j$ that maximizes some target function. The function is computed as follows: (number of points not below $c = i$, multiplied by $w \cdot i$) plus (number of points below $c = i$ and not to the left of $p = j$, multiplied by $j$). Let's move scanning line upwards (consider values $c = 0$, then $c = 1$, etc). For each value of $p$ we will store the value $d[p]$ - the value of the target function with the current value of $c$ and this value of $p$. The problem is: if we have such array $d[]$ for the value $c$, how to recompute it for the value $c + 1$? Let's look at all people that will be affected by the increase of $c$: these are the people with $b[i] = c$. With the current $c$ they are still using free version, after the increase they won't. Each of these people makes the following effect to the array: $d[1] + = 1$, $d[2] + = 2$, ..., $d[b[i]] + = b[i]$ Now the task can be reduced to the problem related with data structures. There are two types of queries: add the increasing arithmetical progression to the prefix of the array and retrieve the maximum value of the array. One of the way to solve it is to use sqrt-decomposition. Let's divide all queries into groups of size $sqrt(q)$. Let's denote the queries from the group as a sequence: $p_{1}, p_{2}, ..., p_{k}$ $(k = sqrt(q))$. For query $p_{i}$ we should perform assignments $d[1] + = 1$, $d[2] + = 2$, ..., $d[p_{i}] + = p_{i}$. Imagine we already preformed all the queries. Each value of new array $d[]$ can be represented as $d[i] = oldD[i] + i \cdot coef[i]$, where $coef[i]$ is the number of $p_{j}$ $(p_{j} > i)$. One can notice that array $coef$ contains at most $sqrt(q)$ distinct values, additionally this array can be splitted into $O(sqrt(q))$ parts such that all elements from the same part will be the same. This is the key observation. We will divide array $coef$ into parts. And for each part will maintain lower envelope of the lines $y = d[i] + i \cdot x$. So, we will have $O(sqrt(q))$ lower envelopes. Each envelope will help us to get maximum value among the segment of array $d[i](oldD[i] + i \cdot coef[i])$. As for each $i$ from some segment factor $coef[i]$ is containt we can just pick $y$-coordinate with $x = coef[i]$ of corresponding lower envelope. Described solution has time complexity of $O(MAXX \cdot sqrt(MAXX))$, where $MAXX$ is the maximum value among $a[i]$ and $b[i]$.
|
[
"brute force",
"data structures",
"dp"
] | 3,000
| null |
437
|
A
|
The Child and Homework
|
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The child will follow the algorithm:
- If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great.
- If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).
You are given a multiple-choice questions, can you predict child's choose?
|
We enumerate each choice $i$, and then enumerate another choice $j$ $(j \neq i)$, let $cnt = 0$ at first, if choice $j$ is twice longer than $i$ let $cnt = cnt + 1$, if choice $j$ is twice shorter than $i$ let $cnt = cnt - 1$. So $i$ is great if and only if $cnt = 3$ or $cnt = - 3$. If there is exactly one great choice, output it, otherwise output C.
|
[
"implementation"
] | 1,300
| null |
437
|
B
|
The Child and Set
|
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set $S$:
- its elements were distinct integers from $1$ to $limit$;
- the value of $\textstyle\sum_{x\in S}l o w b i t(x)$ was equal to $sum$; here $lowbit(x)$ equals $2^{k}$ where $k$ is the position of the first one in the binary representation of $x$. For example, $lowbit(10010_{2}) = 10_{2}, lowbit(10001_{2}) = 1_{2}, lowbit(10000_{2}) = 10000_{2}$ (binary representation).
Can you help Picks and find any set $S$, that satisfies all the above conditions?
|
We could deal with this by digits. Because $lowbit(x)$ is taking out the lowest $1$ of the number $x$, we can enumerate the number of the lowest zero. Then, if we enumerate $x$ as the number of zero, we enumerate $a$ as well, which $a \times 2^{x}$ is no more than $limit$ and $a$ is odd. We can find out that $lowbit(a \times 2^{x}) = 2^{x}$. In this order, we would find out that the $lowbit()$ we are considering is monotonically decresing. Because for every two number $x, y$, $lowbit(x)$ is a divisor of $lowbit(y)$ or $lowbit(y)$ is a divisor of $lowbit(x)$. We can solve it by greedy. When we enumerate $x$ by descending order, we check whether $2^{x}$ is no more than $sum$, and check whether there is such $a$. We minus $2^{x}$ from $sum$ if $x$ and $a$ exist. If at last $sum$ is not equal to 0, then it must be an impossible test. Why? Because if we don't choose a number whose $lowbit = 2^{x}$, then we shouldn't choose two numbers whose $lowbit = 2^{x - 1}$. (Otherwise we can replace these two numbers with one number) If we choose one number whose $lowbit = 2^{x - 1}$, then we can choose at most one number whose $lowbit = 2^{x - 2}$, at most one number whose $lowbit = 2^{x - 3}$ and so on. So the total sum of them is less than $2^{x}$ and we can't merge them into $sum$. If we don't choose one number whose $lowbit = 2^{x - 1}$, then it's just the same as we don't choose one number whose $lowbit = 2^{x}$. So the total time complexity is $O(limit)$.
|
[
"bitmasks",
"greedy",
"implementation",
"sortings"
] | 1,500
| null |
437
|
C
|
The Child and Toy
|
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of $n$ parts and $m$ ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part $i$ as $v_{i}$. The child spend $v_{f1} + v_{f2} + ... + v_{fk}$ energy for removing part $i$ where $f_{1}, f_{2}, ..., f_{k}$ are the parts that are directly connected to the $i$-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all $n$ parts.
|
The best way to delete all n nodes is deleting them in decreasing order of their value. Proof: Consider each edge $(x, y)$, it will contribute to the total cost $v_{x}$ or $v_{y}$ when it is deleted. If we delete the vertices in decreasing order, then it will contribute only $min(v_{x}, v_{y})$, so the total costs is the lowest.
|
[
"graphs",
"greedy",
"sortings"
] | 1,400
| null |
437
|
D
|
The Child and Zoo
|
Of course our child likes walking in a zoo. The zoo has $n$ areas, that are numbered from $1$ to $n$. The $i$-th area contains $a_{i}$ animals in it. Also there are $m$ roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area $p$ to area $q$. Firstly he considers all the simple routes from $p$ to $q$. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as $f(p, q)$. Finally, the child chooses one of the routes for which he writes down the value $f(p, q)$.
After the child has visited the zoo, he thinks about the question: what is the average value of $f(p, q)$ for all pairs $p, q$ $(p ≠ q)$? Can you answer his question?
|
First, there is nothing in the graph. We sort all the areas of the original graph by their animal numbers in decreasing order, and then add them one by one. When we add area $i$, we add all the roads $(i, j)$, where $j$ is some area that has been added. After doing so, we have merged some connected components. If $p$ and $q$ are two areas in different connected components we have merged just then, $f(p, q)$ must equals the $v_{i}$, because they are not connected until we add node $i$. So we use Union-Find Set to do such procedure, and maintain the size of each connected component, then we can calculate the answer easily.
|
[
"dsu",
"sortings"
] | 1,900
| null |
437
|
E
|
The Child and Polygon
|
This time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements:
- each vertex of each triangle is one of the polygon vertex;
- each side of the polygon must be the side of exactly one triangle;
- the area of intersection of every two triangles equals to zero, and the sum of all areas of triangles equals to the area of the polygon;
- each triangle must be completely inside the polygon;
- \textbf{each side of each triangle must contain exactly two vertices of the polygon}.
The picture below depicts an example of a correct splitting.
Please, help the child. Calculate the described number of ways modulo $1000000007$ $(10^{9} + 7)$ for him.
|
In this problem, you are asked to count the triangulations of a simple polygon. First we label the vertex of polygon from $0$ to $n - 1$. Then we let $f[i][j]$ be the number of triangulations from vertex $i$ to vertex $j$. (Suppose there is no other vertices and there is an edge between $i$ and $j$) If the line segment $(i, j)$ cross with the original polygon or is outside the polygon, $f[i][j]$ is just 0. We can check it in $O(n)$ time. Otherwise, we have $f[i][j]=\sum_{i<k<i}f[i][k]*f[k][j]$, which means we split the polygon into the triangulation from vertex $i$ to vertex $k$, a triangle $(i, k, j)$ and the triangulation from vertex $k$ to vertex $j$. We can sum these terms in $O(n)$ time. Finally,the answer is $f[0][n - 1]$. It's obvious that we didn't miss some triangulation. And we use a triangle to split the polygon each time, so if the triangle is different then the triangulation must be different, too. So we didn't count some triangulation more than once. So the total time complexity is $O(n^{3})$, which is sufficient for this problem.
|
[
"dp",
"geometry"
] | 2,500
| null |
438
|
D
|
The Child and Sequence
|
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.
Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array $a[1], a[2], ..., a[n]$. Then he should perform a sequence of $m$ operations. An operation can be one of the following:
- Print operation $l, r$. Picks should write down the value of $\sum_{i=1}^{r}a[i]$.
- Modulo operation $l, r, x$. Picks should perform assignment $a[i] = a[i] mod x$ for each $i$ $(l ≤ i ≤ r)$.
- Set operation $k, x$. Picks should set the value of $a[k]$ to $x$ (in other words perform an assignment $a[k] = x$).
Can you help Picks to perform the whole sequence of operations?
|
The important idea of this problem is the property of $\mathrm{mod}$. Let $r=x{\mathrm{~mod~}}p$. So, $x=k\times p+r,k\in\mathbb{N}$. If $k = 0$, $x\ {\mathrm{mod}}\ p$ remains to be $x$. If $k \neq 0$, $x\;\mathrm{mod}\;p=r={\frac{2r}{2}}<{\frac{p+r}{2}}\leq{\frac{k\times p+r}{2}}\leq{\frac{x}{2}}$. We realize every time a change happening on $x$, $x$ will be reduced by at least a half. So let the energy of $x$ become $\log_{2}x$. Every time when we modify $x$, it may take at least $1$ energy. The initial energy of the sequence is $O(n\log a_{i})$. We use a segment tree to support the query to the maximum among an interval. When we need to deal with the operation $2$, we modify the maximum of the segment until it is less than $x$. Now let's face with the operation 3. Every time we modify an element on the segment tree, we'll charge a element with $O(\log a_{i})$ power. So the total time complexity is : $O(n\log n\log a_{i})$. By the way, we can extend the operation $3$ to assign all the elements in the interval to the same number in the same time complexity. This is an interesting idea also, but a bit harder. You can think of it.
|
[
"data structures",
"math"
] | 2,300
| null |
438
|
E
|
The Child and Binary Tree
|
Our child likes computer science very much, especially he likes binary trees.
Consider the sequence of $n$ distinct positive integers: $c_{1}, c_{2}, ..., c_{n}$. The child calls a vertex-weighted rooted binary tree good if and only if for every vertex $v$, the weight of $v$ is in the set ${c_{1}, c_{2}, ..., c_{n}}$. Also our child thinks that the weight of a vertex-weighted tree is the sum of all vertices' weights.
Given an integer $m$, can you for all $s$ $(1 ≤ s ≤ m)$ calculate the number of good vertex-weighted rooted binary trees with weight $s$? Please, check the samples for better understanding what trees are considered different.
We only want to know the answer modulo $998244353$ ($7 × 17 × 2^{23} + 1$, a prime number).
|
Let $f[s]$ be the number of good vertex-weighted rooted binary trees whose weight exactly equal to $s$, then we have: $f[0] = 1$ $f[s]=\sum_{w\in\{c_{1},\ldots,c_{n}\}}\sum_{i}f[i]\times f[s-w-i]$ Let F(z) be the generating function of f. That is, $F(z)=\sum_{k>0}f[k]z^{k}$ And then let $C(z)=\sum_{k=1}^{n}z^{c_{k}}$ So we have: $F(z) = C(z)F(z)^{2} + 1$ ``$+ 1$'' is for $f[0] = 1$. Solve this equation we have: $f[s]={\frac{1-{\sqrt{1-4C(z)}}}{2C(z)}}={\frac{4C(z)}{2C(z)(1+{\sqrt{1-4C(z)}})}}={\frac{2}{1+{\sqrt{1-4C(z)}}}}$ So the remaining question is: how to calculate the multiplication inverse of a power series and the square root of a power series? There is an interesting algorithm which calculate the inverse of a power series $F(z)$: We use $f(z) \equiv g(z) (mod z^{n})$ to denote that the first $n$ terms of $f(z)$ and $g(z)$ are the same. We can simply calculate a formal power series $R_{1}(z)$ which satisfies $R_{1}(z)F(z) \equiv 1 (mod z^{1})$ Next, if we have $R_{n}(z)$ which satisfies $R_{n}(z)F(z) \equiv 1 (mod z^{n})$, we will get: $(R_{n}(z)F(z) - 1)^{2} \equiv 0 (mod z^{2n})$ $R_{n}(z)^{2}F(z)^{2} - 2R_{n}(z)F(z) + 1 \equiv 0 (mod z^{2n})$ $1 \equiv 2R_{n}(z)F(z) - R_{n}(z)^{2}F(z)^{2} (mod z^{2n})$ $R_{2n}(z) \equiv 2R_{n}(z) - R_{n}(z)^{2}F(z) (mod z^{2n})$ We can simplely use Fast Fourier Transform to deal with multiplication. Note the unusual mod $998244353$ ($7 \times 17 \times 2^{23} + 1)$, thus we can use Number Theoretic Transform. By doubling $n$ repeatedly, we can get the first $n$ terms of the inverse of $F(z)$ in $O(n\log n)$ time. It's because that $T(n)=T(n/2)+O(n\log n)=O(n\log n)$ We can just use the idea of this algorithm to calculate the square root of a power series $F(z)$: We can simply calculate a power series $S_{1}(z)$ which satisfies $S_{1}(z)^{2} \equiv F(z) (mod z^{2n})$ Next, if we have $S_{n}(z)$ which satisfies $S_{n}(z)^{2} \equiv F(z) (mod z^{n})$, we will get: $(S_{n}(z)^{2} - F(z))^{2} \equiv 0 (mod z^{2n})$ $S_{n}(z)^{4} - 2S_{n}(z)^{2}F(z) + F(z)^{2} \equiv 0 (mod z^{2n})$ $S_{n}(z)^{2} - 2F(z) + F(z)^{2}S_{n}(z)^{ - 2} \equiv 0 (mod z^{2n})$ $4F(z) \equiv S_{n}(z)^{2} + 2F(z) + F(z)^{2}S_{n}(z)^{ - 2} (mod z^{2n})$ $4F(z) \equiv (S_{n}(z) + F(z)S_{n}(z)^{ - 1})^{2} (mod z^{2n})$ $F(z)\equiv(\textstyle{{\frac{1}{2}}}(S_{n}(z)+F(z)S_{n}(z)^{-1}))^{2}\,\,(m o d\ z^{2n})$ So, $S_{2n}(z)\equiv{\textstyle{\frac{1}{2}}}(S_{n}(z)+F(z)S_{n}(z)^{-1})~(m o d~z^{2n})$ By doubling $n$ repeatedly, we can get the first $n$ terms of the square root of $F(z)$ in $O(n\log n)$ time. That's all. What I want to share with others is this beautiful doubling algorithm. So the total time complexity of the solution to the original problem is $O(m\log m)$.
|
[
"combinatorics",
"divide and conquer",
"fft",
"number theory"
] | 3,100
|
#include <iostream>
#include <cstdio>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long s64;
const int Mod = 998244353;
const int Mod_G = 3;
const int MaxCN = 100000;
const int MaxS = 100000;
struct modint
{
int a;
modint(){}
modint(int _a)
{
a = _a % Mod;
if (a < 0)
a += Mod;
}
modint(s64 _a)
{
a = _a % Mod;
if (a < 0)
a += Mod;
}
inline modint operator-() const
{
return -a;
}
inline modint inv() const
{
int x1 = 1, x2 = 0, x3 = Mod;
int y1 = 0, y2 = 1, y3 = a;
while (y3 != 1)
{
int k = x3 / y3;
x1 -= y1 * k, x2 -= y2 * k, x3 -= y3 * k;
swap(x1, y1), swap(x2, y2), swap(x3, y3);
}
return y2 >= 0 ? y2 : y2 + Mod;
}
friend inline modint operator+(const modint &lhs, const modint &rhs)
{
return lhs.a + rhs.a;
}
friend inline modint operator-(const modint &lhs, const modint &rhs)
{
return lhs.a - rhs.a;
}
friend inline modint operator*(const modint &lhs, const modint &rhs)
{
return (s64)lhs.a * rhs.a;
}
friend inline modint operator/(const modint &lhs, const modint &rhs)
{
return lhs * rhs.inv();
}
inline modint div2() const
{
return (s64)a * ((Mod + 1) / 2);
}
};
inline modint modpow(const modint &a, const int &n)
{
modint res = 1;
modint t = a;
for (int i = n; i > 0; i >>= 1)
{
if (i & 1)
res = res * t;
t = t * t;
}
return res;
}
const int MaxN = 131072;
const int MaxTN = MaxN * 2;
modint prePowG[MaxTN];
void fft(int n, modint *a, int step, modint *out)
{
if (n == 1)
{
out[0] = a[0];
return;
}
int m = n / 2;
fft(m, a, step + 1, out);
fft(m, a + (1 << step), step + 1, out + m);
for (int i = 0; i < m; i++)
{
modint e = out[i], o = out[i + m] * prePowG[i << step];
out[i] = e + o;
out[i + m] = e - o;
}
}
void poly_mulTo(int n, modint *f, modint *g)
{
/*static modint c[MaxN];
for (int i = 0; i < n; i++)
c[i] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; i + j < n; j++)
c[i + j] = c[i + j] + f[i] * g[j];
copy(c, c + n, f);
return;*/
int tn = n * 2;
static modint tf[MaxTN], tg[MaxTN];
copy(f, f + n, tf), fill(tf + n, tf + tn, modint(0));
copy(g, g + n, tg), fill(tg + n, tg + tn, modint(0));
modint rg = modpow(Mod_G, (Mod - 1) / tn);
prePowG[0] = 1;
for (int i = 1; i < tn; i++)
prePowG[i] = prePowG[i - 1] * rg;
static modint dftF[MaxTN], dftG[MaxTN];
fft(tn, tf, 0, dftF);
fft(tn, tg, 0, dftG);
for (int i = 0; i < tn; i++)
dftF[i] = dftF[i] * dftG[i];
reverse(prePowG + 1, prePowG + tn);
fft(tn, dftF, 0, tf);
reverse(prePowG + 1, prePowG + tn);
modint revTN = modint(tn).inv();
for (int i = 0; i < n; i++)
f[i] = tf[i] * revTN;
}
void poly_inv(int n, modint *f, modint *r)
{
// assert(f[0] == 1)
fill(r, r + n, modint(0));
r[0] = 1;
for (int m = 2; m <= n; m <<= 1)
{
int h = m / 2;
static modint nr[MaxN];
copy(f, f + m, nr);
poly_mulTo(m, nr, r);
fill(nr, nr + h, modint(0));
for (int i = h; i < m; i++)
nr[i] = -nr[i];
poly_mulTo(m, nr, r);
copy(nr + h, nr + m, r + h);
}
}
void poly_sqrt(int n, modint *f, modint *s)
{
// assert(f[0] == 1)
fill(s, s + n, modint(0));
s[0] = 1;
static modint rs[MaxN];
fill(rs, rs + n, modint(0));
rs[0] = 1;
for (int m = 2; m <= n; m <<= 1)
{
int h = m / 2;
static modint nrs[MaxN];
copy(s, s + h, nrs), fill(nrs + h, nrs + m, modint(0));
poly_mulTo(m, nrs, rs);
fill(nrs, nrs + h, modint(0));
for (int i = h; i < m; i++)
nrs[i] = -nrs[i];
poly_mulTo(m, nrs, rs);
copy(rs, rs + h, nrs);
poly_mulTo(m, nrs, f);
for (int i = h; i < m; i++)
s[i] = nrs[i].div2();
copy(s, s + m, nrs);
poly_mulTo(m, nrs, rs);
fill(nrs, nrs + h, modint(0));
for (int i = h; i < m; i++)
nrs[i] = -nrs[i];
poly_mulTo(m, nrs, rs);
copy(nrs + h, nrs + m, rs + h);
}
}
int main()
{
int c_n, s;
static int c[MaxCN];
cin >> c_n >> s;
for (int i = 0; i < c_n; i++)
scanf("%d", &c[i]);
int n = 1;
while (n < s + 1)
n <<= 1;
static modint fD[MaxN];
fD[0] = 1;
for (int i = 0; i < c_n; i++)
if (c[i] <= s)
fD[c[i]] = -4;
static modint fB[MaxN];
poly_sqrt(n, fD, fB);
fB[0] = fB[0] + 1;
for (int i = 0; i < n; i++)
fB[i] = fB[i].div2();
static modint f[MaxN];
poly_inv(n, fB, f);
for (int i = 1; i <= s; i++)
printf("%d\n", f[i].a);
return 0;
}
|
439
|
A
|
Devu, the Singer and Churu, the Joker
|
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing $n$ songs, $i^{th}$ song will take $t_{i}$ minutes exactly.
The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.
People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.
You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:
- The duration of the event must be no more than $d$ minutes;
- Devu must complete all his songs;
- With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.
If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.
|
For checking whether there is a way to conduct all the songs of the singer, you can conduct the event in the following way. First singer will sing a song. Then during $10$ minutes rest of the singer, the joker will crack $2$ jokes(each of $5$ minutes) Then singer will again sing a song, then joker, etc. After the singer has completes all his songs, the joker will keep on cracking jokes of $5$ minutes each. Hence minimum duration of the even needed such that sing could sing all his songs will be $t_{1}$ + $10$ + $t_{2}$ + $10$ + ... +$t_{n}$ = $sum + (n - 1) * 10$ where $sum$ denote the total time of the songs of the singer. So for checking feasibility of the solution, just check whether $sum + (n - 1) * 10 \le duration$ or not?. If it is feasible, then time remaining for joker will be the entire duration except the time when the singer is singing the song. Hence time available for the joker will be $duration - sum$. In that time joker will sing $\frac{d u r a t i o n-s u m}{5}$ songs.
|
[
"greedy",
"implementation"
] | 900
| null |
439
|
B
|
Devu, the Dumb Guy
|
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him $n$ subjects, the $i^{th}$ subject has $c_{i}$ chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is $x$ hours. In other words he can learn a chapter of a particular subject in $x$ hours.
Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.
You can teach him the $n$ subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.
Please be careful that answer might not fit in 32 bit data type.
|
You can formulate the problem in following way. Given two arrays $a$ and $b$. Find minimum cost of matching the elements of array $a$ to $b$. For our problem the array $a$ will be same as $b$. The array $b$ will have content $x$, $x$ - 1, , 1, 1. For a general version of this problem, we can use min cost max flow(min cost matching), but for this problem following simple greedy solution will work. Sort the array $a$ in increasing and $b$ in decreasing order (or vice versa). Now match $i^{th}$ element of the array a with $i^{th}$ element of array b. Proof: It can be easily proved by exchange argument.
|
[
"implementation",
"sortings"
] | 1,200
| null |
439
|
C
|
Devu and Partitioning of the Array
|
Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?
Given an array consisting of distinct integers. Is it possible to partition the whole array into $k$ disjoint non-empty parts such that $p$ of the parts have even sum (each of them must have even sum) and remaining $k$ - $p$ have odd sum? (note that parts need not to be continuous).
If it is possible to partition the array, also give any possible way of valid partitioning.
|
Let us first try to find the condition required to make sure the existence of the partitions. Notice the following points. If the parity of sum does not match with parity of number of odd partitions ($k - p$) , then we can't create the required partitions. eg. $a = [1;2]$, $k = 2$, $p = 0$, Then you can not create two partitions of odd size, because then sum of the elements of the partitions of the array will be even whereas the sum of elements of the array is odd. If the parity of sum does not match with parity of number of odd partitions ($k - p$) , then we can't create the required partitions. eg. $a = [1;2]$, $k = 2$, $p = 0$, Then you can not create two partitions of odd size, because then sum of the elements of the partitions of the array will be even whereas the sum of elements of the array is odd. If number of odd elements in $a$ are less than $k - p$ (number of required partitions with odd sum), then we can not do a valid partitioning. If number of odd elements in $a$ are less than $k - p$ (number of required partitions with odd sum), then we can not do a valid partitioning. If number of even elements are less than $p$, then we can not create even partitions simply by using even numbers, we have to use odd numbers too. Notice the simple fact that sum of two odd numbers is even. Hence we will try to include $2$ odd elements in our partitions too. So if we can create $oddsRemaining / 2$ partitions in which every partition contains $2$ odd elements, then we can do a valid partitioning otherwise we can't. Here $oddsRemaining$ denotes the number of odd elements which are not used in any of the partitions made up to now. If number of even elements are less than $p$, then we can not create even partitions simply by using even numbers, we have to use odd numbers too. Notice the simple fact that sum of two odd numbers is even. Hence we will try to include $2$ odd elements in our partitions too. So if we can create $oddsRemaining / 2$ partitions in which every partition contains $2$ odd elements, then we can do a valid partitioning otherwise we can't. Here $oddsRemaining$ denotes the number of odd elements which are not used in any of the partitions made up to now. Let $oddElements$ denotes the number of odd elements in array $a$. Similarly $evenElements$ denotes the number of even elements. So the answer exists if Number of possible odd partitions are $ \ge $ $k - p$ i.e. $oddElements \ge k - p$. Number of possible even partitions are $ \ge $ $p$ i.e. $evenElements + (oddRemaining) / 2 \ge p.$ where $oddRemaining$ is $oddElements - (k - p)$. For generating the actual partitions, you can follow the same strategy used in detecting the existence of the partitions. We will first generate any valid $p$ partitions (forget about the condition of using the entire array), then we can simply include the remaining elements of the array in the last partition and we are done.
|
[
"brute force",
"constructive algorithms",
"implementation",
"number theory"
] | 1,700
| null |
439
|
D
|
Devu and his Brother
|
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays $a$ and $b$ by their father. The array $a$ is given to Devu and $b$ to his brother.
As Devu is really a naughty kid, he wants the minimum value of his array $a$ should be at least as much as the maximum value of his brother's array $b$.
Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.
You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
|
You can solve the problem in two ways. By using ternary search Let us define a function f. Function f(k) = cost needed to make array a elements $ \ge $ k + cost needed to make array b elements $ \le $ k Instead of proving it formally, try checking the property on many random test cases. You will realize that f is convex. Claim: f is convex: Proof: It is fairly easy to prove. See the derivative of f. $\frac{d(k)}{d k}$ = - (# of elements of b > k) + (# of elements of a < k) The first term (without sign) can only decrease as k increases whereas second term can only increase as k increases. So, ${\frac{d^{2}(f)}{d^{2}k}}\geq0$ By using the fact that optimal values are attainable at the array values: All the extremum points will lie in the elements from the any of the arrays because f is convex and ${\frac{d^{2}(f)}{d^{2}k}}=0$ at the event points (or the points of array a and b). For learning more about ternary search, you can see following topcoder discussion Another smart solution Please see following comment of goovie and proof is given in the reply by himank
|
[
"binary search",
"sortings",
"ternary search",
"two pointers"
] | 1,700
| null |
439
|
E
|
Devu and Birthday Celebration
|
Today is Devu's birthday. For celebrating the occasion, he bought $n$ sweets from the nearby market. He has invited his $f$ friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend.
He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed $n$ sweets to his friends such that $i^{th}$ friend is given $a_{i}$ sweets. He wants to make sure that there should not be any positive integer $x > 1$, which divides every $a_{i}$.
Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo $1000000007$ $(10^{9} + 7)$.
To make the problem more interesting, you are given $q$ \textbf{queries}. Each query contains an $n$, $f$ pair. For each query please output the required number of ways modulo $1000000007$ $(10^{9} + 7)$.
|
There are two possible solutions. dp solution Let $P(n, f)$ be total number of ways of partitioning $n$ into $f$ segments such that each $a_{i}$ is positive. With some manipulations of the generating function, you can find that this is equal to $\textstyle{\binom{n-1}{f-1}}$. So $P(n,f)=\left(\O_{f-1}^{n-1}\right)$ Let $F(n, f, g)$ denotes partitions of $n$ into $f$ parts such that gcd of all the $a_{i}'s$ is $g$. Note that $F(n, f, 1)$ = $P(n, f)$ - sum of $F(n, f, g)$ over all possible gcd $g's$. So $g$ will be a divisor of $n$. In other words, $F(n,f,1)=P(n,f)-\sum_{q\,|n,o r e}F(n,f,g)\ \ {\mathrm{for~every~integer~}}n\geq1$ As $F(n,f,g)=F(\underline{{{\O_{g}}}},f,1)$. $F(n,f,1)=P(n,f)-\sum_{g\,|n,g\neq1}F(n/g,f,1)\quad{\mathrm{for~every~integer~}}n\geq1$ You can implement this solution by a simple dp. You can pre-calculate factorials which will help you to calculate $\textstyle{\binom{n}{r}}$. Complexity of this solution will be $nlogn$ over all the test cases. Please note that this solution might get time limit exceeded in Java. Please read the comment. Mathematical solution Note that $F(n, f, 1) = P(n, f)$ - sum of $F(n, f, g)$ over all possible gcd $g's$ ($g > 1$ such that $g$ is a divisor of $n$. In other words, $F(n,f,1)=P(n,f)-\sum_{q\,|n,oneq1}F(n,f,g)\quad{\mathrm{for~every~integer~}}n\geq1$ As $F(n, f, g)$ = $F(_{g}^{n},f,1)$. $F(n,f,1)=P(n,f)-\sum_{g\,|n,g\neq1}F(n/g,f,1)\quad{\mathrm{for~every~integer~}}n\geq1$ $P(n,f)=F(n,f,1)+\sum_{o\mid n,o r:1}F(n/g,f,1)\quad{\mathrm{for~every~integer~}}n\geq1$ $P(n,f)=\sum_{g\mid n}F(n/g,f,1)\ \ \mathrm{for~every~integer}\;n\geq1$ Now you have to use Möbius inversion formula. Theorem: If $f$ and $g$ are two arithmetic functions satisfying $g(n)=\sum_{d\vdash n}f(d)\quad{\mathrm{~for~every~integer~}}n\geq1$ then $f(n)=\sum_{d\mid n}\mu(d)g(n/d)\quad{\mathrm{for~every~integer}}\ n\geq1$ So In our case: $g(n)$ is $P(n, f)$ and $f(n)$ is $F(n, f, 1)$. For proving complexity: Use the fact that total number of divisors of a number from $1$ to $n$ is $\mathbb{O}(n l o g n).$
|
[
"combinatorics",
"dp",
"math"
] | 2,100
| null |
441
|
A
|
Valera and Antique Items
|
Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows $n$ sellers of antiques, the $i$-th of them auctioned $k_{i}$ items. Currently the auction price of the $j$-th object of the $i$-th seller is $s_{ij}$. Valera gets on well with each of the $n$ sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.
Unfortunately, Valera has only $v$ units of money. Help him to determine which of the $n$ sellers he can make a deal with.
|
You need to implement what written in statement. You could act like that: let's calculate $q_{i}$ - minimum item price from seller $i$. Then if $q_{i} < v$, we can make a deal with seller $i$, otherwise we can't.
|
[
"implementation"
] | 1,000
|
#include <iostream>
#include <vector>
#define forn(i,n) for(int i = 0; i < int(n); ++i)
using namespace std;
int main() {
int n, v;
cin >> n >> v;
vector <int> ans;
forn(i, n) {
bool u = false;
int k, s;
cin >> k;
forn(j, k) {
cin >> s;
if (!u && v > s) {
u = true;
ans.push_back(i);
}
}
}
cout << ans.size() << endl;
forn(i, ans.size())
cout << ans[i]+1 << " ";
return 0;
}
|
441
|
B
|
Valera and Fruits
|
Valera loves his garden, where $n$ fruit trees grow.
This year he will enjoy a great harvest! On the $i$-th tree $b_{i}$ fruit grow, they will ripen on a day number $a_{i}$. Unfortunately, the fruit on the tree get withered, so they can only be collected on day $a_{i}$ and day $a_{i} + 1$ (all fruits that are not collected in these two days, become unfit to eat).
Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than $v$ fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?
|
Let's start counting days from 1 to 3001. Let current day be $i$. Additionally, we'll have $cur$ variable - number of fruit we didn't collect previous days. Suppose $now$ fruit is ripen current day. If $now + cur \le v$, we need to add $now + cur$ to answer and update $cur$ value ($cur = 0$). Otherwise we add $v$ to answer, but $cur$ value need to be updated as follows. Let $tv = max(v - cur, 0)$. Then $cur = now - tv$. In other words, we try to collect fruits that will not be collectable next day. Additionally, problem could be solved with $O(n\log n)$, but this is not required.
|
[
"greedy",
"implementation"
] | 1,400
|
#undef NDEBUG
#ifdef gridnevvvit
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <vector>
#include <string>
#include <deque>
#include <bitset>
#include <algorithm>
#include <utility>
#include <functional>
#include <limits>
#include <numeric>
#include <complex>
#include <cassert>
#include <cmath>
#include <memory.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
typedef long long li;
typedef long double ld;
typedef pair<int,int> pt;
typedef pair<ld, ld> ptd;
typedef unsigned long long uli;
#define pb push_back
#define mp make_pair
#define mset(a, val) memset(a, val, sizeof (a))
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define ft first
#define sc second
#define sz(a) int((a).size())
#define x first
#define y second
template<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }
template<typename X> inline X sqr(const X& a) { return (a * a); }
template<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }
template<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }
template<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << ", " << p.sc << ')'; }
inline int nextInt() { int x; if (scanf("%d", &x) != 1) throw; return x; }
inline li nextInt64() { li x; if (scanf("%I64d", &x) != 1) throw; return x; }
inline double nextDouble() { double x; if (scanf("%lf", &x) != 1) throw; return x; }
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)
#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)
#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
const int INF = int(1e9);
const li INF64 = li(INF) * li(INF);
const ld EPS = 1e-9;
const ld PI = ld(3.1415926535897932384626433832795);
const int N = 3005;
int n, a[N], b[N], v;
inline bool read() {
n = nextInt();
v = nextInt();
forn(i, n)
{
a[i] = nextInt();
b[i] = nextInt();
}
return true;
}
inline void solve() {
int fromLastDays = 0;
int ans = 0;
for(int day = 1; day <= 3001; day++) {
int curDay = 0;
forn(i, n)
if (a[i] == day)
curDay += b[i];
if (curDay + fromLastDays <= v) {
ans += fromLastDays + curDay;
fromLastDays = 0;
} else {
ans += v;
int tv = v - fromLastDays;
if (tv < 0) tv = 0;
fromLastDays = curDay - tv;
}
}
cout << ans << endl;
}
int main()
{
#ifdef gridnevvvit
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
srand(time(NULL));
cout << setprecision(10) << fixed;
cerr << setprecision(5) << fixed;
assert(read());
solve();
#ifdef gridnevvvit
cerr << "===Time: " << clock() << "===" << endl;
#endif
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.