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
⌀ |
|---|---|---|---|---|---|---|---|
185
|
D
|
Visit of the Great
|
The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.
We know that only $LCM(k^{2l} + 1, k^{2l + 1} + 1, ..., k^{2r} + 1)$ dwarves can see the Great Mushroom King. Numbers $k$, $l$, $r$ are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves.
The dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers $k_{i}$, $l_{i}$, $r_{i}$, chosen by the Great Mushroom King for this visit. They also know a prime number $p_{i}$. Help them to count the remainder of dividing the number of dwarves who can see the King, by number $p_{i}$, for each visit.
|
This is number theory problem. I'm trying to explain it step by step: 1) Let's prove, that LCD is maximum 2. Let $k^{2^{n}}+1\dot{z}d\Leftrightarrow k^{2^{n}}\equiv\!\!d-1$. Squaring both sides we get $k^{2^{n+1}}\equiv_{d}1\stackrel{\leftrightarrow}{\leftrightarrow}k^{2^{n+1}}-1^{;}d$, but we want to $k^{2^{n+1}}+1;d$. This means, that $d$ can be only $2$. 2) Let's make this lenghty product simplier. $\left(k^{2^{l}}+1\right)\cdot\dots\cdot\left(k^{2^{r}}+1\right)={\frac{k^{2^{r+1}}-1}{k^{2^{\prime}-1}}}$. We can count this by modulo $p$ fast, and divide it by $2^{r - l}$, if $k$ is odd. 3) There is many interesting things in this solution. Firstly, it doesn't work, when $p = 2$ - but it can easily done by you. The other problem is harder, what if $k^{2^{\overset{n}{}}}-1\mathbf{\hat{}}p$, this means that for each $i \ge l$ : $k^{2^{n}}-1;p$, and this mean, that for each $i \ge l$ : $k^{2i} + 1 \equiv _{p}2$. And the product by modulo $p$ is equal to $2^{r - l + 1}$.
|
[
"math",
"number theory"
] | 2,600
| null |
185
|
E
|
Soap Time! - 2
|
Imagine the Cartesian coordinate system. There are $k$ different points containing subway stations. One can get from any subway station to any one instantly. That is, the duration of the transfer between any two subway stations can be considered equal to zero. You are allowed to travel only between subway stations, that is, you are not allowed to leave the subway somewhere in the middle of your path, in-between the stations.
There are $n$ dwarves, they are represented by their coordinates on the plane. The dwarves want to come together and watch a soap opera at some integer point on the plane. For that, they choose the gathering point and start moving towards it simultaneously. In one second a dwarf can move from point $(x, y)$ to one of the following points: $(x - 1, y)$, $(x + 1, y)$, $(x, y - 1)$, $(x, y + 1)$. Besides, the dwarves can use the subway as many times as they want (the subway transfers the dwarves instantly). The dwarves do not interfere with each other as they move (that is, the dwarves move simultaneously and independently from each other).
Help the dwarves and find the minimum time they need to gather at one point.
|
This problem wasn't taken to ROI, because of that I gave it here. This is pretty hard problem. I can't now realize, what cerealguy wrote, but his solution is $O(nlogn)$ - without binary search. For me it's quite hard to understand, because my first solution was with binary search. And there were solutions, that has a worse asymptothic, but they run faster. Because of that I can only give you key ideas, that can help you. (afterwards you can see the code of cerealguy) Ideas: Let's find for each person the nearest subway point for them. It can be done in nlogn with use of segment tree or something else. We can see, that if one person goes to subway, the others, which distance to subway is smaller, can go to subway too - it doesn't affect the answer. Because of that we sort all persons by their distanse to subway. The area of the person, where he can come in $t$ seconds, is romb. And we can intersect all rombes in $O(n)$ - the intersection is like rectangle. Let's make the first intersection. When nobody goes to subway. We get a rectangle. The main idea, that for this rectangle - the nearest subway becomes always the same. We go throught people in sorted order, we can fast recalculate this small rectangle - and because of that we can fast recalculate the answer. And we get a solution in $O(nlogn)$ time.
|
[
"binary search",
"data structures"
] | 3,000
| null |
186
|
A
|
Comparing Strings
|
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
|
If the lengths of 2 strings aren't equal - that means "NO". We try to find the positions in strings, where chars are different. If there 1 or more than 2 such positions - "NO". After that we swap 2 characters in the first string, and check for their equality.
|
[
"implementation",
"strings"
] | 1,100
| null |
186
|
B
|
Growing Mushrooms
|
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts $t_{1}$ seconds and the second part lasts $t_{2}$ seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of $v_{i}$ meters per second. After $t_{1}$ seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by $k$ percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of $u_{i}$ meters per second. After a $t_{2}$ seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds $a_{i}$ and $b_{i}$, then there are two strategies: he either uses speed $a_{i}$ before the break and speed $b_{i}$ after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
|
We can see, that we can do all in integers, because k is integer number of percent. For each dwarf we should find his optimal strategy - to check 2 strategies with speed. We should sort them.
|
[
"greedy",
"sortings"
] | 1,200
| null |
187
|
A
|
Permutations
|
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers $1$ through $n$ and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.
Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.
|
It is easy to see that if we replace each number in the first permutation with position of that number in the second permutation, the problem reduces to sorting the first permutation. Each time we take a number from the end of array, we can postpone its insertion until we know the most suitable position for insertion. Note that it is not good to insert a number and take it again, as we could make a better decision first time we took the number. So, as long as the remainder of the array is not in increasing order, we should take more numbers from the end. But as soon as you have an increasing subsequence, you can insert the numbers you have taken to make the array sorted. Therefore to solve the problem, we find the largest i such the numbers from 1 to i are in increasing order. The answer would be n-i.
|
[
"greedy"
] | 1,500
| null |
187
|
B
|
AlgoRace
|
PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.
AlgoRace is a special league of car racing where different teams compete in a country of $n$ cities. Cities are numbered $1$ through $n$. Every two distinct cities in the country are connected with one bidirectional road. Each competing team should introduce one driver and a set of cars.
The competition is held in $r$ rounds. In $i$-th round, drivers will start at city $s_{i}$ and finish at city $t_{i}$. Drivers are allowed to change their cars at most $k_{i}$ times. Changing cars can take place in any city in no time. One car can be used multiple times in one round, but total number of changes should not exceed $k_{i}$. Drivers can freely choose their path to destination.
PMP has prepared $m$ type of purpose-built cars. Beside for PMP’s driving skills, depending on properties of the car and the road, a car traverses each road in each direction in different times.
PMP Warriors wants to devise best strategies of choosing car and roads in each round to maximize the chance of winning the cup. For each round they want to find the minimum time required to finish it.
|
First we solve the problem when the number of allowed car changes is zero (_k=0_). Let W(i,j,l) be the length of shortest path from i to j with car l. We use Floyd-Warshal on graph of each car to find this value. Then answer for the case that we can use only one car for each pair of cities i and j is: ans(0,i,j) = min W(i,j,l) for (_1 \le l \le m_) This part has time complexity O(m*n^3). For larger values of maximum number of changes (_k_), we use the following equation: ans(k,i,j) = min (ans(k-1,i,l)+ans(0,l,j)) for (_1 \le l \le k_) which can be computed in O(k*n^3) using dynamic programming. But how large can be k in worst case? We know that shortest paths are simple paths (i.e. they have no repeated vertices). Because otherwise we could eliminate the path we go between two appearances of one vertex and have a smaller result. This and the fact that we change the car at most once in each vertex, guarantees in any optimal solution we will not need more that n car changes. Thus the order of the solution would be O(m*n^3+n^4).
|
[
"dp",
"shortest paths"
] | 1,800
| null |
187
|
C
|
Weak Memory
|
\underline{Zart PMP} is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.
The park has $n$ intersections numbered $1$ through $n$. There are $m$ bidirectional roads that connect some pairs of these intersections. At $k$ intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.
When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most $q$ intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most $q$ that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most $q$ intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.
PMP's initial location is intersection $s$ and the buses are at intersection $t$. There will always be a volunteer at intersection $s$. Your job is to find out the minimum $q$ which guarantees that PMP can find the buses.
|
There were many different correct approaches to this problem during the contest. But I will explain author's solution. First we can use binary search over the value of q. Now for a fixed q we want to check s-t connectivity. Let K be the set of all intersections with volunteers union s and t. One can use BFS from each k \in K, one by one. Then build a graph G' with vertices K. For each two vertices k1,k2 \in K add an edge between them, if their shortest distance is less than or equal to q. Finally use any path finding algorithm to check the connectivity. Unfortunately this solution has time (and space) complexity of O(|K|*m) which is not good enough. We can optimize the above solution by initiating BFS from all k \in K at once. In other words during the initialization step in BFS algorithm, we push all these vertices in the queue with distance 0. Each element in the queue also maintains its source (i.e. the source it is originating from). In BFS each time we have have a vertex u with source su and we want to set the minimum distance to a vertex v that is already set from a different path with source sv, we connect su and sv in G' if d(u)+d(v)+1<= q, where d(x) denotes length of the shortest path from a vertex in K to x. As we are only dealing with connectivity, this approach is correct. (Proof of correctness is left as an exercise) BFS takes O(m) time and we add at most O(m) edges to G', so the overall complexity is O(m) for a fixed q. As we used binary search to find the smallest q, we can solve the problem in O(m*logn).
|
[
"dfs and similar",
"dsu"
] | 2,000
| null |
187
|
D
|
BRT Contract
|
In the last war of PMP, he defeated all his opponents and advanced to the final round. But after the end of semi-final round evil attacked him from behind and killed him! God bless him.
Before his death, PMP signed a contract with the bus rapid transit (BRT) that improves public transportations by optimizing time of travel estimation. You should help PMP finish his last contract.
Each BRT line is straight line that passes $n$ intersecting on its ways. At each intersection there is traffic light that periodically cycles between green and red. It starts illuminating green at time zero. During the green phase which lasts for $g$ seconds, traffic is allowed to proceed. After the green phase the light changes to red and remains in this color for $r$ seconds. During the red phase traffic is prohibited from proceeding. If a vehicle reaches the intersection exactly at a time when the light changes to red, it should stop, but the vehicle is clear to proceed if the light has just changed to green.
All traffic lights have the same timing and are synchronized. In other words the period of red (and green) phase is the same for all of traffic lights and they all start illuminating green at time zero.
The BRT Company has calculated the time that a bus requires to pass each road segment. A road segment is the distance between two consecutive traffic lights or between a traffic light and source (or destination) station. More precisely BRT specialists provide $n + 1$ positive integers $l_{i}$, the time in seconds that a bus needs to traverse $i$-th road segment in the path from source to destination. The $l_{1}$ value denotes the time that a bus needs to pass the distance between source and the first intersection. The $l_{n + 1}$ value denotes the time between the last intersection and destination.
In one day $q$ buses leave the source station. The $i$-th bus starts from source at time $t_{i}$ (in seconds). Decision makers of BRT Company want to know what time a bus gets to destination?
The bus is considered as point. A bus will always move if it can. The buses do not interfere with each other.
|
We define ti as follows: assume a bus starts moving from i-th intersection exactly at the time when the light changes to green. The time it takes for the bus to get the final station is ti. We call the times when a green interval begins t0 (so every g+r seconds t0 occurs once) If a bus gets to i-th intersection during the red phase, it should wait and then start moving at t0. So considering the fact that all lights are synchronized (and length of segments are fixed) if we have ti for i-th intersection, we can compute the time for the bus to get final station. Clearly tn is the length of the last segments. For computing ti we should find the smallest j such that if a bus starts at t0 from i-th intersection, it gets to j-th intersection during the red phase. So we have: ti=tj+d(i,j)+w where d(i,j) is the distance between i-th and j-th intersections and w is the time that the bus should wait behind the red light at j-th intersection. The later value can be computed easily. The only problem that remains is to find j for i-th intersection. So we start iterating over i for (n-1)-th intersection backwards and we compute ti for all intersections. Assume p=g+r and ta=d(i,j)%p. Now if the bus starts from i-th intersection at time t0 and we have ta>=g, in this case we are in red phase at j-th intersection. Actually ta should be in interval [_g, g+r_). Here we can use segment trees. That is for all intersections from i+1 to n, we store some values in the tree that helps us find the smallest j. But we should note the value of ta depends on d(i,j) which changes as i changes. Thus we cannot use ta in the tree. Instead, we define si the be the distance of i-th intersection to the destination. So we have d(i,j)=si-sj and we use the value of sj with storing -sj%p in the segment tree as the key and the value would be j itself. In other words for each intersection we store the key-value pair (-sj%p, j) in the tree. According to what we said so far, to be in the red phase at j-th intersection we should have: ta=(d(i,j)%p)=((si-sj)%p) \in [g,g+r) => -sj%p \in [(g-si)%p, (g+r-si)%p) As we stored -sj%p in the tree, we can retrieve the smallest j in the above interval with a query in the segment tree. This way we can compute ti for all intersections. Answering to each query in the problem can be solve in exactly the same way. So the overall complexity would be O((n+q)logn).
|
[
"data structures"
] | 2,800
| null |
187
|
E
|
Heaven Tour
|
The story was not finished as PMP thought. God offered him one more chance to reincarnate and come back to life. But before he can come back, God told him that PMP should ask $n$ great men including prominent programmers about their life experiences.
The men are standing on a straight line. They are numbered $1$ through $n$ from left to right. The coordinate of the $i$-th man is $x_{i}$ $(x_{i} < x_{i + 1}, i < n)$. PMP should visit all these people one by one in arbitrary order. Each men should be visited \textbf{exactly once}. At the beginning of his tour, he starts at location of $s$-th man and asks him about his experiences.
Each time PMP wants to change his location, he should give a ticket to an angel and the angel carries him to his destination. Angels take PMP from one location, fly to his destination and put him down there. Nobody else is visited in this movement. Moving from $i$-th man to $j$-th man, takes $|x_{i} - x_{j}|$ time. PMP can get back to life as soon as he visits all men.
There are two types of angels: Some angels are going to the right and they only accept right tickets. Others are going the left and they only accept left tickets. There are an unlimited number of angels of each type. PMP has $l$ left tickets and $n - 1 - l$ right tickets.
PMP wants to get back to life as soon as possible to be able to compete in this year's final instead of the final he missed last year. He wants to know the quickest way to visit all the men exactly once. He also needs to know the exact sequence moves he should make.
|
Step 1. Solve the problem if the starting man is the leftmost man and the finishing man is the rightmost man. Obviously every segment (the distance between two consecutive men) should be covered at least once. We also argue that at least l (the number of left tickets) segments should be covered at least three times. Proof: Each time you use a left ticket to go to man i with 1<i<n-1, the segment between i-th and (_i+1_)-th men is covered at least three times: Once for you should go after i be in a position to come back. Once for you use a left ticked to come back to i And once again you should go after i, because you want to finish at man number n Note that in the first and the last segments are always covered once, no matter what we do. But except for these two segments, every other segment can be chosen to be among the segments that are covered three times, and every combination that we choose l segments is feasible. (Proof it as practice) So we choose the smallest l segments and the problem can be solved with a simple sort in O(n*logn). Step 2. Solve the problem if the starting man is the leftmost man, but the finishing man can be anywhere. To solve this problem we first fix the finishing man. With reasoning similar to that of step 1, we conclude that at least l segments should be covered with at least two times if they are after the finishing man or three times if they are before him. But obviously every segment after the finishing man is covered at least two times. So it is always good to waste as many left tickets as possible after the finishing man to prevent them from breaching the left side of finishing man and becoming multiple three. So the algorithm would be: iterate over i, the number of finishing man, and maintain the l-(n-i) smallest segments to the right of finishing man as you progress. This can be implemented in O(n*logn). Step 3. Solve the problem if the starting man is fixed, but the finishing man can be anywhere. Assume that the starting man is not the first man or the last man, otherwise we could use algorithm of step 2 to solve the problem. Without loss of generality assume that you finish your tour to the right side of finishing man. Therefore every segment to the left of starting man is covered at least two times and actually it is always possible to arrange visits such that every segment to right is covered exactly two times. So just like what we said in step 2, it is good to waste as many left tickets as possible in this area. So the algorithm would be, choose to finish left or right first, then greedily waste as many bad moves (by bad moves I mean the moves that if breach to the other side will be more costly) as possible there and follow the algorithm in step 2 to solve the whole problem. There are some special cases such as when the tour cannot be finished at all, that we left to readers find a way how to handle them.
|
[
"data structures",
"greedy"
] | 2,900
| null |
189
|
A
|
Cut Ribbon
|
Polycarpus has a ribbon, its length is $n$. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length $a$, $b$ or $c$.
- After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
|
The problem is to maximize x+y+z subject to ax+by+cz=n. Constraints are low, so simply iterate over two variables (say x and y) and find the third variable (if any) from the second equation. Find the maximum over all feasible solutions. Other approaches: Use dynamic programming with each state being the remainder of ribbon. Select the next piece to be a, b or c.
|
[
"brute force",
"dp"
] | 1,300
| null |
189
|
B
|
Counting Rhombi
|
You have two positive integers $w$ and $h$. Your task is to count the number of rhombi which have the following properties:
- Have positive area.
- With vertices at integer points.
- All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points $(0, 0)$, $(w, 0)$, $(w, h)$, $(0, h)$. In other words, for all vertices $(x_{i}, y_{i})$ of the rhombus the following conditions should fulfill: $0 ≤ x_{i} ≤ w$ and $0 ≤ y_{i} ≤ h$.
- Its diagonals are parallel to the axis.
Count the number of such rhombi.
Let us remind you that a rhombus is a quadrilateral whose four sides all have the same length.
|
Observe that lots of rhombi have the same shape, but are in different locations. What uniquely determines the shape of a rhombus? Its width and its height. Is it possible to build a rhombus with every width and every height such that the vertices of the rhombus are in integer points? No, it is possible only if the width and the height are both even. How many places we can put a rhombus of width w0 and height h0 in a rectangle of width w and height h? (w * w0 + 1)(h * h0 + 1) So, iterator over all even widths and heights and for each of them add the number of possible locations to the final result.
|
[
"brute force",
"math"
] | 1,300
| null |
190
|
A
|
Vasya and the Bus
|
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had $n$ grown-ups and $m$ kids..."
The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.
The bus fare equals one berland ruble in High Bertown. However, not everything is that easy — \textbf{no more than one} child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his $k$ $(k > 0)$ children, pays overall $k$ rubles: a ticket for himself and $(k - 1)$ tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.
We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.
Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.
|
Firstly, if $n = 0$, then children can't be in the bus, so if $m = 0$ then the answer is $(0, 0)$, otherwise the answer is $"Impossible"$. Now $n > 0$. If $m = = 0$, than it is only one possible variant of passage - the answer is $(n, n)$. Otherwise, more grown-up take some children, less the sum that people pay. So, if only one adult takes all children, than we get maximal sum - $n + m - 1$. Maximum $min(n, m)$ adults can take the children with them, so the minimal answer is $n + m - min(n, m) = max(n, m)$.
|
[
"greedy",
"math"
] | 1,100
| null |
190
|
B
|
Surrounded
|
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most $r$ from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most $r$). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius $(r)$ is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius $r$ $(r ≥ 0)$ such, that a radar with radius $r$ can be installed at some point and it can register \textbf{the start of the movements} of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.
|
Let's find the minimum distance between two circles $L$. Then the answer to our problem is $L / 2$. Now $d$ is the distance between the centers of the circles, $R$, $r$ - their radiuses. There are 3 possible cases: - Circles don't intersect. Then $L = d - R - r$. Firstly, it's reachable: let's consider the segment, connecting the centers of the circles, and take its part, which is out of both circles - its length is exactly $d - R - r$. Let's prove that lesser distance is impossible. If the segment connecting two points of distinct circles have length l, than $R + l + r > = d$, so $l > = d - R - r$. - If one circle is into another, than analogically the answer is $R - d - r$, where $R$ is the radius of the bigger circle. - If the circles intersect, then the answer is 0.
|
[
"geometry"
] | 1,800
| null |
190
|
C
|
STL
|
Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.
We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.
Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store $n$ integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--:
- First, a type is a string "int".
- Second, a type is a string that starts with "pair", then followed by angle brackets listing \textbf{exactly two} comma-separated other types of language X--. This record contains no spaces.
- No other strings can be regarded as types.
More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.
Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores $n$ integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.
Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.
|
In this problem we have an array of strings $(s_{1}, s_{2}, ...s_{n})$, where $s_{i}$ $= pair$ or $int$. Let's consider $bal_{i}$ = the difference between number of "pair" and "int" int the subarray $(s_{1}, s_{2}, ...s_{i})$. Than we can prove that the type can be reestablished from the array $s$ $< = >$ $bal_{i} > = 0$ for $1 < = i < n$ and $bal_{n} = - 1$. This can be proved using mathematical induction, the parameter is the number of $"int"$-s in the array. And how to find the solution, if we know that is exists? Consider the function $gettype(inti)$, which builds the type beginning in the position $i$ and returns the index, next to the position where it finished building of type. How it works? If $s_{i} =$ $"int"$, then the function prints $"int"$ and returns $i + 1$. Else it prints $"pair < "$, $gettype(i + 1)$ is launched, let it returns $j$. Then we print $", "$ and launch $gettype(j)$ (it returns $k$), then we print $" > "$ and return $k$. We can not to do check if the type can be reestablished from the array in the beginning: launch $gettype()$ and print "Error occurred" if there became some contradiction during the building of type.
|
[
"dfs and similar"
] | 1,500
| null |
190
|
D
|
Non-Secret Cypher
|
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.
The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number $m$, the enemies use an array of integers $a$. The number of its subarrays, in which there are at least $k$ equal numbers, equals $m$. The number $k$ has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.
Help Vasya, given an array of integers $a$ and number $k$, find the number of subarrays of the array of numbers $a$, which has at least $k$ equal numbers.
Subarray $a[i... j] (1 ≤ i ≤ j ≤ n)$ of array $a = (a_{1}, a_{2}, ..., a_{n})$ is an array, made from its consecutive elements, starting from the $i$-th one and ending with the $j$-th one: $a[i... j] = (a_{i}, a_{i + 1}, ..., a_{j})$.
|
First solution: Let's use the method of two pointers. For every number we will know how many times it occurs in the current segment $[l, r]$. For fixed $l$ we increase $r$ until $a[r]$ occurs in the current segment less than $k$ times. If $a[r]$ occurs int the segment $[l, r]$ $k$ times, we add to the answer all segments $[l, t]$ for all $t > = r$ and increase $l$ (and do not forget to decrease the number of $a[l]$ in the current segment). To keep the number of every value in the segment we can use $map$ or compression of the coordinates. Also it's important not to forget that the maximal answer is $\textstyle{\frac{n(n+1)}{2}}$, which doesn't fit in $int$. Second solution: firstly, let's do the compression of the coordinates. For every value $X$ we write the list of the positions $i$ such that $a[i] = X$. Now using that we fill the array $b$: $b[i]$ is the minimum index that segment $[i, b[i]]$ contains $k$ numbers equal to $a[i]$ (obviosly, $a[b[i]] = a[i]$), if this index doesn't exist, then $b[i] = n + 1$. Let's find for every index $i$ a minimal index $j$ such that segment $[i, j]$ contsins $k$ equal numbers (if such $j$ doesn't exist, we say that $j = n + 1$) - then we add to the answer $n + 1 - j$. This $j$ is equal to $\operatorname*{min}_{k=i,\ldots n}b_{k}$. All that minimums can be found in a single pass through $a$ from its end. Then we can sum the answers for all indexes $1 < = i < = n$. The complexity of these solutions is $O(nlogn)$.
|
[
"two pointers"
] | 1,900
| null |
190
|
E
|
Counter Attack
|
Berland has managed to repel the flatlanders' attack and is now starting the counter attack.
Flatland has $n$ cities, numbered from $1$ to $n$, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.
The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the \textbf{actual} roads. Also the cities from different groups are unreachable from each other, moving along the \textbf{actual} roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!
Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
|
This problem has several different solutions. Anyway, we should consider towns as the vertices of the graph, roads as its edges. Now we are to find the connected components of the complementary graph (CG) of the given graph. Let's take the vertex $A$ with the minimal degree $c$: $c<={\frac{m}{n}}$. We call the set of the vertices who are connected with $A$ - $B$, that are not connected - $D$ . All vertices which don't connect with $A$ will be in the same connected component of the CG. Let's build the complemented graph to the subgraph including $A$ and set $B$ - there are $O({\frac{m}{n}})$ vertices and $O({\frac{\mu-\mu}{n\,n}})$ $=$ $O(m\cdot{\frac{m}{n n}})$ $=$ $O(m)$ edges. Let's build DSU for the vertices of given graph and merge components which we have found using the new-built graph. All that we should do after it is to consider vertices from $B$: now we look to the vertex $v$. We put $v$ in the same component as $A$ if $v$ has edges not to all vertices of $D$ (we do it using DSU too). The complexity of this solution is $O(m)$ or $O(mlogn)$. Another solution: we keep $set$ $a$, which contains vertices, which haven't been visited yet. Let's run series of bfs to find the components of CG. If we are working now with the vertex $v$, pass through $a$. Consider $u$ is the element of $a$. If edge $(u, v)$ isn't in the given graph, than $u$ is in the same component of CG as $v$, so, we can erase it from $a$ and add to queue. Otherwise, we do nothing. What is the complexity of this solution? To understand that, we must know how many times whe consider fixed vertex $u$ in the $set$ $a$. $u$ remains int $a$ when we run to them from vertex $v$ $< = >$ edge $(u, v)$ is in the given graph. So, every vertex $u$ remains in $a$ no more than its degree. So, the complexity of this algorithm is $O(mlogn)$ (log n because of binsearch - we need use it to know, is $(u, v)$ in the graph). If we use $HashMap$, we'll get $O(m)$.
|
[
"data structures",
"dsu",
"graphs",
"hashing",
"sortings"
] | 2,100
| null |
193
|
A
|
Cutting Figure
|
You've gotten an $n × m$ sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as $A$. Set $A$ is connected. Your task is to find the minimum number of squares that we can delete from set $A$ to make it not connected.
A set of painted squares is called connected, if for every two squares $a$ and $b$ from this set there is a sequence of squares from the set, beginning in $a$ and ending in $b$, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
|
Main idea: using the fact that the answer cannot be greater than 2, check answer 1. Let's proof that the answer is not greater than 2. Let area of the figure be greater than 3. Let's examine the leftmost of all topmost squares. There is no neighbors left or up to it. So, number of its neighbors is not more than 2. Thus, if we delete its neighbors, we shall disconnect the figure. If the area is equal to 3, we always can disconnect the figure by deletion of one square. It can be proofed by considering all two primary cases. If the area is not greater than 2, there is no way to disconnect the figure. The algorithm: Check answer 1. We can simply brute-force the square to delete, and for each instance start dfs from any existing square. If during the dfs we visited not all of the remaining squares, we have found the square to delete. The answer is 1 if our bruteforce succeeded, and 2 otherwise. That was necessary to consider the case when there is no answer. The complexity of the described algorithm is $O(n^{4})$. That was possible to search for articulation points and solve the problem in complexity $O(n^{2})$, but in my opinion that required more time and effort.
|
[
"constructive algorithms",
"graphs",
"trees"
] | 1,700
| null |
193
|
B
|
Xor
|
John Doe has four arrays: $a$, $b$, $k$, and $p$. Each array consists of $n$ integers. Elements of all arrays are indexed starting from $1$. Array $p$ is a permutation of integers $1$ to $n$.
John invented a game for his friends and himself. Initially a player is given array $a$. The player must consecutively execute exactly $u$ operations on $a$. You are permitted to execute the following operations:
- Operation 1: For each $i\in\{1,2,\dots,n\}$ change $a_{i}$ into $a_{i}\oplus b_{i}$. Expression $x\oplus y$ means applying the operation of a bitwise xor to numbers $x$ and $y$. The given operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "^", in Pascal — as "xor".
- Operation 2: For each $i\in\{1,2,\dots,n\}$ change $a_{i}$ into $a_{pi} + r$. When this operation is executed, all changes are made at the same time.
After all $u$ operations are applied, the number of points the player gets is determined by the formula $s=\textstyle\sum_{i=1}^{i\geq n}a_{i}k_{i}$.
John wants to find out what maximum number of points a player can win in his game. Help him.
|
Main idea: bruteforce in complexity $O(F_{u}n)$ where $F_{u}$ if fibonacci number at position $u$. This problem had complex statements. We have an array $a$, and we can transform it in two ways. The goal was to maximize the sum of all its elements with given multipliers after exactly $u$ operations. A simple bruteforce of all combinations of operations with subsequent modeling leads to complexity $O(2^{u} * nu)$, what is not fast enough. That was possible to optimize it by modeling parallel to recursive bruteforce. Now we have complexity $O(2^{u}n)$. Actually, the correct solution is not too far from this algorithm. There is just one conjecture: every two successive xor operations change nothing, and we can move them to any place of the combination. Thus, it will be enough to bruteforce only combinations in which every pair of successive xor operations is at the end. It could be done using recoursive bruteforce. We must change in previous solution two things. First, we must n't put xor after xor. Besides that, we should update answer if number $u - l$ is even, where $l$ is current level of recoursion (all remaining operations in the end separates to pairs of xors). Let's calculate complexity of this algo. There are $F_{i}$ sequences of length $i$ without two consecutive xors. It's easy to proof, you can calculate some dp to see it. That's why, complexity of our algo is $O(F_{u}n)$.
|
[
"brute force"
] | 2,000
| null |
193
|
C
|
Hamming Distance
|
Hamming distance between strings $a$ and $b$ of equal length (denoted by $h(a, b)$) is equal to the number of distinct integers $i$ $(1 ≤ i ≤ |a|)$, such that $a_{i} ≠ b_{i}$, where $a_{i}$ is the $i$-th symbol of string $a$, $b_{i}$ is the $i$-th symbol of string $b$. For example, the Hamming distance between strings "aba" and "bba" equals $1$, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals $4$.
John Doe had a paper on which four strings of equal length $s_{1}$, $s_{2}$, $s_{3}$ and $s_{4}$ were written. Each string $s_{i}$ consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.
Help John restore the strings; find some four strings $s'_{1}$, $s'_{2}$, $s'_{3}, s'_{4}$ of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set $s'_{i}$ must satisfy the condition $\forall i,j\in\{1,2,3,4\},h(s_{i},s_{j})=h(s_{i}^{\prime},s_{j}^{\prime})$.
To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of \textbf{minimum length}.
|
Main idea: reduction to system of linear equations and solving it using Gauss algorithm. Let's notice that order of columns in answer doesn't matter. That's why there is only one important thing - quantity of every type of column. There is only $2^{4} = 16$ different columns. Let's represent Hamming distance between every pair of strings as sum of quantities of types of columns. It's possible because every column adds to every distance between pairs $0$ or $1$. Now we have system of 6 linear equations with 16 variables. It's not good, let's decrease number of variables. First, some columns adds same values to every Hamming distance. For example strings "abbb" and "baaa". For every column $q$ we can replace all letters "a" by letters "b" and all letters "b" by letters "a" and reach column that adds same values to every distance. We reduced number of variables to 8. We also can notice that columns "aaaa" and "bbbb" is useless and reduce number of variables to 7. This system can be solved using Gauss algorithm. One variable steel be free. Let's fix it. It's value can't be more than maximum of $h(s_{i}, s_{j})$ because column adds positive value to one or more Hamming distance. For every fixed value we should check if all variables take non-negative integer value and choose the best answer. We can solve system of equations in integers because coefficients of equation is little. Complexity of this solution if $O(max(h(s_{i}, s_{j})))$. If we solve it in rational numbers complexity will change to $O(m a x(h(s_{i},s_{i}))\cdot\log A n s)$.
|
[
"constructive algorithms",
"greedy",
"math",
"matrices"
] | 2,400
| null |
193
|
D
|
Two Segments
|
Nick has some permutation consisting of $p$ integers from $1$ to $n$. A segment $[l, r]$ ($l ≤ r$) is a set of elements $p_{i}$ satisfying $l ≤ i ≤ r$.
Nick calls a pair of segments $[a_{0}, a_{1}]$ and $[b_{0}, b_{1}]$ ($1 ≤ a_{0} ≤ a_{1} < b_{0} ≤ b_{1} ≤ n$) good if all their $(a_{1} - a_{0} + b_{1} - b_{0} + 2)$ elements, when sorted in ascending order, form an arithmetic progression with a difference of $1$. That is, when they sorted in ascending order, the elements are in the form ${x, x + 1, x + 2, ..., x + m - 1}$, for some $x$ and $m$.
Your task is to find the number of distinct pairs of good segments in the given permutation. Two pairs of segments are considered distinct if the sets of elements contained in these pairs of segments are distinct. For example, any segment $[l, r]$ $(l < r)$ can be represented as a pair of segments, as $[l, i]$ and $[i + 1, r]$ ($l ≤ i ≤ r$). As all these pairs consist of the same set of elements, they are considered identical.
See the notes accompanying the sample tests for clarification.
|
Main idea: inverse the permutation and solve simplified problem (see below), consider function "quantity of segments of permutation that form the given segment of natural series". In order to solve this problem, we suggest solve another: <<we have a permutation $p_{n}$, we have to calculate the count of segments such that their elements form one or two segments of natural series>>. If we solve the inverse problem for some permutation $q_{n}$ such that $\forall i(q_{p_{i}}=i)$, we shall get the answer for the initial problem and initial permutation $p_{i}$. Straight-forward algo: let's bruteforce the segment of permutation and mark its elements in a boolean array. Check that in that array there is not more than two marked segments. This algo has complexity $O(n^{3})$. Let's notice that during the changeover from $[l, r]$ to $[l, r + 1]$ the quantity of segments changes in some predictable way. Let $s([a, b])$ be quantity of segments that form segment $[a, b]$ of permutation. There are three cases (see picture below): If the new element $p_{r + 1}$ is between two marked elements (that is, both elements with values $p_{r + 1} - 1$ and $p_{r + 1} + 1$ belong to segment $[l, r]$), then $s([l, r + 1]) = s([l, r]) - 1$. The new element will <> the segments near it. If the new element $p_{r + 1}$ has only one neighbor with value belonging to $[l, r]$, then $s([l, r + 1]) = s([l, r])$. The new element will lengthen one of existing segments. If there are no marked elements near $p_{r + 1}$ the new element forms a new segment, $s([l, r + 1]) = s([l, r]) + 1$. The new element is red, elements that are marked to this moment are black. Improved algo: Let's bruteforce position of the left border and for each instance move the right border from left to right. During each move we shall recount the actual quantity of segments forming the current segment of permutation ($s([l, r])$). Now we have a solution in complexity $O(n^{2})$. It works fast enough even when $n = 20000$. Obviously, that is not enough to get AC. Move on full solution. It is based on previous. Now we can calc $s([l, r])$ using $s([l, r - 1])$. Now we should look at way of changing $s([l - 1, r])$ as compared with $s([l, r])$. Let's move left border of segment from the right to left and support some data structure with $s([l, i])$ for every $i$ satisfying $l < i \le n$ and current $l$. This structure should answer queries "count numbers 1 and 2 in structure", that is count segments $[l, i]$ that generates one or two segments in the original permutaton. Let $ \Delta _{i}$ be $s([l - 1, i]) - s([l, i])$. $ \Delta _{l}$ will be equal to $1$ because one element form one segment in permutation (notice that in final answer we must not consider 1-element segments, that's why we must subtract $n$ from answer in the end of solution). $ \Delta _{i}$ determined by the number of neighbors of element $l - 1$ in the segment $[l - 1, i]$. Neighbors of $l - 1$ is elements $p_{l - 1} + 1$ and $p_{l - 1} - 1$ if they're exist. If $l - 1$ hasn't neighbors in this segment, $ \Delta _{i} = 1$, because $l - 1$ froms new 1-element segment. If $l - 1$ has one neighbor in this segment $ \Delta _{i} = 0$, because $l - 1$ join to existing segment of its neighbor. If $l - 1$ has two neighbors in this segment $ \Delta _{i} = - 1$, because $l - 1$ connect segments of its neighbors. Number of neighbors in segment $[l - 1, i]$ non-decreasing with increasing $i$. That's why $ \Delta _{i}$ non-decreasing with increasing $i$. That means that there are only three segments of equivalence of $ \Delta _{i}$. We are interested only in neighbors of $l - 1$ which positions are right than $l - 1$. Let $a$ is position of first neighbor, $b$ is position of second neighbor, without loss of generality $a < b$. Then $\forall i\in[l,a-1]\Delta_{i}=1$, $\forall i\in[a,b-1]\Delta_{i}=0$, $\forall i\in[b,n-1]\Delta_{i}=-1$. (elements of permutation are numbered from 0). If $a$ and $b$ aren't exist, for all $i\in[l,n-1]$ $ \Delta _{i} = 1$. If only $b$ isn't exist for $i\in[l,a-1]\Delta_{i}=1$, for $i\in[a,n-1]\Delta_{i}=0$. Look at example to clear your understanding. ($ \Delta _{i}$ is in top right corners, $l = 3, p_{l} = 5$) Using this facts we can code data structure support following operations: Add +1 or -1 on segment Calc number of 1 and 2 in the structure. Sum of answers of structure in every iteration (for every $l$) is answer to problem. Let's notice that all numbers in structure will be positive. That's why elements 1 and 2 will be minimal of pre-minimal in the structure. Using this fact we can code segment tree, supports these operations. Complexity of this solution is $O(n\log n)$. We also can code sqrt-decomposition and obtain complexity $O(n{\sqrt{n}})$.
|
[
"data structures"
] | 2,900
| null |
193
|
E
|
Fibonacci Number
|
John Doe has a list of all Fibonacci numbers modulo $10^{13}$. This list is infinite, it starts with numbers $0$ and $1$. Each number in the list, apart from the first two, is a sum of previous two modulo $10^{13}$. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by $10^{13}$.
John got interested in number $f$ ($0 ≤ f < 10^{13}$) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number $f$ in the list or otherwise state that number $f$ does not occur in the list.
The numeration in John's list starts from zero. There, the $0$-th position is the number $0$, the $1$-st position is the number $1$, the $2$-nd position is the number $1$, the $3$-rd position is the number $2$, the $4$-th position is the number $3$ and so on. Thus, the beginning of the list looks like this: $0, 1, 1, 2, 3, 5, 8, 13, 21, ...$
|
Main idea: baby-step-giant-step. In this problem we had some Fibonacci number modulo $10^{13}$ $f$, and we had to determine the position of its first occurence in Fibonacci sequence modulo $10^{13}$. Let $a$ and $b$ be two different coprime modula - divisors of $10^{13}$. Let $F$ be the actual Fibonacci number such that $F\mathrm{\mod\10^{13}}=f$. Then $f\ \ \mathrm{mod}\ a=F\ \mathrm{mod}\ a$ and $f\mod b=F\,\mod b$. Find all occurences of number $f{\mathrm{~mod~}}a$ in Fibonacci sequence modulo $a$ period. Find all occurences of number $f\mod b$ in Fibonacci sequence modulo $b$ period. Let's fix a pair of such occurences. Let the occurence modulo $a$ be in position $i$, and the occurence modulo $b$ be in position $j$. Let $t(m)$ be Fibonacci sequence modulo $m$ period. From the Chinese Remainder Theorem, it follows that $t(ab) = LCM(t(a), t(b))$ (remember that $a$ and $b$ are coprime). Then from fixed occurences of $f$ in periods of sequences modulo $a$ and $b$ we can recover the position of occurence of $f$ in period of sequence modulo $ab$. It could be done by solving the following Diophantine equation: $i + t(a) * x = j + t(b) * y$. We can solve it using a simple bruteforce of one of the roots. If the occurence in sequence modulo $ab$ period ( we have just found it) is $u$, then every occurence $f$ in Fibonacci sequence modulo $10^{13}$ period can be represented as $t(ab) * k + u$. Then let's bruteforce $k$ and find all occurences in sequence modulo $10^{13}$ period. To determine Fibonacci number on position $ \alpha + t(ab)$ from known Fibonacci number on position $ \alpha $, we need to multiply the vector ($F_{ \alpha }, F_{ \alpha + 1}$) and some matrix. Let's choose $a = 5^{9}$ and $b = 2^{13}$. Note that there is no number that occur Fibonacci sequence modulo $a$ or $b$ period more than $8$ times. That means that total count of pairs will never be greater than $64$. For each occurence we'll bruteforce not more than $\frac{t(10^{13})}{L C M(t(5^{9}),t(2^{13}))}$ numbers. That was the author's solution. Also that was possible to use the fact that for any number the count of its occurences in period of sequence modulo $10^{p}$ (for any natural $p$) is not big more efficiently. From occurences in sequence modulo $10^{i}$ period we could get occurences in sequence modulo $10^{i + 1}$ period using the method we use to jump from modulus $ab$ to modulus $10^{13}$.
|
[
"brute force",
"math",
"matrices"
] | 2,900
| null |
194
|
A
|
Exams
|
One day the Codeforces round author sat exams. He had $n$ exams and he needed to get an integer from $2$ to $5$ for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark $2$.
The author would need to spend too much time and effort to make the sum of his marks strictly more than $k$. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than $k$, the author's mum won't be pleased at all.
The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams.
Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all $n$ exams equal exactly $k$.
|
Let's notice that $2n \le k \le 5n$. If $k < 3n$ author has to get $2$ on some exams. There are $3n - k$ such exams and that's the answer). If $3n \le k$ author will pass all exams (answer is $0$).
|
[
"implementation",
"math"
] | 900
| null |
194
|
B
|
Square
|
There is a square painted on a piece of paper, the square's side equals $n$ meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks $(n + 1)$ meters, he draws a cross (see picture for clarifications).
John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?
\begin{center}
{\scriptsize The figure shows the order in which John draws crosses for a square with side $4$. The lower left square has two crosses. Overall John paints $17$ crosses.}
\end{center}
|
Let the pencil move by the line and put crosses through every $(n + 1)$ point. Lets associate every point on the line with point on square perimeter. Namely, point $x$ on the line will be associated with point on square perimeter that we will reach if we move pencil around square to $x$ clockwise. Then lower left corner will be associated with all points $4np$ for every non-negative integer $p$. Crosses will be associated with points $k(n + 1)$ for some non-negative $k$. Nearest point of overlap of two families of points will be in point LCM($n + 1$, $4n$). Then we will put $\frac{L C M\left(n+1,4n\right)}{n+1}\ +\ 1$ crosses.
|
[
"math"
] | 1,200
| null |
195
|
A
|
Let's Watch Football
|
Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the size of downloaded data per second.
The guys want to watch the whole video without any pauses, so they have to wait some \textbf{integer} number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.
Let's suppose that video's length is $c$ seconds and Valeric and Valerko wait $t$ seconds before the watching. Then for any moment of time $t_{0}$, $t ≤ t_{0} ≤ c + t$, the following condition must fulfill: the size of data received in $t_{0}$ seconds is not less than the size of data needed to watch $t_{0} - t$ seconds of the video.
Of course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses.
|
The whole video will be downloaded in $all = (c \cdot a + b - 1) / b$ seconds. In this problem you can choose every $1 < = t < = all$ as an answer. To fulfill coditions of the problem it is enough to check the condition $t0 \cdot b > = (t0 - t) \cdot a$ at the moment of time t0 = all.
|
[
"binary search",
"brute force",
"math"
] | 1,000
| null |
195
|
B
|
After Training
|
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has $n$ balls and $m$ baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from $1$ to $m$, correspondingly. The balls are numbered with numbers from $1$ to $n$.
Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which ${\bigg|}{\frac{m+1}{2}}-i{\bigg|}$ is minimum, where $i$ is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.
For every ball print the number of the basket where it will go according to Valeric's scheme.
Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
|
In this problem you should carefully implement the given process. Firstly note that ball number $i > m$ will be in the same basket as ball number $i - m$. Therefore it is enough to distribute first $m$ balls. It can be done using two pointers $lf$, $rg$ from the middle. Alternately put one ball to the left and to the right and shift pointers. In only case you should shift left pointer twice in the first moment of time if $m$ is odd.
|
[
"data structures",
"implementation",
"math"
] | 1,300
| null |
195
|
C
|
Try and Catch
|
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
- The try operator. It opens a new try-catch-block.
- The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.
The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type $a$. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type $a$ as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".
To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.
Your task is: given a program in VPL, determine, what message will be displayed on the screen.
|
In this problem you was to implement what was writen in the statement. In my solution I did the following. Erase all spaces from the text except spaces in messages in try-catch blocks. Then when we get word "try" we put number of the new try-catch block in stack. When we get word "throw" we remember it's type and current state of stack (that is what try-catch blocks are opened). For example, put these number in set. When we get word "catch" if it's type equals to type of operator "throw" and the number of current try-catch block is in your set then write the answer now else erase this try-catch block from stack. If there was no suitable try-catch block write "Unhandled Exception".
|
[
"expression parsing",
"implementation"
] | 1,800
| null |
195
|
D
|
Analyzing Polyline
|
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
\[
y_{i}(x)=\left\{k_{i}\cdot x+b_{i},\quad{\mathrm{if~}}k_{i}\cdot x+b_{i}\geq0;\quad\mathrm{o;}
\]
Let's define a sum of $n$ functions $y_{1}(x), ..., y_{n}(x)$ of the given type as function $s(x) = y_{1}(x) + ... + y_{n}(x)$ for any $x$. It's easy to show that in this case the graph $s(x)$ is a polyline. You are given $n$ functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph $s(x)$, that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
|
In fact in this problem we were given lines $y_{i} = k_{i} * x + b_{i}$ but negative values were replaced by zero. Your task was to find the number of angles that do not equal 180 degrees in the graph s(x), that is the sum of the given functions. Firstly note that sum of two lines is also line. Indeed $y = y_{1} + y_{2}$ is $y = k_{1} * x + b_{1} + k_{2} * x + b_{2} = (k_{1} + k_{2}) * x + (b_{1} + b_{2})$. Consider points where $y_{i} = 0$, that is $x_{i} = - b_{i} / k_{i}$. While we assume that $k_{i}$ doesn't equal to 0. Then line number $i$ is divided in two lines one of which identically equals to 0. Consider all different points $x_{i}$ and sort them. Then, obviously, the sum of the given functions between two consecutive points is line. Find the equation of the line. Assume that we consider point $i$ from the left. Then equation of the line between points $i$ and $i + 1$ will not be equal to equation of the line between points $i$ and $i - 1$. That is in point $i$ is formed an angle that doesn't equal 180 degrees. So we should find equations of lines between every pair of points $i$ and $i + 1$. It can be easily done using two arrays with queries of increasing value on the interval offline.
|
[
"geometry",
"math",
"sortings"
] | 1,900
| null |
195
|
E
|
Building Forest
|
An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.
The root of vertex $v$ of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex $v$ moving along the edges of the weighted oriented forest. We denote the root of vertex $v$ as $root(v)$.
The depth of vertex $v$ is the sum of weights of paths passing from the vertex $v$ to its root. Let's denote the depth of the vertex $v$ as $depth(v)$.
Let's consider the process of constructing a weighted directed forest. Initially, the forest does not contain vertices. Vertices are added sequentially one by one. Overall, there are $n$ performed operations of adding. The $i$-th $(i > 0)$ adding operation is described by a set of numbers $(k, v_{1}, x_{1}, v_{2}, x_{2}, ... , v_{k}, x_{k})$ and means that we should add vertex number $i$ and $k$ edges to the graph: an edge from vertex $root(v_{1})$ to vertex $i$ with weight $depth(v_{1}) + x_{1}$, an edge from vertex $root(v_{2})$ to vertex $i$ with weight $depth(v_{2}) + x_{2}$ and so on. If $k = 0$, then only vertex $i$ is added to the graph, there are no added edges.
Your task is like this: given the operations of adding vertices, calculate the sum of the weights of all edges of the forest, resulting after the application of all defined operations, modulo $1000000007$ $(10^{9} + 7)$.
|
The longest operation in this problem is to find the root of some vertex and the sum of the path to this root. To find these values fast we will use compression ways heuristics which is used in data structure "disjoint-set-union". For every vertex v we keep two values : $c[v]$ and $sum[v]$. $c[v] = v$, if $v$ - root, else $c[v]$ - next vertex on path from $v$ to root. $sum[v]$ = sum of lengths of edges on path from $v$ to $c[v]$. To add new edge from $u$ to $v$ of length $w$ it is enough to do $c[u] = v$ and $sum[u] = w$. Note that we only add new edges (we don't erase edges). That is, if we find $root(v)$ and $depth(v)$ for some vertex $v$ we can assign $c[v] = root(v)$, Unable to parse markup [type=CF_TEX] time. The approximate implementation is shown below. int root(int v){ if(c[v] == v){ return v; }else{ int u = root(c[v]); sum[v] = (sum[c[v]] + sum[v]) % M; c[v] = u; return u; } } It can proved that such implementation works using $O(log(n))$ time for every query. The complexity of the solution is $O(n * log(n))$.
|
[
"data structures",
"dsu",
"graphs"
] | 2,000
| null |
196
|
A
|
Lexicographically Maximum Subsequence
|
You've got string $s$, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string $s[p_{1}p_{2}... p_{k}] = s_{p1}s_{p2}... s_{pk}(1 ≤ p_{1} < p_{2} < ... < p_{k} ≤ |s|)$ a subsequence of string $s = s_{1}s_{2}... s_{|s|}$.
String $x = x_{1}x_{2}... x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{|y|} = y_{|y|}$, or exists such number $r$ $(r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in lines are compared like their ASCII codes.
|
Solution is greedy. First, write all 'z' letters (if there is any) - answer must contain them all for sure. Now it's time for 'y' letters. We can use only those of them which are on the right of last used 'z' letter. Then write 'x' letters - they must be on the right of the last used 'y' and 'z' letters. And so on.
|
[
"greedy",
"strings"
] | 1,100
| null |
196
|
B
|
Infinite Maze
|
We've got a rectangular $n × m$-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell $(x, y)$ is a wall if and only if cell $(x{\mathrm{~mod~}}n,y{\mathrm{~mod~}}m)$ is a wall.
In this problem $a{\mathrm{~mod~}}b$ is a remainder of dividing number $a$ by number $b$.
The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell $(x, y)$ he can go to one of the following cells: $(x, y - 1)$, $(x, y + 1)$, $(x - 1, y)$ and $(x + 1, y)$, provided that the cell he goes to is not a wall.
|
Answer is "Yes" iff there are two distinct, reachable from start position cells, which correspond to same cell in initial labyrinth. Proof: If these cells exist, move to first of them, and infinitely repeat moves leading from first to second. On the contrary, if infinite far path exist, on this path we obviously can find such cells. How to find out if they exist? Start DFS from initial cell. For each cell visited, let $visit[x%n][y%m] = (x, y)$. Now, if DFS tries to go to cell $(x, y)$, $visit[x%n][y%m]$ contains something, and $(x, y) \neq visit[x%n][y%m]$, we found these cells: they are $(x, y)$ and $visit[x%n][y%m]$. Notice that DFS will visit no more than $nm + 1$ cells (Dirichlet's principle). So the asymptotic is $O(nm)$.
|
[
"dfs and similar",
"graphs"
] | 2,000
| null |
196
|
C
|
Paint Tree
|
You are given a tree with $n$ vertexes and $n$ points on a plane, no three points lie on one straight line.
Your task is to paint the given tree on a plane, using the given points as vertexes.
That is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If two vertexes of the tree are connected by an edge, then the corresponding points should have a segment painted between them. The segments that correspond to non-adjacent edges, should not have common points. The segments that correspond to adjacent edges should have exactly one common point.
|
No three points are in the same line, so the solution always exists. First, choose any one vertex as the root of tree. Find size of each subtree using dfs. Then, we can build the answer recursively. Put the root of tree to the most lower left point. Sort all other points by angle relative to this lower left point. Let us name the sizes of subtrees of the root as $s_{1}$, $s_{2}$, ..., $s_{k}$. Run the algorithm recursively, giving first $s_{1}$ points (in sorted order) for the first subtree of root, next $s_{2}$ points for the second subtree and so on. Obviously, no two edges from different subtrees can intersect now. At each step of recursion we are to put the root of current subtree to the first point in sorted-by-angle order, and then sort other points by angle relative to it. So, no two subtrees will have any intersecting edges. The asymptotic of solution is $O(N^{2}\log N)$.
|
[
"constructive algorithms",
"divide and conquer",
"geometry",
"sortings",
"trees"
] | 2,200
| null |
196
|
D
|
The Next Good String
|
In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to $d$.
You are given string $s$, consisting only of lowercase English letters. Find a good string $t$ with length $|s|$, consisting of lowercase English letters, which is lexicographically larger than $s$. Of all such strings string $t$ must be lexicographically minimum.
We will call a non-empty string $s[a ... b] = s_{a}s_{a + 1}... s_{b}$ $(1 ≤ a ≤ b ≤ |s|)$ a substring of string $s = s_{1}s_{2}... s_{|s|}$.
A non-empty string $s = s_{1}s_{2}... s_{n}$ is called a palindrome if for all $i$ from $1$ to $n$ the following fulfills: $s_{i} = s_{n - i + 1}$. In other words, palindrome read the same in both directions.
String $x = x_{1}x_{2}... x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{|y|} = y_{|y|}$, or there exists such number $r$ $(r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in such strings are compared like their ASCII codes.
|
464B - Restore Cube
|
[
"data structures",
"greedy",
"hashing",
"strings"
] | 2,800
| null |
196
|
D
|
The Next Good String
|
In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to $d$.
You are given string $s$, consisting only of lowercase English letters. Find a good string $t$ with length $|s|$, consisting of lowercase English letters, which is lexicographically larger than $s$. Of all such strings string $t$ must be lexicographically minimum.
We will call a non-empty string $s[a ... b] = s_{a}s_{a + 1}... s_{b}$ $(1 ≤ a ≤ b ≤ |s|)$ a substring of string $s = s_{1}s_{2}... s_{|s|}$.
A non-empty string $s = s_{1}s_{2}... s_{n}$ is called a palindrome if for all $i$ from $1$ to $n$ the following fulfills: $s_{i} = s_{n - i + 1}$. In other words, palindrome read the same in both directions.
String $x = x_{1}x_{2}... x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{|y|} = y_{|y|}$, or there exists such number $r$ $(r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in such strings are compared like their ASCII codes.
|
Notice, that only palindromes with length $d$ and $d + 1$ matter. Any palindrome with greater length contains one of them. Let's call these palindromes bad. First, find leftmost position $pos$, in which we surely should increase value of symbol. If there are no bad subpalindromes, $pos = |s| - 1$, else $pos$ is leftmost position amongst all ends of bad palindromes. Increase $s[pos]$. Increase it more, while $s[pos]$ is end of bad subpalindrome. If you try increase 'z' symbol, you should proceed to increasing previous symbol. If this way you reached situation when you need to increase first symbol, and it is 'z', answer is "Impossible". Now, let pos be position of leftmost changed symbol. We know, that prefix $s[0..pos]$ doesn't contain bad palindromes. Now we can greedily fill suffix $s[pos + 1..length(s) - 1]$: go over positions $i$ in ascending order, assign $s[i]$ = 'a', and increase it, while $s[i]$ is end of bad palindrome. Obviously, any of suffix symbols will be 'a', 'b' or 'c'. So we got algorithm, which requires fast implementation of next operations - assigning single symbol, and query: is given substring palindrome? You can perform this operations using hashes and Fenwick tree. Let's learn, how to get hash of substring in dynamically changing string. If we can it, we will keep string $s$ and it's reversed copy. For query of second type we just need to compare hashes of substring in $s$ and hash of corresponding substring in reversed copy. Let Fenwick tree store values $h[i] = s[i]P^{i}$, where $P$ is the prime number used for hashing. Then hash of substring $s[L..R]$ equals to $(h[L] + h[L + 1] + ...h[R])P^{ - L}$. For assigning $s[i] = c$, add value $(c - s[i])P^{i}$ to $h[i]$. Both these operations Fenwick tree does in $O(\log N)$.
|
[
"data structures",
"greedy",
"hashing",
"strings"
] | 2,800
| null |
196
|
E
|
Opening Portals
|
Pavel plays a famous computer game. A player is responsible for a whole country and he can travel there freely, complete quests and earn experience.
This country has $n$ cities connected by $m$ bidirectional roads of different lengths so that it is possible to get from any city to any other one. There are portals in $k$ of these cities. At the beginning of the game all portals are closed. When a player visits a portal city, the portal opens. Strange as it is, one can teleport from an open portal to an open one. The teleportation takes no time and that enables the player to travel quickly between rather remote regions of the country.
At the beginning of the game Pavel is in city number $1$. He wants to open all portals as quickly as possible. How much time will he need for that?
|
First of all, we can note that if each graph vertex is portal, the answer will be a sum of all edges' weights in MST (minimal spanning tree). We can find MST by using Kruskal's algo. In this problem, not an every vertex is portal. Let's fix this. Start with a precalculation. Run Dijkstra's algo from all the portals, simultaneously. We will get $d[i]$ - a distance between vertex $i$ and $p[i]$ - the nearest portal to vertex $i$. Let's trace Kruskal's algo on a graph of portals. On the first iteration, it will choose the edge with the minimal cost, i.e. a shortest path between all the portals in the original graph. Let the path leads from portal $x$ to portal $y$. Note that there exists a path with the same length such as $p[i]$ changes only once through it. Indeed, $p[x] = x$, $p[y] = y$, i.e. $p[i]$ changed on the path. If it happens on edge $i\rightarrow j\,$, $p[i] = x$, a path $\overline{{{\cal T}}}\rightarrow\L_{++}\rightarrow\bar{\cal l}^{'}\rightarrow\L_{++}\rightarrow\L_{+}\rightarrow\L_{+}\rightarrow\L\bar{\cal U}\big|\bar{\cal J}\big|$ will not be longer than the path from $x$ to $y$. As $p[i] = x$ and $p[i] = y$, we can see that the length of this path will be $d[i] + w(i, j) + d[j]$, where $w(i, j)$ is the weight of edge $(i, j)$. Kruskal's algo will add this value to the answer and merge portals $x$ and $y$. The shortest-path trees of vertexes $x$ and $y$ will also be merged. Note, that almost nothing changed. The next edge for Kruskal's algo can be find in a similar way - $\operatorname*{min}_{i,j}d[i]+w(i,j)+d[j]$. If this edge connects $x$ and $y$ again, DSU makes us not to count this edge, otherwise this edge connects a different pair of edges and will be counted in an answer. We can easily implement this. Just create a new graph of portals, with an edge $(p[i], p[j])$ of weight $d[i] + w(i, j) + d[j]$ for every edge $(i, j)$ of weight $w(i, j)$ from original graph and run Kruskal's algo. Finally, note that if the starting vertex is not a portal, we shall add $d[1]$ to the answer.
|
[
"dsu",
"graphs",
"shortest paths"
] | 2,600
| null |
197
|
A
|
Plate Game
|
You've got a rectangular table with length $a$ and width $b$ and the infinite number of plates of radius $r$. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.
|
If first player can't make first move (table is too small and plate doesn't fit it, i.e. $2r > min(a, b)$), second player wins. Else first player wins. Winning strategy for first player: place first plate to the center of table. After that he symmetrically reflects moves of second player with respect to center of table. If second player has move, first player has symmetrical move, too. If not, first player won.
|
[
"constructive algorithms",
"games",
"math"
] | 1,600
| null |
197
|
B
|
Limit
|
You are given two polynomials:
- $P(x) = a_{0}·x^{n} + a_{1}·x^{n - 1} + ... + a_{n - 1}·x + a_{n}$ and
- $Q(x) = b_{0}·x^{m} + b_{1}·x^{m - 1} + ... + b_{m - 1}·x + b_{m}$.
Calculate limit $\operatorname*{lim}_{x\to+\infty}{\frac{P(x)}{Q(x)}}$.
|
From math lessons we know, that only higher degrees of polinomials matter in this problem. If denominator degree is larger than numenator degree, answer is "0/1". If numenator degree is larger, answer is infinity. But what is sign of this infinity? To get it consider signs of highest degree factors of polinomials. If they are same, answer is positive infinity, else - negative infinity. If degrees of numenator and denominator are equal, answer is ${\frac{a_{0}}{b_{\mathrm{U}}}}$. To get irreducible fraction, you should divide this numbers by $gcd(a_{0}, b_{0})$. And don't forget that denominator of answer must be positive.
|
[
"math"
] | 1,400
| null |
200
|
A
|
Cinema
|
The capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into $n$ rows, each row consists of $m$ seats.
There are $k$ people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office started selling tickets, each person found the seat that seemed best for him and remembered it as a pair of coordinates $(x_{i}, y_{i})$, where $x_{i}$ is the row number, and $y_{i}$ is the seat number in this row.
It is possible that some people have chosen the same place, then when some people see their favorite seat taken in the plan of empty seats in the theater, they choose and buy a ticket to another place. Each of them has the following logic: let's assume that he originally wanted to buy a ticket to seat $(x_{1}, y_{1})$, then when he comes to the box office, he chooses such empty seat $(x_{2}, y_{2})$, which satisfies the following conditions:
- the value of $|x_{1} - x_{2}| + |y_{1} - y_{2}|$ is minimum
- if the choice is not unique, then among the seats that satisfy the first condition, this person selects the one for which the value of $x_{2}$ is minimum
- if the choice is still not unique, among the seats that satisfy the first and second conditions, this person selects the one for which the value of $y_{2}$ is minimum
Your task is to find the coordinates of a seat for each person.
|
In this problem were given the field, which size is $n \times m$, and $k$ queries. Each query is the cell of the field. You had to find closest free cell for given one (there was used manhattan metric). Than found cell was marked as used. The time complexity of the solution is supposed to be $O(k \cdot \sqrt{k})$. Firstly, we show the main idea, than we show why solution has time complexity $O(k \cdot \sqrt{k})$. First of all, if $n > m$, than rotate matrix by 90 degrees (than we explain purpose of this transformation). We will have two matrices, size of each is $n \times m$. In this matrices we will maintain for each cell the nearest free one to the left and to the right. Suppose we have query - cell $(x, y)$. Iterate $d$ - how much rows we will go above or below. Suppose we fix $d$, than look at the row $x - d$, for example (also we should do same things for row $x + d$). Lets find in this row nearest free cells to the left and to the right of $(x - d, y)$ by using our matrices and try to update answer. When $d$ will be greater than current found answer we will stop, because answer won't update in this case. After we find the answer, we have to change value in some cells of our matrices. It can be done by using structure DSU for each row. Lets show why this solution has time complexity $O(k \cdot \sqrt{k})$. Suppose all queries are equal, for example each query is $(x, y)$. Than if field is big enough, all points will be placed in form of square, which is rotated by 45 degrees and have center in point $(x, y)$. Also the side of the square will have length $\sqrt{k}$. Than diagonal will have length $O({\sqrt{k}})$ too. It means that we see $O({\sqrt{k}})$ rows in each query and we do $O(1)$ operations in each row. If the square doesn't fit into the field, than field is too thin verticaly or horizontaly. So we will have figure looks like rectangle, and one side of this rectangle will be less than $\sqrt{k}$. In this case rotate field so, than least side of rectangle means rows. Than we will see not greater than $\sqrt{k}$ rows in each query and will perform not greater than $O(1)$ operations in each row. This problem is supposed to be the hardest problem of the contest.
|
[
"brute force",
"data structures"
] | 2,400
| null |
200
|
B
|
Drinks
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are $n$ drinks in his fridge, the volume fraction of orange juice in the $i$-th drink equals $p_{i}$ percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the $n$ drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink.
|
This problem was the easiest problem of the contest. There you had to find average of the given numbers. The most participants solved this problem.
|
[
"implementation",
"math"
] | 800
| null |
200
|
C
|
Football Championship
|
Any resemblance to any real championship and sport is accidental.
The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship:
- the team that kicked most balls in the enemy's goal area wins the game;
- the victory gives 3 point to the team, the draw gives 1 point and the defeat gives 0 points;
- a group consists of four teams, the teams are ranked by the results of six games: each team plays exactly once with each other team;
- the teams that get places 1 and 2 in the group stage results, go to the next stage of the championship.
In the group stage the team's place is defined by the total number of scored points: the more points, the higher the place is. If two or more teams have the same number of points, then the following criteria are used (the criteria are listed in the order of falling priority, starting from the most important one):
- the difference between the total number of scored goals and the total number of missed goals in the championship: the team with a higher value gets a higher place;
- the total number of scored goals in the championship: the team with a higher value gets a higher place;
- the lexicographical order of the name of the teams' countries: the country with the lexicographically smaller name gets a higher place.
The Berland team plays in the group where the results of 5 out of 6 games are already known. To be exact, there is the last game left. There the Berand national team plays with some other team. The coach asks you to find such score $X$:$Y$ (where $X$ is the number of goals Berland scored and $Y$ is the number of goals the opponent scored in the game), that fulfills the following conditions:
- $X$ > $Y$, that is, Berland is going to win this game;
- after the game Berland gets the 1st or the 2nd place in the group;
- if there are multiple variants, you should choose such score $X$:$Y$, where value $X - Y$ is minimum;
- if it is still impossible to come up with one score, you should choose the score where value $Y$ (the number of goals Berland misses) is minimum.
|
In this problem was given description of the group stage of some football competition and scoring system. There were given results of all matches, excepting one, and you had to find result of the last match, satisfied some given criterias. Also Berland's team must be first or the second team of the group after than match. Lets note, that in each finished match were not greater than 18 goals. It means that we can brute-force all results of the last match, when score is not greater than 200 goals, and find the best one. One of the easiest way is to fill table to the end (it means to change points value and balls value), than to sort teams according to the given rules and to check that Berland is the first or the second team of the group.
|
[
"brute force",
"implementation"
] | 1,800
| null |
200
|
D
|
Programming Language
|
Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).
Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.
A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled:
- its name equals to the name of the called procedure;
- the number of its parameters equals to the number of parameters of the procedure call;
- the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same.
You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call.
|
In this task were given the list of template functions. Each function have its name and the list of types of arguments (also it can be used universal type). Also there were given set of variables and thier types, and some queries. Each query is function, which has name and list of arguments. For each query you had to find, how many functions from the given list fit to the function from query. There fit means that functions have the same name, same number of arguments and types of all arguments also equal. For solving this problem it is needed to implement comparing of functions. Constrains gave the possibility to brute-force function from the given list and check if the names and arguments of functions are equal.
|
[
"binary search",
"brute force",
"expression parsing",
"implementation"
] | 1,800
| null |
200
|
E
|
Tractor College
|
While most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college — the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Those who score lower marks are unfortunately expelled.
The college has $n$ students, and oddly enough, each of them can be on scholarship. The size of the scholarships varies each term. Since the end-of-the-term exam has just ended, it's time to determine the size of the scholarship to the end of next term.
The monthly budget for the scholarships of the Tractor college is $s$ rubles. To distribute the budget optimally, you must follow these rules:
- The students who received the same mark for the exam, should receive the same scholarship;
- Let us denote the size of the scholarship (in roubles) for students who have received marks $3$, $4$ and $5$ for the exam, as $k_{3}$, $k_{4}$ and $k_{5}$, respectively. The values $k_{3}$, $k_{4}$ and $k_{5}$ must be integers and satisfy the inequalities $0 ≤ k_{3} ≤ k_{4} ≤ k_{5}$;
- Let's assume that $c_{3}$, $c_{4}$, $c_{5}$ show how many students received marks $3$, $4$ and $5$ for the exam, respectively. The budget of the scholarship should be fully spent on them, that is, $c_{3}·k_{3} + c_{4}·k_{4} + c_{5}·k_{5} = s$;
- Let's introduce function $\begin{array}{r}{\int\left({\frac{k}{k_{3}}},{\dot{k}}_{4},{\dot{k}}_{5}\right)=\left|c_{9}\cdot{\dot{k}}_{3}-c_{4}\cdot{\dot{k}}_{4}\right|+\left|c_{4}\cdot{\dot{k}}_{4}-{\dot{c}}_{5}\cdot{\dot{k}}_{5}\right|$ — the value that shows how well the scholarships are distributed between students. In the optimal distribution function $f(k_{3}, k_{4}, k_{5})$ takes the \textbf{minimum} possible value.
Given the results of the exam, and the budget size $s$, you have to find the optimal distribution of the scholarship.
|
In this problem were given four integer numbers $c_{3}, c_{4}, c_{5}, s$. You had to find $0 \le k_{3} \le k_{4} \le k_{5}$ such, that $c_{3} \cdot k_{3} + c_{4} \cdot k_{4} + c_{5} \cdot k_{5} = s$ and $|c_{3} \cdot k_{3}-c_{4} \cdot k_{4}| + |c_{4} \cdot k_{4}-c_{5} \cdot k_{5}|$ is minimal. Firstly, brute-force $k_{4}$ so, that $s-c_{4} \cdot k_{4} \ge 0$. Than look at 4 cases, according to the sign of the value in each modulus. Lets see the case, when $c_{3} \cdot k_{3}-c_{4} \cdot k_{4} \ge 0$ and $c_{4} \cdot k_{4}-c_{5} \cdot k_{5} \ge 0$. Than we have to minimize $c_{3} \cdot k_{3}-c_{5} \cdot k_{5}$. Also $0 \le k_{3} \le k_{4} \le k_{5}$ and $c_{3} \cdot k_{3} + c_{5} \cdot k_{5} = s-c_{4} \cdot k_{4}$. Lets see diofant equation $c_{3} \cdot k_{3} + c_{5}... k_{5} = s-c_{4} \cdot k_{4}$. It can be that this equation doesn't have solution. Lets see the case, when equation has solution. As $c_{3}, c_{5} \ge 0$, than for minimization $c_{3} \cdot k_{3}-c_{5} \cdot k_{5}$ we have to minimize $k_{3}$ and maximize $k_{5}$. All solutions of diofant equation $c_{3} \cdot k_{3} + c_{5} \cdot k_{5} = s-c_{4} \cdot k_{4}$ can be described by using one argument $k$. Than we have to find such segment, that for all $k$ from it, $k_{3}$ will fit above constrains, such segment, that for all $k$ from it, $k_{5}$ will fit above constrains, find intersection of this segments and, if intersection isn't empty, choose such $k$, that $k_{5}$ is maximal. Similar you have to manage remain 3 cases and choose optimal values $k_{3}$ and $k_{5}$ for fixed $k_{4}$. Also you can note, that in all cases minimized function is linear and in segment it has minimal value in one of its ends. So we can only find such segments, that for all $k$ from that segments $k_{3}, k_{5}$ will fit above constrains, and calculate answer in the ends of this segments. If for all fixed $k_{4}$ diofant equation doesn't have solution, or intersections of the described segments are empty, than answer is $IMPOSSIBLE$, else we should find the best. So the time complexity is $O(s \cdot log(s))$ - brute-force of $k_{4}$ and solving diofant equation for fixed $k_{4}$.
|
[
"implementation",
"math",
"number theory",
"ternary search"
] | 2,400
| null |
201
|
A
|
Clear Symmetry
|
Consider some square matrix $A$ with side $n$ consisting of zeros and ones. There are $n$ rows numbered from $1$ to $n$ from top to bottom and $n$ columns numbered from $1$ to $n$ from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the $i$-row and the $j$-th column as $A_{i, j}$.
Let's call matrix $A$ \underline{clear} if no two cells containing ones have a common side.
Let's call matrix $A$ \underline{symmetrical} if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair $(i, j)$ $(1 ≤ i, j ≤ n)$ both of the following conditions must be met: $A_{i, j} = A_{n - i + 1, j}$ and $A_{i, j} = A_{i, n - j + 1}$.
Let's define the \underline{sharpness} of matrix $A$ as the number of ones in it.
Given integer $x$, your task is to find the smallest positive integer $n$ such that there exists a clear symmetrical matrix $A$ with side $n$ and sharpness $x$.
|
It's interesting that originally the authors had an idea not to include the $x = 3$ case into pretests. Imagine the number of successful hacking attempts in this contest -- considering the fact that none of the first $43$ solutions to this problem passed pretests :) Note that the sought $n$ is always an odd number. Indeed, if $n$ is even, then two central rows of matrix $A$ must contain zeroes, otherwise there will exist two neighbouring cells containing ones. Similar restriction applies to two central columns of matrix $A$. Replacing two central rows with just one and two central columns with just one and leaving zeroes in them, we'll obtain a smaller matrix with the same sharpness. Note that the sharpness of a matrix with side $n$ can't exceed $\frac{n^2 + 1}{2}$. It's easy to see that it's possible to lay out $\textstyle{\frac{n^{2}-1}{2}}$ "domino pieces" $1$ by $2$ without intersections on a field with side $n$ (in other words, all cells except one can be divided into pairs so that each pair contains neighbouring cells). Then there can be at most one one in the cells under each "domino piece" in the corresponding matrix. Therefore, the total number of ones doesn't exceed $n^{2}-{\frac{n^{2}-1}{2}}={\frac{n^{2}+1}{2}}$. Note that a matrix with side $n$ and sharpness $\frac{n^2 + 1}{2}$ exists for an odd $n$. Paint all cells of the matrix in chess order and put ones into black cells and zeroes into white cells. It's easy to see that such a matrix is both clear and symmetrical and has sharpenss exactly $\frac{n^2 + 1}{2}$. Intuitively it seems that if there exists a matrix with sharpness $\frac{n^2 + 1}{2}$ there should also exist a matrix with every smaller sharpness. That's correct except only one case -- there doesn't exist a matrix with side $3$ and sharpness $3$, though there exists a matrix with side $3$ and sharpness $5$. Let's show that the claim above is correct for odd $n \ge 5$. We'll build a matrix with sharpness $\frac{n^2 + 1}{2}$ as shown above and gradually turn ones into zeroes reducing the sharpness. Cells containing ones in the matrix can be divided into three types. The first type is the central cell. The number in it can be turned into zero and the matrix won't stop satisfying the required conditions. The second type is the cells in the central row and the central column (except central cell). Such cells are divided into pairs by the condition of symmetry -- if we turn the number in one of them into zero, we should turn the number in its pair cell into zero as well. The third type is all the other cells. Such cells are divided into groups of four by the condition of symmetry -- if we turn the number in one of them into zero, we should turn the number in all cells from this group into zero as well. Now for obtaining the required sharpness of $x$ we'll act greedily. Let's turn ones into zeroes in third type cells by four until the current shapness exceeds $x$ by less than $4$ or there are no third type cells with ones remaining. After that let's turn ones into zeroes in second type cells by pairs while the current sharpness exceeds $x$ by at least $2$. At this moment the sharpness of our matrix is either $x$ or $x + 1$. If it's equal to $x + 1$, let's put a zero into the central cell and obtain a matrix with sharpness $x$. It's easy to check that we'll be able to obtain a matrix with any sharpness acting this way. Why is this reasoning incorrect for $n = 3$? Because second type cells are absent in the matrix with sharpness $5$ obtained from chess coloring. For $n \ge 5$ this matrix contains cells of all types, which is important for the algorithm above. It's better to find the answers for $x \le 5$ by hand but carefully -- for example, a lot of contestants decided that the answer for $x = 2$ is $5$ instead of $3$.
|
[
"constructive algorithms",
"dp",
"math"
] | 1,700
| null |
201
|
B
|
Guess That Car!
|
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".
The game show takes place on a giant parking lot, which is $4n$ meters long from north to south and $4m$ meters wide from west to east. The lot has $n + 1$ dividing lines drawn from west to east and $m + 1$ dividing lines drawn from north to south, which divide the parking lot into $n·m$ $4$ by $4$ meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from $0$ to $n$ from north to south and from $0$ to $m$ from west to east. Each square has coordinates $(i, j)$ so that the square in the north-west corner has coordinates $(1, 1)$ and the square in the south-east corner has coordinates $(n, m)$. See the picture in the notes for clarifications.
Before the game show the organizers offer Yura to occupy any of the $(n + 1)·(m + 1)$ intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" $c$ placed in a square whose center is at distance $d$ from Yura takes $c·d^{2}$ seconds. The time Yura spends on turning his head can be neglected.
It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.
|
We need to find such $x$ and $y$ that the value of $\textstyle\sum_{i_{j}}c_{i j}((x-x_{i})^{2}+(y-y_{j})^{2})$ is minimum possible. This expression can be rewritten as $\textstyle\sum_{i,j}c_{i j}(x-x_{i})^{2}+\sum_{i,j}c_{i j}(y-y_{j})^{2}$. Note that the first part doesn't depend on $y$ and the second part doesn't depend on $x$, so we can minimize these parts separately. Here is how to minimize $\sum_{i,j}c_{i j}(x-x_{i})^{2}$, the second part is minimized similarly. As the expression in the brackets doesn't depend on $j$, this part can be rewritten as $\textstyle\sum_{i}s_{i}(x-x_{i})^{2}$, where $s_{i}=\sum_{j}c_{i j}$. Now it's enough to calculate the required value for all possible values of $x$ and choose $x$ for which this value is the smallest. The optimal value of $y$ can be found similarly. The overall complexity of this solution is $O(n \cdot m + n^{2} + m^{2})$. As the objective function is convex, other approaches to this problem are possible, for example, ternary search, gradient descent or analytical approach (calculation of derivatives).
|
[
"math",
"ternary search"
] | 1,800
| null |
201
|
C
|
Fragile Bridges
|
You are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.
The bonus level consists of $n$ small platforms placed in a line and numbered from $1$ to $n$ from left to right and ($n - 1$) bridges connecting adjacent platforms. The bridges between the platforms are very fragile, and for each bridge the number of times one can pass this bridge from one of its ends to the other before it collapses forever is known in advance.
The player's actions are as follows. First, he selects one of the platforms to be the starting position for his hero. After that the player can freely move the hero across the platforms moving by the undestroyed bridges. As soon as the hero finds himself on a platform with no undestroyed bridge attached to it, the level is automatically ended. The number of points scored by the player at the end of the level is calculated as the number of transitions made by the hero between the platforms. Note that if the hero started moving by a certain bridge, he has to continue moving in the same direction until he is on a platform.
Find how many points you need to score to be sure that nobody will beat your record, and move to the next level with a quiet heart.
|
There are a few different ways to solve this problem, the editorial contains one of them. For any solution the following fact is useful. Suppose the sought path starts on platform $i$ and ends on platform $j$ ($i \le j$, if that's not the case, we can reverse the path). Then all bridges between platforms $i$ and $j$ will be passed through an odd number of times, and all other bridges will be passed through an even number of times. Let's find the maximum length of a path with its ends on platforms $i$ and $j$. To do that, let's find the following auxiliary values for each platform: $left_{i}$ -- the maximum length of a path starting and ending on platform $i$ and passing only through bridges to the left of platform $i$; $right_{j}$ -- similarly for bridges to the right of platform $j$. Also for each bridge define $odd_{i}$ as the largest odd number not larger than $a_{i}$, and for each platform define $sumOdd_{i}$ as the sum of $odd_{j}$ for all bridges to the left of platform $i$. Then the maximum length of a path with its ends on platforms $i$ and $j$ is equal to $left_{i} + right_{j} + (sumOdd_{j} - sumOdd_{i})$, or, which is the same, $(right_{j} + sumOdd_{j}) + (left_{i} - sumOdd_{i})$. Now we can find the pair $(i, j)$ for which this value is the largest in linear time. Let's loop over $j$. From the formula it's obvious that we should find such $i \le j$ that $(left_{i} - sum_{Odd}_{i})$ is the largest. If we loop over $j$ from $1$ to $n$, we can maintain the largest value of this expression for all $i \le j$ and recalculate it when moving to the next $j$, comparing $(left_{j} - sumOdd_{j})$ with the current maximum and possibly updating this maximum. This way for each $j$ we have to check only one value of $i$ and not all $i \le j$. The last thing to show is how to find all $left_{i}$ quickly (all $right_{j}$ can be found similarly). Clearly $left_{1} = 0$, then we'll calculate $left_{i}$ using $left_{i - 1}$. Note that when $a_{i - 1} = 1$, we have $left_{i} = 0$ as after passing the bridge to platform $(i - 1)$ this bridge will collapse and it will be impossible to return to platform $i$. If $a_{i - 1} > 1$, then $left_{i} = left_{i - 1} + even_{i - 1}$, where $even_{i - 1}$ is the largest even number not larger than $a_{i - 1}$. Indeed, we can move to platform $(i - 1)$, then move along the path corresponding to $left_{i - 1}$, and then move along the bridge between platforms $(i - 1)$ and $i$ until the limit on the number of transitions is less than $2$ (finishing on platform $i$). The overall complexity of this solution is $O(n)$.
|
[
"dp"
] | 2,000
| null |
201
|
D
|
Brand New Problem
|
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.
You are invited to act as a fair judge and determine whether the problem is indeed \underline{brand new}, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.
You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.
The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as $p={\frac{n-(n-1)}{2}}-x+1$, where $n$ is the number of words in Lesha's problem and $x$ is the number of inversions in the chosen permutation. Note that the "similarity" $p$ is always a positive integer.
The problem is called \underline{brand new} if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.
Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
|
The first solution coming to mind is dynamic programming $f[i][j] =$ (the smallest possible number of inversions to the moment if among the first $j$ words of the archive problem we've found a permutation of words included in bitmask $i$). In this solution parameter $j$ varies from $0$ to $500000$, parameter $i$ varies from $0$ to $2^{15} - 1$ and calculation of each value is possible in $O(1)$ (we are either using the current word in the subsequence or not). That's too much. Let's make use of a standard technique: make the value of DP a new parameter and make one of the existing parameters the value of DP. Not for every DP this is possible, but at least it's possible for this one :) It's clear that with a fixed subset of words and a fixed number of inversions it's optimal to choose the first occurrences of these words giving this number of inversions. Let $f[i][j] =$ (the smallest number $z$ such that among first $z$ words of the archive problem there exists a permutation of words from bitmask $i$ containing exactly $j$ inversions). The basis of this DP is $f[0][0] = 0$, $f[0][j] = \infty $ for $j > 0$. Recalculation of values happens in the following way: loop over a word $q$ from the bitmask $i$ which was the last in the permutation. With the knowledge of this word and the number of inversions $j$ it's easy to find how many inversions $j'$ there were without this word - that's $j$ minus the number of words in the mask which appeared later in Lesha's problem than word $q$. Let $p = f[i^(1<<q)][j']$. Then we should consider $p_{2}$ equal to the position of the next occurrence of word $q$ after position $p$ as a possible value for $f[i][j]$. To find $p_{2}$ quickly we should fill an array $next[500010][15]$ so that $next[i][j] =$ (the smallest position $k > i$ such that the $k$-th word in the archive problem equals the $j$-th word in Lesha's problem) for each archive problem in advance. This array can be easily filled passing from right to left once. The total number of operations can be calculated as $m \cdot (k \cdot n + 2^{n} \cdot C_{n}^{2} \cdot n)$, where $m$ is the number of problems in the archive, $k$ is the number of words in one archive problem description and $n$ is the number of words in Lesha's problem description. Under the given constraints that is about $200$ million operations, and the author's solutions (including a Java solution) worked for less than $2$ seconds. The time limit was set with a margin -- 5 seconds.
|
[
"bitmasks",
"brute force",
"dp"
] | 2,600
| null |
201
|
E
|
Thoroughly Bureaucratic Organization
|
Once $n$ people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of $n$ people made an appointment on one of the next $n$ days, and no two persons have an appointment on the same day.
However, the organization workers are very irresponsible about their job, so none of the signed in people was told the exact date of the appointment. The only way to know when people should come is to write some requests to TBO.
The request form consists of $m$ empty lines. Into each of these lines the name of a signed in person can be written (it can be left blank as well). Writing a person's name in the same form twice is forbidden, such requests are ignored. TBO responds very quickly to written requests, but the reply format is of very poor quality — that is, the response contains the correct appointment dates for all people from the request form, but the dates are in completely random order. Responds to all requests arrive simultaneously at the end of the day (each response specifies the request that it answers).
Fortunately, you aren't among these $n$ lucky guys. As an observer, you have the following task — given $n$ and $m$, determine the minimum number of requests to submit to TBO to clearly determine the appointment date for each person.
|
Let's imagine that we have a magic function $maxN(m, k)$ that returns, given $m$ and $k$, the largest value of $n$ such that it's possible to solve the problem for $n$ people and $m$ empty lines in the form using $k$ requests. Then we'll be able to use binary search on the answer -- the number of requests $k$. Suppose we've made $k$ requests. Let's match a string of length $k$ to each person, where the $i$-th character is equal to $1$ if this person is mentioned in the $i$-th request and $0$ otherwise. Note that we'll be able to determine the exact appointment date for each person if and only if all $n$ strings of length $k$ are pairwise distinct. Indeed, if two persons' strings are the same, their appointment dates could be exchanged and the responses to the requests wouldn't have changed. If all strings are distinct, for each date we may find the person appointed for this date looking at the set of requests with responses containing this date and finding the person mentioned in the same set of requests. The constraint on $m$ empty lines in the form means that each of $k$ positions in the strings should contain no more than $m$ ones in all $n$ strings overall. Thus function $maxN(m, k)$ should return the maximum size of a set of distinct $k$-bit strings meeting this condition. Let's make this restriction weaker: we'll search for a set such that the total number of ones in all $n$ strings doesn't exceed $k \cdot m$. As we'll prove later, the answer won't change. With this weaker restriction the problem can be solved using a simple greedy strategy. It's obvious that strings with smaller number of ones are better. Let's loop over the number of ones $i$ in the string from $0$ to $k$ and also maintain a variable $t$ containing the remaining number of ones (initially it's equal to $k \cdot m$). Then at the $i$-th step we can take at most $p=m i n(\underline{{{t}}},C_{k}^{i})$ strings containing $i$ ones. Let's add $p$ to the answer and subtract $p \cdot i$ from $t$. Note that the values of $C_{k}^{i}$ should be calculated with care -- they can turn out to be too large, so it's important not to allow overflows. It can be shown that the overall complexity of this algorithm is at most $O(log^{2}$ $n)$. The remaining thing is to prove the claim above. The idea of the proof below belongs to rng_58 (the author's proof is notably harder). Let's solve the problem with a greedy algorithm with the $k \cdot m$ constraint on the total number of ones. The resulting set of strings may not satisfy the restriction of $m$ ones for each position. If it doesn't, some of the positions contain more than $m$ ones and some contain less than $m$ ones. Let's pick any position $X$ containing more than $m$ ones and any position $Y$ containing less than $m$ ones. Find all strings containing $1$ at $X$ and $0$ at $Y$ (suppose there are $x$ such strings) and all strings containing $0$ at $X$ and $1$ at $Y$ (suppose there are $y$ such strings). It's clear that $x > y$. In each of $x$ strings we can try to put $0$ at $X$ and $1$ at $Y$ -- then the string we obtain will either remain unique in this set or coincide with one of those $y$ strings (but only one). As $x > y$, for at least one of $x$ strings the change above leaves this string unique. Let's take this string and put $0$ at $X$ and $1$ at $Y$. Now position $X$ contains one $1$ less, and position $Y$ contains one $1$ more. It means that the total number of "extra" ones in the positions has been decreased (as $Y$ still contains no more than $m$ ones). Doing this operation for a needed number of times, we'll achieve our goal.
|
[
"binary search",
"combinatorics"
] | 2,600
| null |
202
|
A
|
LLPS
|
\underline{This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.}
You are given string $s$ consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string $s[p_{1}$$p_{2}... p_{k}]$ = $s_{p1}s_{p2}... s_{pk}$ ($1$ $ ≤ $ $p_{1} < p_{2} < ... < p_{k}$ $ ≤ $ $|s|$) a \underline{subsequence} of string $s$ = $s_{1}$$s_{2}... s_{|s|}$, where $|s|$ is the length of string $s$. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String $x$ = $x_{1}$$x_{2}... x_{|x|}$ is \underline{lexicographically larger} than string $y$ = $y_{1}$$y_{2}... y_{|y|}$ if either $|x|$ > $|y|$ and $x_{1} = y_{1}$, $x_{2} = y_{2}$, ..., $x_{|y|} = y_{|y|}$, or there exists such number $r$ ($r < |x|$, $r < |y|$) that $x_{1} = y_{1}$, $x_{2} = y_{2}$, ..., $x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String $s$ = $s_{1}$$s_{2}... s_{|s|}$ is a \underline{palindrome} if it matches string $rev(s)$ = $s_{|s|}$$s_{|s| - 1}... s_{1}$. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
|
It's assumed that this problem can be solved just looking at the samples and without reading the statement itself :) Let's find the letter in the given string which comes last in the alphabet, denote this letter by $z$. If this letter occurs $p$ times in the given string, then the answer is string $a$ consisting of letter $z$ repeated $p$ times. Why is it so? Using the definition of lexicographical comparison and the fact that $z$ is the largest letter in the string it's easy to understand that if some other subsequence $b$ of the given string is lexicographically larger than $a$, then string $b$ should be longer than $a$ and, moreover, $a$ should be a prefix of $b$ (that is, $b$ should start with $a$). But string $b$ must be a palindrome, therefore its last letter must be $z$. In this case string $b$ must contain more occurrences of letter $z$ than the original string $s$ does, which is impossible as $b$ is a subsequence of $s$. Besides that, the constraint on the length of the string was very low, so the problem could be solved using brute force. For every subsequence of the given string it's necessary to check whether it's a palindrome, and from all palindromic subsequences of $s$ the lexicographically largest should be chosen as the answer. The complexity of such a solution is $O(2^{n} \cdot n)$, where $n$ is the length of the string (unlike the solution above with complexity $O(n)$).
|
[
"binary search",
"bitmasks",
"brute force",
"greedy",
"implementation",
"strings"
] | 800
| null |
202
|
B
|
Brand New Easy Problem
|
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.
You are invited to act as a fair judge and determine whether the problem is indeed \underline{brand new}, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.
You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.
The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as $p={\frac{n-(n-1)}{2}}-x+1$, where $n$ is the number of words in Lesha's problem and $x$ is the number of inversions in the chosen permutation. Note that the "similarity" $p$ is always a positive integer.
The problem is called \underline{brand new} if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.
Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
|
The constraints in this problem were so low that a solution with complexity $O(m \cdot k^{n})$ was just fine. In each problem's description it's enough to loop over all possible subsequences of words which are permutations of words in Lesha's problem, for each of them calculate the number of inversions and choose a permutation with the smallest number of inversions. This can result in a short solution using recursion or, for example, you can use several nested loops (from $1$ to $4$). Here is an example of pseudocode for $n = 4$: w - array of words of Lesha''s problem s - the description of the current problem best = 100 for a = 1 to k do for b = 1 to k do for c = 1 to k do for d = 1 to k do if s[a] == w[1] and s[b] == w[2] and s[c] == w[3] and s[d] == w[4] then inversions = 0 if a > b then inversions = inversions + 1 if a > c then inversions = inversions + 1 if a > d then inversions = inversions + 1 if b > c then inversions = inversions + 1 if b > d then inversions = inversions + 1 if c > d then inversions = inversions + 1 if inversions < best then best = inversionsAt the end you should choose the problem with the smallest value of $best$ and print the answer in the corresponding form.
|
[
"brute force"
] | 1,700
| null |
204
|
A
|
Little Elephant and Interval
|
The Little Elephant very much loves sums on intervals.
This time he has a pair of integers $l$ and $r$ $(l ≤ r)$. The Little Elephant has to find the number of such integers $x$ $(l ≤ x ≤ r)$, that the first digit of integer $x$ equals the last one (in decimal notation). For example, such numbers as $101$, $477474$ or $9$ will be included in the answer and $47$, $253$ or $1020$ will not.
Help him and count the number of described numbers $x$ for a given pair $l$ and $r$.
|
It is well-known that for such problem you need to write function $F(x)$ which solves the problem for the interval $0..x$, and the answer then is $F(r) - F(l - 1)$. Now you need to write $F(x)$ function. If $x < 10$, then answer is, of course, equal to $x$. Otherwise, let $len$ be the length of $x$, $x'$ - the integer $x$ but without first and last digits, $x_{i}$ - the $i$-th digit of integer $x$ (from left to right, starting from $0$). Interate through all possible first digit $d$ (which is the last at the same time) and through the length $i$ of the number. Then if $i < len - 2$ or ($i = len - 2$ and $d < x_{0}$) you need to add $10^{i}$ to the answer. Otherwise, if $i = len - 2$ and $d = x_{0}$ you need to add $x'$ to the answer. Finally, if $i = len - 2$ and $d = x_{0}$ and $x_{len - 1} \ge d$ add $1$ to the answer. This problems also can be solved using DP.
|
[
"binary search",
"combinatorics",
"dp"
] | 1,500
| null |
204
|
B
|
Little Elephant and Cards
|
The Little Elephant loves to play with color cards.
He has $n$ cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of $n$ cards funny.
|
It is nice to use the $map$ structure in this problem, but you can solve it without $map$ (using sorting and binary serach). Lets iterate through all possible colors that we have and suppose that this currect color is the one that will make our set funny. The minimal number through all this will be the answer. To find the minimal number of turns to make our set funny using current color we need to know two numbers: the number of cards with current color on the front side and the number of cards with the current color on back side (but not at the same time). Let it be integers $a$ and $b$. Let $m = (n + 1) / 2$ - the minimal number of the same cards required to get the funny set. Then if $a + b < m$ it is impossible to make set funny using current color at all. If $a \ge m$ then the answer is $0$, otherwise the answer is $m - a$.
|
[
"binary search",
"data structures"
] | 1,500
| null |
204
|
C
|
Little Elephant and Furik and Rubik
|
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length $a$ and $b$, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length — the first one from string $a$, the second one from string $b$. The choice is equiprobable among all possible pairs. Let's denote the substring of $a$ as $x$, and the substring of $b$ — as $y$. The Little Elephant gives string $x$ to Furik and string $y$ — to Rubik.
Let's assume that $f(x, y)$ is the number of such positions of $i$ ($1 ≤ i ≤ |x|$), that $x_{i} = y_{i}$ (where $|x|$ is the length of lines $x$ and $y$, and $x_{i}$, $y_{i}$ are the $i$-th characters of strings $x$ and $y$, correspondingly). Help Furik and Rubik find the expected value of $f(x, y)$.
|
This problem is to find the expected value. Important fact here is the linearity of the expected value. This means that we can for each element of the first strings find the probability that exactly this element will me matched with some other (but, of course, equal) from the second string. The answer will be the sum of all such probabilities. Let the current character of the first string be the $i$-th character (1-based numeration). Firstly we try to solve problem in $O(N^{2})$ time. Namely, as it was said above, we need to find the number of such pairs of substrings that $i$-th character (which is on probably some other position in substring) is the same as the corresponding character of the second substring. Iterate through all $j$ ($j \le i$) such that $A_{i} = B_{j}$. The number of such pairs of substrings that have match in that characters is $j(n - i + 1)$ (considering 1-based numeration). This is $O(N^{2})$. And because we need to find the sum of such values for all possible $j$, we can rewrite it as $S_{i}(n - i + 1)$, where $S_{i}$ equals to the sum of all integers $j$ ($j \le i$) that $A_{i} = B_{i}$. Array $S$ can be simply computed in a linear time. Analogically you should process all indices to the right from $i$. After we know the number of pairs of substrings with the match with the $i$-th character (let it be $count$), the probability is $count / total$, where $total$ is the total number of pair of substrings (it can be found by loop or with some simple formula). The comlexity is $O(N)$.
|
[
"math",
"probabilities"
] | 2,000
| null |
204
|
D
|
Little Elephant and Retro Strings
|
The Little Elephant has found a ragged old black-and-white string $s$ on the attic.
The characters of string $s$ are numbered from the left to the right from $1$ to $|s|$, where $|s|$ is the length of the string. Let's denote the $i$-th character of string $s$ as $s_{i}$. As the string is black-and-white, each character of the string is either letter "B", or letter "W". Unfortunately, the string is very old and some characters are damaged. The damaged positions are denoted as "X".
The Little Elephant in determined to restore the string and hang it on the wall. For that he needs to replace each character "X" by a "B" or a "W". The string must look good on the wall, so it must be \underline{beautiful}. The Little Elephant considers a string beautiful if it has two non-intersecting substrings of a given length $k$, such that the left one fully consists of characters "B", and the right one fully consists of characters "W". More formally, there are four integers $a, b, c, d$ $(1 ≤ a ≤ b < c ≤ d ≤ |s|; b - a + 1 = d - c + 1 = k)$ such that $s_{i}$ = "B" $(a ≤ i ≤ b)$ and $s_{j}$ = "W" $(c ≤ j ≤ d)$.
Help the Little Elephant find the number of different beautiful strings he can obtain from string $s$. Two strings are considered different if there is such position, where the character in the first string differs from the corresponding character in the second string. If this string doesn't contain characters «X» and it is already beautiful — the answer is 1.
As the answer can be rather large, print it modulo $1000000007$ $(10^{9} + 7)$.
|
Firstly we should solve following subproblem: for each prefix find the number of it's fillings such that there is no consecutive block of $k$ characters $B$. Let it be $F(x)$, where $x$ is the index in of the last character if the prefix. Assing $F(x) = F(x - 1) * cnt$, where $cnt = 2$ if $S_{x}$ = 'X' and $1$ otherwise. After such assing there may be some bad filling included to $F(x)$. Since we suppouse that $F(x - 1)$ is caclulated correctly, all bad filling must contain blocks of $k$ charcters $B$ only at the end of the prefix (they may be included only if substring $S_{x - k + 1..x}$ doesn't contain characters $W$ and character $S_{x - k}$ is not $B$). So, if it's possible, we must subtract from $F(x)$ value $F(x - k - 1)$, because it's exactly the number of bad fillings. With the same DP you should you calc the same values for suffixes (but this time changing $B$ by $W$ and vice versa). Now we should carefully calculate the result in such way that now repeatings occur. Let iterate (from right to left) through all possible positions of the first blocks of $k$ characters $B$ (this means that we suppose that no block occur to the left). Using our DP we can simply find the number of fillings of all characters to the left from that block in such way that no another blocks of $k$ characters $B$ occur. Considering $O(N^{2})$ solutions, we can iterate through all possible indexes of the begging of the last block of $k$ characters $W$ (again we suppose that this blocks must be the last and no another may occur to the right) and agin using our DP count the number of fillings to the right. We don't care what is between that blocks, so we just multiply answer by 2^(the number of characters $X$ between blocks). But, since we are going from right to the left, we can just keep tracking on all possible last blocks and get $O(N)$ solution.
|
[
"dp"
] | 2,400
| null |
204
|
E
|
Little Elephant and Strings
|
The Little Elephant loves strings very much.
He has an array $a$ from $n$ strings, consisting of lowercase English letters. Let's number the elements of the array from 1 to $n$, then let's denote the element number $i$ as $a_{i}$. For each string $a_{i}$ $(1 ≤ i ≤ n)$ the Little Elephant wants to find the number of pairs of integers $l$ and $r$ $(1 ≤ l ≤ r ≤ |a_{i}|)$ such that substring $a_{i}[l... r]$ is a substring to at least $k$ strings from array $a$ (including the $i$-th string).
Help the Little Elephant solve this problem.
If you are not familiar with the basic notation in string problems, you can find the corresponding definitions in the notes.
|
To solve this problems we can use suffix array. More information about suffix arrays you can find in the Internet. Firstly, concatenate all strings into the one separating consecutive strings by some unique characters (it was also useful to not use strings, but arrays of integers). For example, three strings $abc, a, ab$ may be concatenated in the following way: $abc#a@ab$. Now we should build suffix array using this total string, this allows to us to sort all cyclic shifts of the string. After that each cyclic shift will either begin with additional character or the character from the input strings. Notice now that to find the result we need to find for each cyclic shift (begging of which doesn't contain additional character) the largest size of it's prefix such that this prefix is substring of at least $k$ different input strings. This value can be found by binary search, but for this we need some function $F(x, len)$ which can answer the questions: how many input strings contain prefix of size $len$ of $x$ cyclic shift as a substring. How to make $F(x, len)$? Look at all cyclic shifts, prefix of size $len$ of which is equal to preifx of size $len$ of $x$-th shift. Since all shifts are sorted lexicoraphically, this set of shifts can be represented as integral $[l;r]$ of indices of shifts ($1 \le l \le x \le r$). How to find $l$ and $r$? For each pair of consecutive shifts we can find it's greatest common prefix (using properties of suffix array). Than $l$ and $r$ can be found using RMQ. For $l$ we need to know the rigthmost pair of shift (but to the left from $x$) that their greatest common prefix is less than $len$. Analogically we can find $r$. After that we have interval $[l;r]$ and we need to find the number of different input strings that belongs to the shifts from $l$-th to $r$-th (actually, we need to find the number of different integer on interval). But, notice that we dont need the exactly number of different integers, we need to know just it is at least $k$ or not. So let $L[i]$ equals to the greatest $j$ ($j \le i$) such that the number of different integers on interval $[j;i]$ is equal to $k$. Then if $L[r] \ge l$, obiously, interval $[l;r]$ will also contains at least $k$ different. So $F(x, len)$ is done. The only thing to done is to fill array $L$. This is pretty simple using $set$ (but it is possible without it but using RMQ). We will go from left to righ at keep the indices of the last (the rightmost) $k$ different integers in the $set$. If some integer comes, then (if it was earlier) we need to erase this previous index from set (if it was still in) and insert new current. While the size of set is greater than $k$, we should erase the minimal number from it. Then if in some position $i$ the size of the set (after above changings) is equal to $k$, than $L[i]$ is equal to the minimal number in set. Since we $O(N)$ times use binary search, and function $F(x, len)$ works in $O(logN)$ time, the total complexity is $O(Nlog^{2}N)$.
|
[
"data structures",
"implementation",
"string suffix structures",
"two pointers"
] | 2,800
| null |
205
|
A
|
Little Elephant and Rozdil
|
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.
For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
|
This problem was the simplest in the problemset. All you need to do is just to sort all distances (keeping track on all indices). If the first two distances are equal, just output "Still Rozdil", otherwise output the index of the first element of the array. The complexity is $O(NlogN)$.
|
[
"brute force",
"implementation"
] | 900
| null |
205
|
B
|
Little Elephant and Sorting
|
The Little Elephant loves sortings.
He has an array $a$ consisting of $n$ integers. Let's number the array elements from 1 to $n$, then the $i$-th element will be denoted as $a_{i}$. The Little Elephant can make one move to choose an arbitrary pair of integers $l$ and $r$ $(1 ≤ l ≤ r ≤ n)$ and increase $a_{i}$ by $1$ for all $i$ such that $l ≤ i ≤ r$.
Help the Little Elephant find the minimum number of moves he needs to convert array $a$ to an arbitrary array sorted in the non-decreasing order. Array $a$, consisting of $n$ elements, is sorted in the non-decreasing order if for any $i$ $(1 ≤ i < n)$ $a_{i} ≤ a_{i + 1}$ holds.
|
In this problem you need to notice the fact (which can be proven, but it is almost obvious) that if you are doing some operation for interval from $l$ to $r$ (inclusive), $r$ must be equal to $n$. This is becuase when you add something to all right part the answer can't be worse. After that you need to go from left to right and greedly add appropriate number of turns. The complexity is $O(N)$.
|
[
"brute force",
"greedy"
] | 1,400
| null |
208
|
A
|
Dubstep
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
|
This problem was technical. First, you should erase all occurrences or word WUB in the beginning and in the end of the string. And then parse the remaining string separating tokens by word WUB. Empty tokens should be also erased. Given string was rather small, you can realize the algorithm in any way.
|
[
"strings"
] | 900
| null |
208
|
B
|
Solitaire
|
A boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules:
- A deck of $n$ cards is carefully shuffled, then all $n$ cards are put on the table in a line from left to right;
- Before each move the table has several piles of cards lying in a line (initially there are $n$ piles, each pile has one card). Let's number the piles from left to right, from 1 to $x$. During one move, a player can take the whole pile with the maximum number $x$ (that is the rightmost of remaining) and put it on the top of pile $x - 1$ (if it exists) or on the top of pile $x - 3$ (if it exists). The player can put one pile on top of another one only if the piles' top cards have the same suits or values. Please note that if pile $x$ goes on top of pile $y$, then the top card of pile $x$ becomes the top card of the resulting pile. Also note that each move decreases the total number of piles by 1;
- The solitaire is considered completed if all cards are in the same pile.
Vasya has already shuffled the cards and put them on the table, help him understand whether completing this solitaire is possible or not.
|
In this problem you could write breadth-first search. The state is the following four elements: number of remaining piles and three strings - three rightmost cards on the top of three rightmost piles. We have two transitions in general case. We can take the rightmost pile and shift it left by $1$ or $3$ on another pile. If the number of remaining piles become $0$ at some moment print $YES$, else print $NO$. The number of states is $O(N^{4})$, the number of transitions $2$, so the complexity of solution is $O(N^{4})$.
|
[
"dfs and similar",
"dp"
] | 1,900
| null |
208
|
C
|
Police Station
|
The Berland road network consists of $n$ cities and of $m$ bidirectional roads. The cities are numbered from 1 to $n$, where the main capital city has number $n$, and the culture capital — number $1$. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city $v$ to city $u$, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for \textbf{all} the shortest paths from the cultural capital to the main capital would take the maximum value.
|
In this problem we will find the sought quantity for every vertex and find the maximum value. For this for every vertex $v$ count two values: $cnt1[v]$ and $cnt2[v]$ - number of shortest paths from vertex $v$ to $n$-th and $1$-st vertices respectively. For this you should construct graph of shortest paths and use dynamic programming on the constructed graph (because the new graph will be acyclic). To construct the graph of shortest paths you should leave only useful edges in original graph. It can be done, for example, using breadth-first search launched from vertices $1$ and $n$ respectively. After values $cnt1[v]$ and $cnt2[v]$ are found consider every useful edge $(u, v$) and add to vertices $u$ and $v$ value $(cnt2[u] * cnt1[v]) / (cnt2[n-1])$, which is the contribution of this edge in the sought quantity for the vertices $u$ and $v$. Note that value $(cnt2[n-1])$ is the number of shortest paths between $1$ and $n$. All said values can be found in time $O(N + M)$. The complexity of solution is $O(N + M)$.
|
[
"dp",
"graphs",
"shortest paths"
] | 1,900
| null |
208
|
D
|
Prizes, Prizes, more Prizes
|
Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.
Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.
The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):
- a mug (costs $a$ points),
- a towel (costs $b$ points),
- a bag (costs $c$ points),
- a bicycle (costs $d$ points),
- a car (costs $e$ points).
Now Vasya wants to recollect what prizes he has received. You know sequence $p_{1}, p_{2}, ..., p_{n}$, where $p_{i}$ is the number of points Vasya got for the $i$-th bar. The sequence of points is given in the chronological order. You also know numbers $a$, $b$, $c$, $d$, $e$. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.
|
In this problem every time you get points you should greedily get as much prizes as you can. For this, consider every prize from the most expensive and try to get as much as you can. If we have $cnt$ points and the prize costs $p$ points you can get $\left\lfloor{\frac{c-t}{p}}\right\rfloor$ prizes. So we get simple solution with complexity $O(5 * N)$.
|
[
"implementation"
] | 1,200
| null |
208
|
E
|
Blood Cousins
|
Polycarpus got hold of a family relationship tree. The tree describes family relationships of $n$ people, numbered 1 through $n$. Each person in the tree has no more than one parent.
Let's call person $a$ a 1-ancestor of person $b$, if $a$ is the parent of $b$.
Let's call person $a$ a $k$-ancestor $(k > 1)$ of person $b$, if person $b$ has a 1-ancestor, and $a$ is a $(k - 1)$-ancestor of $b$'s 1-ancestor.
Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an $x$-ancestor for himself, for some $x$, $x > 0$).
\textbf{Let's call two people $x$ and $y$ $(x ≠ y)$ $p$-th cousins $(p > 0)$, if there is person $z$, who is a $p$-ancestor of $x$ and a $p$-ancestor of $y$.}
Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote $m$ pairs of integers $v_{i}$, $p_{i}$. Help him to calculate the number of $p_{i}$-th cousins that person $v_{i}$ has, for each pair $v_{i}$, $p_{i}$.
|
In this problem you have some set of rooted down- oriented trees. First, launch depth-first search from every root of every tree and renumber the vertices. Denote size of subtree of vertex $v$ as $cnt[v]$. In this way all descendants of vertex $v$ (including $v$) wiil have numbers $[v;v + cnt[v]-1]$. Then we wiil handle requests $(v, p)$ in their order. First, go up from vertex $v$ on $p$ steps to the root using binary rise like in LCA algorithm. Denote this vertex $u$. If $u$ doesn't exist print $0$ else you should count the number of descendants of vertex $u$ on the same height as vertex $v$. For this write all numbers of vertices for every height in some array. Then you should determine which of these vertices are descendants of $u$. You can do it using binary search in corresponding array. Find the segment of appropriate vertices (because we know the numbers of all descendants of $u$), find the amount of them, subtract one (vertex $v$), and this is the answer. The complexity of the solution is $O(Nlog(N))$.
|
[
"binary search",
"data structures",
"dfs and similar",
"trees"
] | 2,100
| null |
213
|
A
|
Game
|
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of $n$ parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies.
Rubik has $3$ computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from $1$ to $3$. Rubik can perform the following actions:
- Complete some part of the game on some computer. Rubik spends exactly $1$ hour on completing any part on any computer.
- Move from the 1-st computer to the 2-nd one. Rubik spends exactly $1$ hour on that.
- Move from the 1-st computer to the 3-rd one. Rubik spends exactly $2$ hours on that.
- Move from the 2-nd computer to the 1-st one. Rubik spends exactly $2$ hours on that.
- Move from the 2-nd computer to the 3-rd one. Rubik spends exactly $1$ hour on that.
- Move from the 3-rd computer to the 1-st one. Rubik spends exactly $1$ hour on that.
- Move from the 3-rd computer to the 2-nd one. Rubik spends exactly $2$ hours on that.
Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.
|
Solution - Greedy. Lets our computers settled on circle, and moves (1->2, 2->3, 3->1) will be steps "forward", and moves (1->3,3->2,2->1) will steps "back". Note that "back" moves is not optimal, as we can make two moves "forward" that is identical in time. We will look over all starts. Further, we will go by circle while we not complited all game. For every level we will remember number ne[i] - count of another level that "direct" need for it. We will complited levels with ne[i]=0 and update all ne[i] that we must. It can be implemented with O(n^3) time.
|
[
"dfs and similar",
"greedy"
] | 1,700
| null |
213
|
B
|
Numbers
|
Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.
There is integer $n$ and array $a$, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive integers with the following properties:
- the number's length does not exceed $n$;
- the number doesn't have leading zeroes;
- digit $i$ $(0 ≤ i ≤ 9)$ occurs in the number at least $a[i]$ times.
|
Solution - dynamic programming. Look over for length of the number that we will build. Further, we will use DP f(len,i) - how many numbers with length len we can make with digits i..9. Recount: - f(len,0) = sum(f(len-i,1)*C(len-1,i), i=a[0]..len); - f(len,j) = sum(f(len-i,j+1)*C(len,i), i=a[j]..len), 0<j<9; - f(len,9) = 1, if len>=a[9], 0 if len<a[9]. C(n,k) - binomial coefficient.
|
[
"combinatorics",
"dp"
] | 1,900
| null |
213
|
C
|
Relay Race
|
Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of $n$ meters. The given square is split into $n × n$ cells (represented as unit squares), each cell has some number.
At the beginning of the race Furik stands in a cell with coordinates $(1, 1)$, and Rubik stands in a cell with coordinates $(n, n)$. Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates $(i, j)$, then he can move to cell $(i + 1, j)$ or $(i, j + 1)$. After Furik reaches Rubik, Rubik starts running from cell with coordinates $(n, n)$ to cell with coordinates $(1, 1)$. If Rubik stands in cell $(i, j)$, then he can move to cell $(i - 1, j)$ or $(i, j - 1)$. Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified.
To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. \textbf{Each cell counts only once in the sum}.
Print the maximum number of points Furik and Rubik can earn on the relay race.
|
Solution - dynamic programming. Note, that we can make 2 pathes form cell (1,1) to cell (n,n). Note, that after each move our cells will be located on the same diagonal. We will solve the problem with DP f(d,i1,i2), d - diagonal number, i1 - 1st coordinate 1st path, i2 - 1st coordinate 2nd path. It is clear that we can calculate 2nd coordinate when we know number of the diagonal and 1st coordinate. Recount - obvious, we make all 4 transition, and if pathes are intersected in temporary point, we add value of the cell only one, otherwise we add both values of the cells. We can imlement this solution with O(n^2) memory if we will rewrite array of DP after increasing of diagonal number. Also we must remember that answer can be lower then 0.
|
[
"dp"
] | 2,000
| null |
213
|
D
|
Stars
|
Furik loves painting stars. A star is a shape that results if we take a regular pentagon and paint all diagonals in it.
Recently he decided to teach Rubik to paint stars. After many years of training Rubik could paint stars easily. But now Furik decided to test Rubik and complicated the task. Rubik must paint $n$ stars, observing the following rules:
- all stars must be painted in a single move (i.e. it is forbidden to take the pen away from the paper);
- it is forbidden to paint the same segment of non-zero length more than once;
- the stars can intersect only in their vertexes;
- the length of a side of the regular pentagon, in which Rubik paints each star, must equal 10.
Help Rubik to cope with this hard task.
|
I present solution as few pictures: Implementation. We have only one difficult moment - how to count coordinates? We can calculate them from regular pentagon, all that you need, you can read there.
|
[
"constructive algorithms",
"geometry"
] | 2,300
| null |
213
|
E
|
Two Permutations
|
Rubik is very keen on number permutations.
A permutation $a$ with length $n$ is a sequence, consisting of $n$ different numbers from 1 to $n$. Element number $i$ $(1 ≤ i ≤ n)$ of this permutation will be denoted as $a_{i}$.
Furik decided to make a present to Rubik and came up with a new problem on permutations. Furik tells Rubik two number permutations: permutation $a$ with length $n$ and permutation $b$ with length $m$. Rubik must give an answer to the problem: how many distinct integers $d$ exist, such that sequence $c$ $(c_{1} = a_{1} + d, c_{2} = a_{2} + d, ..., c_{n} = a_{n} + d)$ of length $n$ is a subsequence of $b$.
Sequence $a$ is a subsequence of sequence $b$, if there are such indices $i_{1}, i_{2}, ..., i_{n}$ $(1 ≤ i_{1} < i_{2} < ... < i_{n} ≤ m)$, that $a_{1} = b_{i1}$, $a_{2} = b_{i2}$, $...$, $a_{n} = b_{in}$, where $n$ is the length of sequence $a$, and $m$ is the length of sequence $b$.
You are given permutations $a$ and $b$, help Rubik solve the given problem.
|
For given two permutation we will make two another by next transformation: New_A[A[i]] = i, where New_A - news permutation, A - given permutation. Lets we get two permutation A and B. Now our problem is next: how many sub-arrays of length n are equals to firs permutation. Two arrays will be equal if after swaping every element with its number in sorted array obtained arrays will be element-wise equal. Further solution hashes, but we will use not only modulo 2^64, we will use some big modulos, but they must be smaller then 2^32-1. Lets step[i] = 1000003^i. Lets F(A) = num[1]*step[1] + num[2]*step[2] + ... + num[n]*step[n], where num[i] - number of the element A[i] in sorted array. If we will compare arrays, we can use this function. But it can be very big, so we will count it by modulos. So now our problem is to calculate F function to every subarray. Lets look what will change after adding/deleting some elent from set: some element from num array willnot change, and some will become grater after adding, and become lower after deleting. So we must use some interval-tree to recount our F function. We need to know sum of step[i] on some interval of added numbers and count of elements on some interval. Uses this information we can simply recount out function. Also we must remember that after adding element with coeficinet step[i], where i>n and deleting some previos element our function will become grater that we need. So we will multiple hash of first array by 1000003 to avoid this issue.
|
[
"data structures",
"hashing",
"strings"
] | 2,700
| null |
215
|
A
|
Bicycle Chain
|
Vasya's bicycle chain drive consists of two parts: $n$ stars are attached to the pedal axle, $m$ stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.
We know that the $i$-th star on the pedal axle has $a_{i}$ $(0 < a_{1} < a_{2} < ... < a_{n})$ teeth, and the $j$-th star on the rear wheel axle has $b_{j}$ $(0 < b_{1} < b_{2} < ... < b_{m})$ teeth. Any pair $(i, j)$ $(1 ≤ i ≤ n$; $1 ≤ j ≤ m)$ is called a gear and sets the indexes of stars to which the chain is currently attached. Gear $(i, j)$ has a gear ratio, equal to the value $\frac{b_{i}}{a_{i}}$.
Since Vasya likes integers, he wants to find such gears $(i, j)$, that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears $(i, j)$ he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.
In the problem, fraction $\frac{b_{i}}{a_{i}}$ denotes division in real numbers, that is, no rounding is performed.
|
Because of small constraints we can iterate $i$ from $1$ to $n$, iterate $j$ from $1$ to $m$, check that $b_{j}$ divide $a_{i}$ and find max value of $\frac{b_j}{a_i}$. Then we can start this process again and find amount of the pairs in which $\frac{b_j}{a_i}$ is max value.
|
[
"brute force",
"implementation"
] | 900
| null |
215
|
B
|
Olympic Medal
|
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of $r_{1}$ cm, inner radius of $r_{2}$ cm, $(0 < r2 < r1)$ made of metal with density $p_{1}$ g/cm$^{3}$. The second part is an inner disk with radius $r_{2}$ cm, it is made of metal with density $p_{2}$ g/cm$^{3}$. The disk is nested inside the ring.
The Olympic jury decided that $r_{1}$ will take one of possible values of $x_{1}, x_{2}, ..., x_{n}$. It is up to jury to decide which particular value $r_{1}$ will take. Similarly, the Olympic jury decided that $p_{1}$ will take one of possible value of $y_{1}, y_{2}, ..., y_{m}$, and $p_{2}$ will take a value from list $z_{1}, z_{2}, ..., z_{k}$.
According to most ancient traditions the ratio between the outer ring mass $m_{out}$ and the inner disk mass $m_{in}$ must equal $m_{o u t}/m_{i n}={\frac{A}{B}}$, where $A, B$ are constants taken from ancient books. Now, to start making medals, the jury needs to take values for $r_{1}$, $p_{1}$, $p_{2}$ and calculate the suitable value of $r_{2}$.
The jury wants to choose the value that would maximize radius $r_{2}$. Help the jury find the sought value of $r_{2}$. Value $r_{2}$ doesn't have to be an integer.
Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
|
Let amagine we have values of $r_{1}$, $p_{1}$ and $p_{2}$. Then: ${\frac{m_{\omega u t}}{m_{i n}}}={\frac{A}{B}}$ $\frac{\pi{\cdot}p_{1}{\cdot}(r_{1}^{2}-r_{2}^{2})}{\pi{\cdot}p_{2}{\cdot}r_{2}^{2}}\ =\ \frac{A}{B}$ $r_{2}^{2} \cdot (B \cdot p_{1} + A \cdot p_{2}) = r_{1}^{2} \cdot B \cdot p_{1}$ $r_{2}=r_{1}\cdot{\sqrt{\frac{B.p_{1}}{B\cdot p_{1}+A.p_{2}}}}$Now it's easy of understand, we must take maximum value of $r_{1}$ and $p_{1}$, and minimum value of $p_{2}$ to maximize $r_{2}$. You could not use three cycles for iterating all values, but you could find property above about at least one value and use two cycles.
|
[
"greedy",
"math"
] | 1,300
| null |
215
|
C
|
Crosses
|
There is a board with a grid consisting of $n$ rows and $m$ columns, the rows are numbered from $1$ from top to bottom and the columns are numbered from $1$ from left to right. In this grid we will denote the cell that lies on row number $i$ and column number $j$ as $(i, j)$.
A group of six numbers $(a, b, c, d, x_{0}, y_{0})$, where $0 ≤ a, b, c, d$, is a cross, and there is a set of cells that are assigned to it. Cell $(x, y)$ belongs to this set if \textbf{at least one} of two conditions are fulfilled:
- $|x_{0} - x| ≤ a$ and $|y_{0} - y| ≤ b$
- $|x_{0} - x| ≤ c$ and $|y_{0} - y| ≤ d$
\begin{center}
{\scriptsize The picture shows the cross $(0, 1, 1, 0, 2, 3)$ on the grid $3 × 4$.}
\end{center}
Your task is to find the number of different groups of six numbers, $(a, b, c, d, x_{0}, y_{0})$ that determine the crosses of an area equal to $s$, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell $(x, y)$ of the cross $1 ≤ x ≤ n; 1 ≤ y ≤ m$ holds). The area of the cross is the number of cells it has.
\textbf{Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.}
|
Let's iterate $n_{1} = max(a, c)$ and $m_{1} = max(b, d)$ - sides of bounding box. Then we can calculate value of function $f(n_{1}, m_{1}, s)$, and add to the answer $f(n_{1}, m_{1}, s) \cdot (n - n_{1} + 1) \cdot (m - m_{1} + 1)$, where two lastest brackets mean amount of placing this bounding box to a field $n \times m$. Now we must calculate $f(n_{1}, m_{1}, s)$. At first, if $n_{1} \cdot m_{1} = s$ then the result of the function is $2 \cdot ( \lfloor n_{1} / 2 \rfloor + 1) \cdot ( \lfloor m_{1} / 2 \rfloor + 1) - 1$ (you can prove it to youself). If $n_{1} \cdot m_{1} > s$ then we must to cut 4 corners which are equal rectangles with square $\frac{n_{1}\cdot m_{1}-s}{4}$. We can iterate length of a one of sides, calculate another side, check all constraints and add $2$ to the result of the function for all such pairs of sides. The time of a solution is $O(n^{3})$, but it's with very small constant, less then $1$.
|
[
"brute force",
"implementation"
] | 2,100
| null |
215
|
D
|
Hot Days
|
The official capital and the cultural capital of Berland are connected by a single road running through $n$ regions. Each region has a unique climate, so the $i$-th $(1 ≤ i ≤ n)$ region has a stable temperature of $t_{i}$ degrees in summer.
This summer a group of $m$ schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the $i$-th region and has $k$ schoolchildren, then the temperature inside the bus is $t_{i} + k$ degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the $i$-th region, if it has more than $T_{i}$ degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as $x_{i}$ rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the $i$-th region will cost the organizers $cost_{i}$ rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
|
You can use only two features about this problem: the solution is independenly for all regions and there are only 2 possible situations: all children are in exactly one bus or organizers must take minimum amount of bus such no children got a compensation. It's bad idea to place some children to hot bus and to place some children to cool bus simultaneously. For solving you must calculate this 2 values and get minimum.
|
[
"greedy"
] | 1,900
| null |
215
|
E
|
Periodical Numbers
|
A non-empty string $s$ is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string $s$ from 1 to the string's length and let's denote the $i$-th character in string $s$ as $s_{i}$.
Binary string $s$ with length $n$ is periodical, if there is an integer $1 ≤ k < n$ such that:
- $k$ is a divisor of number $n$
- for all $1 ≤ i ≤ n - k$, the following condition fulfills: $s_{i} = s_{i + k}$
For example, binary strings "101010" and "11" are periodical and "10" and "10010" are not.
A positive integer $x$ is periodical, if its binary representation (without leading zeroes) is a periodic string.
Your task is to calculate, how many periodic numbers are in the interval from $l$ to $r$ (both ends are included).
|
Ok, in the very beginning let's try solve some other task. We'll find the number of such integers in the interval $(2^{k}, x]$, where $k=\lfloor\log_{2}(x)\rfloor$. And someone can see that $x$ has length $len = k + 1$. Then we should try blocks of ${0, 1}$ to be the same part of periodical number. These blocks have length, which is divisor of $len$. Let's calculate number $g[i]$ of such blocks of length $i$, where $i$ is some divisor of $len$. We get $i$ of first(from the left side) bits of number $x$ and name it as $t = x$ >> $(len - i)$, e.g. if $x = 10011000_{2}$, and $i = 4$ then $t = 1001_{2}$, if $i = 2$ then $t = 10_{2}$. Firstly, we should check block $t$, it needs for example to check number $p = ttttt...$ repeated $\frac{I_{\ell}\eta}{i}$ times, it can be calculated in a loop $p = p$ << $i + t$. It's clear if $p \le x$, then we should take into account this block $g[i] = 1$. It's clear that every correct block less or equal than $t$, and it should begin from $1$ (because of periodical number is without leading zeroes). Case of equality we took. And we should add to $g[i]$ difference between $t$ and $2^{i} = 10000..._{2}$ i-1 zeroes, $g[i] = g[i] + t - (1$ << $(i - 1))$. It seems that all is ready and we can sum $g[i]$ for every divisor of $len$ and not equal $len$, but we cant. Because some cases we count more than once, e.g. $x = 10101100_{2}$, $i = 4$, $g[4] = 1 + (1010_{2} - 1000_{2}) = 3$ we considered cases of blocks $1000, 1001, 1010$, and when we count for $i = 2$,$g[2] = 1 + (10_{2} - 10_{2}) = 1$, we considered one case $10$, but $1010$ is obtained from $10$ repeated two times. But we can easily escape these problems, for this we should substract from $g[i]$ all $g[j]$ where $j < i$ and $j$ divides $i$. Some note. We get some DP problem, we calculate $g[i]$ from $i = 1$ to the most divisor of $len$ which is not equal to $len$, and update its value by substracting all g[j]. Let us summarize some ideas, we can count number of periodical numbers in the interval $(2^{k}, x]$, by going through divisors of $len$ and calculating $g[i]$, and then we return sum of $g[i]$ where $i < len$ and $i$ divides $len$. One can see that $2^{k}$ cant be periodical. Given this fact we will calculate this value for $x = 2^{k} - 1$, then $2^{k - 1} - 1$ and so on.In the end we get $x = 1$, and we get set of non-intersecting intervals, counting on each of them and sum up it we get answer. It can be done recursively.
|
[
"combinatorics",
"dp",
"number theory"
] | 2,100
|
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
#define pb push_back
#define VI vector <int>
#define clr(x) memset((x),0,sizeof(x))
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)
#define pw(x) (1ll<<(x))
typedef long long ll;
ll g[32];
VI divs[63];
void prec()
{
for(int i=1;i<61;i++)
for(int j=1;j<i;j++)
if (i%j==0)
divs[i].pb(j);
}
inline int lg(ll n)
{
int l = 0;
while (n)
{
l++;
n>>=1;
}
return l;
}
inline void upd(int i)
{
fori(j,divs[i])
g[i]-=g[*j];
}
ll f(ll n)
{
if (n<=1) return 0;
ll ans = 0;
int l = lg(n);
ans+=f(pw(l-1) - 1);
clr(g);
fori(it, divs[l])
{
int i = *it;
ll t = n >> (l-i);
ll p = t;
forn(j,l/i-1)
p = (p << i) + t;
if (p <= n) g[i]++;
g[i] += t - pw(i-1);
upd(i);
ans += g[i];
}
return ans;
}
int main()
{
prec();
ll l,r;
cin >> l >> r;
cout << f(r)-f(l-1);
return 0;
}
|
216
|
A
|
Tiling with Hexagons
|
Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.
The hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has $a$, $b$, $c$, $a$, $b$ and $c$ adjacent tiles, correspondingly.
To better visualize the situation, look at the picture showing a similar hexagon for $a = 2$, $b = 3$ and $c = 4$.
According to the legend, as the King of Berland obtained the values $a$, $b$ and $c$, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same?
|
For solving this problem you might find some formula like $res = abc - (a - 1)(b - 1)(c - 1)$, $res = ab + bc + ca - a - b - c + 1$, or something else. Also the problem can be solved in $O(a + b + c)$ time - you can move from the top line to the bottom line of hexagon and sum number of tiles in every line.
|
[
"implementation",
"math"
] | 1,200
| null |
216
|
B
|
Forming Teams
|
One day $n$ students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.
We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student $A$ is an archenemy to student $B$, then student $B$ is an archenemy to student $A$.
The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.
Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.
|
You can build some graph where vertices are students and edges are enmities. You should drop some vertices and then paint them in two colors. Any edge should connect vertices of distinct colors and numbers of vertices of every color should be same. You can see that graph consists chians, cycles and sepatated vertices. Every of that component can be painted in 2 colors except one case: cycles of odd length. So, you should drop one vertex from every odd cycle. After that you can get odd number of vertices. Then you should drop one more vertex (you can chose any of them). The obtained graph can be easily painted in 2 colors in the required manner.
|
[
"dfs and similar",
"implementation"
] | 1,700
| null |
216
|
C
|
Hiring Staff
|
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least $k$ people must work in the store.
Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly $n$ consecutive days, then rest for exactly $m$ days, then work for $n$ more days and rest for $m$ more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day $x$, then he should work on days $[x, x + 1, ..., x + n - 1]$, $[x + m + n, x + m + n + 1, ..., x + m + 2n - 1]$, and so on. Day $x$ can be chosen arbitrarily by Vitaly.
There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.
Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from $1$ to infinity. In other words, on each day with index from $1$ to infinity, the store must have at least $k$ working employees, and one of the working employees should have the key to the store.
Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.
|
The first solution: analysis of the cases 1. $k = 1$. For $n \le m + 1$ 3 employees is enough (in most cases). For $n > m + 1$ answer is 2. Also, there are only one tricky corner case: for $n = 2, m = 2, k = 1$ answer is 4. 2. $k > 1$. If $n = m$, answer is $2k + 1$, otherwise answer is $2k$. For any case it is easy to construct solution, and prove that this solution is optimal. The second solution: greedy. Let's create an array where we will store current number of employees for some number of the first days. Now you should iterate over all days from the first to the $n + m$-th and hire employees every time when it needed. You should hire workers if there are less than $k$ people in the current day; also you should hire worker if there will be no people tomorrow (thet worker will bring the key to the workers that will work tomorrow). This solution works in $O((n + m)k)$. This solution also works correctly for cases $n < m$, but then it has bigger complexity and requires more time.
|
[
"greedy"
] | 1,800
| null |
216
|
D
|
Spider's Web
|
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.
There are $n$ main threads going from the center of the web. All main threads are located in one plane and divide it into $n$ equal infinite sectors. The sectors are indexed from $1$ to $n$ in the clockwise direction. Sectors $i$ and $i + 1$ are adjacent for every $i$, $1 ≤ i < n$. In addition, sectors $1$ and $n$ are also adjacent.
Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.
A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.
Unstable cells are marked red in the figure. Stable cells are marked green.
Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.
|
For every sector you should sort bridges in order of increasing distance from the conter of the web. Now for every sector you should iterate over bridges of the current sector and two adjacent sectors using 3 pointers. During every pass you should carefully calculate number of bad cells. That is all solution. Solition in $O(m\log m)$, where $m$ is total number of bridges.
|
[
"binary search",
"sortings",
"two pointers"
] | 1,700
| null |
216
|
E
|
Martian Luck
|
You know that the Martians use a number system with base $k$. Digit $b$ ($0 ≤ b < k$) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year $b$ (by Martian chronology).
A digital root $d(x)$ of number $x$ is a number that consists of a single digit, resulting after cascading summing of all digits of number $x$. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.
For example, $d(3504_{7}) = d((3 + 5 + 0 + 4)_{7}) = d(15_{7}) = d((1 + 5)_{7}) = d(6_{7}) = 6_{7}$. In this sample the calculations are performed in the 7-base notation.
If a number's digital root equals $b$, the Martians also call this number lucky.
You have string $s$, which consists of $n$ digits in the $k$-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.
Note that substring $s[i... j]$ of the string $s = a_{1}a_{2}... a_{n}$ ($1 ≤ i ≤ j ≤ n$) is the string $a_{i}a_{i + 1}... a_{j}$. Two substrings $s[i_{1}... j_{1}]$ and $s[i_{2}... j_{2}]$ of the string $s$ are different if either $i_{1} ≠ i_{2}$ or $j_{1} ≠ j_{2}$.
|
Digital root of number is equal to that number modulo $k - 1$ for most cases. It is lie only for digital roots 0 and $k - 1$ - in that cases number modulo $k - 1$ will be 0. But you can get digital root 0 only for numbers like $00...00$. Total number of numbers that type you can find using any other way. So, now you can find number of substrings that have some digital root, if you know number of substrings that equals some number modulo $k - 1$. How to find number of substrings of some modulo? You should iterate over all digits of $s$ from the left to the rigth and for every modulo store number of prefixes of that modulo in some array dp[] of size $k$. Let's current position is $i$. Then number of substrings modulo $b$ that ends in position $i$ equals to number of prefixes leftmost position $i$ that have modulo $(x - b)mod(k - 1)$, where $x$ is modulo of $s[1... i]$. I.e. just $dp[(x - b)mod(k - 1)]$. To fit into memory limit, you should replace array dp[] by some associative array. For example, std::map from C++ or some hashtable. So we have solution in $O(nz)$, where $z$ is complexety of access to dp[] ($O(\log n)$ for std::map and $O(1)$ for hashtable).
|
[
"math",
"number theory"
] | 2,000
| null |
217
|
A
|
Ice Skating
|
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
|
Notice that the existence of a snow drift at the point $(x, y)$ implies that "if I'm on the horizontal line at $y$ then I am certainly able to get to the vertical line at $x$, and vice versa". Thus, the snow drifts are the edges of a bipartite graph between x- and y- coordinates. The number of snow drifts that need to be added to make this (as well as the original) graph connected is the number of its connected components reduced by one.
|
[
"brute force",
"dfs and similar",
"dsu",
"graphs"
] | 1,200
| null |
217
|
B
|
Blackboard Fibonacci
|
Fibonacci numbers are the sequence of integers: $f_{0} = 0$, $f_{1} = 1$, $f_{2} = 1$, $f_{3} = 2$, $f_{4} = 3$, $f_{5} = 5$, $...$, $f_{n} = f_{n - 2} + f_{n - 1}$. So every next number is the sum of the previous two.
Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations:
- operation "T": replace the top number with the sum of both numbers;
- operation "B": replace the bottom number with the sum of both numbers.
If he performs $n$ operations, starting with "T" and then choosing operations alternately (so that the sequence of operations looks like "TBTBTBTB$...$"), the last number written will be equal to $f_{n + 1}$.
Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute $f_{7}$, then he would want to do $n = 6$ operations: "TBTBTB". If he instead performs the sequence of operations "TTTBBT", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations («TT» or «BB»).
You are given the number $n$ of operations that Bajtek has made in an attempt to compute $f_{n + 1}$ and the number $r$ that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of $n$ operations resulting in $r$ with that number of mistakes.
Assume that Bajtek always correctly starts with operation "T".
|
If you look at the described process backwards, it resembles the Euclidean algorithm a lot. Indeed, if you rewinded a recording of Bajtek's actions, he always takes the larger out of two numbers (say Unable to parse markup [type=CF_TEX] ) and replaces them by $a - b, b$. Since we know one of the final numbers ($r$) we can simply check all numbers between $1$ and $r$ and run a faster version of Euclid's algorithm (one that replaces $a, b$ by $a{\mathrm{~mod~}}b.b$) for all possibilities for a total runtime of $O(r \log r)$. This was one of the expected solutions.However, with some insight, it can be seen that this optimization is in fact not neccessary - we can simply simulate the reverse process as described (replacing $a, b$ by $a - b, b$) for all candidates between $1$ and $r$ and the total runtime of our algorithm will remain $O(r \log r)$. The proof of this fact is left to the reader.
|
[
"brute force",
"math"
] | 2,100
| null |
217
|
C
|
Formurosa
|
The Bytelandian Institute for Biological Research (BIBR) is investigating the properties of two species of bacteria, named simply 0 and 1. Even under a microscope, bacteria of those two species are very difficult to distinguish. In fact, the only thing the scientists possess that is able to differentiate between them is a plant called Formurosa.
If the scientists place a sample of colonies of bacteria on each on Formurosa's leaves, it will activate a complicated nutrition process. During that process color of Formurosa changes to reflect the result of a — possibly very complicated — logical formula on the species of bacteria, involving constants and the operators $|$ (OR), $&$ (AND) and $^$ (XOR). If it is 0, the plant will turn red, otherwise — it will turn blue.
For example, if the nutrition process of Formurosa is described by the formula: $(((?^?)|?)&(1^?))$; then Formurosa has four leaves (the "?" signs denote the leaves). If we place $0, 1, 0, 0$ on the respective leaves, the result of the nutrition process will be $(((0^1)|0)&(1^0)) = 1$, therefore the plant will turn blue.
The scientists have $n$ colonies of bacteria. They do not know their types; the only thing they know for sure is that \textbf{not all colonies are of the same type}. They want to attempt to determine the bacteria's species by repeated evaluations with Formurosa. During each evaluation they must place exactly one sample on every leaf of the plant. However, they may use multiple samples of one colony during a single evaluation; they can even cover the whole plant with bacteria from one colony!
Is it possible for them to always determine the species of each colony, no matter what they are (assuming they are not all the same)?
|
One of the major difficulties in this problem is finding an easily formulated condition for when Formurosa can be used to distinguish the bacteria. Let Formurosa's digestive process be a function $F(s)$ that maps binary sequences of length $m$ to elements of ${0, 1}$. It turns out that the condition we seek for can be stated as follows: We can distinguish all the bacteria if and only if there exists a sequence $s$ of length $m$ for which $F(s) \neq F( - s)$, where $- s$ is the negation of $s$. First, not that if no such sequence exists, then there is no way to distinguish between zero and one. If such a sequence exists, we can pick any two bacteria $a$ and $b$ and try both ways to substitute them for $0$ and $1$ in the expression. If the two expressions evaluate to different values, we will determine the exact types of both bacteria. Otherwise, we will be certain that the bacteria are of the same type. Repeating the process for all pairs of bacteria will let us identify all the types (since it is guaranteed that not all bacteria are of the same type). To determine whether such a sequence $s$ exists, dynamic programming over the expression tree of Formurosa can be applied. The model solution keeps track for each subtree $G$ of the expression which of the following sequences can be found: a sequence $s$ such that $G(s) = G( - s) = 0$ a sequence $s$ such that $G(s) = G( - s) = 1$ a sequence $s$ such that $G(s) \neq G( - s)$
|
[
"divide and conquer",
"dp",
"expression parsing"
] | 2,600
| null |
217
|
D
|
Bitonix' Patrol
|
Byteland is trying to send a space mission onto the Bit-X planet. Their task is complicated by the fact that the orbit of the planet is regularly patrolled by Captain Bitonix, the leader of the space forces of Bit-X.
There are $n$ stations around Bit-X numbered clockwise from 1 to $n$. The stations are evenly placed on a circular orbit, so the stations number $i$ and $i + 1$ $(1 ≤ i < n)$, and the stations number 1 and $n$, are neighboring. The distance between every pair of adjacent stations is equal to $m$ space miles. To go on a patrol, Captain Bitonix jumps in his rocket at one of the stations and flies in a circle, covering a distance of at least one space mile, before finishing in some (perhaps the starting) station.
Bitonix' rocket moves by burning fuel tanks. After Bitonix attaches an $x$-liter fuel tank and chooses the direction (clockwise or counter-clockwise), the rocket flies exactly $x$ space miles along a circular orbit in the chosen direction. Note that the rocket has no brakes; it is not possible for the rocket to stop before depleting a fuel tank.
For example, assume that $n = 3$ and $m = 60$ and Bitonix has fuel tanks with volumes of 10, 60, 90 and 100 liters. If Bitonix starts from station 1, uses the 100-liter fuel tank to go clockwise, then uses the 90-liter fuel tank to go clockwise, and then uses the 10-liter fuel tank to go counterclockwise, he will finish back at station 1. This constitutes a valid patrol. Note that Bitonix does not have to use all available fuel tanks. Another valid option for Bitonix in this example would be to simply use the 60-liter fuel tank to fly to either station 2 or 3.
However, if $n$ was equal to 3, $m$ was equal to 60 and the only fuel tanks available to Bitonix were one 10-liter tank and one 100-liter tank, he would have no way of completing a valid patrol (he wouldn't be able to finish any patrol exactly at the station).
The Byteland space agency wants to destroy some of Captain Bitonix' fuel tanks so that he cannot to complete any valid patrol. Find how many different subsets of the tanks the agency can destroy to prevent Captain Bitonix from completing a patrol and output the answer modulo $1000000007$ $(10^{9} + 7)$.
|
Observation 1. Fuel tanks for which capacity gives the same remainder $\bmod d$ are equivalent for Bitonix's purposes. Moreover, fuel tanks for which the capacities' remainders $\bmod d$ sum to $D$ are also equivalent. Out of every group of equivalent tanks, the agency can only leave at most one. Observation 2. If more than six tanks remain, Bitonix can certainly complete his patrol. Indeed, let us assume that $7$ tanks were left undestroyed by the agency. Out of the 128 possible subsets of those tanks, at least two distinct ones, say $A$ and $B$, sum up to the same remainders modulo $D$. Thus, if Bitonix moves forward with tanks from $A - B$ and backwards with tanks from $B - A$, he will finish at some station after an actual journey. Because of observations 1 and 2, it turns out that a simple recursive search suffices to solve the problem. However, because of the large constraints, it may prove necessary to use some optimizations, such as using bitmasks for keeping track of what distances Bitonix can cover.
|
[
"bitmasks",
"brute force",
"combinatorics",
"dfs and similar",
"math"
] | 2,900
| null |
217
|
E
|
Alien DNA
|
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations — each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as $s_{1}s_{2}... s_{11}$, its mangled copy is $s_{2}s_{4}s_{6}s_{8}s_{10}s_{1}s_{3}s_{5}s_{7}s_{9}s_{11}$.
For example, if the original sequence was "ACTGG" and the mutation happened on the segment $[2, 4]$ (that is the activated subsequence is "CTG"), the mutated DNA is: "{ACTG\textbf{TCG}G}". The mangled copy of the activated subsequence is marked with bold font.
Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first $k$ elements of the DNA sequence after all the mutations.
|
Note that it is easy to determine, looking at only the last mutation, how many letters it adds to the final result. Indeed, if we need to print out the first $k$ letters of the sequence, and the last mutation is $[l, r]$, it suffices to find out the length of the overlap of segments $[1, k]$ and $[r + 1, 2r - l + 1]$. Say that it is $x$. Then, after the next to last mutation, we are only interested in the first $k - x$ letters of the result - the rest is irrelevant, as it will become "pushed out" by the elements added in the last mutation. Repeating this reasoning going backwards, we shall find out that we can spend linear time adding letters to the result after every mutation, which turns out to be the main idea needed to solve the problem.
|
[
"data structures",
"dsu",
"trees"
] | 2,800
|
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
//BEGINTEMPLATE_BY_ACRUSH_TOPCODER
#define SIZE(X) ((int)(X.size()))//NOTES:SIZE(
#define LENGTH(X) ((int)(X.length()))//NOTES:LENGTH(
#define MP(X,Y) make_pair(X,Y)//NOTES:MP(
typedef long long int64;//NOTES:int64
typedef unsigned long long uint64;//NOTES:uint64
#define two(X) (1<<(X))//NOTES:two(
#define twoL(X) (((int64)(1))<<(X))//NOTES:twoL(
#define contain(S,X) (((S)&two(X))!=0)//NOTES:contain(
#define containL(S,X) (((S)&twoL(X))!=0)//NOTES:containL(
const double pi=acos(-1.0);//NOTES:pi
const double eps=1e-11;//NOTES:eps
template<class T> inline void checkmin(T &a,T b){if(b<a) a=b;}//NOTES:checkmin(
template<class T> inline void checkmax(T &a,T b){if(b>a) a=b;}//NOTES:checkmax(
template<class T> inline T sqr(T x){return x*x;}//NOTES:sqr
typedef pair<int,int> ipair;//NOTES:ipair
template<class T> inline T lowbit(T n){return (n^(n-1))&n;}//NOTES:lowbit(
template<class T> inline int countbit(T n){return (n==0)?0:(1+countbit(n&(n-1)));}//NOTES:countbit(
//Numberic Functions
template<class T> inline T gcd(T a,T b)//NOTES:gcd(
{if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);}
template<class T> inline T lcm(T a,T b)//NOTES:lcm(
{if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));}
template<class T> inline T euclide(T a,T b,T &x,T &y)//NOTES:euclide(
{if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;}
if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;}
if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}}
template<class T> inline vector<pair<T,int> > factorize(T n)//NOTES:factorize(
{vector<pair<T,int> > R;for (T i=2;n>1;){if (n%i==0){int C=0;for (;n%i==0;C++,n/=i);R.push_back(make_pair(i,C));}
i++;if (i>n/i) i=n;}if (n>1) R.push_back(make_pair(n,1));return R;}
template<class T> inline bool isPrimeNumber(T n)//NOTES:isPrimeNumber(
{if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;}
template<class T> inline T eularFunction(T n)//NOTES:eularFunction(
{vector<pair<T,int> > R=factorize(n);T r=n;for (int i=0;i<R.size();i++)r=r/R[i].first*(R[i].first-1);return r;}
//Matrix Operations
const int MaxMatrixSize=40;//NOTES:MaxMatrixSize
template<class T> inline void showMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:showMatrix(
{for (int i=0;i<n;i++){for (int j=0;j<n;j++)cout<<A[i][j];cout<<endl;}}
template<class T> inline T checkMod(T n,T m) {return (n%m+m)%m;}//NOTES:checkMod(
template<class T> inline void identityMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:identityMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=(i==j)?1:0;}
template<class T> inline void addMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];}
template<class T> inline void subMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];}
template<class T> inline void mulMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulMatrix(
{ T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];
for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]+=A[i][k]*B[k][j];}
template<class T> inline void addModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addModMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]+B[i][j],m);}
template<class T> inline void subModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subModMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]-B[i][j],m);}
template<class T> inline T multiplyMod(T a,T b,T m) {return (T)((((int64)(a)*(int64)(b)%(int64)(m))+(int64)(m))%(int64)(m));}//NOTES:multiplyMod(
template<class T> inline void mulModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulModMatrix(
{ T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];
for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]=(C[i][j]+multiplyMod(A[i][k],B[k][j],m))%m;}
template<class T> inline T powerMod(T p,int e,T m)//NOTES:powerMod(
{if(e==0)return 1%m;else if(e%2==0){T t=powerMod(p,e/2,m);return multiplyMod(t,t,m);}else return multiplyMod(powerMod(p,e-1,m),p,m);}
//Point&Line
double dist(double x1,double y1,double x2,double y2){return sqrt(sqr(x1-x2)+sqr(y1-y2));}//NOTES:dist(
double distR(double x1,double y1,double x2,double y2){return sqr(x1-x2)+sqr(y1-y2);}//NOTES:distR(
template<class T> T cross(T x0,T y0,T x1,T y1,T x2,T y2){return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);}//NOTES:cross(
int crossOper(double x0,double y0,double x1,double y1,double x2,double y2)//NOTES:crossOper(
{double t=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);if (fabs(t)<=eps) return 0;return (t<0)?-1:1;}
bool isIntersect(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4)//NOTES:isIntersect(
{return crossOper(x1,y1,x2,y2,x3,y3)*crossOper(x1,y1,x2,y2,x4,y4)<0 && crossOper(x3,y3,x4,y4,x1,y1)*crossOper(x3,y3,x4,y4,x2,y2)<0;}
bool isMiddle(double s,double m,double t){return fabs(s-m)<=eps || fabs(t-m)<=eps || (s<m)!=(t<m);}//NOTES:isMiddle(
//Translator
bool isUpperCase(char c){return c>='A' && c<='Z';}//NOTES:isUpperCase(
bool isLowerCase(char c){return c>='a' && c<='z';}//NOTES:isLowerCase(
bool isLetter(char c){return c>='A' && c<='Z' || c>='a' && c<='z';}//NOTES:isLetter(
bool isDigit(char c){return c>='0' && c<='9';}//NOTES:isDigit(
char toLowerCase(char c){return (isUpperCase(c))?(c+32):c;}//NOTES:toLowerCase(
char toUpperCase(char c){return (isLowerCase(c))?(c-32):c;}//NOTES:toUpperCase(
template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}//NOTES:toString(
int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt(
int64 toInt64(string s){int64 r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt64(
double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toDouble(
template<class T> void stoa(string s,int &n,T A[]){n=0;istringstream sin(s);for(T v;sin>>v;A[n++]=v);}//NOTES:stoa(
template<class T> void atos(int n,T A[],string &s){ostringstream sout;for(int i=0;i<n;i++){if(i>0)sout<<' ';sout<<A[i];}s=sout.str();}//NOTES:atos(
template<class T> void atov(int n,T A[],vector<T> &vi){vi.clear();for (int i=0;i<n;i++) vi.push_back(A[i]);}//NOTES:atov(
template<class T> void vtoa(vector<T> vi,int &n,T A[]){n=vi.size();for (int i=0;i<n;i++)A[i]=vi[i];}//NOTES:vtoa(
template<class T> void stov(string s,vector<T> &vi){vi.clear();istringstream sin(s);for(T v;sin>>v;vi.push_bakc(v));}//NOTES:stov(
template<class T> void vtos(vector<T> vi,string &s){ostringstream sout;for (int i=0;i<vi.size();i++){if(i>0)sout<<' ';sout<<vi[i];}s=sout.str();}//NOTES:vtos(
//Fraction
template<class T> struct Fraction{T a,b;Fraction(T a=0,T b=1);string toString();};//NOTES:Fraction
template<class T> Fraction<T>::Fraction(T a,T b){T d=gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;}
template<class T> string Fraction<T>::toString(){ostringstream sout;sout<<a<<"/"<<b;return sout.str();}
template<class T> Fraction<T> operator+(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b+q.a*p.b,p.b*q.b);}
template<class T> Fraction<T> operator-(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b-q.a*p.b,p.b*q.b);}
template<class T> Fraction<T> operator*(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.a,p.b*q.b);}
template<class T> Fraction<T> operator/(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b,p.b*q.a);}
//ENDTEMPLATE_BY_ACRUSH_TOPCODER
const int maxL=3<<20;
const int maxn=50000+5;
char s[maxL];
int k;
int n,L[maxn],R[maxn];
char r[maxL];
class Segment
{
public:
int L;
char *s;
};
int n_segs;
Segment segs[maxn<<2];
int split(int pos)
{
for (int i=0;i<n_segs;i++)
if (pos==0)
{
n_segs++;
for (int k=n_segs-1;k>i;k--) segs[k]=segs[k-1];
return i;
}
else if (segs[i].L<=pos)
pos-=segs[i].L;
else
{
n_segs+=2;
for (int k=n_segs-1;k>i+1;k--) segs[k]=segs[k-2];
segs[i+2].L=segs[i].L-pos;
segs[i+2].s=segs[i].s+pos;
segs[i].L=pos;
return i+1;
}
return n_segs++;
}
void getr(int H,int T)
{
int L=0;
for (int i=0;T>=0 && i<n_segs;i++)
if (segs[i].L<=H)
{
H-=segs[i].L;
T-=segs[i].L;
}
else
{
for (int k=max(0,H);k<segs[i].L && k<=T;k++) r[L++]=segs[i].s[k];
int D=min(segs[i].L,T);
H-=D;
T-=D;
}
}
void construct(int d,int length)
{
if (d<0)
{
Segment key;
key.L=length;
key.s=s+1;
segs[n_segs++]=key;
return;
}
if (R[d]>=length)
{
construct(d-1,length);
return;
}
int C=R[d]-L[d]+1;
if (R[d]+C>=length)
{
construct(d-1,R[d]);
Segment key;
key.L=length-R[d];
key.s=new char[key.L];
int C_2=C/2;
int D=(key.L>=C_2)?C:(key.L*2);
getr(L[d],L[d]+D-1);
for (int i=0;i<key.L;i++)
if (i<C_2)
key.s[i]=r[i+i+1];
else
key.s[i]=r[(i-C_2)<<1];
segs[n_segs++]=key;
}
else
{
construct(d-1,length-C);
int pos=split(R[d]+1);
Segment key;
key.L=C;
key.s=new char[C];
int C_2=C/2;
getr(L[d],R[d]);
for (int i=0;i<C;i++)
if (i<C_2)
key.s[i]=r[i+i+1];
else
key.s[i]=r[(i-C_2)<<1];
segs[pos]=key;
}
}
int main()
{
#ifdef _MSC_VER
freopen("input.txt","r",stdin);
#endif
scanf("%s%d",s+1,&k);
scanf("%d",&n);
for (int i=0;i<n;i++) scanf("%d%d",&L[i],&R[i]);
n_segs=1;
segs[0].L=1;
segs[0].s=new char[1];
segs[0].s[0]=' ';
construct(n-1,k);
getr(0,k);
r[k+1]=0;
printf("%s
",r+1);
return 0;
}
|
219
|
A
|
k-String
|
A string is called a $k$-string if it can be represented as $k$ concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string $s$, consisting of lowercase English letters and a positive integer $k$. Your task is to reorder the letters in the string $s$ in such a way that the resulting string is a $k$-string.
|
Count the occurrences of each character. If any character appears a number of times not divisible by K, obviously, there is no solution. Otherwise, form the solution by first making the string B. The string B can be any string with the following property: if some character ch appears q times in the string B, the same character appears q***K** times in the given string. Now, just print that string K times.
|
[
"implementation",
"strings"
] | 1,000
| null |
219
|
B
|
Special Offer! Super Price 999 Bourles!
|
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be $p$ bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect.
Polycarpus agrees to lower the price by no more than $d$ bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.
Note, Polycarpus counts only the trailing nines in a price.
|
The following observation will help you code the solution: The largest number smaller than p ending with at least k nines is p - p MOD 10^k - 1 If the result turns out to be -1 , you can not reach a positive number with k or more nines. I will not explain the solution in detail - be careful when coding and have all the task statements in mind.
|
[
"implementation"
] | 1,400
| null |
219
|
C
|
Color Stripe
|
A colored stripe is represented by a horizontal row of $n$ square cells, each cell is pained one of $k$ colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to $k$ to repaint the cells.
|
There are two cases to consider , when K=2 and when K>2. For K=2 there are only two possible solutions: the string "ABABAB..." and "BABABA..." For both strings, simply count the number of differences between it and the given string and print a string with fewer differences. For K>2 , decompose the string into contiguous single-colored sequences. Observe one such sequence. If it has an odd number of characters, say 2m+1, replace m characters with some other character in the following fashion: AAAAA becomes ABABA It can be observed that by changing less than m characters doesn't remove all pairs of adjacent identical characters. Similarly, for sequences of even length, say 2m characters, observe a character in the original string right after the last character of the observed sequence, and choose a character different from both. Example: AAAAAAB becomes ACACACB Again, it is sufficient and necessary to change m characters.
|
[
"brute force",
"dp",
"greedy"
] | 1,600
| null |
219
|
D
|
Choosing Capital for Treeland
|
The country Treeland consists of $n$ cities, some pairs of them are connected with unidirectional roads. Overall there are $n - 1$ roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city $a$ is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city $a$ to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
|
Arbitrarily root the tree at some vertex, say vertex 1. Now, all the edges are oriented either up (towards the root) or down (away from it). We will call upwards oriented edges red, and downwards oriented edges green. Now, with a single depth-first search, for each vertex, calculate its distance from the root (in number of edges) and the number of red edges along the path to the root. Also, count the number of red edges in the entire tree. Now comes the interesting part: Observe that all edges outside the path from the root to vert should turn green, and those on the path should turn red. The number of edges that need to be flipped if vert is chosen as a capital is given by: RedEntireTree - 2*RedOnPath[vert] + RootDistance[vert]
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,700
| null |
219
|
E
|
Parking Lot
|
A parking lot in the City consists of $n$ parking spaces, standing in a line. The parking spaces are numbered from 1 to $n$ from left to right.
When a car arrives at the lot, the operator determines an empty parking space for it. For the safety's sake the chosen place should be located as far from the already occupied places as possible. That is, the closest occupied parking space must be as far away as possible. If there are several such places, then the operator chooses the place with the minimum index from them. If all parking lot places are empty, then the car gets place number $1$.
We consider the distance between the $i$-th and the $j$-th parking spaces equal to $4·|i - j|$ meters.
You are given the parking lot records of arriving and departing cars in the chronological order. For each record of an arriving car print the number of the parking lot that was given to this car.
|
Use a heap to maintain sequences of empty parking spaces as intervals. The comparison function for such intervals should return an interval which could store a car farthest from any other car, and if there is a tie, it should return the leftmost such interval. When inserting a car, pop the heap, look at the interval, place a car in the corresponding space and push two new intervals onto the heap. When removing a car, you should be able to find the two intervals which end at that car, remove them from the heap and push a new interval which forms when the two merge.
|
[
"data structures"
] | 2,200
| null |
220
|
A
|
Little Elephant and Problem
|
The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array $a$ of length $n$ and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array $a$, only if array $a$ can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.
Help the Little Elephant, determine if he could have accidentally changed the array $a$, sorted by non-decreasing, himself.
|
There are multiple possible solutions for this problem. For example, the following. Find the last index $x$ such that there exists some $y$ $(y < x)$ (minimal possible) that $A_{x}$ < $A_{y}$. Then you just need to try two possibilities - either swap $A_{x}$ and $A_{y}$, or don't change anything.
|
[
"implementation",
"sortings"
] | 1,300
| null |
220
|
B
|
Little Elephant and Array
|
The Little Elephant loves playing with arrays. He has array $a$, consisting of $n$ positive integers, indexed from 1 to $n$. Let's denote the number with index $i$ as $a_{i}$.
Additionally the Little Elephant has $m$ queries to the array, each query is characterised by a pair of integers $l_{j}$ and $r_{j}$ $(1 ≤ l_{j} ≤ r_{j} ≤ n)$. For each query $l_{j}, r_{j}$ the Little Elephant has to count, how many numbers $x$ exist, such that number $x$ occurs exactly $x$ times among numbers $a_{lj}, a_{lj + 1}, ..., a_{rj}$.
Help the Little Elephant to count the answers to all queries.
|
This problem can be solve in simpler $O(NsqrtN)$ solution, but I will describe $O(NlogN)$ one. We will solve this problem in offline. For each $x$ $(0 \le x < n)$ we should keep all the queries that end in $x$. Iterate that $x$ from 0 to $n - 1$. Also we need to keep some array $D$ such that for current $x$ $D_{l} + D_{l + 1} + ... + D_{x}$ will be the answer for query $[l;x]$. To keep $D$ correct, before the processing all queries that end in $x$, we need to update $D$. Let $t$ be the current integer in $A$, i. e. $A_{x}$, and vector $P$ be the list of indices of previous occurences of $t$ (0-based numeration of vector). Then, if $|P| \ge t$, you need to add $1$ to $D_{P[|P| - t]}$, because this position is now the first (from right) that contains exactly $t$ occurences of $t$. After that, if $|P| > t$, you need to subtract $2$ from $D_{P[|P| - t - 1]}$, in order to close current interval and cancel previous. Finally, if $|P| > t + 1$, then you need additionally add $1$ to $D_{P[|P| - t - 2]}$ to cancel previous close of the interval.
|
[
"constructive algorithms",
"data structures"
] | 1,800
| null |
220
|
C
|
Little Elephant and Shifts
|
The Little Elephant has two permutations $a$ and $b$ of length $n$, consisting of numbers from 1 to $n$, inclusive. Let's denote the $i$-th $(1 ≤ i ≤ n)$ element of the permutation $a$ as $a_{i}$, the $j$-th $(1 ≤ j ≤ n)$ element of the permutation $b$ — as $b_{j}$.
The distance between permutations $a$ and $b$ is the minimum absolute value of the difference between the positions of the occurrences of some number in $a$ and in $b$. More formally, it's such minimum $|i - j|$, that $a_{i} = b_{j}$.
A cyclic shift number $i$ $(1 ≤ i ≤ n)$ of permutation $b$ consisting from $n$ elements is a permutation $b_{i}b_{i + 1}... b_{n}b_{1}b_{2}... b_{i - 1}$. Overall a permutation has $n$ cyclic shifts.
The Little Elephant wonders, for all cyclic shifts of permutation $b$, what is the distance between the cyclic shift and permutation $a$?
|
Each of the shifts can be divided into two parts - the right (the one that starts from occurrence 1) and the left (the rest of the elements). If we could keep minimal distance for each part, the minimal of these numbers will be the answers for the corresponding shift. Lets solve the problems of the right part, the left will be almost the same. Let we have some shift, for example $34567[12]$ and the permutation $A$ is $4312765$ and $B$ is $2145673$, then shifted $B$ is $4567321$. Let we keep two sets ($S1$ and $S2$). The first will keep all the distances from integers in current left part to the corresponding positions in $A$ (for the example above, it is \texttt{2, 4}). When you come to the next shift, all integers in $S1$ should be decreased by 1 (that is because all distances are also decreased by 1). But now some integers in set may be negative, when any negative integer occures (it always will be -1) you need to delete it from $S1$ and put 1 to the $S2$. Also after shifting to the next shifts, all integers in $S2$ must be increase by 1. After that, for any shift, the answer will be minimum from the smallest numbers in $S1$ and $S2$. It was very useful to use standart "set" in C++.
|
[
"data structures"
] | 2,100
| null |
220
|
D
|
Little Elephant and Triangle
|
The Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers $(x; y)$, such that $0 ≤ x ≤ w$ and $0 ≤ y ≤ h$. Thus, the Little Elephant knows only $(w + 1)·(h + 1)$ distinct integer points.
The Little Elephant wants to paint a triangle with vertexes at integer points, the triangle's area must be a positive integer. For that, he needs to find the number of groups of three points that form such triangle. At that, the order of points in a group matters, that is, the group of three points $(0;0)$, $(0;2)$, $(2;2)$ isn't equal to the group $(0;2)$, $(0;0)$, $(2;2)$.
Help the Little Elephant to find the number of groups of three integer points that form a nondegenerate triangle with integer area.
|
Let iterate all possible points that, as we consider, must be the first point. Let it be $(x;y)$. Let the second and the third points be $(x1;y1)$ and $(x2;y2)$. Then the doubled area is $|(x1 - x)(y2 - y) - (x2 - x)(y1 - y)|$. We need this number to be even and nonzero. For first we will find the number of groups of points that are even, after that just subtract the number of groups with area equal to zero. For the first subproblem, we need to rewrite our formula. It is equal to $|x(y1 - y2) + y(x2 - x1)|$. Since we know $x$ and $y$ and we just need to check parity, we can try all possible $2^{4}$ values of parity of $x1$, $y1$, $x2$ and $y2$ (let it be $d0$, $d1$, $d2$ and $d3$, respectively). And check whether they will form a $0$ after multiplications and taking modulo $2$. If it froms a $0$, then add to the answer value $cx_{d0}cy_{d1}cx_{d2}cy_{d3}$, where $cx_{d}$ is equal to the number of integers between $0$ and $n$, inclusve, that modulo $2$ are equal $d$. $cy_{d}$ is the same but in range $[0..m]$. Now we need to subtract bad groups - the ones that has the area equal to zero. This means that they will either form a dot or a segment. If it is segment, we can just iterate $dx = |x1 - x2|$ and $dy = |y1 - y2|$ instead of all 4 coordinates. Then the number of such segments on the plane will be $(n - dx + 1)(m - dy + 1)$. Also for counting the number of triples of points on the segment you need to find the number of integer coordinates on the segment. It is well-know problem, and the answer is $gcd(dx, dy) + 1$. This gives us, with some simple optimizations, and $O(nm)$ solution.
|
[
"geometry",
"math"
] | 2,500
| null |
220
|
E
|
Little Elephant and Inversions
|
The Little Elephant has array $a$, consisting of $n$ positive integers, indexed from 1 to $n$. Let's denote the number with index $i$ as $a_{i}$.
The Little Elephant wants to count, how many pairs of integers $l$ and $r$ are there, such that $1 ≤ l < r ≤ n$ and sequence $b = a_{1}a_{2}... a_{l}a_{r}a_{r + 1}... a_{n}$ has no more than $k$ inversions.
An \underline{inversion} in sequence $b$ is a pair of elements of the sequence $b$, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers $i$ and $j$, such that $1 ≤ i < j ≤ |b|$ and $b_{i} > b_{j}$, where $|b|$ is the length of sequence $b$, and $b_{j}$ is its $j$-th element.
Help the Little Elephant and count the number of the described pairs.
|
In this problems you can use a method of two pointers. Also some RMQ are required. If you do not know about RMQ, please, read about it in the Internet before solving this problem. Firstly, map all the elements in the input array. After that all of them will be in range $[0..n - 1]$. We need to keep two RMQs, both of size $n$. Let the first RMQ be $Q1$ and the second $Q2$. $Q1_{i}$ will contain the number of numbers $i$ in current left subarray. $Q2_{i}$ will contain the number of numbers $i$ in the left subarray. Firstly, add all $n$ number to the $Q2$. After that iterate some pointer $r$ from $n - 1$ downto $1$, by the way keeping point $l$ (which, at the beggining, is equal to $n - 1$) Using RMQs, you can keep the number of inversions when you decrease $r$ or $l$ (using "sum on the range" operation). While the current number of inversions is more then $k$ and $l \ge 0$, decrease $l$. Then for each $r$ the answer of correct $l$ will be $l + 1$ (considering 0-based numeration). This makes the algorithm working in $O(NlogN)$ time with correct realisation.
|
[
"data structures",
"two pointers"
] | 2,400
| null |
221
|
A
|
Little Elephant and Function
|
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let $a$ is a permutation of an integers from 1 to $n$, inclusive, and $a_{i}$ denotes the $i$-th element of the permutation. The Little Elephant's recursive function $f(x)$, that sorts the first $x$ permutation's elements, works as follows:
- If $x = 1$, exit the function.
- Otherwise, call $f(x - 1)$, and then make $swap(a_{x - 1}, a_{x})$ (swap the $x$-th and $(x - 1)$-th elements of $a$).
The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to $n$, such that after performing the Little Elephant's function (that is call $f(n)$), the permutation will be sorted in ascending order.
|
In this problems you should notice that the answer for the problem is always of the following form: $n$, 1, 2, 3, ..., $n$-1. In such case array will be always sorted after the end of the algorithm.
|
[
"implementation",
"math"
] | 1,000
| null |
221
|
B
|
Little Elephant and Numbers
|
The Little Elephant loves numbers.
He has a positive integer $x$. The Little Elephant wants to find the number of positive integers $d$, such that $d$ is the divisor of $x$, and $x$ and $d$ have at least one common (the same) digit in their decimal representations.
Help the Little Elephant to find the described number.
|
Here you just need to find all divisors of $n$. This can be done using standart algorithm with iterating from 1 to $sqrt(n)$. After that you need to write some function that checks whether two numbers has same digits. This also can be done using simple loops.
|
[
"implementation"
] | 1,300
| null |
222
|
A
|
Shooshuns and Sequence
|
One day shooshuns found a sequence of $n$ integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
- Find the number that goes $k$-th in the current sequence and add the same number to the end of the sequence;
- Delete the first number of the current sequence.
The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
|
Note that the k-th element is copied to the end. Then the (k+1)-th element from the initial sequence is copied, then (k+2)-th, \dots , n-th, k-th, (k+1)-th, etc. So all the numbers on the blackboard will become equal if and only if all the numbers from the k-th to the n-th in the initial sequence were equal. It's now also obvious that the number of operations needed for it is equal to the index of the last number that is not equal to the n-th element of the initial sequence, because it's exactly the number of deletions needed to eliminate the elements that are not equal to the last one. If this number is greater than k, than answer is -1. Complexity - O(n).
|
[
"brute force",
"implementation"
] | 1,200
| null |
222
|
B
|
Cosmic Tables
|
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an $n × m$ table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:
- The query to swap two table rows;
- The query to swap two table columns;
- The query to obtain a secret number in a particular table cell.
As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
|
Let's store the order of the rows and columns of table. Thus, row[x] is the number of the row x in the initial table and column[x] is the number of column x in the initial table. Then, the value of an element in the row x and column y in the current table is equal to t[row[x], column[y]], where t - initial table. When we get the update request, we need to swap the x-th element and the y-th element in the corresponding array. Complexity - O(n * m + k).
|
[
"data structures",
"implementation"
] | 1,300
| null |
222
|
C
|
Reducing Fractions
|
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.
|
Let's factorize the numerator and denominator. Now for each prime integer x we know the extent of x in the factorization of the numerator(a[x]) and the denominator(b[x]). For each prime number x we can calculate the extent of x in the factorization of the numerator and the denominator after reduction : newa[x]=a[x]-min(a[x], b[x]), newb[x]=b[x]-min(a[x],b[x]). We have the numerator and the denominator of the answer in factorized form. Now we have to bring them into the form which is required in the condition. One of the ways to do it is to note that the fraction from the statement satisfies the conditions. We can factorize it again and in the answer we will have the same fraction for which there will not be such a prime x so that the degree of x in answer would be greater than newa[x] or newb[x]. (This operation can be called reduction) The result will satisfy the condition and the fraction will be equal to the required number. If you try to build answer greedily (put factors in the answer till their product <= 10^7), the count of numbers in the answer (n_out or m_out) will be bigger than 10^5. Factorization by O(sqrt(max)) received TL. You should have found a faster way. For example you could have used linear sieve of Eratosthenes. Complexity - O(max + n * log(max)). log(max) is size of factorization.
|
[
"implementation",
"math",
"number theory",
"sortings"
] | 1,800
| null |
222
|
D
|
Olympiad
|
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least $x$ points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.
Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.
|
First of all, note that in any case the best place which Vasya can take is the first place for he can earn maximum points. Now we must find the worst place which Vasya can take. We need to find maximal matching in bipartite graph, where the edge between vertice i from the first part and vertice j from the second part exists if a[i] + b[j] >= x. To solve this task, it is enough just to sort the vertices in both parts of the graph by their weights and use two pointers method. Suppose that we have sorted all the vertices by non-increasing points (a1 >= a2 >= ... >= an). Let's take two pointers - L = 1 in the first part and R = N in the second part. While a[L] + b[R] < x we must decrease R to find the first vertice such a[L] + b[R] >= x. When we found such R, we must add this edge to the answer, i.e. increase the answer, increase L by 1, decrease R by 1. It is easy to show why this algo is correct and it finds the optimal solution. I have discovered a truly marvelous proof of this, but the margins of this analysis are too narrow to for him. Complexity - O(N log N) for sorting and O(N) for two pointers.
|
[
"binary search",
"greedy",
"sortings",
"two pointers"
] | 1,900
| null |
222
|
E
|
Decoding Genome
|
Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most $m$ different nucleotides, numbered from $1$ to $m$. Special characteristics of the Martian DNA prevent some nucleotide pairs from following consecutively in this chain. For example, if the nucleotide 1 and nucleotide 2 can not follow consecutively in the Martian DNA, then the chain of nucleotides [1, 2] is not a valid chain of Martian DNA, but the chain of nucleotides [2, 1] can be a valid chain (if there is no corresponding restriction). The number of nucleotide pairs that can't follow in the DNA chain consecutively, is $k$.
The needs of gene research required information about the quantity of correct $n$-long chains of the Martian DNA. Your task is to write a program that will calculate this value.
|
1) Solution with complexity O(n*m*m), using the dynamic programming: State - d[n][m] - the number of allowed chains of length n that ends in symbol m. Transition - sort out all possible characters, and check if you can put the symbol k after symbol m. 2) Solution with complexity O(m*m*m*log n): Note that the transition in the first solution is always the same. So we can make the transition matrix A of size MxM. If j-th symbol can follow i-th then A[i][j]=1 else A[i][j]=0. Define a vector of size 1xM b={1,1, \dots ,1}. We can see that b * a^(n-1) = answer. Now we can use fast exponentiation for computing a^(n-1). We should consider the case with n=1 separately. The answer is the sum of numbers in the vector ans. Complexity - O(m^3) from matrix multiplication and O(log n) from fast exponentiation.
|
[
"dp",
"matrices"
] | 1,900
| null |
223
|
A
|
Bracket Sequence
|
A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. \textbf{The empty string is a correct bracket sequence by definition.}
A substring $s[l... r]$ $(1 ≤ l ≤ r ≤ |s|)$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is the string $s_{l}s_{l + 1}... s_{r}$. \textbf{The empty string is a substring of any string by definition}.
You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.
|
You were given a bracket sequence $s$ consisting of brackets of two kinds. You were to find regular bracket sequence that was a substring of $s$ and contains as many <<[>> braces as possible. We will try to determine corresponding closing bracket for every opening one. Formally, let a bracket on the i-th position be opening, then the closing bracket on the position j is corresponding to it if and only if a substring $s_{i}... s_{j}$ is the shortest regular bracket sequence that begins from the i-th position. In common case there can be brackets with no corresponding ones. We scan the sting $s$ and put positions with the opening brackets into a stack. Let us proceed the i-th position. If $s_{i}$ is an opening bracket we simply put $i$ on the top of the stack. Otherwise, we have to clean the stack if the stack is empty or the bracket on the top does not correspond to the current one. But if the bracket on the top is ok we just remove the top of the stack and remember that the bracket on position $i$ is corresponding to the bracket removed from the top. So, we find all the correspondings for all the brackets. Then we can split $s$ into blocks. Let block be a segment $[l, r]$ such that the bracket on the $r$-th position is corresponding for the bracket on the $i$-th and there is no couple of corresponding brackets on positions $x$ and $y$ such that $[l,r]\in[x,y]$ and $[l, r] \neq [x, y]$. It is easy to understand that the blocks do not intersect and the split is unique. We can join the consequent blocks into the regular bracket sequences. We should join as many blocks as possible in order to get the maximal number of braces. We get several substrings that are regular bracket sequences after we join all the consecutive blocks. The answer is the substring that has the largest amount of braces <<[>>. The complexity is $O(|s|)$.
|
[
"data structures",
"expression parsing",
"implementation"
] | 1,700
| null |
223
|
B
|
Two Strings
|
A subsequence of length $|x|$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is a string $x = s_{k1}s_{k2}... s_{k|x|}$ $(1 ≤ k_{1} < k_{2} < ... < k_{|x|} ≤ |s|)$.
You've got two strings — $s$ and $t$. Let's consider all subsequences of string $s$, coinciding with string $t$. Is it true that each character of string $s$ occurs in at least one of these subsequences? In other words, is it true that for all $i$ $(1 ≤ i ≤ |s|)$, there is such subsequence $x = s_{k1}s_{k2}... s_{k|x|}$ of string $s$, that $x = t$ and for some $j$ $(1 ≤ j ≤ |x|)$ $k_{j} = i$.
|
You were given two strings: $s$ and $t$. You were required to examine all occurrences of the string $t$ in the string $s$ as subsequence and to find out if it is true that for each position of the $s$ string there are such occurrence, that includes this position. For each position $i$ of the $s$ string we calculate two values $l_{i}$ and $r_{i}$ where $l_{i}$ is the maximal possible number that the string $t_{1}... t_{li}$ occurs as subsequence in the string $s_{1}... s_{i}$, $r_{i}$ is the maximal possible number that the string $t_{|t| - ri + 1}... t_{|t|}$ occurs in the string $s_{i}... s_{|s|}$ as subsequence. Let us find all of $l$ for the position $1... i - 1$ and want to find $l_{i}$. If the symbol $t_{li - 1 + 1}$ exists and concurs with the symbol $s_{i}$ then $l_{i} = l_{i - 1} + 1$, in other case $l_{i} = l_{i - 1}$. In the same way we can find $r_{i}$ if we move from the end of the string. Now we should check if the position $i$ in the string $s$ belongs to at least one occurrence. Let us assume this to be correct and the symbol $s_{i}$ corresponds to the symbol $t_{j}$ of the string $t$. Then $l_{i - 1} \ge j - 1$ and $r_{i + 1} \ge |t| - j$ by definition of the $l$ and $r$. Then if $j$ exists that $s_{i} = t_{j}$ and $l_{i - 1} + 1 \ge j \ge |t| - r_{i + 1}$, then the position $i$ of the string $s$ belongs to at least one occurrence of the $t$, in other case the occurrence doesn't exist. We can easily check it by creating an array $cnt_{a, i}$ for each letter, which is a number of letters $a$ in the positions $1... i$ of the string $t$. The complexity of the solution is $O(|s| + |t|)$.
|
[
"data structures",
"dp",
"strings"
] | 1,900
| null |
223
|
C
|
Partial Sums
|
You've got an array $a$, consisting of $n$ integers. The array elements are indexed from 1 to $n$. Let's determine a two step operation like that:
- First we build by the array $a$ an array $s$ of partial sums, consisting of $n$ elements. Element number $i$ ($1 ≤ i ≤ n$) of array $s$ equals $s_{i}=\left(\sum_{j=1}^{i}a_{j}\right)\mathrm{\mod\(10^{9}+7)}$. The operation $x mod y$ means that we take the remainder of the division of number $x$ by number $y$.
- Then we write the contents of the array $s$ to the array $a$. Element number $i$ ($1 ≤ i ≤ n$) of the array $s$ becomes the $i$-th element of the array $a$ ($a_{i} = s_{i}$).
You task is to find array $a$ after exactly $k$ described operations are applied.
|
You were given an array $a$ in this problem. You could replace $a$ by the array of its partial sums by one step. You had to find the array after $k$ such steps. All the calculations were modulo $P = 10^{9} + 7$. Write partial sums in following way: $s_{i}=\sum_{j=1}^{n}B_{i,j}a_{j}$where $B_{i, j} = 1$ if $i \ge j$ and $B_{i, j} = 0$ if $i < j$, for each $1 \le i, j \le n$. We can represent $a$ and $s$ as vector-columns, therefore one step corresponds to multiplying matrix $B$ and vector-column $a$. Then the array $a$ after $k$ steps is equal to $B^{k}a$. We can raise a matrix to a power for $O(n^{3}\log k)$. It is not bad, but not fast enough. We can notice, that $(B^{k})_{i,j}$ = $\left(B^{k}\right)_{i-j+1,1}$, i.e. the elements of the matrix $B^{k}$ on diagonals parallel to the main are the equal. It is easy to prove this fact using mathematical induction. You may prove it by yourself. Then we can determine the matrix by an array of numbers $\left(b^{k}\right)_{i}=\left(B^{k}\right)_{i,1}$, equal to the elements of the first column. The elements of the first column of the product $B^{k}B^{l}$ are equal $\left(b^{k+l}\right)_{i}=\sum_{j=1}^{t}\left(b^{k}\right)_{j}\left(b^{l}\right)_{i-j+1}$. It is a straight consequence of formula of matrix product. The computing of one element requires $O(n)$ time, there are $n$ elements therefore we can multiply matrices in $O(n^{2})$ time. Then we can solve the problem in $O(n^{2}\log k)$ time and this solution fits the consrtaints. This problem can be solved faster. We can assure that $\left(b^{k}\right)_{i}=C_{k+i-1}^{k-1}$. Let this formula be correct for some $k$. Prove that it is correct for $k + 1$ either. Using the formula of product we get: $\bigl(b^{k+1}\bigr)_{i}=\sum_{j=1}^{i}C_{k+j-1}^{k-1}$ $\sum_{j=1}^{t}C_{k+j-1}^{k-1}=C_{k}^{k}+C_{k}^{k-1}+\sum_{j=3}^{t}C_{k+j-1}^{k-1}$ $C_{k}^{k}+C_{k}^{k-1}+\sum_{j=3}^{t}C_{k+j-1}^{k-1}=C_{k+1}^{k}+C_{k+1}^{k-1}+\sum_{j=4}^{t}C_{k+j-1}^{k}=\dots=C_{k+1}^{k}$ Using the formula $C_{n}^{k} = n! / k!(n - k)!$ we can obtain $(b^k)_{i+1} / (b^k)_i = (k+i) / (i+1)$, so we can find all the coefficients $b$ if we can divide modulo $P$. Therefore it is significant that $P$ is prime. Inverse $x$ modulo $P$ is equal to $x^{P-2} \bmod P$ according to the Fermat little theorem. Therefore we get $O(n^{2})solution$.
|
[
"combinatorics",
"math",
"number theory"
] | 1,900
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.