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
⌀ |
|---|---|---|---|---|---|---|---|
526
|
A
|
King of Thieves
|
In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.
An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.
A dungeon consists of $n$ segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.
One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number $i_{1}$, he can make a sequence of jumps through the platforms $i_{1} < i_{2} < ... < i_{k}$, if $i_{2} - i_{1} = i_{3} - i_{2} = ... = i_{k} - i_{k - 1}$. Of course, all segments $i_{1}, i_{2}, ... i_{k}$ should be exactly the platforms, not pits.
Let's call a level to be good if you can perform a sequence of \textbf{four} jumps of the same length or in the other words there must be a sequence $i_{1}, i_{2}, ..., i_{5}$, consisting of \textbf{five} platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.
|
This task is easy for many of you. We can just iterate over all possible $i_{1}$ and $i_{2} - i_{1}$, then we can compute $i_{3, ..., 5}$, and check whether this subsequence satisfies the condition mentioned in the task.
|
[
"brute force",
"implementation"
] | 1,300
| null |
526
|
B
|
Om Nom and Dark Park
|
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.
The park consists of $2^{n + 1} - 1$ squares connected by roads so that the scheme of the park is a full binary tree of depth $n$. More formally, the entrance to the park is located at the square $1$. The exits out of the park are located at squares $2^{n}, 2^{n} + 1, ..., 2^{n + 1} - 1$ and these exits lead straight to the Om Nom friends' houses. From each square $i$ ($2 ≤ i < 2^{n + 1}$) there is a road to the square $\left\lfloor{\frac{i}{2}}\right\rfloor$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly $n$ roads.
To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square $i$ to square $\left\lfloor{\frac{i}{2}}\right\rfloor$ has $a_{i}$ lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.
He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
|
We use greedy and recursion to solve this task. For each tree rooted at $v$, we adjust its two subtrees at first, using recursion. Then we increase one edge from $v$'s child to $v$.
|
[
"dfs and similar",
"greedy",
"implementation"
] | 1,400
| null |
526
|
C
|
Om Nom and Candies
|
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?
One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs $W_{r}$ grams and each blue candy weighs $W_{b}$ grams. Eating a single red candy gives Om Nom $H_{r}$ joy units and eating a single blue candy gives Om Nom $H_{b}$ joy units.
Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than $C$ grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.
|
If there is a kind of candy which weighs greater than $\sqrt{C}$, then we can iterate over the number of it to buy, which is less than $\sqrt{C}$. Otherwise, without loss of generality we suppose ${\frac{H_{b}}{W_{b}}}<{\frac{H_{s}}{W_{r}}}$. If the number of the blue candies that Om Nom eats is more than $W_{r}$, he could eat $W_{b}$ red candies instead of $W_{r}$ blue candies, because $H_{b} \times W_{r} < W_{b} \times H_{r}$. It means the number of the blue candies will be less than $\sqrt{C}$, and we can iterate over this number.
|
[
"brute force",
"greedy",
"math"
] | 2,000
| null |
526
|
D
|
Om Nom and Necklace
|
One day Om Nom found a thread with $n$ beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly.
Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads $S$ is regular if it can be represented as $S = A + B + A + B + A + ... + A + B + A$, where $A$ and $B$ are some bead sequences, "$ + $" is the concatenation of sequences, there are exactly $2k + 1$ summands in this sum, among which there are $k + 1$ "$A$" summands and $k$ "$B$" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if $A$ or $B$ is an empty sequence.
Help Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.
|
This task is to determine whether a string is in the form of $ABABA... ABA$ for each prefixes of a given string $S$ For a prefix P, let's split it into some blocks, just like $P = SSSS... SSSST$, which $T$ is a prefix of $S$. Obviously, if we use KMP algorithm, we can do it in linear time, and the length of $S$ will be minimal. There are only two cases : $T = S, T \neq S$. $T = S$. When $T = S, P = SSS... S$. Assume that $S$ appears $R$ times. Consider "ABABAB....ABABA", the last $A$ must be a suffix of $P$, and it must be like $SS... S$, so $A$ will be like $SS... SS$, and so will $B$. By greedy algorithm, the length of $A$ will be minimal, so it will be $SSS... S$, where $S$ appears $R{\mathrm{~mod~}}Q$ times. And $B$ will be $SSS... S$, where $S$ appears $(R/Q-R\mod Q)$ times. So we just need to check whether $R/Q-R\mod Q\geq0$. $T \neq S$ . When $T \neq S$, the strategy is similar to $T = S$. A will be like "SS...ST", and its length will be minimal. At last we just need to check whether $R/Q-R\mod Q>0$ . The total time complexity is $O(n)$.
|
[
"hashing",
"string suffix structures",
"strings"
] | 2,200
| null |
526
|
E
|
Transmitting Levels
|
Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application.
In one secret game developed deep in the ZeptoLab company, the game universe consists of $n$ levels, located in a circle. You can get from level $i$ to levels $i - 1$ and $i + 1$, also you can get from level $1$ to level $n$ and vice versa. The map of the $i$-th level description size is $a_{i}$ bytes.
In order to reduce the transmitted traffic, the game gets levels as follows. All the levels on the server are divided into $m$ groups and each time a player finds himself on one of the levels of a certain group for the first time, the server sends all levels of the group to the game client as a single packet. Thus, when a player travels inside the levels of a single group, the application doesn't need any new information. Due to the technical limitations the packet can contain an arbitrary number of levels but their total size mustn't exceed $b$ bytes, where $b$ is some positive integer constant.
Usual situation is that players finish levels one by one, that's why a decision was made to split $n$ levels into $m$ groups so that each group was a continuous segment containing multiple neighboring levels (also, the group can have two adjacent levels, $n$ and $1$). Specifically, if the descriptions of all levels have the total weight of at most $b$ bytes, then they can all be united into one group to be sent in a single packet.
Determine, what minimum number of groups do you need to make in order to organize the levels of the game observing the conditions above?
As developing a game is a long process and technology never stagnates, it is yet impossible to predict exactly what value will take constant value $b$ limiting the packet size when the game is out. That's why the developers ask you to find the answer for multiple values of $b$.
|
Our task is to compute at least how many number of blocks are needed to partition a circular sequence into blocks whose sum is less than $K$. By monotonicity, it is easy to get the length of maximal blocks which starts from 1 to $n$ in $O(n)$. Assume the block with minimal length is $A$ and its length is $T$, it is obvious that whatever the blocks are, there must be a block that it starts in $A$. So, we can iterate over all the $T$ numbers of $A$, making it the start of a block, and calculate the number of blocks. Notice that all the lengths of blocks is (non-strictly) greater than $T$, therefore the number of blocks we need is at most $N / T + 1$. We need to iterate $T$ times, but each time we can get the answer in $O(N / T)$, so finally we can check whether the answer is legal in $T * O(N / T) = O(N)$.
|
[
"dp",
"implementation"
] | 2,400
| null |
526
|
F
|
Pudding Monsters
|
In this problem you will meet the simplified model of game Pudding Monsters.
An important process in developing any game is creating levels. A game field in Pudding Monsters is an $n × n$ rectangular grid, $n$ of its cells contain monsters and some other cells contain game objects. The gameplay is about moving the monsters around the field. When two monsters are touching each other, they glue together into a single big one (as they are from pudding, remember?).
Statistics showed that the most interesting maps appear if initially each row and each column contains exactly one monster and the rest of map specifics is set up by the correct positioning of the other game objects.
A technique that's widely used to make the development process more efficient is reusing the available resources. For example, if there is a large $n × n$ map, you can choose in it a smaller $k × k$ square part, containing exactly $k$ monsters and suggest it as a simplified version of the original map.
You wonder how many ways there are to choose in the initial map a $k × k$ ($1 ≤ k ≤ n$) square fragment, containing exactly $k$ pudding monsters. Calculate this number.
|
Actually this problem is to compute how many segments in a permutation forms a permutation of successive integers. We use divide and conquer to solve this problem. If we want to compute the answer for an interval $[1, n]$, we divide this interval into two smaller ones $[1, m], [m + 1, n]$ where $m=\lfloor{\frac{n+1}{2}}\rfloor$. We only care about the segments which crosses $m$. We call the first interval $L$ and the latter one $R$. Considering the positiions of maximum numbers and minimum numbers in these valid segments, There are four possible cases: the maximum number is in $L$, the the minimum is also in $L$; the maximum number is in $R$, the the minimum is also in $R$; the maximum number is in $L$, the the minimum is in $R$; the maximum number is in $R$, the the minimum is in $L$; Let $A$ be the given sequence and we define $Lmax_{p} = max_{p \le i \le m}A_{i}$. Similarly we can define $Rmax_{p}, Rmin_{p}, Lmin_{p}$. For simplicity we only cares about case 1 and case 4. In Case 1, we iterate over the start position of the segment, so we know the maximum and minimum number so we can compute the length of the segment and check the corresponding segment using $Rmin$ and $Rmax$. In Case 4, we iterate over the start position again, denoted as $x$. Suppose the right end is $y$, then we know that $Lmin_{x} < Rmin_{y}, Lmax_{x} < Rmax_{y}$ so we can limit $y$ into some range. Another constraint for $y$ is that $Rmax_{y} - Lmin_{x} = y - x$, i.e. $Rmax_{y} - y = Lmin_{x} - x$. Note that when $x$ varies, the valid range for $y$ also varies, but the range is monotone, so we can maintain how many times a number appears in linear time. It's easy to show that this algorithm runs for $O(n\log n)$, by Master Theorem. There are some other people using segment trees.
|
[
"data structures",
"divide and conquer"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2000010;
int mn[N], add[N], cnt[N];
void build(int x, int l, int r) {
mn[x] = l;
add[x] = 0;
cnt[x] = 1;
if (l < r) {
int y = (l + r) >> 1;
build(x + x, l, y);
build(x + x + 1, y + 1, r);
}
}
inline void push(int x) {
if (add[x] != 0) {
add[x + x] += add[x];
add[x + x + 1] += add[x];
add[x] = 0;
}
}
inline void gather(int x) {
int a = mn[x + x] + add[x + x];
int b = mn[x + x + 1] + add[x + x + 1];
mn[x] = (a < b ? a : b);
cnt[x] = (a == mn[x] ? cnt[x + x] : 0) + (b == mn[x] ? cnt[x + x + 1] : 0);
}
void modify(int x, int l, int r, int ll, int rr, int value) {
if (ll <= l && r <= rr) {
add[x] += value;
return;
}
push(x);
int y = (l + r) >> 1;
if (ll <= y) {
modify(x + x, l, y, ll, rr, value);
}
if (rr > y) {
modify(x + x + 1, y + 1, r, ll, rr, value);
}
gather(x);
}
int a[N];
int up[N], down[N];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
a[i] = -1;
}
for (int i = 0; i < n; i++) {
int x, y;
scanf("%d %d", &x, &y);
x--; y--;
a[x] = y;
}
build(1, 0, n - 1);
long long ans = 0;
int cup = 1, cdown = 1;
up[0] = -1;
down[0] = -1;
for (int i = 0; i < n; i++) {
while (cup >= 2 && a[i] < a[up[cup - 1]]) {
modify(1, 0, n - 1, up[cup - 2] + 1, up[cup - 1], +a[up[cup - 1]]);
cup--;
}
while (cdown >= 2 && a[i] > a[down[cdown - 1]]) {
modify(1, 0, n - 1, down[cdown - 2] + 1, down[cdown - 1], -a[down[cdown - 1]]);
cdown--;
}
up[cup++] = i;
down[cdown++] = i;
modify(1, 0, n - 1, up[cup - 2] + 1, up[cup - 1], -a[up[cup - 1]]);
modify(1, 0, n - 1, down[cdown - 2] + 1, down[cdown - 1], +a[down[cdown - 1]]);
ans += cnt[1];
}
cout << ans << endl;
return 0;
}
|
526
|
G
|
Spiders Evil Plan
|
Spiders are Om Nom's old enemies. They love eating candies as much as he does and that's why they keep trying to keep the monster away from his favorite candies. They came up with an evil plan to trap Om Nom.
Let's consider a rope structure consisting of $n$ nodes and $n - 1$ ropes connecting the nodes. The structure is connected, thus, the ropes and the nodes form a tree. Each rope of the formed structure is associated with its length. A candy is tied to node $x$ of the structure. Om Nom really wants to eat this candy.
The $y$ spiders are trying to stop him from doing it. They decided to entangle the candy and some part of the structure into a web, thus attaching the candy to as large as possible part of the rope structure.
Each spider can use his web to cover all ropes on the path between two arbitrary nodes $a$ and $b$. Thus, $y$ spiders can cover the set of ropes which is a union of $y$ paths in the given tree. These $y$ paths can arbitrarily intersect each other. The spiders want the following conditions to be hold:
- the node containing the candy is adjacent to at least one rope covered with a web
- the ropes covered with the web form a connected structure (what's the idea of covering with a web the ropes that are not connected with the candy?)
- the total length of the ropes covered with web is as large as possible
The spiders haven't yet decided to what node of the structure they will tie the candy and how many spiders will cover the structure with web, so they asked you to help them. Help them calculate the optimal plan for multiple values of $x$ and $y$.
|
In this task, we are given a tree and many queries. In each query, we are supposed to calculate the maximum total length of $y$ paths with the constraint that $x$ must be covered. Consider $S$ is the union of the paths (it contains nodes and edges). For each query $(x, y)$, if $y > 1$ , then there is always a method that $S$ is connected. Further, we could get the following theorem: For an unrooted tree, if it has $2k$ leaves, then $k$ paths can cover this tree completely. Proof for this theorem is that, if some edge $u - v$ is not covered, we can interchange two paths, i.e. we change two paths $a - b$ and $c - d$ to $a - c$ and $b - d$, for $a - b$ in the subtree of $u$ and $c - d$ in the subtree of $v$. So a query $(x, y)$ could be described as : Find $2y$ leaves in the tree, with node $x$ in $S$, and maximize the total of weight of the edges in $S$. For a query $(x, y)$, we can make $x$ the root. Then this task is how to choose the leaves. Note that we could select leaves one by one, every time we select the leaf which makes answer larger without selecting the others, as follow : But if for every query we need to change the root, the time complexity cannot be accepted. Assuming the longest path in the tree is $(a, b)$ , we could find that whatever the query is, $S$ will contain either $a$ or $b$ certainly. So, we just need to make $a$ and $b$ the root in turn, and get the maximum answers. However, there is another problem : $x$ may not be in $S$. Like this : But it doesn't matter. We just need to link $x$ with the selected, and erase some leaf. Of course after erasing, the answer should be maximum.
|
[
"greedy",
"trees"
] | 3,300
| null |
527
|
A
|
Playing with Paper
|
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular $a$ mm $ × $ $b$ mm sheet of paper ($a > b$). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
After making a paper ship from the square piece, Vasya looked on the remaining $(a - b)$ mm $ × $ $b$ mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
|
It's easy to see that described process is equivalent to the following loop: But such naive approach will obviously lead to verdict TLE, since it makes ~$10, 2015 - 03 - 19^{12}$ operations even on the third sample test. The key idea is to replace repeating subtraction operations with integer division operations. This leads to the logarithmic-time solution that looks similar to the Euclid algorithm:
|
[
"implementation",
"math"
] | 1,100
| null |
527
|
B
|
Error Correct System
|
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings $S$ and $T$ of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings $S$ and $T$ of the same length, which is defined as the number of positions in which $S$ and $T$ have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string $S$, so that the Hamming distance between a new string $S$ and string $T$ would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
|
The first observation is that the new Hamming distance may not be less than the old one minus two, since we change only two characters. So the task is to actually determine, if we can attain decrease by two, one or can't attain decrease at all. The decrease by two is possible if there are two positions with the same two letters in two strings but that appear in different order (like "double" <-> "bundle"). If there are no such positions, then we just need to check that we may decrease the distance. This can be done by just "fixing" the character that stands on the wrong position, like in "permanent" <-> "pergament" (here n stands in wrong pair with m, and there is also unmatched m, so we may fix this position). Otherwise, the answer is to keep everything as it is. Implementation can be done by keeping for each pair (x, y) of symbols position where such pair appears in S and T and then by carefully checking the conditions above.
|
[
"greedy"
] | 1,500
| null |
527
|
C
|
Glass Carving
|
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular $w$ mm $ × $ $h$ mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
|
Obviously the largest glass piece at any moment is the one that is product of the largest horizontal segment by the largest vertical segment. One of the possible solutions is to carefully implement what described in the statement and keep all horizontal segments and all vertical segments in priority queue or std::set, or some logarithmic data structure. This solution works in $O(k*\log(n+m))$. But there is also a nice linear solution if we answer all queries in reverse order. Suppose segments are not cutting, but merging. In this case we may keep the horizontal and vertical cut lines in double-linked lists and track the current maximum (that can only increase and become equal to the newly-merged segment each time). This solution works in $O(k + n + m)$.
|
[
"binary search",
"data structures",
"implementation"
] | 1,500
| null |
527
|
D
|
Clique Problem
|
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph $G$. It is required to find a subset of vertices $C$ of the maximum size such that any two of them are connected by an edge in graph $G$. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider $n$ distinct points on a line. Let the $i$-th point have the coordinate $x_{i}$ and weight $w_{i}$. Let's form graph $G$, whose vertices are these points and edges connect exactly the pairs of points $(i, j)$, such that the distance between them is not less than the sum of their weights, or more formally: $|x_{i} - x_{j}| ≥ w_{i} + w_{j}$.
Find the size of the maximum clique in such graph.
|
One may think that this task is about graph theory, but it after some investigation and several equivalent changes in task statement it can be reduced to the well-known greedy problem. Initially you have that points may lie together in a set if they are not too close, i. e. $|x_{i} - x_{j}| \ge w_{i} + w_{j}$. This is obviously equivalent to the following condition. Let's consider interval of radius $w_{i}$ with center in point $x_{i}$ and call this interval to be the interval of point i. Then the statement actually says that no two such intervals should be intersecting. This task is well-known and can be solved greedily after sorting segments in ascending order of right endpoint: It's easy to prove that this solution is correct. Among all ways to choose first $k$ segments, the best way is the one that minimizes x-coordinate of the right endpoint of the last segment (since it restricts us in the least possible way).
|
[
"data structures",
"dp",
"greedy",
"implementation",
"sortings"
] | 1,800
| null |
527
|
E
|
Data Center Drama
|
The project of a data center of a Big Software Company consists of $n$ computers connected by $m$ cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is not yet approved, it wasn't determined yet in which direction information will go along each cable. The cables are put so that each computer is connected with each one, perhaps through some other computers.
The person in charge of the cleaning the data center will be Claudia Ivanova, the janitor. She loves to tie cables into bundles using cable ties. For some reasons, she groups the cables sticking out of a computer into groups of two, and if it isn't possible, then she gets furious and attacks the computer with the water from the bucket.
It should also be noted that due to the specific physical characteristics of the Very Important Information, it is strictly forbidden to connect in one bundle two cables where information flows in different directions.
The management of the data center wants to determine how to send information along each cable so that Claudia Ivanova is able to group all the cables coming out of each computer into groups of two, observing the condition above. Since it may not be possible with the existing connections plan, you are allowed to add the minimum possible number of cables to the scheme, and then you need to determine the direction of the information flow for each cable (yes, sometimes data centers are designed based on the janitors' convenience...)
|
Problem legend asks you to add minimum number of edges to the given connected undirected graph (possibly, with loops and duplicating edges) and choose direction for its edges so that both the incoming and outgoing degrees of all vertices are even. First idea is that the resulting graph before we choose the direction (but after we added some edges) will contain Euler circuit, since all degrees are even. That's almost what we need: if we have an Euler circuit that contains even number of edges, we may direct them like following: a <- b -> c <- d -> e \dots It's easy to see that each vertex appearance in this cycle adds 2 to its ingoing or outgoing degree, so the resulting degrees will be even. But if the Euler circuit is odd (meaning that there is odd number of edges in the graph), we must add some extra edge to the graph before we continue, the easiest way is to add a loop from vertex 0 to itself, since it doesn't affect the Euler tour, but now tour length is even, so everything is ok. Now we should think how to add edges optimally. It's easy to see that the optimal way is to first fix all odd degrees of vertices (i. e. combine all odd vertices by pairs and put an edge in each pair), and then, possibly, add an extra loop as described above. The last part is to actually find an Euler circuit, and to print the answer.
|
[
"dfs and similar",
"graphs"
] | 2,600
| null |
528
|
D
|
Fuzzy Search
|
Leonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.
Let's consider the following scenario. There is a fragment of a human DNA chain, recorded as a string $S$. To analyze the fragment, you need to find all occurrences of string $T$ in a string $S$. However, the matter is complicated by the fact that the original chain fragment could contain minor mutations, which, however, complicate the task of finding a fragment. Leonid proposed the following approach to solve this problem.
Let's write down integer $k ≥ 0$ — the error threshold. We will say that string $T$ occurs in string $S$ on position $i$ ($1 ≤ i ≤ |S| - |T| + 1$), if after putting string $T$ along with this position, each character of string $T$ corresponds to the some character of the same value in string $S$ at the distance of at most $k$. More formally, for any $j$ ($1 ≤ j ≤ |T|$) there must exist such $p$ ($1 ≤ p ≤ |S|$), that $|(i + j - 1) - p| ≤ k$ and $S[p] = T[j]$.
For example, corresponding to the given definition, string "ACAT" occurs in string "AGCAATTCAT" in positions $2$, $3$ and $6$.
Note that at $k = 0$ the given definition transforms to a simple definition of the occurrence of a string in a string.
Help Leonid by calculating in how many positions the given string $T$ occurs in the given string $S$ with the given error threshold.
|
There were issues with this task. Intended constraints were actually $n, m, k \le 500000$, and the intended solution was using Fast Fourier Transformation, that leads to $|\ast n\log n$ running time. But unfortunately the statement contained wrong constraints, so we reduced input size during the tour. Nevertheless, we will add the harder version of this task and you will be able to submit it shortly. Key idea is to reduce this task to a polynomial multiplication. Let's solve the task in following manner. For each position i of the S for each character c from "ATGC" we will calculate match(c, i) that is equal to the number of c characters that have matching symbol in S if we put string T in position i. Then the criteria for us to have an occurrence at position i is that match(A, i) + match(T, i) + match(G, i) + match(C, i) == |T| (that means exactly that each character from T being put at position i has a corresponding character in S). Now let's find out how to calculate match(c, i). Let's keep only c characters and "not c" characters in both strings and denote them by 1 and 0 respectively. Let's also spread each 1 in string S by the distance k to the left and to the right. For example, k = 1 for the sample string AGCAATTCAT and the character A corresponding bit vector will be 111110111, and for the character C it will be 0111001110. This bitvector can be calculated in $O(n)$ by putting two events "+1" and "-1" in string S in positions $x - k$ and $x + k$ for each $1$ in original string S and then sweeping from left to right over the string S and processing those events. Now our task is reduced to searching all positions where the bitvector T is the submask of the bitvector S. In constraints $n, m, k \le 200000$ this can be done by using bitsets in $O(m(n - m) / 32)$. Nevertheless, this task can be seen as calculation of polynomials S and reversed(T) product. We will keep this as an exercise for those who decide to submit the harder version of this task.
|
[
"bitmasks",
"brute force",
"fft"
] | 2,500
| null |
528
|
E
|
Triangles 3000
|
\url{CDN_BASE_URL/2fdd572a668b63052b21147ea5152e78}
|
Let's draw a bounding box that contains all intersection points. Let's fix a triangle and consider three angles shown on the picture. Calculate area of intersection of those area with the bounding box and call this area to be the "area of an angle". Then it's easy to see, that those three angles are complement to the triangle itself in the bounding box, i. e. triangle area is bounding box area minus three angle areas. This leads us to the idea how to solve this task by carefully calculating for each possible formed angle on the plane, how much times does it appear in total answer if we sum all values like $(S - angle_area(a, b) - angle_area(b, c) - angle_area(c, a))$ over all triples $(a, b, c)$ of lines. Actually, the angle is considered as many times, as many lines there are that intersect both sides of its right adjacent angle. So, our task is reduced to calculate for each angle on plane how much lines intersect its sides (i. e. its rays). This can be done in $O(n^{2}\log{n})$ by fixing the first side of the angle and then adding lines in ascending order of polar angle, and then by keeping the number of lines that intersect the base line to the left and that intersect the base line to the right. Key idea is that the exact of four angles formed by the pair of lines $(a, b)$ that is crossed by some third line c, can be determined by two numbers: its polar angle alpha and its crossing with a coordinate x. Further details are shown on the picture below. There is also a nice short $O(n^{2})$ solution from enot110 here.
|
[
"geometry",
"sortings"
] | 3,100
|
/* --- author: enot-the-rockstar ---*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <ctime>
#include <cassert>
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
#define forn(i, n) for(int i = 0 ; (i) < (n) ; ++i)
#define forit(it,v) for(typeof((v).begin()) it = v.begin() ; it != (v).end() ; ++it)
#define eprintf(...) fprintf(stderr, __VA_ARGS__),fflush(stderr)
#define sz(a) ((int)(a).size())
#define all(a) (a).begin(),a.end()
static inline unsigned long long rdtsc() { unsigned long long d; __asm__ __volatile__ ("rdtsc" : "=A" (d) ); return d; }
using namespace std;
typedef long long ll;
typedef double dbl;
typedef vector<int> vi;
typedef pair<int, int> pi;
const int inf = (int)1e9;
const dbl eps = 1e-9;
/* --- main part --- */
#define TASK "a"
const int maxn = 3010;
struct line
{
dbl a, b, c;
line(){}
line (dbl aa, dbl bb, dbl cc): a(aa), b(bb), c(cc) {}
void read()
{
double aa, bb, cc;
scanf("%lf%lf%lf", &aa, &bb, &cc);
a = aa, b = bb, c = cc;
}
void norm()
{
dbl d = sqrt(a * a + b * b);
a /= d;
b /= d;
c /= d;
if (a < -eps) a = -a, b = -b, c = -c;
}
void rot(dbl alp)
{
dbl aa = a * cos(alp) - b * sin(alp);
dbl bb = a * sin(alp) + b * cos(alp);
a = aa;
b = bb;
}
};
line l[maxn];
pair<dbl, int> A[maxn];
inline dbl getS(line l1, line l2)
{
dbl Y = (l1.a * l2.c - l2.a * l1.c) / (l1.b * l2.a - l2.b * l1.a);
dbl DX = l2.c / l2.a - l1.c / l1.a;
return abs(Y * DX) / 2;
}
int main()
{
#ifdef home
assert(freopen(TASK".in", "r", stdin));
assert(freopen(TASK".out", "w", stdout));
#endif
int n;
scanf("%d", &n);
forn(i, n) l[i].read();
forn(i, n)
{
l[i].norm();
l[i].rot(0.123);
l[i].norm();
}
forn(i, n)
{
dbl alp = atan2(l[i].b, l[i].a);
while (alp < -M_PI / 2) alp += 2 * M_PI;
while (alp > M_PI / 2) alp -= 2 * M_PI;
A[i] = mp(alp, i);
}
sort(A, A + n);
dbl res = 0;
forn(i2, n) forn(i1, i2)
{
int ii1 = A[i1].sc;
int ii2 = A[i2].sc;
dbl S = getS(l[ii1], l[ii2]);
int mn = i2 - i1 - 1;
int pl = n - mn - 2;
res += S * (pl - mn);
}
dbl cnt = n * (n - 1.) * (n - 2.) / 6.;
res /= cnt;
printf("%.10lf\n", res);
#ifdef home
eprintf("Time: %d ms\n", (int)(clock() * 1000. / CLOCKS_PER_SEC));
#endif
return 0;
}
|
529
|
B
|
Group Photo 2 (online mirror version)
|
Many years have passed, and $n$ friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.
Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the $i$-th of them in a standing state occupies a $w_{i}$ pixels wide and a $h_{i}$ pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a $h_{i}$ pixels wide and a $w_{i}$ pixels high rectangle.
The total photo will have size $W × H$, where $W$ is the total width of all the people rectangles, and $H$ is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than $n / 2$ of them can lie on the ground (it would be strange if more than $n / 2$ gentlemen lie on the ground together, isn't it?..)
Help them to achieve this goal.
|
In an online mirror version the problem was slightly harder. Let's call people with $w \le h$ \textit{high}, and remaining people \textit{wide}. Let's fix photo height $H$. Let's consider several following cases: If a high person fits into height $H$, we leave him as is. If a high person doesn't fit into height $H$, the we have to ask him to lie down, increasing the counter of such people by $1$. If a wide person fits into height $H$, but doesn't fit lying on the ground, then we leave him staying. If a wide person fits into height $H$ in both ways, then we first ask him to stay and write into a separate array value of answer decrease if we ask him to lie on the ground: $w - h$. If somebody doesn't fit in both ways, then such value of $H$ is impossible. Now we have several people that have to lie on the ground (from second case) and if there are too many of them (more than $n / 2$) then such value of $H$ is impossible. After we put down people from second case there can still be some vacant ground positions, we distribute them to the people from fourth case with highest values of $w - h$. Then we calculate the total area of the photo and relax the answer.
|
[
"brute force",
"greedy",
"sortings"
] | 1,900
| null |
533
|
A
|
Berland Miners
|
The biggest gold mine in Berland consists of $n$ caves, connected by $n - 1$ transitions. The entrance to the mine leads to the cave number $1$, it is possible to go from it to any remaining cave of the mine by moving along the transitions.
The mine is being developed by the InMine Inc., $k$ miners work for it. Each day the corporation sorts miners into caves so that each cave has at most one miner working there.
For each cave we know the height of its ceiling $h_{i}$ in meters, and for each miner we know his height $s_{j}$, also in meters. If a miner's height doesn't exceed the height of the cave ceiling where he is, then he can stand there comfortably, otherwise, he has to stoop and that makes him unhappy.
Unfortunately, miners typically go on strike in Berland, so InMine makes all the possible effort to make miners happy about their work conditions. To ensure that no miner goes on strike, you need make sure that no miner has to stoop at any moment on his way from the entrance to the mine to his cave (in particular, he must be able to stand comfortably in the cave where he works).
To reach this goal, you can choose exactly one cave and increase the height of its ceiling by several meters. However enlarging a cave is an expensive and complex procedure. That's why InMine Inc. asks you either to determine the minimum number of meters you should raise the ceiling of some cave so that it is be possible to sort the miners into the caves and keep all miners happy with their working conditions or to determine that it is impossible to achieve by raising ceiling in exactly one cave.
|
We can add $n - k$ miners with height $0$ and it won't affect answer. So we can assume that numbers of miners and caves are the same. For every cave let's define $t_{i}$ as maximal possible height of miner working in cave $i$ if we wouldn't change any cave. We can calculate it from root to leaves with line $t_{i} = min(t_{father}, h_{i})$. Let's say we don't change anything. We will try to assign all workers if it's possible or to do the best possible assignment otherwise - the one where there are few free (not occupied) caves and they are high (value $t_{i}$ is big). I will say later why we want them to be high. Formal definition (you don't have to read the next paragraph): For every assignment let's sort free caves by $t_{i}$. In the best assignment number of free caves is minimal possible. And for every position in such a list free cave in the best assignment has value $t_{i}$ not lower than in any other assignment. It can be proven that best possible assignment exists (it's not so obvious though). How to find the best possible assignment? Let's sort caves ascending by $t_{i}$ and for every cave let's assign the tallest free miner who can work here. It will give us the best possibble assignment. Why? Let's say we've just made first bad decision (different than in the best assignment). It doesn't make sense to leave a cave empty if we can assign here someone. So we put a worker somewhere and we won't be able to do assignment now (we assumed that we've just made bad decision). From definition "we put here tallest possible miner" we know that we couldn't assign here taller guy. Maybe we want to assign here shorter miner and this "highest possible" goes somewhere else? But we can swap them and everything will be ok. So there remains last option: we don't want to put anyone here. But we will have to assign our guy to some higher cave so we can leave his destiny cave empty and put him here. To sum up, it's ok to assign highest possible free worker with iterating over caves sorted by $t_{i}$. Almost the same sentences are the proof for other lemma: If we want to have few free (not assigned) miners and we want them to be short it's optimal to iterate somehow over caves and to assign the tallest possible free miner in every cave. It works for every order of iterating over caves. And every order gives us the same set of free miners (but not necessarily the same set of free caves). Why did we want free caves to be high? Because to assign everyone we must change height of cave not higher than the lowest free cave. Why? In short: otherwise that lowest free cave will remain free after running our assignment-algo (described above) on new tree. But we managed to find maximal possible height of lowest free cave. Let's call this value as $LIM$. And we know minimal set of free miners. Changing height of cave $i$ from $a$ to something bigger does something only when $t_{i} = a \le LIM$. And then in set of $t_{i}$ some changes happen. There were caves blocked before by cave $i$ so they had $t$ equal to $a$. These caves will have bigger $t$ so in set of values $t$ we have change e.g. from ${5, 5, 5}$ to ${7, 10, 8}$ ($a$ was equal to $5$). Let's throw out miners from caves with changed $t_{c}$ (maybe some of these caves were empty anyway). If we can't assign free miners (we found them before) to new caves then assigning everything isn't possible. Otherwise it is - we assign them in these caves with changed $t$ and there are some threw out miners. But all of them were in caves with $t = a \le LIM$ so they are not higher than $LIM$. And we know that every free cave has $t_{free} \ge LIM$ because $LIM$ is height of lowest free cave. So we can put them there. Solution is to find result with binary search and to answer question: can we assign miners to caves with changing one cave by at most $D$? With our assignment-algo we calculate optimal lowest free cave and set of free miners. Then for every cave we try to increase its height by $D$ if it had $t$ not higher than $LIM$. It's also important that checking change of every cave has amortized linear complexity. If increasing height of cave A affects $t$ of cave $B$ below then later changing height of $B$ does nothing - B is blocked by A anyway.
|
[
"binary search",
"data structures",
"dfs and similar",
"greedy",
"trees"
] | 3,000
| null |
533
|
B
|
Work Group
|
One Big Software Company has $n$ employees numbered from $1$ to $n$. The director is assigned number $1$. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.
We will call person $a$ a subordinates of another person $b$, if either $b$ is an immediate supervisor of $a$, or the immediate supervisor of $a$ is a subordinate to person $b$. In particular, subordinates of the head are all other employees of the company.
To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer $a_{i}$, where $i$ is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.
The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.
Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.
|
This problem can be solved by using dynamic programming over subtrees of company hierarchy. Denote as $D[v][e]$ maximum possible efficiency that can be obtained by taking several people from subtree of $v$ so that pairity of their number is $e$ in order condition from statement is fullfilled for all already taken people. Then it is easy to calculate $D[v][e]$ from values of children of $v$ by considering intermediate value $T[i][e]$ - maximum possible efficiency that we can obtain by using first $i$ subtrees of $v$ with overall pairity $e$. It's important to not to forget that there are two cases: we may take $v$ itself or we may decide to not take it. In first case it is important that all subtrees have overall even number of taken people. In the second case there is no such restriction.
|
[
"dfs and similar",
"dp",
"graphs",
"strings",
"trees"
] | 2,000
| null |
533
|
C
|
Board Game
|
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell $(x, y)$ to $(x - 1, y)$ or $(x, y - 1)$. Vasiliy can move his pawn from $(x, y)$ to one of cells: $(x - 1, y), (x - 1, y - 1)$ and $(x, y - 1)$. \textbf{Both players} are also allowed to skip move.
There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative $x$-coordinate or $y$-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell $(0, 0)$.
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
|
We will consider three cases: 1) $x_{p} + y_{p} \le max(x_{v}, y_{v})$. In this case Polycarp can be in $(0, 0)$ after $x_{p} + y_{p}$ moves and Vasiliy will always be ,,behind''. It's enough for Polycarp to make any move and he is always able to do it. It makes Polycarp closer to $(0, 0)$ and after Vasiliy's move we again have $x_{p} + y_{p} \le max(x_{v}, y_{v})$ condition fulfilled and in some moment Polycarp will reach $(0, 0)$. It's impossible that Vasiliy wins because our condition would be unfulfilled. 2) $x_{p} \le x_{v}, y_{p} \le y_{v}$. In this scenario Polycarp must block Vasiliy somehow. He must make such a move that after any Vasiliy's response condition will be fulfilled again. If $x_{p} = x_{v} > 0$ he goes to $(x_{p} - 1, y_{p})$. If $y_{p} = y_{v} > 0$ he goes to $(x_{p}, y_{p} - 1)$. Otherwise he makes any move. With this strategy Vasiliy is unable to get out of our new condition. 3) Otherwise we can consider any shortest path to $(0, 0)$ for Vasiliy. Lenght of it is $max(x_{v}, y_{v})$. For any cell on this path Polycarp has greater distance than Vasiliy to it so he can't be there before Vasiliy and he can't block him. Vasiliy wins. Alternative explanation: after any possible Polycarp move Vasiliy can make a move that none of conditions (1) and (2) aren't fulfilled.
|
[
"games",
"greedy",
"implementation",
"math"
] | 1,700
| null |
533
|
D
|
Landmarks
|
We have an old building with $n + 2$ columns in a row. These columns support the ceiling. These columns are located in points with coordinates $0 = x_{0} < x_{1} < ... < x_{n} < x_{n + 1}$. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary.
For each column we know its durability $d_{i}$. Let's consider an ordinary column with coordinate $x$. Let's assume that the coordinate of the closest to it column to the left (bearing or ordinary) is $a$ and the coordinate of the closest to it column to the right (also, bearing or ordinary) is $b$. In this task let's assume that this column supports the segment of the ceiling from point $\textstyle{\frac{\mu+a}{2}}$ to point $\scriptstyle{\frac{x+b}{2}}$ (here both fractions are considered as real division). If the length of the segment of the ceiling supported by the column exceeds $d_{i}$, then the column cannot support it and it crashes after a while, and after that the load is being redistributeed between the neighbouring columns according to the same principle.
Thus, ordinary columns will be crashing for some time until the process stops at some state. One can prove that the set of the remaining columns doesn't depend on the order in which columns crash. If there are only two bearing columns left in the end, then we assume that the whole construction crashes under the weight of the roof. But if at least one ordinary column stays in addition to the bearing ones, then the building doesn't crash.
To make the building stronger, we can add one extra ordinary column of arbitrary durability $d'$ at any (not necessarily integer) point $0 < x' < x_{n + 1}$. If point $x'$ is already occupied by an ordinary column, it is replaced by a new one.
Your task is to find out: what minimal durability can the added column have so that the building doesn't crash?
|
First observation: column crashes only if distance between its neighbours is greater than $2d_{i}$ so it doesn't matter where exactly is this column. The only important thing is how far are left and right neighbour of it. For every column $C$ let's calculate does there exist subset of columns on the left that everything is stable between $C$ and leftmost bearing column. If answer is yes then how close can be left neighbour of $C$? Then we will know how far the right neighbour can be. We will use dynamic programming. Slow approach: For every previous column let's check if it can be neighbours with $C$. The closest column fulfilling this condition is best left neighbour of $C$. Faster approach: Let's denote $far[i]$ as the biggest possible coordinate where right neighbour of column $i$ can be. In our dp we need an extra stack with possible candidates for being left neighbour of new column. In this stack columns are sorted in ascending order by index (and coordinate) and in descending order by $far[i]$. For every new column we must remove from the top of stack columns which have too low $far[i]$. Then last column on stack is the best left neighbour and we can calculate value $far$ for current column. It is $O(n)$ algorithm. Some columns can't be connected with leftmost bearing column and for them we have $far[i] = 0$. If there exists column with $far[i]$ not less than coordinate of rightmost bearing column then we don't have to add new column and answer is $0$. Ok. Now let's run the same dp from right to the left. Some columns are connected with leftmost bearing column, some other columns with righmost one. And we will want to place new column somewhere between them. Brute force solution is to check every pair of columns and to say: we want these two columns to be neighbours of added column. With values $far[i]$ calculated in dp we check if we can have such a situation and we eventually consider result to be half of a distance between these two columns. How to make this last part faster? We must create two stacks with best candidates for neighbours of new column. One stack with columns connected to the leftmost column, one with the ones connected to the rightmost one. On these stacks we can find answer with two pointers technique. Whole solution is linear in time and memory.
|
[
"data structures",
"dp"
] | 3,000
| null |
533
|
E
|
Correcting Mistakes
|
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.
Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.
Implement a program that can, given two distinct words $S$ and $T$ of the same length $n$ determine how many words $W$ of length $n + 1$ are there with such property that you can transform $W$ into both $S$, and $T$ by deleting exactly one character. Words $S$ and $T$ consist of lowercase English letters. Word $W$ also should consist of lowercase English letters.
|
Suppose that $S$ is obtained from $W$ by deleteing the earlier symbol than $T$. Then it is true that $W = A + x + B + y + C$, $S = A + x + B + C$, $T = A + B + y + C$, where $x$ and $y$ are deleted symbols and $A$, $B$ and $C$ are some (possibly, empty) strings. Let's calculate $A$ as a longest common prefix of $S$ and $T$ and $C$ as a longest common suffix. Remove both of them from strings. Now we now that $x$ and $y$ are respectively the first letter of string $S$ and last letter of string $T$. Remove them too. The only thing left is to check if remaining parts of strings are equal. Perform such operation for $S$ and $T$ and for $T$ and $S$.
|
[
"constructive algorithms",
"dp",
"greedy",
"hashing",
"strings",
"two pointers"
] | 1,800
| null |
533
|
F
|
Encoding
|
Polycarp invented a new way to encode strings. Let's assume that we have string $T$, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in $T$ with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word "parallelogram" according to the given encoding principle transforms to word "qolorreraglom".
Polycarpus already has two strings, $S$ and $T$. He suspects that string $T$ was obtained after applying the given encoding method from some substring of string $S$. Find all positions $m_{i}$ in $S$ ($1 ≤ m_{i} ≤ |S| - |T| + 1$), such that $T$ can be obtained fro substring $S_{mi}S_{mi + 1}... S_{mi + |T| - 1}$ by applying the described encoding operation by using some set of pairs of English alphabet letters
|
There are two possible ideas for solving this task. Fix pair of letters $x$ and $y$. Replace all letters $x$ in $S$ with 1s and all remaining letters with 0s. Do the same for $y$ with string $T$. By using KMP algorithm or Z-function determine all positions where string $T$ can be attached to string $S$ so there is a match. If such condition is fullfilled for pair ($x$, $y$), and for pair ($y$, $x$) then this position is a possible match position if we use pair ($x$, $y$) and possibly some other pairs. Now for each suitable position we need to check if letters can be distributed in pairs according to the information we know. This can be done in O(sigma) where $sigma = 26$ - the size of the alphabet. So, this solution works in $O(n * sigma^{2} + n * sigma) = O(n * sigma^{2})$. It fits in time limit if implementation is efficient enough. Another way is to perform such transformation with both strings that allows us to compare them up to letters renaming. Let's replace each letter with distance from it to the closes letter to the left from it that is the same (or with -inf if there is no such letter). Now for strings to be equal we just need to check that string $T$ matches the substring of $S$ in all positions except, possibly, first occurence of each letter in $T$. This can be done by modified prefix-function or by hashing. Now suppose we know that in some position string $T$ is the same as string $S$ up to renaming letters. It's not hard to determine the letter permutation for this renaming (by just checking what matches in $S$ with first occurence of each letter in string $T$). Let's check that this permutation is a set of transpositions in $O(sigma)$. So, we have a solution in $O(n * sigma)$.
|
[
"hashing",
"string suffix structures",
"strings"
] | 2,400
| null |
534
|
A
|
Exam
|
An exam for $n$ students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers ($i$ and $i + 1$) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
|
Is easy to see that $k = n$ with $n \ge 4$. There are many algorithms that can be used to build a correct sequence of length $n$ with $n \ge 4$. For example, students can be seated from left to right with the first to seat students with odd numbers in decreasing order starting with largest odd number. Then similary to seat students with even numbers. In this sequence the absolute difference between two adjacent odd (or even) numbers equal to 2. And the difference between odd and even numbers greater or equal 3 (because $n \ge 4$). Cases $n = 1$, $n = 2$, $n = 3$ are considered separately. Solution complexity - $O(n)$.
|
[
"constructive algorithms",
"implementation",
"math"
] | 1,100
|
#include <stdio.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int N = 5001;
int n;
int a[N];
int main() {
scanf("%d", &n);
if (n == 2) {
printf("1\n1");
return 0;
}
if (n == 3) {
printf("2\n1 3");
return 0;
}
int cur = n & 1 ? n : n - 1;
for(int i = 0; i < n; i++) {
if (cur < 0) {
cur = n & 1 ? n - 1 : n;
}
a[i] = cur;
cur -= 2;
}
printf("%d\n", n);
forn(i, n)
printf("%d ", a[i]);
return 0;
}
|
534
|
B
|
Covered Path
|
The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals $v_{1}$ meters per second, and in the end it is $v_{2}$ meters per second. We know that this section of the route took exactly $t$ seconds to pass.
Assuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by $d$ meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed $d$ in absolute value), find the maximum possible length of the path section in meters.
|
It can be easily proved that every second $i$ ($0 \le i \le t - 1$) the maximum possible speed is $v_{i}=\operatorname*{min}\,(v_{1}+d\cdot i,v_{2}+d\cdot(t-i-1))$. You can iterate through $i$ from $0$ to $t - 1$ and the values of $v_{i}$. Solution complexity - $O(t)$. Also you can use next fact. If current speed equal to $u$ and left $t$ seconds then there is a way to get $v_{2}$ speed at the end only if $|u - v_{2}| \le t \cdot d$. Consider this criteria, one can simply try to change speed to maximum possible (from $u + d$ down to $u - d$), choosing first giving a way to reach the end of the path.
|
[
"dp",
"greedy",
"math"
] | 1,400
|
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int v1, v2;
int n, d;
cin >> v1 >> v2;
cin >> n >> d;
int ans = v1;
int curv = v1;
for(int i = 1; i < n; i++) {
int newv;
for(int dd = d; dd >= -d; dd--) {
newv = curv + dd;
if (abs(newv - v2) <= (n - i - 1) * d)
break;
}
curv = newv;
ans += curv;
}
cout << ans;
return 0;
}
|
534
|
C
|
Polycarpus' Dice
|
Polycarp has $n$ dice $d_{1}, d_{2}, ..., d_{n}$. The $i$-th dice shows numbers from $1$ to $d_{i}$. Polycarp rolled all the dice and the sum of numbers they showed is $A$. Agrippina didn't see which dice showed what number, she knows only the sum $A$ and the values $d_{1}, d_{2}, ..., d_{n}$. However, she finds it enough to make a series of statements of the following type: dice $i$ couldn't show number $r$. For example, if Polycarp had two six-faced dice and the total sum is $A = 11$, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).
For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is $A$.
|
Solution uses next fact. With $k$ dice $d_{1}, d_{2}, ..., d_{k}$ you can dial any sum from $k$ to $\sum_{i=1}^{k}d_{i}$. This is easily explained by the fact that if there is a way to get the amount of $s > k$, then there is a way to dial the sum equal $s - 1$, which is obtained by decreasing the value of one die by one. Let's denote sum of all $n$ dice as $S=\sum_{i=1}^{n}d_{i}$. Fix the dice $d_{i}$ (value on it denote as $x$ ($1 \le x \le d_{i}$). Using the other dice we can select $s$ ($n - 1 \le s \le S - d_{i}$). We know that average value $s + x = A$, and $n - 1 \le A - x \le S - d_{i}$, giving $A - (n - 1) \ge x \ge A - (S - d_{i})$. Using facts described above, for every dice one can calculate a possible values segment, giving the answer for the count of impossible values of that dice. Solution asymptotic - $O(n)$.
|
[
"math"
] | 1,600
|
#include <stdio.h>
#include <algorithm>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int N = 200002;
int n;
int a[N];
long long A, sum;
int main() {
scanf("%d%I64d", &n, &A);
forn(i, n) {
scanf("%d", &a[i]);
sum += a[i];
}
forn(i, n) {
int l = max(1LL, A - (sum - a[i]));
int r = min(0LL + a[i], A - (n - 1));
int k = a[i] - (r - l + 1);
printf("%d ", k);
}
return 0;
}
|
534
|
D
|
Handshakes
|
On February, 30th $n$ students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.
At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.
Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.
Please note that some students could work independently until the end of the day, without participating in a team contest.
|
From here we will not consider resulting permutation but correct handshakes sequence (rearranged given sequence). Formally, the sequence of handshakes count $a_{i}$ is correct if and only if $a_{i + 1} \le a_{i} + 1$ and $a_{i + 1} \equiv a_{i} + 1 \pm od{m}$ and $a_{1} = 0$. To form correct sequence, we can use following greedy algorithm. First, place 0 as the first number. Next, for every following number $a_{i + 1}$ we will select maximum possible number from numbers left, matching above constraints (in simple case it will be $a_{i} + 1$, otherwise we will check if $a_{i} - 2$ left, e.t.c). The solution may divide given sequence into three parts (depending on modulo by 30), and using, for example, data structure ''set'', quickly find the next number to place into resulting sequence. Such solution will work in $O(n\log n)$. There is also possible to get $O(n)$ asymptotics using path compression technique.
|
[
"binary search",
"constructive algorithms",
"data structures",
"greedy"
] | 1,900
|
#include <stdio.h>
#include <algorithm>
#include <set>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef pair<int, int> pii;
const int N = 1000001;
int n;
set<pii> a[3];
int ans[N];
int main() {
scanf("%d", &n);
forn(i, n) {
int x;
scanf("%d", &x);
a[x % 3].insert(make_pair(x, i));
}
int cur = 0;
forn(i, n) {
set <pii> :: iterator it = a[cur % 3].lower_bound(make_pair(cur, -1));
pii c;
if (it != a[cur % 3].end() && (*it).first == cur) {
c = *(it);
ans[i] = c.second + 1;
} else {
if (it == a[cur % 3].begin()) {
puts("Impossible");
return 0;
} else {
it--;
c = *(it);
ans[i] = c.second + 1;
}
}
a[cur % 3].erase(c);
cur = c.first + 1;
}
puts("Possible");
forn(i, n)
printf("%d ", ans[i]);
return 0;
}
|
534
|
E
|
Berland Local Positioning System
|
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are $n$ bus stops located along the street, the $i$-th of them is located at the distance $a_{i}$ from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, $a_{i} < a_{i + 1}$ for all $i$ from 1 to $n - 1$. The bus starts its journey from the first stop, it passes stops $2$, $3$ and so on. It reaches the stop number $n$, turns around and goes in the opposite direction to stop $1$, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop $n$. During the day, the bus runs non-stop on this route.
The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.
One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.
For example, if the number of stops is $6$, and the part of the bus path starts at the bus stop number $5$, ends at the stop number $3$ and passes the stops as follows: ${\mathfrak{f}}\to6\to{\mathfrak{i}}\to4\to3$, then the request about this segment of the path will have form: $3, 4, 5, 5, 6$. If the bus on the segment of the path from stop $5$ to stop $3$ has time to drive past the $1$-th stop (i.e., if we consider a segment that ends with the second visit to stop $3$ on the way from $5$), then the request will have form: $1, 2, 2, 3, 3, 4, 5, 5, 6$.
You will have to repeat the Berland programmers achievement and implement this function.
|
Suppose that the bus started his way from the stop with number 1 and modulate its way during $m$ stops. For every stop we will calculate how many times this stop was visited by the bus at that way. Check if that counts match counts in the input and update the answer if needed. Then we will try to move the start stop to stop with number 2. It's easy to see that the last visited stop (as long as bus must visit $m$ stops) will move to the next stop. So we need to modulate bus way to another one stop from first stop and from last stop to change the starting stop to another (it makes maximum of four counts to be updated). It could be done in $O(1)$ time. This way we need to move starting stop to every variant (its count is equal to $2n - 2$) and for every variant update the answer if needed. Average solution works in $O(n)$ time.
|
[
"constructive algorithms",
"greedy",
"hashing",
"implementation"
] | 2,400
|
#define _CRT_SECURE_NO_DEPRECATE
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <stack>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <set>
#include <iterator>
#include <memory.h>
#include <vector>
#include <map>
#include <queue>
#include <iomanip>
#include <ctime>
#include <cassert>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define mp(a, b) make_pair(a, b)
#define sqr(x) ( (x) * (x) )
#define all(a) a.begin(), a.end()
#define X first
#define Y second
typedef long long ll;
typedef double ld;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef pair<int, int> pii;
const int INF = 1e9;
const ll INF64 = 1e18;
const int MOD = 1000000007;
const int N = 200002;
int n, m;
int a[N];
int cnt[N], cur[N];
int pos[2 * N];
int main() {
scanf("%d", &n);
forn(i, n)
scanf("%d", &a[i]);
scanf("%d", &m);
forn(i, m) {
int x;
scanf("%d", &x);
cnt[x - 1]++;
}
forn(i, n)
pos[i] = i;
forn(i, n - 1)
pos[n + i] = n - i - 2;
ll ans = 0;
bool f = false;
int nn = 2 * n - 2;
for(int dir = 1; dir >= -1; dir -= 2) {
memset(cur, 0, sizeof(cur));
int st = dir == 1 ? 0 : n - 1;
int v = st;
ll res = 0;
forn(i, m - 1) {
int nv = (v + dir + nn) % nn;
res += abs(a[ pos[v] ] - a[ pos[nv] ]);
cur[ pos[v] ]++;
v = nv;
}
cur[ pos[v] ]++;
int wr = 0;
forn(i, n)
wr += (cur[i] != cnt[i]);
if (!wr) {
if (f && res != ans) {
cout << -1;
return 0;
}
ans = res;
f = true;
}
for(int i = st + dir; dir == 1 ? (i < n) : (i >= 0); i += dir) {
int nv = (v + dir + nn) % nn;
int pv = pos[v];
int pnv = pos[nv];
res -= abs(a[i] - a[i - dir]);
res += abs(a[pnv] - a[pv]);
wr -= (cur[i - dir] != cnt[i - dir]);
wr -= (cur[pnv] != cnt[pnv]);
cur[i - dir]--;
cur[pnv]++;
wr += (cur[i - dir] != cnt[i - dir]);
wr += (cur[pnv] != cnt[pnv]);
if (!wr) {
if (f && res != ans) {
cout << -1;
return 0;
}
ans = res;
f = true;
}
v = nv;
}
}
cout << ans;
return 0;
}
|
534
|
F
|
Simplified Nonogram
|
In this task you have to write a program dealing with nonograms on fields no larger than $5 × 20$.
Simplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous black segments is specified.
For example if size of the field is $n = 3, m = 5$, аnd numbers of contiguous black segments in rows are: $[2, 3, 2]$ and in columns are: $[1, 0, 1, 2, 1]$ then the solution may look like:
It is guaranteed that on each test in the testset there exists at least one solution.
|
This task has several solution algorithms. One of them could be described next way. Let's divide $n \times m$ field into two parts with almost same number of columns (it will be $n \times k$ and $n \times (m - k)$). Let's solve the puzzle for every part of the field with brute-force algorithm (considering column constraints on number of blocks) with memorization (we do not need same solutions with same number of blocks in rows). Then we will use meet-in-the-middle approach to match some left part with right part to match constraints on $n \times m$ field. Another solution could be profile dynamic programming, where the profile is the number of blocks in the row.
|
[
"bitmasks",
"dp",
"hashing",
"meet-in-the-middle"
] | 2,400
|
#include <cstdio>
#include <cstdlib>
#include <vector>
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define sz(a) (int)(a.size())
const int N = 5;
const int M = 20;
const int B = 6;
const int S = 7776; // B ^ N
using namespace std;
int n, m, a[N], b[M], bc[1 << N];
typedef char dpmat[M / 2 + 2][S][1 << N];
int c[M + 1];
dpmat lft, rgt;
int make_move(int s, int mask1, int mask2, int mul) {
int ns = s;
int dm = mask2 & (mask1 ^ mask2);
int pw = 1 * mul;
forn(c, n) {
if (dm & (1 << c))
ns += pw;
pw *= B;
}
return ns;
}
char ans[N][M + 1];
void calcdp(int m, dpmat dp) {
forn(i, m + 1)
forn(s, S)
forn(j, 1 << n)
dp[i][s][j] = -1;
dp[0][0][0] = 0;
forn(i, m) {
forn(s, S) {
forn(mask1, 1 << n) {
if (bc[mask1] != c[i]) continue;
if (dp[i][s][mask1] == -1) continue;
forn(mask2, 1 << n) {
if (bc[mask2] != c[i + 1]) continue;
int ns = make_move(s, mask1, mask2, +1);
dp[i + 1][ns][mask2] = mask1;
}
}
}
}
}
int res[M];
int al[M], ar[M];
void restore(int m, int s, int mask, dpmat dp) {
for (int i = m; i >= 1; --i) {
res[i - 1] = mask;
int pmask = dp[i][s][mask];
s = make_move(s, pmask, mask, -1);
mask = pmask;
}
}
int main() {
scanf("%d %d", &n, &m);
forn(i, n)
scanf("%d", &a[i]);
forn(i, m)
scanf("%d", &b[i]);
forn(i, 1 << n) {
int c = 0;
int prv = 0;
forn(j, n) {
int cur = ((i >> j) & 1);
if (cur && cur != prv)
c++;
prv = cur;
}
bc[i] = c;
}
int l = m / 2, r = m - l;
int il = l - 1, ir = l;
forn(i, l)
c[i + 1] = b[i];
calcdp(l, lft);
forn(i, r)
c[i + 1] = b[m - i - 1];
calcdp(r, rgt);
forn(sl, S) {
forn(ml, 1 << n) {
if (bc[ml] != b[il]) continue;
if (lft[l][sl][ml] == -1) continue;
forn(mr, 1 << n) {
if (bc[mr] != b[ir]) continue;
int sr = 0;
int pw = 1;
int csl = sl;
forn(i, n) {
int cs = a[i];
int cl = csl % B; csl /= B;
al[i] = cl;
int cr = cs - cl;
if (mr & ml & (1 << i))
cr++;
if (cr < 0 || cr >= B) {
sr = -1;
break;
}
sr += pw * cr;
ar[i] = cr;
pw *= B;
}
if (sr == -1) continue;
if (rgt[r][sr][mr] != -1) {
restore(l, sl, ml, lft);
forn(i, l)
forn(j, n)
ans[j][i] = ((res[i] >> j) & 1) ? '*' : '.';
restore(r, sr, mr, rgt);
forn(i, r)
forn(j, n)
ans[j][m - 1 - i] = ((res[i] >> j) & 1) ? '*' : '.';
forn(i, n)
puts(ans[i]);
return 0;
}
}
}
}
puts("Impossible");
return 0;
}
|
535
|
A
|
Tavas and Nafas
|
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
He ate coffee mix without water again, so right now he's really messed up and can't think.
Your task is to help him by telling him what to type.
|
First of all check if $n$ is one of the values $0, 10, 11, \dots , 19$. Then, let's have array $x[]$ = {"", "", "twenty", "thirty", \dots , "ninety"} and $y[]$ = {"", "one", \dots , "nine"}. Let $a={\frac{n}{10}}$ and $b = n modulo 10$. If $n$ is not one of the values above, then if $a = 0$, print $y[b]$, else if $b = 0$ print $x[a]$ otherwise print $x[a]$-$y[b]$. Time complexity: $O(1)$
|
[
"brute force",
"implementation"
] | 1,000
|
#include <iostream>
using namespace std;
string a[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
string b[10] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
string c[10] = {"tmp", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
int main() {
int n;
cin >> n;
if (n < 10)
cout << a[n];
else if (n < 20)
cout << b[n % 10];
else {
cout << c[n / 10];
if (n % 10)
cout << '-' << a[n % 10];
}
cout << endl;
}
|
535
|
B
|
Tavas and SaDDas
|
\underline{Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."}
The problem is:
You are given a lucky number $n$. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of $n$?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
|
Sol1: Consider $n$ has $x$ digits, $f(i) =$ decimal representation of binary string $i$, $m$ is a binary string of size $x$ and its $i - th$ digit is 0 if and only if the $i - th$ digit of $n$ is $4$. Finally, answer equals to $2^{1} + 2^{2} + \dots + 2^{x - 1} + f(m) + 1$. Time complexity: $O(log(n))$ Sol2: Count the number of lucky numbers less than or equal to $n$ using bitmask (assign a binary string to each lucky number by replacing 4s with 0 and 7s with 1). Time complexity: $O(2^{log(n)})$
|
[
"bitmasks",
"brute force",
"combinatorics",
"implementation"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define max(x,y) ((x) > (y) ? (x) : (y))
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
inline ll binary(string n){
ll ans = 0LL;
For(i,0,n.size())
ans = (2LL*ans + (ll)(n[i]-'0'));
ll p = 1LL;
For(i,0,n.size())
p = (p << 1);
ans += p-1LL;
return ans;
}
inline string lu(string s){
For(i,0,s.size())
s[i] = (char)(s[i]=='4'?'0':'1');
return s;
}
int main(){
iOS;
string n;
cin >> n;
cout << binary(lu(n)) << endl;
}
|
535
|
C
|
Tavas and Karafs
|
\underline{Karafs is some kind of vegetable in shape of an $1 × h$ rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.}
Each Karafs has a positive integer height. Tavas has an infinite \textbf{1-based} sequence of Karafses. The height of the $i$-th Karafs is $s_{i} = A + (i - 1) × B$.
For a given $m$, let's define an $m$-bite operation as decreasing the height of at most $m$ distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.
Now SaDDas asks you $n$ queries. In each query he gives you numbers $l$, $t$ and $m$ and you should find the largest number $r$ such that $l ≤ r$ and sequence $s_{l}, s_{l + 1}, ..., s_{r}$ can be eaten \textbf{by performing $m$-bite no more than $t$ times} or print -1 if there is no such number $r$.
|
Lemma: Sequence $h_{1}, h_{2}, \dots , h_{n}$ is $(m, t) -$Tavas-Eatable if and only if $max(h_{1}, h_{2}, \dots , h_{n}) \le t$ and $h_{1} + h_{2} + \dots + h_{n} \le m \times t$. Proof: only if is obvious (if the sequence is Tavas-Eatable, then it fulfills the condition). So we should prove that if the conditions are fulfilled, then the sequence is Tavas-Eatable. Use induction on $h_{1} + h_{2} + ... + h_{n}$. Induction definition: the lemma above is true for every sequence $h$ with sum of elements at most $k$. So now we should prove it for $h_{1} + h_{2} + ... + h_{n} = k + 1$. There are two cases: 1- There are at least $m$ non-zero elements in the sequence. So, the number of elements equal to $t$ is at most $m$ (otherwise sum will exceed $m \times t$). So, we decrease $m$ maximum elements by $1$. Maximum element will be at most $t - 1$ and sum will be at least $m \times t - m = m(t - 1)$. So according to the induction definition, the new sequence is $(m, t - 1) -$ Tavas-Eatable, so $h$ is $(m, t) -$ Tavas-Eatable. 2- There are less than $m$ non-zero elements in the sequence. We decrease them all by 1. Obviously, the new sequence has maximum element at most equal to $t - 1$ so its sum will be at most $m(t - 1)$. So according to the induction definition, the new sequence is $(m, t - 1) -$ Tavas-Eatable, so $h$ is $(m, t) -$ Tavas-Eatable. For this problem, use binary search on $r$ and use the fact that the sequence is non-decreasing and $h_{l}+\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot h_{r}=A(r-l+1)+B(\frac{r*(r-1)}{2}-\stackrel{(l-1)(l-2)}{2})$ . Time complexity: $O(qlog(mt))$
|
[
"binary search",
"greedy",
"math"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define max(x,y) ((x) > (y) ? (x) : (y))
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
ll A,B,n,l,t,m,s;
inline ll comb(ll x){
return (x * (x-1LL))/2LL;
}
inline ll h(ll i){
return A + (i-1LL) * B;
}
inline bool check(ll r){
ll e = comb(r) - comb(l-1LL);
if(B && (double)e > 2e18 / (double)B)
return false;
if(h(r) > t) return false;
s = m * t;
s -= e * B;
s -= A * (r - l + 1LL);
return (s >= 0LL);
}
int main(){
iOS;
cin >> A >> B >> n;
while(n --){
cin >> l >> t >> m;
if(h(l) > t){
cout << -1 << '\n';
continue;
}
ll lo = l, hi = max(t, m) + l + 5;
while(lo < hi){
ll mid = (lo + hi)/2LL;
if(check(mid))
lo = mid;
else
hi = mid - 1LL;
if(lo + 1LL == hi){
if(check(hi))
lo = hi;
else
hi = lo;
}
}
cout << lo << '\n';
}
}
|
535
|
D
|
Tavas and Malekas
|
\underline{Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string $s$ of length $n$ comes out from Tavas' mouth instead.}
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on $s$. Malekas has a favorite string $p$. He determined all positions $x_{1} < x_{2} < ... < x_{k}$ where $p$ matches $s$. More formally, for each $x_{i}$ ($1 ≤ i ≤ k$) he condition $s_{xi}s_{xi + 1}... s_{xi + |p| - 1} = p$ is fullfilled.
Then Malekas wrote down one of subsequences of $x_{1}, x_{2}, ... x_{k}$ (possibly, he didn't write anything) on a piece of paper. Here a sequence $b$ is a subsequence of sequence $a$ if and only if we can turn $a$ into $b$ by removing some of its elements (maybe no one of them or all).
After Tavas woke up, Malekas told him everything. He couldn't remember string $s$, but he knew that both $p$ and $s$ only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.
Tavas wonders, what is the number of possible values of $s$? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.
Answer can be very large, so Tavas wants you to print the answer modulo $10^{9} + 7$.
|
First of all you need to find uncovered positions in $s$ (because rest of them will determine uniquely). If there is no parados in covered positions (a position should have more than one value), then the answer will be $0$, otherwise it's $26^{uncovered}$. To check this, you just need to check that no two consecutive matches in $s$ have parados. So, for this purpose, you need to check if a prefix of $t$ is equal to one of its suffixes in $O(1)$. You can easily check this with prefix function (or Z function). Time complexity: $O(n + m)$
|
[
"greedy",
"hashing",
"string suffix structures",
"strings"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define max(x,y) ((x) > (y) ? (x) : (y))
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
inline vi prefix(string p){
vi pi;
int m = p.size();
For(i,0,m)
pi.pb(-1);
int k = -1;
For(i,1,m){
while(k != -1 && p[k+1] != p[i])
k = pi[k];
if(p[k+1] == p[i])
k++;
pi[i] = k;
}
return pi;
}
set<int> s;
inline void shift(string p){
vector<int> pi = prefix(p);
int m = p.size();
int k = pi[m-1];
while(k!=-1){
s.insert(m-k);
k = pi[k];
}
}
int main(){
iOS;
ll n,m;
cin >> n >> m;
string p;
cin >> p;
vi pi = prefix(p);
shift(p);
vi v;
For(i,0,m){
int a;
cin >> a;
v.pb(a);
}
bool ok = true;
For(i,1,v.size()){
ll r = v[i] , l=v[i-1];
if(r<(l+p.size()) && s.find((r-l+1))==s.end()){
cout << 0 << endl;
ok = false;
break;
}
if((p.size()+r-1)>n && ok){
cout<< 0 <<endl;
ok = false;
break;
}
}
ll x = n;
if(ok){
v.pb(2000000000);
For(i,0,v.size()-1)
x -= min((int)p.size(),v[i+1]-v[i]);
}
ll ans=1;
if(x < 0 && ok){
cout<< 0 <<endl;
ok = false;
}
For(i,0,x)
ans = (ans*(ll)26) % 1000000007;
if(ok)
cout<< ans <<endl;
}
|
535
|
E
|
Tavas and Pashmaks
|
\underline{Tavas is a cheerleader in the new sports competition named "Pashmaks".}
This competition consists of two part: swimming and then running. People will immediately start running $R$ meters after they finished swimming exactly $S$ meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).
Before the match starts, Tavas knows that there are $n$ competitors registered for the match. Also, he knows that $i$-th person's swimming speed is $s_{i}$ meters per second and his/her running speed is $r_{i}$ meters per second. Unfortunately, he doesn't know the values of $R$ and $S$, but he knows that they are real numbers greater than $0$.
As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of $R$ and $S$ such that with these values, (s)he will be a winner.
Tavas isn't really familiar with programming, so he asked you to help him.
|
For each competitor put the point $\textstyle{{\binom{1}{s_{i}}},\ {\frac{1}{r_{i}}}}$ in the Cartesian plane. So, the time a competitor finishes the match is $\underline{{{S}}}_{s i}+\frac{R}{r_{i}}=(S,R).(\underline{{{1}}}_{s i},\underline{{{1}}}_{t})$. Determine their convex hull(with maximum number of points. i.e it doesn't matter to have $ \pi $ radians angle). Let $L$ be the leftmost point on this convex hull (if there are more than one, choose the one with minimum $y$ component). Similarly, let $D$ be the point with minimum $y$ component on this convex hull (if there are more than one, consider the leftmost). Proof: $(S,R)(\textstyle{\frac{1}{8}},\textstyle{\frac{1}{n}})$ is the scalar product that is smaller if the point $\textstyle{{\binom{1}{s_{i}}},\ {\frac{1}{r_{i}}}}$ is farther in the direction of $(S, R)$. It's obvious that the farthest points in some direction among the given set lie on a convex hull. $(S, R)$ can get any value that is vector in first quadrant. So we need the points on the convex hull that we actually calculate (also we know that the points on the right or top of the convex hull, are not in the answer, because they're always losers). It's easy to see that the answer is the points on the path from $D$ to $L$ on the convex hull (bottom-left arc). i.e the bottom-left part of the convex hull. Time complexity: $O(nlog(n))$ In this problem, we recommend you to use integers. How ? Look at the code below In this code, function CROSS returns $\left(a_{x}a_{y}b_{x}b_{y}o_{x}o_{y}\right)\left(\left({\frac{1}{a_{x}}}-{\frac{1}{a_{x}}},{\frac{1}{a_{y}}}-{\frac{1}{o_{y}}}\right)\times\left({\frac{1}{b_{x}}}-{\frac{1}{o_{x}}},{\frac{1}{b_{y}}}-{\frac{1}{o_{y}}}\right)\right)$ (it's from order of $10^{16}$, so there won't be any overflows.) In double version, you should have a very small epsilon.
|
[
"geometry",
"math"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define max(x,y) ((x) > (y) ? (x) : (y))
//#define double long double
typedef long long ll;
#define int ll
typedef pair<ll,ll>pii;
typedef vector<int> vi;
//typedef complex<double> point;
const int maxn = 1e6 + 100;
map <pii, vi> mp;
struct point{
ll x,y;
point(){
x = y = 0;
}
point(ll a,ll b){
x = a, y = b;
}
inline void init(ll a,ll b){
x = a, y = b;
}
inline point operator - (point p){
return point(x - p.x, y - p.y);
}
inline ll dis(point p){
return sqr(x - p.x) + sqr(y - p.y);
}
inline pii PII(){
return pii(x, y);
}
};
inline ll CROSS(point o, point a,point b){
return (a.y * b.x * o.x * o.y - a.y * o.x * b.x * b.y - o.y * b.x * a.x * a.y + a.x * b.x * a.y * b.y) -
(a.x * b.y * o.x * o.y - a.x * o.y * b.x * b.y - o.x * b.y * a.x * a.y + a.x * b.x * a.y * b.y);
}
point o;
point l;
inline bool ocmp(const point &a, const point &b){
return make_pair(a.y, a.x) > make_pair(b.y, b.x);
}
inline bool lcmp(const point &a, const point &b){
return make_pair(a.x, a.y) > make_pair(b.x, b.y);
}
inline bool scmp(const point &a,const point &b){
ll cross = CROSS(o, a, b);
if(!cross)
return o.dis(a) < o.dis(b);
return cross < 0;
}
vector<point> v;
vector<point> hull;
int n;
main(){
iOS;
cin >> n;
For(i,0,n){
int a,b;
cin >> a >> b;
mp[{a, b}].pb(i + 1);
}
if(mp.size() == 1){
For(i,1,n+1)
cout << i << ' ';
cout << endl;
return 0;
}
Foreach(q, mp){
pii p = q->x;
int x = p.x, y = p.y;
point P;
P.init(x, y);
v.pb(P);
}
o = *min_element(all(v), ocmp);
l = *min_element(all(v), lcmp);
if(o.PII() == l.PII()){
rep(a, mp[o.PII()])
cout << a << ' ';
cout << endl;
return 0;
}
sort(all(v), scmp);
int po = 2;
For(i,0,2)
hull.pb(v[i]);
vi ans;
while(po < v.size() && hull.back().PII() != l.PII()){
while(hull.size() > 1 && CROSS(hull[hull.size()-2], hull[hull.size()-1], v[po]) > 0LL)
hull.PB;
hull.pb(v[po++]);
}
rep(p, hull)
rep(a, mp[p.PII()])
ans.pb(a);
sort(all(ans));
rep(a, ans)
cout << a << ' ';
cout << endl;
}
|
536
|
D
|
Tavas in Kansas
|
Tavas lives in Kansas. Kansas has $n$ cities numbered from 1 to $n$ connected with $m$ bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities.
Tavas invented a game and called it "Dashti". He wants to play Dashti with his girlfriends, Nafas.
In this game, they assign an arbitrary integer value to each city of Kansas. The value of $i$-th city equals to $p_{i}$.
During the game, Tavas is in city $s$ and Nafas is in city $t$. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer $x$ and his/her score increases by the sum of values of all cities with (shortest) distance no more than $x$ from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero.
There is an additional rule: the player must choose $x$ such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule.
The game ends when nobody can make a move.
A player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points.
If Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers.
They're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends.
|
For each vertex $v$, put a point $(dis(s, v), dis(v, t))$ with its point (score) in the Cartesian plane. The first player in his/her turn chooses a vertical line and erases all the points on its left side. Second player in his/her turn chooses a horizontal line and erases all the point below it. Each player tries to maximize his/her score. Obviously, each time a player chooses a line on the right/upper side of his/her last choice. Imagine that there are $A$ different $x$ components $x_{1} < x_{2} < \dots < x_{A}$ and $B$ different $y$ components $y_{1} < y_{2} < \dots < y_{B}$ among all these lines. So, we can show each state before the game ends with a pair $(a, b)$ ($1 \le a \le A, 1 \le b \le B$ It means that in this state a point $(X, Y)$ is not erased yet if and only if $x_{a} \le X$ and $y_{b} \le Y$). So, using dp, $dp[a][b][i]$ ($1 \le i \le 2$) is the maximum score of $i - th$ player in state $(a, b)$ and it's $i - th$ player's turn. So, consider $s[a][b]$ is the sum of the scores of all valid points in state $(a, b)$ and $t[a][b]$ is the amount of them. So, If $i = 1$ then, $dp[a][b][i] = max(s[a][b] - dp[c][b][2])$ ($a \le c \le A, t[c][b] < t[a][b]$). Otherwise $dp[a][b][i] = max(s[a][b] - dp[a][c][1])$ ($b \le c \le B, t[a][c] < t[a][b]$). So we need two backward fors for our dp and another for on $i$. So, now the only thing that matters is updating the dp. For this purpose, we need two more arrays $QA$ and $QB$. $QA[b][1] =$ the minimum value of pairs $(dp[j][b][2], t[j][b])$ and $QA[b][2] =$ minimum value of pairs $(dp[j][b][2], t[j][b])$ such that $t[j][b] > QA[b][1].second$ in the states we've seen so far. Similarly, $QB[a][1] =$ the minimum value of pairs $(dp[a][j][1], t[a][j])$ and $QB[a][2] =$ minimum value of pairs $(dp[a][j][1], t[a][j])$ such that $t[a][j] > QB[a][1].second$ in the states we've seen so far. Now updating dp is pretty easy : $dp[a][b][1] = s[a][b] - (t[a][b] \le QA[b][1].second?QA[b][2].first: QA[b][1].first)$. $dp[a][b][2] = s[a][b] - (t[a][b] \le QB[a][1].second?QB[a][2].first: QB[a][1].first)$. And updating $QA$ and $QB$ is super easy. Now, let $f = dp[1][1][1]$ and $S$ be the sum of scores of all points. So, the score of first player is $f$ and the second one is $S - f$. Time complexity: $O(n^{2})$
|
[
"dp",
"games"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define pb pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define max(x,y) ((x) > (y) ? (x) : (y))
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef pair<long long,long long> PLL;
# define FF x
# define SS y
typedef ll LL;
# define PB push_back
# define MP make_pair
//typedef complex<double> point;
const int MAX_N=2000+5;
const int MAX_E=100*1000+5;
vector<PLL> adj[MAX_N],A,B;
LL N,E,K,PA,PB,P[MAX_N],Sum[MAX_N][MAX_N];
int SZ[MAX_N][MAX_N],SZA,SZB;
vector<LL> DA,DB;
LL ALLSUM,Ans;
PLL QA[MAX_N][2],QB[MAX_N][2];
bool mrk[MAX_N];
LL D[MAX_N];
void Dijstkra(int s,vector<PLL> &V,vector<LL> &H){
D[s]=0;
for(int tmp=0;tmp<N;tmp++){
int mn=-1;
for(int i=1;i<=N;i++)
if(!mrk[i] &&(mn==-1 || D[mn]>D[i]))
mn=i;
mrk[mn]=true;
V.PB(PLL(D[mn],mn));
H.PB(D[mn]);
for(int i=0;i<(int)adj[mn].size();i++){
int v=adj[mn][i].FF;
if(mrk[v])continue;
D[v]=min(D[v],D[mn]+adj[mn][i].SS);
}
}
}
void CLR(){
A.clear(),B.clear();
DA.clear(),DB.clear();
Ans=0;
ALLSUM=0;
for(int i=0;i<MAX_N;i++){
adj[i].clear();
P[i]=0;
QA[i][0]=MP(0LL,0LL);
QA[i][1]=MP(0LL,0LL);
QB[i][0]=MP(0LL,0LL);
QB[i][1]=MP(0LL,0ll);
for(int j=0;j<MAX_N;j++)
Sum[i][j]=0,
SZ[i][j]=0;
}
}
void FillSum(){
memset(mrk,0,sizeof(mrk));
memset(D,63,sizeof(D));
Dijstkra(PA,A,DA);
memset(mrk,0,sizeof(mrk));
memset(D,63,sizeof(D));
Dijstkra(PB,B,DB);
sort(DA.begin(),DA.end());
DA.resize(unique(DA.begin(),DA.end())-DA.begin());
sort(DB.begin(),DB.end());
DB.resize(unique(DB.begin(),DB.end())-DB.begin());
SZA=(int)DA.size();
SZB=(int)DB.size();
memset(mrk,0,sizeof(mrk));
LL AnsA=ALLSUM,P1=0,SizeA=N;
for(int i=0;i<SZA;i++){
while(P1<(int)A.size() && A[P1].FF<DA[i]){
AnsA-=P[A[P1].SS];
mrk[A[P1].SS]=true;
SizeA--;
P1++;
}
LL P2=0,AnsB=AnsA,SizeB=SizeA;
for(int j=0;j<SZB;j++){
while(P2<(int)B.size() && B[P2].FF<DB[j]){
if(!mrk[B[P2].SS])
AnsB-=P[B[P2].SS],
SizeB--;
P2++;
}
Sum[i][j]=AnsB;
SZ[i][j]=SizeB;
}
}
}
int main(){
CLR();
scanf("%lld%lld",&N,&E);
scanf("%lld%lld",&PA,&PB);
for(int i=1;i<=N;i++)
scanf("%lld",P+i),
ALLSUM+=P[i];
for(int i=0;i<E;i++){
int u,v,w;
scanf ("%d%d%d",&u,&v,&w);
adj[u].PB(PLL(v,w));
adj[v].PB(PLL(u,w));
}
FillSum();
for(int i=SZA;i>=0;i--)
for(int j=SZB;j>=0;j--)
for(int k=0;k<2;k++){
if(!SZ[i][j])
continue;
if(!k){
LL TMP;
if(SZ[i][j]<=QA[j][0].FF)
TMP=QA[j][1].SS;
else
TMP=QA[j][0].SS;
LL DUMMY=TMP+Sum[i][j];
if(SZ[i][j]==QB[i][0].FF)
QB[i][0].SS=max(QB[i][0].SS,-DUMMY);
else{
QB[i][0].SS=max(QB[i][0].SS,QB[i][1].SS);
QB[i][1]=QB[i][0];
QB[i][0]=MP(SZ[i][j],-DUMMY);
QB[i][0].SS=max(QB[i][0].SS,QB[i][1].SS);
}
if(!i && !j)
Ans=DUMMY;
}
else{
LL TMP;
if(SZ[i][j]<=QB[i][0].FF)
TMP=QB[i][1].SS;
else
TMP=QB[i][0].SS;
LL DUMMY=TMP+Sum[i][j];
if(SZ[i][j]==QA[j][0].FF)
QA[j][0].SS=max(QA[j][0].SS,-DUMMY);
else{
QA[j][0].SS=max(QA[j][0].SS,QA[j][1].SS);
QA[j][1]=QA[j][0];
QA[j][0]=MP(SZ[i][j],-DUMMY);
QA[j][0].SS=max(QA[j][0].SS,QA[j][1].SS);
}
}
}
if(2*Ans > ALLSUM)
cout<< "Break a heart" <<endl;
else if(2*Ans == ALLSUM)
cout<< "Flowers" <<endl;
else
cout<< "Cry" <<endl;
return 0;
}
|
536
|
E
|
Tavas on the Path
|
Tavas lives in Tavaspolis. Tavaspolis has $n$ cities numbered from $1$ to $n$ connected by $n - 1$ bidirectional roads. There exists a path between any two cities. Also each road has a length.
Tavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like $s = s_{1}s_{2}... s_{k}$, $T(s)$ is its $Goodness$. $T(s)$ can be calculated as follows:
Consider there are exactly $m$ blocks of $1$s in this string (a block of $1$s in $s$ is a maximal consecutive substring of $s$ that only contains $1$) with lengths $x_{1}, x_{2}, ..., x_{m}$.
Define $T(s)=\sum_{i=1}^{m}f_{x_{i}}$ where $f$ is a given sequence (if $m = 0$, then $T(s) = 0$).
Tavas loves queries. He asks you to answer $q$ queries. In each query he gives you numbers $v, u, l$ and you should print following number:
Consider the roads on the path from city $v$ to city $u$: $e_{1}, e_{2}, ..., e_{x}$.
Build the binary string $b$ of length $x$ such that: $b_{i} = 1$ if and only if $l ≤ w(e_{i})$ where $w(e)$ is the length of road $e$.
You should print $T(b)$ for this query.
|
Let's call the answer for vertices $v$ and $u$ with edges $e_{1}, e_{2}, ..., e_{k}$ on the path, score of sequence $w(e_{1}), w(e_{2}), ..., w(e_{k})$. Use heavy-light decomposition. Decompose the edges into chains. So, for each Query, decompose the path into subchains. After solving the problem for them, combine them. Problem for subchains is : We have an array $a_{1}, a_{2}, \dots , a_{n}$ and $q$ queries. Each query gives numbers $x, y, l$ ($1 \le x \le y \le n$) and we should print the goodness of subarray $a_{x}, a_{x + 1}, \dots , a_{y}$. For this problem, we have too choices: 1.Solve offline with a normal segment tree. 2.Solve online using persistent segment tree. Now, I prefer to use the first approach. Sort the array to have a permutation of $1, 2, \dots , n$: $p_{1}, p_{2}, \dots , p_{n}$ and $a_{p1} \ge a_{p2} \ge \dots \ge a_{pn}$. Also sort the queries in the decreasing order of $l$. No for $i - th$ query (in the sorted order) we have information: $x, y, l, index$. Then, use two pointers. Keep a pointer = n and Initially we have a binary string $b$, of length $n$ with all indices set to $0$. Then in each query: Now, we should fins $T(b_{x} \dots T_{y})$. For this purpose, we need a segment tree. In each node of the segment tree, we need to keep a package named node. A package node is used for calculating $T$ of a binary string $c$. $p =$ the number of leading 1s, $s =$ the number of trading 1s, $cnt =$ the total number of 1s, $tot =$ the $T$ value of the binary string after deleting its leading and trading 1s. Merging two nodes is really easy. Also after reversing $c$, we just need to swap $p$ and $s$. So, we can determine the node of this subarray in subchains. After solving these offline for subchains it's time for combining. Merge the node of subchains in the path from $v$ to $LCA(v, u)$ then merge the result with the reverse of the nodes of answers in the subchains in path from $LCA(v, u)$ to $u$. Time complexity: $O((n + m)log^{2}(n))$ Code by PrinceOfPersia (This was one of the hardest codes I ever wrote in competitive programming :D) Shorter Code by Haghani Java Code by Zlobober If there's any suggestion or error, just let me know.
|
[
"data structures",
"divide and conquer",
"trees"
] | 3,100
|
#include <bits/stdc++.h>
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define max(x,y) ((x) > (y) ? (x) : (y))
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef pair<long long,long long> PLL;
const int maxn = 1e5 + 100;
const int maxl = 20;
int sz[maxn], f[maxn], par[maxn][maxl], h[maxn];
vi adj[maxn], adw[maxn];
int chn[maxn];
int w[maxn];
struct node{
ll p,s,tot,cnt;
node(){
cnt = p = s = tot = 0LL;
}
node(int x){
tot = 0LL;
p = s = cnt = x;
}
inline bool ish(){
return (cnt == p && p && s);
}
inline node operator * (node a){
node ans;
ans.cnt = a.cnt + cnt;
bool h = ish(), H = a.ish();
ans.tot = a.tot + tot;
if(!h && !H){
ans.tot += f[s + a.p];
ans.p = p;
ans.s = a.s;
}
else if(!h && H){
ans.p = p;
ans.s = s + a.s;
}
else if(h && !H){
ans.p = p + a.p;
ans.s = a.s;
}
else{
ans.p = ans.s = p + a.p;
}
return ans;
}
inline ll score(){
ll ans = tot + f[p];
if(!ish())
ans += f[s];
return ans;
}
inline node reverse(){
node ans;
ans.p = s;
ans.s = p;
ans.tot = tot;
ans.cnt = cnt;
return ans;
}
};
struct seg{
vector<node> s;
int sz;
seg(){
sz = 0;}
seg(int n){
while(s.size() < 4 * n)
s.pb(node());
sz = n;
}
inline void add(int p,int id,int l,int r){
if(r - l < 2){
s[id] = node(1);
return ;
}
int mid = (l+r)/2;
if(p < mid)
add(p, L(id), l, mid);
else
add(p, R(id), mid, r);
s[id] = s[L(id)] * s[R(id)];
}
inline node get(int x,int y,int id,int l,int r){
if(x <= l && r <= y)
return s[id];
int mid = (l+r)/2;
if(y <= mid)
return get(x, y, L(id), l, mid);
else if(mid <= x)
return get(x, y, R(id), mid, r);
return get(x, y, L(id), l, mid) * get(x, y, R(id), mid, r);
}
inline void ADD(int p){
add(p, 1, 0, sz);
}
inline node score(int x,int y){
return get(x, y, 1, 0, sz);
}
};
struct query{
int ind, mnh, mxh, l;
query(){
}
query(int a,int b,int c,int d){
ind = a;
mnh = b;
mxh = c;
l = d;
}
};
inline bool qcmp (const query &a, const query & q){
return a.l < q.l;
}
inline bool cmp(const pii &p, const pii &q){
if(p.y - q.y)
return p.y > q.y;
return p.x < q.x;
}
struct chain{
int X,x,y;
seg s;
umap <int, node> MP;
chain(){}
chain(int a,int b): X(a), y(b){}
chain(int a,int b,int c): X(a), x(b), y(c){}
vector<pii> vpn;
vector<query> QQ;
inline void proc(int i){
int v = y;
while(v != X){
if(par[v][0] == X)
x = v;
vpn.pb({h[v], w[v]});
chn[v] = i;
v = par[v][0];
}
sort(all(vpn));
}
inline void solve(){
sort(all(QQ), qcmp);
s = seg(vpn.size());
vector<pii> vs = vpn;
sort(all(vs), cmp);
reverse(all(QQ));
int po = 0;
rep(q, QQ){
while(po < vs.size() && vs[po].y >= q.l){
int i = lower_bound(all(vpn), pii(vs[po].x, -1)) - vpn.begin();
s.ADD(i);
po ++;
}
int l = lower_bound(all(vpn), pii(q.mnh, -1)) - vpn.begin();
int r = upper_bound(all(vpn), pii(q.mxh, 1e9)) - vpn.begin();
MP[q.ind] = s.score(l, r);
}
}
};
vector<chain> HLD;
inline int dfs(int v = 0,int p = -1){
if(p + 1)
h[v] = h[p] + 1;
par[v][0] = p;
For(i,1,maxl) if(par[v][i-1] + 1)
par[v][i] = par[par[v][i-1]][i-1];
sz[v] = 1;
For(i,0,adj[v].size()){
int u = adj[v][i];
if(u - p){
w[u] = adw[v][i];
sz[v] += dfs(u, v);
}
}
return sz[v];
}
inline void prepHLD(int v = 0,bool h = 0,int f = -1){
if(f == -1){
if(par[v][0] != -1)
f = par[v][0];
else
f = v;
}
bool hh = 0, ch = 0, is = 0;
rep(u, adj[v]){
if(u - par[v][0] && sz[u] * 2 >= sz[v])
hh = 1;
if(u - par[v][0])
ch = 1;
}
if(par[v][0] != -1){
if(h && !hh && !ch)
HLD.pb(chain(f,v));
if(!h && !ch)
HLD.pb(chain(par[v][0],v));
}
rep(u, adj[v])
if(u - par[v][0]){
if(sz[u] * 2 < sz[v]){
if(!is && !hh)
prepHLD(u,1,f);
else
prepHLD(u);
}
else
prepHLD(u,1,f);
is = 1;
}
}
inline int lca(int v,int u){
if(h[u] > h[v])
swap(v, u);
rof(i, maxl - 1, -1)
if(par[v][i] + 1 && h[par[v][i]] >= h[u])
v = par[v][i];
if(v == u) return v;
rof(i, maxl - 1, -1)
if(par[v][i] - par[u][i])
v = par[v][i], u = par[u][i];
return par[v][0];
}
inline vi dec(int v,int H){
vi ans;
while(v + 1 && h[v] > H){
ans.pb(chn[v]);
v = HLD[chn[v]].X;
}
return ans;
}
inline vi decompose(int v,int u){
int x = lca(v, u);
int H = h[x];
vi ans = dec(v, H);
vi V = dec(u, H);
reverse(all(V));
rep(w, V)
ans.pb(w);
return ans;
}
stringstream ss;
inline void prepQ(int i,int v,int w,int l){
while(v + 1 && h[v] > h[w]){
int j = chn[v];
int mnh = h[w] + 1;
int mxh = h[v];
HLD[j].QQ.pb(query(i, mnh, mxh, l));
v = HLD[chn[v]].X;
}
}
inline void prepq(int i,int v,int u,int l){
ss << v << ' ' << u << ' ' << l << '\n';
int w = lca(v, u);
prepQ(i, v, w, l);
prepQ(i, u, w, l);
}
int IND;
inline ll ANS(){
int v,u,l;
ss >> v >> u >> l;
int w = lca(v, u);
vi V = decompose(v, w);
vi U = decompose(w, u);
node N(0);
rep(c, V)
N = N * HLD[c].MP[IND].reverse();//, error(HLD[c].MP[IND].reverse().cnt);
rep(c, U){
N = N * HLD[c].MP[IND];
/* error(HLD[c].MP[IND].cnt);
error(HLD[c].MP[IND].p);
error(HLD[c].MP[IND].s);
error(HLD[c].y);*/
}
IND ++;
//Error(N.s, N.p);
//error(N.cnt);
return N.score();
}
int n,q;
int main(){
memset(par, -1, sizeof(par));
iOS;
cin >> n >> q;
For(i,1,n)
cin >> f[i];
int v,u,w;
For(i,1,n){
cin >> v >> u >> w;
-- v, -- u;
adj[v].pb(u);
adj[u].pb(v);
adw[v].pb(w);
adw[u].pb(w);
}
dfs();
prepHLD();
For(i,0,HLD.size())
HLD[i].proc(i);
//error(HLD.size());
For(i,0,q){
cin >> v >> u >> w;
-- v, -- u;
prepq(i, v, u, w);
}
For(i,0,HLD.size())
HLD[i].solve();
For(i,0,q)
cout << ANS() << '\n';
}
|
538
|
A
|
Cutting Banner
|
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforces$^{ω}$ that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.
There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.
Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.
|
Let me first clarify the statement (I really wish I didn't have to do that but it seems many participants had trouble with the correct understanding). You had to erase exactly one substring from the given string so that the rest part would form the word CODEFORCES. The (somewhat vague) wording some substring in the English translation may be the case many people thought that many substrings can be erased; still, it is beyond my understanding how to interpret that as 'more than one substring'. Anyway, I'm sorry for the inconvenience. Right, back to the problem. The most straightforward approach is to try over all substrings (i.e. all starting and ending positions) to erase them and check if the rest is the wanted word. When doing this, you have to be careful not to forget any corner cases, such as: erase few first letters, erase few last letters, erase a single letter, and so on. A popular question was if an empty substring may be erased or not. While it is not clarified explicitly in the statement, the question is irrelevant to the solution, for it is guaranteed in the statement that the initial string is not CODEFORCES, so erasing nothing will not make us happy. From the technical point of view, you could erase a substring from the string using standard functions like substr in C++ or similar, or do some bare-hands work and perform conditional iterating over all symbols. Depending on the implementation, this would be either $O(n^{2})$ or $O(n^{3})$ solution; both of these fit nicely. One way of solving this in linear time is to compute the longest common prefix and suffix for the given string and the string CODEFORCES. If their total length is at least 10 (the length of CODEFORCES), it is possible to leave only some parts of the common prefix and suffix, thus the rest part (being a substring, of course) may be removed for good. If the total length is less than 10, no such way exists. This is clearly $O(n)$ solution (rather $O(n)$ for reading the input, and $O(|t|)$ for comparisons where $t$ is CODEFORCES in our case).
|
[
"brute force",
"implementation"
] | 1,400
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
string s;
cin >> s;
int N = s.size();
string t = "CODEFORCES";
int l = 0, r = 0;
while (l < min(10, N) && s[l] == t[l]) ++l;
while (r < min(10, N) && s[N - r - 1] == t[10 - r - 1]) ++r;
cout << (l + r >= 10 ? "YES" : "NO") << '\n';
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
B
|
Quasi Binary
|
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer $n$. Represent it as a sum of minimum number of quasibinary numbers.
|
$n$ is up to $10^{6}$. We may note that there are only $2^{6} + 1 = 65$ quasi-binary numbers not exceeding $10^{6}$, so we could find them all and implement a DP solution that counts the optimal representation for all numbers up to $n$, or even a brute-force recursive solution (which is not guaranteed to pass, but has a good odds). Are there more effective solutions? Sure enough. First of all, one can notice that the number of summands in a representation can not be less than $d$ - the largest digit in decimal representation of $n$. That is true because upon adding a quasi-binary number to any number the largest digit may not increase by more than 1 (easy enough to prove using the standard algorithm for adding numbers). On the other hand, $d$ quasi-binary numbers are always enough. To see that, construct a number $m$ as follows: for every digit of $n$ that is not 0, place 1 in the corresponding digit of $m$, and for all the other digits place 0. Clearly, $m$ is quasi-binary. If we subtract $m$ from $n$, all non-zero digits will decrease by 1 (clearly, no carrying will take place), thus the largest digit of $n - m$ will be equal to $d - 1$. Proceeding this way, we end up with the representation of $n$ as a sum of $d$ quasi-binary numbers. This solution is good for every numeric base, and works in $O(d\log_{d}n)=O(d\log n/\log d)$ where $d$ is the base.
|
[
"constructive algorithms",
"dp",
"greedy",
"implementation"
] | 1,400
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int N;
cin >> N;
vi a;
while (N) {
int n = N, m = 0, p = 1;
while (n) {
if (n % 10) m += p;
n /= 10; p *= 10;
}
a.pb(m);
N -= m;
}
cout << a.size() << '\n';
sort(all(a));
for (int x: a) cout << x << ' ';
cout << '\n';
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
C
|
Tourist's Notes
|
A tourist hiked along the mountain range. The hike lasted for $n$ days, during each day the tourist noted height above the sea level. On the $i$-th day height was equal to some integer $h_{i}$. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all $i$'s from 1 to $n - 1$ the inequality $|h_{i} - h_{i + 1}| ≤ 1$ holds.
At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits $|h_{i} - h_{i + 1}| ≤ 1$.
|
We want to make the maximum height as large as possible. Consider the part of the chain that was travelled between $d_{i}$ and $d_{i + 1}$; we can arrange it in any valid way independently of any other parts of the chain, thus we consider all these parts separately. There also parts before $d_{1}$ and after $d_{n}$, but it is fairly easy to analyze them: make them monotonously decreasing (respectively, increasing), as this maximizes the top point. Without the loss of generality consider $d_{i} = 0$ and $d_{i + 1} = t$ (they may be increased of decreased simultaneously without changing the answer), and $h_{di} = a$, $h_{di + 1} = b$. Clearly, in consistent data $|a - b| \le t$, so if this condition fails for a single pair of adjacent entries, we conclude the data is flawed. If the condition holds, it is fairly easy to construct a valid way to move between the days under the $|h_{i} - h_{i + 1}| \le 1$ condition: increase or decrease the height while it differs from $b$, than stay on the same height. That does not make the optimal way, but at least we are sure that the data is not inconsistent. How to construct the optimal arrangement? From the adjacent difference inequality if follows that for any $i$ between $0$ and $t$ the inequalities $h_{i} \le a + i$ and $h_{i} \le b + (t - i)$ hold. Let $h_{i} = min(a + i, b + (t - i))$ on the [0; $t$] segment; clearly, every $h_{i}$ accomodates the largest possible value, therefore the value of maximum is also the largest possible. It suffices to show that these $h_{i}$ satisfy the difference condition. Basically, two cases should be considered: if for $h_{i} = a + i$ and $h_{i + 1} = a + i + 1$, or $h_{i} = b + (t - i)$ and $h_{i + 1} = b + (t - i - 1)$, the statement is obvious. Else, $h_{i} = a + i$ but $h_{i} < b + (t - i) = h_{i + 1} + 1$, and $h_{i + 1} = b - (t - i - 1)$ but $h_{i + 1} < a + (i + 1) = h_{i} + 1$. Thus, $|h_{i} - h_{i + 1}| < 1$, and $h_{i} = h_{i + 1}$. To find the maximum value of maximum height (I really struggle not to use 'maximum maximum') we may either use ternary search on the $h$ function, or find the point where lines $a + i$ and $b + (t - i)$ intersect and try integer points besides the intersection. If we use this approach analytically, we arrive at the formula $(t + a + b) / 2$ (try to prove that yourself!).
|
[
"binary search",
"brute force",
"greedy",
"implementation",
"math"
] | 1,600
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int N, M;
cin >> N >> M;
vi d(M), h(M);
forn(i, M) cin >> d[i] >> h[i];
int ans = max(h[0] + d[0] - 1, h[M - 1] + (N - d[M - 1]));
bool ok = true;
forn(i, M - 1) {
ok &= abs(h[i] - h[i + 1]) <= d[i + 1] - d[i];
ans = max(ans, max(h[i], h[i + 1]) + (d[i + 1] - d[i] - abs(h[i] - h[i + 1])) / 2);
}
if (!ok) cout << "IMPOSSIBLE\n";
else cout << ans << '\n';
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
D
|
Weird Chess
|
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.
Igor's chessboard is a square of size $n × n$ cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.
Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to $n$. Let's assign to each square a pair of integers $(x, y)$ — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers $(dx, dy)$; using this move, the piece moves from the field $(x, y)$ to the field $(x + dx, y + dy)$. You can perform the move if the cell $(x + dx, y + dy)$ is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than $(x, y)$ and $(x + dx, y + dy)$ are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).
Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.
|
Instead of trying to find out where the piece may go, let's try to find out where it can not go. Initially mark all the moves as possible; if there is a field ($x_{1}$, $y_{1}$) containing a piece, and a field ($x_{2}$, $y_{2}$) not containing a piece and not being attacked, clearly a move ($x_{2} - x_{1}$, $y_{2} - y_{1}$) is not possible. Let us iterate over all pieces and over all non-attacked fields and mark the corresponding moves as impossible. Suppose we let our piece make all the rest moves (that are not yet marked as impossible), and recreate the position with all the pieces in the same places. If a field was not attacked in the initial position, it will not be attacked in the newly-crafted position: indeed, we have carefully removed all the moves that could take a piece to this field. Thus, the only possible problem with the new position is that some field that was attacked before is not attacked now. But our set of moves is maximal in the sense that adding any other move to it will cause the position to be incorrect. Thus, if the new position doesn't coincide with the initial position, the reconstruction is impossible. Else, we have already obtained a correct set of moves. This solution has complexity of $O(n^{4})$ for iterating over all pieces and non-attacked fields. No optimizations were needed to make solution this pass.
|
[
"brute force",
"constructive algorithms",
"implementation"
] | 1,800
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
int d[300][300], t[300][300];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int N;
cin >> N;
vector<string> f(N);
forn(i, N) cin >> f[i];
forn(i, 2 * N - 1) forn(j, 2 * N - 1) d[i][j] = 1;
forn(i, N) forn(j, N) {
if (f[i][j] != 'o') continue;
forn(x, N) forn(y, N) if (f[x][y] == '.') d[x - i + N - 1][y - j + N - 1] = 0;
}
forn(i, N) forn(j, N) {
if (f[i][j] != 'o') continue;
forn(x, 2 * N - 1) forn(y, 2 * N - 1) {
int xx = i + x - (N - 1), yy = j + y - (N - 1);
if (min(xx, yy) < 0 || max(xx, yy) >= N || !d[x][y]) continue;
t[xx][yy] = 1;
}
}
bool ok = true;
forn(i, N) forn(j, N) {
if (f[i][j] == 'o') continue;
ok &= (f[i][j] == 'x') == (t[i][j] == 1);
}
d[N - 1][N - 1] = 2;
if (ok) {
cout << "YES\n";
forn(i, 2 * N - 1) {
forn(j, 2 * N - 1) cout << ".xo"[d[i][j]];
cout << '\n';
}
} else cout << "NO\n";
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
E
|
Demiurges Play Again
|
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.
There is a rooted tree on $n$ nodes, $m$ of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to $m$ are placed in such a way that each number appears exactly in one leaf.
Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.
Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.
|
With such large constraints our only hope is the subtree dynamic programming. Let us analyze the situation and how the subtrees are involved. Denote $w(v)$ the number of leaves in the subtree of $v$. Suppose that a non-leaf vertex $v$ has children $u_{1}$, $...$, $u_{k}$, and the numbers to arrange in the leaves are 1, $...$, $w(v)$. We are not yet sure how to arrange the numbers but we assume for now that we know everything we need about the children's subtrees. Okay, what is the maximal number we can achieve if the maximizing player moves first? Clearly, he will choose the subtree optimally for himself, and we are eager to help him. Thus, it makes sense to put all the maximal numbers in a single subtree; indeed, if any of the maximal numbers is not in the subtree where the first player will go, we swap it with some of the not-so-maximal numbers and make the situation even better. If we place $w(u_{i})$ maximal numbers (that is, $w(v) - w(u_{i}) + 1$, $...$, $w(v)$) in the subtree of $w(u_{i})$, we must also arrange them optimally; this task is basically the same as arranging the numbers from 1 to $w(u_{i})$ in the subtree of $w(u_{i})$, but now the minimizing player goes first. Introduce the notation $d_{m a x/m i n}\left(v\right)$ for the maximal possible result if the maximizing/minimizing (depending on the lower index) player starts. From the previous discussion we obtain $d_{m a x}(v)=\operatorname*{max}_{i=1}\bigl(\boldsymbol{u}\bigl(\boldsymbol{v}\bigr(\boldsymbol{v}\bigr)-w\bigl(\boldsymbol{u_{i}}\bigr)+d_{m i n}\bigl(\boldsymbol{u_{i}}\bigr)\bigr)$. Thus, if we know $d_{m i n}(u_{i})$ for all children, the value of $d_{m a x}(v)$ can be determined. How does the situation change when the minimizing player goes first? Suppose that for each $i$ we assign numbers $n_{1, 1}$, $...$, $n_{1, w(ui)}$ to the leaves of the subtree of $u_{i}$ in some order; the numbers in the subtree of $u_{i}$ will be arranged so that the result is maximal when the maximizing player starts in $u_{i}$. Suppose that numbers $n_{i, j}$ are sorted by increasing of $j$ for every $i$; the minimizing player will then choose the subtree $u_{i}$ in such a way that $n_{i_{1}d p_{m a x}}(u_{i})$ is minimal. For every arrangement, the minimizing player can guarantee himself the result of at most $\textstyle{\sum_{i=1}^{k}(d p_{m a x}(u_{i})-1)+1=r}$. Indeed, if all the numbers ${\cal H}_{i_{1}d p_{m a x}}(u_{i})$ are greater than $r$, all the numbers $n_{i, j}$ for $j>d p_{m a x}(u_{i})$ should also be greater than $r$; but there are $\sum_{i=1}^{k}(w(u_{i})-d p_{m a x}(u_{i})+1)=w(v)-r+1$ numbers $n_{i, j}$ that should be greater than $r$, while there are only $w(v) - r$ possible numbers from 1 to $w(v)$ to place; a contradiction (pigeonhole principle). On the other hand, the value of $r$ is easily reachable: place all the numbers less than $r$ as $n_{i, j}$ with $j<d p_{m a x}(u_{i})$, and $r$ as, say, $n_{1, dpmax(u1)}$; the first player will have to move to $u_{1}$ to achieve $r$. Thus, $r=\sum_{i=1}^{k}(d p_{m a x}(u_{i})-1)+1=d p_{m i n}(v)$. The previous, rather formal argument can be intuitively restated as follows: suppose we put the numbers from 1 to $w(v)$ in that order to different subtrees of $v$. Once a subtree of $u_{i}$ contains $dp_{max}(u_{i})$ numbers, the minimizing player can go to $u_{i}$ and grab the current result. It follows that we may safely put $dp_{max}(u_{i}) - 1$ numbers to the subtree of $u(i)$ for each $i$, and the next number (exactly $r$) will be grabbed regardless of what we do (if we do not fail and let the minimizing player grab a smaller number). That DP scheme makes for an $O(n)$ solution, as processing the $k$ children of each node is done in $O(k)$ (provided their results are already there). As an easy exercise, think about how the optimal arrangement of number in the leaves can be constructed; try to make implementation as simple as possible.
|
[
"dfs and similar",
"dp",
"math",
"trees"
] | 2,200
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
const int MAXN = 210000;
vi e[MAXN];
int w[MAXN];
int dpmax[MAXN], dpmin[MAXN];
void dfs(int v) {
if (e[v].empty()) {
w[v] = 1;
dpmax[v] = dpmin[v] = 0;
return;
}
int md = 1e9, s = 0;
w[v] = 0;
for (int u: e[v]) {
dfs(u);
w[v] += w[u];
uin(md, dpmin[u]);
s += w[u] - dpmax[u];
}
dpmax[v] = w[v] - md - 1;
dpmin[v] = s - 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int N;
cin >> N;
forn(i, N - 1) {
int x, y;
cin >> x >> y;
e[--x].pb(--y);
}
dfs(0);
cerr << w[0] << '\n';
cout << dpmax[0] + 1 << ' ' << dpmin[0] + 1 << '\n';
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
F
|
A Heap of Heaps
|
Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.
The teacher gave Andrew an array of $n$ numbers $a_{1}$, $...$, $a_{n}$. After that he asked Andrew for each $k$ from 1 to $n - 1$ to build a $k$-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.
Andrew looked up on the Wikipedia that a $k$-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to $n$, then the children of element $v$ are elements with indices $k(v - 1) + 2$, $...$, $kv + 1$ (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any $k$-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote $p(v)$ as the number of the parent of the element with the number $v$. Let's say that for a non-root element $v$ the property of the heap is violated if $a_{v} < a_{p(v)}$.
Help Andrew cope with the task!
|
The first approach. For a given $k$ and an element $v$, how do we count the number of children of $v$ that violate the property? This is basically a range query 'how many numbers in the range are greater than $v$' (because, evidently, children of any element occupy a subsegment of the array); the answers for every $k$ are exactly the sums of results for queries at all non-leaf vertices. Online data structures for this query type are rather involved; however, we may process the queries offline by decreasing $v$, with a structure that is able to support an array, change its elements and take sum over a range (e.g., Fenwick tree or segment tree). This can be done as follows: for every element of the initial array store 1 in the same place of the structure array if the element has already been processed, and 0 otherwise. Now, if we sum over the range for the element $v$, only processed elements will have impact on the sum, and the result of the query will be exactly the number of elements greater than $v$. After all the queries for $v$, we put 1 in the corresponding element so that queries for smaller elements would take it into account. That makes for an $O((q+n)\log n)$ solution. Estimate $q$: notice that for a given $k$ there are only $\sim n/k$ non-leaf vertices, thus the total number of queries will be $\sim\sum_{i=1}^{n-1}n/i=O(n\log n)$ (harmonic sum estimation). To sum up, this solution works in $O(n\log^{2}n)$ time. The second approach. Let us index the elements of the array starting from 0. It is easy to check that for a given $k$ the parent of the element $a_{v}$ is the element $a_{[(v-1)/k]}$. One can show that there are only $O({\sqrt{v}})$ different elements that can be the parent of $a_{v}$ for some $k$. Indeed, if $k>{\sqrt{v-1}}$, the index of the parent is less that $\sqrt{v-1}$, and all $k\leq{\sqrt{v-1}}$ produce no more than $\sqrt{v-1}$ different parents too. Moreover, each possible parent corresponds to a range of values of $k$. To show that, solve the equality $\left\lfloor{\frac{v-1}{k}}\right\rfloor=p$ for $k$. Transform: $p\leq{\frac{v-1}{k}}<p+1$, $pk \le v - 1 < (p + 1)k$, $\begin{array}{c}{{\frac{v-1}{p+1}<k\leq\frac{v-1}{p}}}\end{array}$, $\lfloor{\frac{v-1}{p+1}}\rfloor\ <k\leq\lfloor{\frac{v-1}{p}}\rfloor$. For every $k$ in the range above the property is either violated or not (that depends only on $a_{v}$ and $a_{p}$); if it's violated we should add 1 to all the answers for $k$'s in the range. That can be done in $O(1)$ offline using delta-encoding (storing differences between adjacent elements in the process and prefix-summing them in the end). There will be only $O(n{\sqrt{n}})$ queries to the delta array (as this is the number of different child-parent pairs for all $k$). This makes for a simple $O(n{\sqrt{n}})$ solution which barely uses any heavy algorithmic knowledge at all.
|
[
"brute force",
"data structures",
"math",
"sortings"
] | 2,200
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
const int MAXN = 210000;
int a[MAXN];
int delta[MAXN];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int N;
cin >> N;
forn(i, N) cin >> a[i];
for1(i, N - 1) {
int p;
for (p = 0; p * p <= i - 1; ++p) {
int l = (p == 0 ? N - 1 : (i - 1) / p), r = (i - 1) / (p + 1);
if (a[i] < a[p]) ++delta[r + 1], --delta[l + 1];
}
for (int k = 1; k <= (i - 1) / p; ++k) {
int par = (i - 1) / k;
if (a[i] < a[par]) ++delta[k], --delta[k + 1];
}
}
int s = 0;
for1(i, N - 1) {
s += delta[i];
cout << s << " \n"[i + 1 == N];
}
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
G
|
Berserk Robot
|
Help! A robot escaped our lab and we need help finding it.
The lab is at the point $(0, 0)$ of the coordinate plane, at time 0 the robot was there. The robot's movements are defined by a program — a string of length $l$, consisting of characters U, L, D, R. Each second the robot executes the next command in his program: if the current coordinates of the robot are $(x, y)$, then commands U, L, D, R move it to cells $(x, y + 1)$, $(x - 1, y)$, $(x, y - 1)$, $(x + 1, y)$ respectively. The execution of the program started at time 0. The program is looped, i.e. each $l$ seconds of executing the program start again from the first character. Unfortunately, we don't know what program was loaded into the robot when he left the lab.
Our radars managed to find out the position of the robot at $n$ moments of time: we know that at the moment of time $t_{i}$ the robot is at the point $(x_{i}, y_{i})$. Given this data, either help to determine what program could be loaded into the robot, or determine that no possible program meets the data and the robot must have broken down.
|
First of all, we'll simplify the problem a bit. Note that after every command the values of $x + y$ and $x - y$ are altered by $ \pm 1$ independently. Suppose we have a one-dimensional problem: given a sequence of $x$'s and $t$'s, provide a looped program of length $l$ with commands $ \pm 1$ which agrees with the data. If we are able to solve this problem for numbers $x_{i} + y_{i}$ and $x_{i} - y_{i}$ separately, we can combine the answers to obtain a correct program for the original problem; if one of the subproblems fails, no answer exists. (Most - if not all - participants who solved this problem during the contest did not use this trick and went straight ahead to the two-dimensional problem. While the idea is basically the same, I'm not going into details for their approach, but you can view the submitted codes of contestants for more info on this one.) Ok, now to solve the one-dimensional problem. Let us change the command set from $ \pm 1$ to $+ 0 / + 1$: set $x_{i}^{\prime}=(x_{i}+t_{i})/2$. If the division fails to produce an integer for some entry, we must conclude that the data is inconsistent (because $x_{i}$ and $t_{i}$ should have the same parity). Now it is clear to see that the operation $- 1$ becomes operation $0$, and the operation $+ 1$ stays as it is. A program now is a string of length $l$ that consists of 0's and 1's. Denote $s_{i}$ the number of 1's among the first $i$ commands, and $s = s_{l}$ for simplicity. Evidently, an equation $x_{i}=s\cdot\left\lfloor{\frac{t_{i}}{l}}\right\rfloor+s_{t_{i}\,\mathrm{mod}\,1}$ holds, because the full cycle is executed $ \lfloor t_{i} / l \rfloor $ times, and after that $t_{i}{\bmod{1}}$ more first commands. From this, we deduce $s_{t_{i}\,{\mathrm{mod}}\,1}=x_{i}-s\cdot\left\lfloor{\frac{t_{i}}{l}}\right\rfloor$. Suppose that we know what $s$ is equal to. Using this, we can compute all $s_{t_{i}\,{\mathrm{mod}}}|$; they are fixed from now on. One more important fixed value is $s_{l} = s$. In any correct program $s_{i} \le s_{i + 1} \le s_{i} + 1$, but not all values of $s_{i}$ are known to us. When is it possible to fill out the rest of $s_{i}$ to match a correct program? If $s_{a}$ and $s_{b}$ are adjacent entries that are fixed (that is, every $s_{c}$ under $a < c < b$ is not fixed), the inequality $0 \le s_{b} - s_{a} \le b - a$ must hold ($a$ and $b$ may coincide if for different $i$ several values of $t_{i}{\bmod{1}}$ coincide). Furthermore, if the inequality holds for every pair of adjacent fixed entries, a correct program can be restored easily: move over the fixed values, and place $s_{b} - s_{a}$ 1's between positions $a$ and $b$ in any possible way, fill with 0's all the other positions in between. The trouble is that we don't know $s$ in advance. However, we know the positions and the order in which fixed values of $s_{a}$ come! Sort them by non-decreasing of $a$. All fixed $s_{a}$ can be expressed as linear functions of $s$; if we substitute these expressions in the $0 \le s_{b} - s_{a} \le b - a$, from each pair of adjacent fixed values we obtain an inequality of general form $0 \le p \cdot s + q \le d$, where $p$, $q$, $d$ are known values. If the obtained system of inequalities has a solution, we can get ourselves a valid $s$ and restore the program as discussed above. It suffices to notice that every inequality of the system has a set of solutions of general form $l \le s \le r$ (if the set is not empty), where $l$ and $r$ should be calculated carefully depending on the sign of $p$. All the intervals should be intersected, and the resulting interval provides a range of valid values of $s$. Overall, the solution works in $O(n\log n+l)$, or even in $O(n + l)$ if we use bucketing instead of sorting. Note that the $l$ summand in the complexity is only there for the actual program reconstruction; if we were only to check the existence of a program, an $O(n)$ solution would be possible.
|
[
"constructive algorithms",
"math",
"sortings"
] | 3,100
|
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <numeric>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef pair<i64, i64> pi64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
const int MAXN = 210000;
i64 t[MAXN], x[MAXN], y[MAXN];
int N, L;
struct TPoint {
i64 t, a, b;
TPoint(i64 t = 0, i64 a = 0, i64 b = 0)
: t(t)
, a(a)
, b(b)
{
}
bool operator<(const TPoint &p) const {
return t < p.t;
}
};
i64 fl(i64 x, i64 y) {
if (x >= 0) return x / y;
return x / y - (x % y ? 1 : 0);
}
i64 cl(i64 x, i64 y) {
if (x >= 0) return (x + y - 1) / y;
return x / y;
}
vi solve(vi64 x) {
forn(i, N) {
if ((x[i] + t[i]) % 2) return vi();
x[i] = (x[i] + t[i]) / 2;
}
vector<TPoint> q;
forn(i, N) {
q.pb(TPoint(t[i] % L, -(t[i] / L), x[i]));
}
q.pb(TPoint(0, 0, 0));
q.pb(TPoint(L, 1, 0));
sort(all(q));
i64 l = 0, r = L;
forn(i, (int)q.size() - 1) {
i64 a = q[i + 1].a - q[i].a, b = q[i + 1].b - q[i].b;
i64 d = q[i + 1].t - q[i].t;
i64 lh = -b, rh = d - b;
if (!a) {
if (lh > 0 || rh < 0) return vi();
} else {
if (a < 0) {
a = -a;
swap(lh, rh);
lh = -lh; rh = -rh;
}
uin(r, fl(rh, a));
uax(l, cl(lh, a));
}
}
if (l > r) return vi();
vi ans;
int s = 0;
cerr << l << ' ' << r << '\n';
forn(i, q.size()) {
while (s < l * q[i].a + q[i].b) {
ans.pb(1);
++s;
}
while (ans.size() < q[i].t) ans.pb(0);
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
cin >> N >> L;
forn(i, N) cin >> t[i] >> x[i] >> y[i];
vi64 x1(N), x2(N);
forn(i, N) {
x1[i] = x[i] + y[i]; x2[i] = x[i] - y[i];
}
vi ans1 = solve(x1), ans2 = solve(x2);
if (ans1.empty() || ans2.empty()) {
cout << "NO\n";
} else {
forn(i, L) cout << "LDUR"[2 * ans1[i] + ans2[i]];
cout << '\n';
}
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
538
|
H
|
Summer Dichotomy
|
$T$ students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least $t$ students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!)
During a shift the students from the ZPP grade are tutored by $n$ teachers. Due to the nature of the educational process, each of the teachers should be assigned to exactly one of two groups (it is possible that no teacher will be assigned to some of the groups!). The $i$-th teacher is willing to work in a group as long as the group will have at least $l_{i}$ and at most $r_{i}$ students (otherwise it would be either too boring or too hard). Besides, some pairs of the teachers don't like each other other and therefore can not work in the same group; in total there are $m$ pairs of conflicting teachers.
You, as the head teacher of Summer Irrelevant School, have got a difficult task: to determine how many students to enroll in each of the groups and in which group each teacher will teach.
|
The problem has several possible approaches. The first approach. More popular one. Forget about $t$ and $T$ for a moment; we have to separate teachers into two groups so that no conflicting teachers are in the same group, and the number of students in each group can be chosen to satisfy all the teachers. Consider a connected component via the edges which correspong to conflicting pairs. If the component is not bipartite, there is clearly no valid distribution. Else, the teachers in the component can be separated into two sets such that each set should be in the same group, and the groups for the sets should be different. The teachers in the same set will always go together in the same group, so we may as well make them into a single teacher whose interval is the intersection of all the intervals for the teachers we just compressed. Now, the graph is the set of disjoint edges (for simplicity, if a teacher does not conflict with anyone, connect him with a 'fake' teacher whose interval is $[0; \infty ]$). Consider all possible distributions of students; they are given by a pair $(n_{1}, n_{2})$. Provided this distribution, in what cases a pair of conflicting teachers can be arranged correctly? If the teachers' segments are $[l_{1}, r_{1}]$ and $[l_{2}, r_{2}]$, either $l_{1} \le n_{1} \le r_{1}$ and $l_{2} \le n_{2} \le r_{2}$, or $l_{2} \le n_{1} \le r_{2}$ and $l_{1} \le n_{2} \le r_{1}$ must hold. Consider a coordinate plane, where a point $(x, y)$ corresponds to a possible distribution of students. For a pair of conflicting teachers the valid configurations lie in the union of two rectangles which are given by the inequalities above. Valid configurations that satisfy all pairs of teachers lie exactly in the intersection of all these figures. Thus, the problem transformed to a (kinda) geometrical one. A classical approach to this kind of problems is to perform line-sweeping. Note that any 'union of two rectangles' figure (we'll shorten it to UOTR) is symmetrical with respect to the diagonal line $x = y$. It follows that for any $x$ the intersection of the vertical line given by $x$ with any UOTR is a subsegment of $y$'s. When $x$ sweeps from left to right, for any UOTR there are $O(1)$ events when a subsegment changes. Sort the events altogether and perform the sweeping while updating the sets of subsegments' left and right ends and the subsegments intersection (which is easy to find, given the sets). Once the intersection becomes non-empty, we obtain a pair $(x, y)$ that satisfies all the pairs of teachers; to restore the distribution is now fairly easy (don't forget that every teacher may actually be a compressed set of teachers!). Didn't we forget something? Right, there are bounds $t$ and $T$ to consider! Consider an adjacent set of events which occurs when $x = x_{1}$ and $x = x_{2}$ respectively. The intersection of subsegments for UOTRs obtained after the first event will stay the same while $x_{1} \le x < x_{2}$. Suppose the $y$'s subsegmen intersection is equal to $[l;r]$. If we stay within $x_{1} \le x < x_{2}$, for a satisfying pair of $(x, y)$ the minimal value of $x + y$ is equal to $x_{1} + l$, and the maximal value is $x_{2} + r - 1$. If this range does not intersect with $[t;T]$, no answer is produced this turn. In the other case, choose $x$ and $y$ while satisfying all boundaries upon $x$, $y$ and $x + y$ (consider all cases the rectangle can intersect with a 45-angle diagonal strip). Thus, the requirement of $t$ and $T$ does not make our life much harder. This solution can be implemented in $O(m+n\log n)$ using an efficient data structure like std::set or any self-balancing BST for sets of subsegments' ends. The very same solution can be implemented in the flavour of rectangles union problem canonical solution: represent a query 'add 1 to all the points inside UORT' with queries 'add $x$ to all the points inside a rectangle', and find a point with the value $m$. The second approach. Less popular, and probably much more surprising. Imagine that the values of $t$ and $T$ are small. Introduce the set of boolean variables $z_{i, j}$ which correspond to the event '$n_{i}$ does not exceed $j$' ($i$ is either 1 or 2, $j$ ranges from 0 to $T$). There are fairly obvious implication relations between them: $z_{i,j}\Rightarrow z_{i,j+1}$. As $t \le n_{1} + n_{2} \le T$, we must also introduce implications $z_{i,j}\Rightarrow\!|z_{i^{\prime},t-j-1}|$ (here $i'$ is 1 or 2 not equal to $i$) because if $a + b \ge t$ and $a \le j$, $b$ must be at least $t - j$, and $[z_{i,j}\Rightarrow z_{i^{\prime},T-j-1}$ for a similar reason. In this, $z_{i, j}$ for $j < 0$ clearly must be considered automatically false, and $z_{i, j}$ for $j \ge T$ must be considered automatically true (to avoid boundary fails). The last thing to consider is the teachers. For every teacher introduce a binary variable $w_{j}$ which corresponds to the event 'teacher $j$ tutors the first group'. The implications $w_{j}\Rightarrow z_{1,r_{i}}\cap|z_{1,l_{i}-1}$ and $|w_{j}\Rightarrow z_{2,r_{i}}|1z_{2,l_{i}-1}$ are pretty much self-explanating. A conflicting pair of teachers $j$ and $k$ is resolved in a straightforward way: $w_{j}\Rightarrow\!\left\{w_{k}$, $1w_{j}\Rightarrow w_{k}$. If a set of values for all the boolean variables described satisfies all the restrictions, a valid distribution can be restored explicitly: $n_{1}$ and $n_{2}$ are maximal so that $z_{1, n1}$ and $z_{2, n2}$ hold, and the teachers are distributed unequivocally by values of $w_{j}$. It suffices to notice that the boolean system is a 2-SAT instance, and can be solved in linear time. If we count carefully, we obtain that the whole solution has linear complexity as well: $O(n + m + T)$. Didn't we forget something? Right! The value of $T$ may be too much to handle $ \Omega (T)$ variables explicitly. To avoid that, one may notice that the set of possible values of $n_{1}$ and $n_{2}$ may be reduced to $0$, $t$, $l_{i}$, $t - l_{i}$, $r_{i}$, $t - r_{i}$. We can prove that by starting from any valid values of $n_{1}$ and $n_{2}$ and trying to make them as small as possible; the listed values are the ones we may end up with. Thus, we can only use $O(n)$ variables instead of $ \Omega (T)$. The implications can be built similarily, but using lower/upper bound on the list of possible values instead of exact values (much care is advised!). Finally, this solution can be made to work in $O(m+n\log n)$, with the logarithmic factor from all the sorting and lower/upperbounding.
|
[
"2-sat",
"data structures",
"dfs and similar",
"greedy"
] | 3,200
|
#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
template<class T>
bool uin(T &a, T b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template<class T>
bool uax(T &a, T b) {
if (a < b) {
a = b;
return true;
}
return false;
}
const int MAXN = 110000;
int l[MAXN], r[MAXN];
const int MAXT = 2000000;
int vis[MAXT], comp[MAXT];
vi e[MAXT], re[MAXT];
void addEdge(int v, int u) {
e[v].pb(u);
e[u ^ 1].pb(v ^ 1);
re[u].pb(v);
re[v ^ 1].pb(u ^ 1);
}
vi ord;
void dfs_ord(int v) {
if (vis[v]) return;
vis[v] = 1;
for (int u: e[v]) dfs_ord(u);
ord.pb(v);
}
void dfs_mark(int v, int c) {
if (vis[v]) return;
vis[v] = 1;
comp[v] = c;
for (int u: re[v]) dfs_mark(u, c);
}
int val(int v) {
return comp[v] > comp[v + 1];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int t, T;
cin >> t >> T;
int N, M;
cin >> N >> M;
forn(i, N) cin >> l[i] >> r[i];
vector<pii> conf(M);
forn(i, M) {
cin >> conf[i].fi >> conf[i].se;
--conf[i].fi; --conf[i].se;
}
bool ok = true;
vi v;
v.pb(0);
v.pb(t);
v.pb(T);
forn(i, N) {
v.pb(l[i]);
if (l[i] <= t) v.pb(t - l[i]);
v.pb(r[i]);
if (r[i] <= t) v.pb(t - r[i]);
}
sort(all(v));
v.erase(unique(all(v)), v.end());
while (v.back() > T) v.pop_back();
// for (int u: v) cerr << u << ' ';
// cerr << '\n';
int K = v.size();
int off1 = 0, off2 = 2 * K, off3 = 4 * K;
int V = off3 + 2 * N;
assert(V <= MAXT);
int j = K - 1;
forn(i, K - 1) {
addEdge(off1 + 2 * i, off1 + 2 * (i + 1));
addEdge(off2 + 2 * i, off2 + 2 * (i + 1));
}
forn(i, K - 1) {
while (j >= 0 && v[i + 1] + v[j] > T) --j;
if (j < 0) break;
addEdge(off1 + 2 * i + 1, off2 + 2 * j);
addEdge(off2 + 2 * i + 1, off1 + 2 * j);
}
addEdge(off1 + 2 * K - 1, off1 + 2 * K - 2);
addEdge(off2 + 2 * K - 1, off2 + 2 * K - 2);
j = K - 1;
forn(i, K) {
while (j >= 0 && v[i] + v[j] >= t) --j;
if (j < 0) break;
// cerr << v[i] << " => !" << v[j] << '\n';
addEdge(off1 + 2 * i, off2 + 2 * j + 1);
addEdge(off2 + 2 * i, off1 + 2 * j + 1);
}
forn(i, N) {
int j = (upper_bound(all(v), r[i]) - v.begin()) - 1;
assert(j >= 0);
// cerr << "p" << i << " => " << v[j] << '\n';
addEdge(off3 + 2 * i, off1 + 2 * j);
addEdge(off3 + 2 * i + 1, off2 + 2 * j);
j = (lower_bound(all(v), l[i]) - v.begin()) - 1;
if (j < 0) continue;
// cerr << "!p" << i << " => !" << v[j] << '\n';
addEdge(off3 + 2 * i, off1 + 2 * j + 1);
addEdge(off3 + 2 * i + 1, off2 + 2 * j + 1);
}
forn(i, M) {
int x = conf[i].fi, y = conf[i].se;
addEdge(off3 + 2 * x, off3 + 2 * y + 1);
addEdge(off3 + 2 * x + 1, off3 + 2 * y);
}
forn(i, V) dfs_ord(i);
reverse(all(ord));
forn(i, V) vis[i] = 0;
int cc = 0;
for (int v: ord) {
if (vis[v]) continue;
dfs_mark(v, cc++);
}
forn(i, V / 2) ok &= comp[2 * i] != comp[2 * i + 1];
if (!ok) {
cout << "IMPOSSIBLE\n";
return 0;
}
cout << "POSSIBLE\n";
int A = 0, B = 0;
forn(i, K) if (val(off1 + 2 * i) == 1) {
A = v[i]; break;
}
forn(i, K) if (val(off2 + 2 * i) == 1) {
B = v[i]; break;
}
cout << A << ' ' << B << '\n';
forn(i, N) cout << (val(off3 + 2 * i) ? '1' : '2');
cout << '\n';
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
540
|
A
|
Combination Lock
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by $n$ rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
|
For every symbol we should determine how to rotate the disk. This can be done either by formula: $min(abs(a[i] - b[i]), 10 - abs(a[i] - b[i]))$ or even by the two for cycles: in both directions.
|
[
"implementation"
] | 800
| null |
540
|
B
|
School Marks
|
Little Vova studies programming in an elite school. Vova and his classmates are supposed to write $n$ progress tests, for each test they will get a mark from 1 to $p$. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value $x$, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than $y$ points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.
Vova has already wrote $k$ tests and got marks $a_{1}, ..., a_{k}$. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.
|
First count the number of marks that are less than $y$. If there are more than $\scriptstyle{\frac{n-1}{2}}$ such marks, we can't satisfy the second condition (about the median), and the answer is -1. Otherwise we can get exactly such number of $y$ marks so that the total number of marks greater than or equal to $y$ is at least $\textstyle{\frac{n+1}{2}}$ (maybe it's already satisfied). This is the required action for satisfying the second condition. Now, in order not to break the first condition, get the remaining marks as lower as possible - all ones - and check the sum of the marks. If it is greater than $x$, the answer is -1, otherwise the correct answer is found.
|
[
"greedy",
"implementation"
] | 1,700
| null |
540
|
C
|
Ice Cave
|
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.
The level of the cave where you are is a rectangular square grid of $n$ rows and $m$ columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.
Let's number the rows with integers from $1$ to $n$ from top to bottom and the columns with integers from $1$ to $m$ from left to right. Let's denote a cell on the intersection of the $r$-th row and the $c$-th column as $(r, c)$.
You are staying in the cell $(r_{1}, c_{1})$ and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell $(r_{2}, c_{2})$ since the exit to the next level is there. Can you do this?
|
There are three cases here, though some of them can be merged. If the start and finish cells are equal, let's count the intact neighbours of this cell. If there is one, move there and instantly move back - the answer is YES. Otherwise it's NO. If the start and finish cells are neighbours, the solution depends on the type of the destination cell. If it's cracked, the answer is YES - we can just move there and fall down. Otherwise it must have at least one intact neighbour to get the positive answer - we can move to the finish cell, then to this intact neighbour, and then return to the finish cell. In the general case, check if the path from the start cell to the finish cell exists. If it doesn't, the answer is NO. Otherwise check the type of the destination cell. If it's cracked, it must have at least one intact neighbour, and if it's intact, it must have two intact neighbours.
|
[
"dfs and similar"
] | 2,000
| null |
540
|
D
|
Bad Luck Island
|
The Bad Luck Island is inhabited by three kinds of species: $r$ rocks, $s$ scissors and $p$ papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
|
Let's count the values dp[r][s][p] - the probability of the situation when r rocks, s scissors and p papers are alive. The initial probability is 1, and in order to calculate the others we should perform the transitions. Imagine we have r rocks, s scissors and p papers. Let's find the probability of the rock killing scissors (the other probabilities are calculated in the same way). The total number of the possible pairs where one species kills the other one is $rs + rp + sp$, and the number of possible pairs (rock, scissors) is $rs$. As all meetings are equiprobable, the probability we want to find is $\frac{T s}{r s+r p+s p}$. This is the probability with which we go the the state dp[r][s - 1][p], with the number of scissors less by one. In the end, for example, to get the probability of the event that the rocks are alive, we should sum all values dp[i][0][0] for i from 1 to r (the same goes to the other species).
|
[
"dp",
"probabilities"
] | 1,900
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
typedef long double ld;
ld a[105][105][105];
int main() {
int R, S, P;
cin >> R >> S >> P;
a[R][S][P] = 1;
for (int sum = R + S + P; sum > 0; sum--) {
for (int r = R; r >= 0; r--) {
for (int s = S; s >= 0; s--) {
int p = sum - r - s;
if (p < 0 || p > P) continue;
if (r == 0 && s == 0) continue;
if (r == 0 && p == 0) continue;
if (s == 0 && p == 0) continue;
ld cur = a[r][s][p];
int waysR = r * s;
int waysS = s * p;
int waysP = p * r;
int totalWays = waysR + waysS + waysP;
if (r > 0) a[r - 1][s][p] += cur * waysP / totalWays;
if (s > 0) a[r][s - 1][p] += cur * waysR / totalWays;
if (p > 0) a[r][s][p - 1] += cur * waysS / totalWays;
}
}
}
ld ansR = 0;
ld ansS = 0;
ld ansP = 0;
for (int r = 1; r <= R; r++) ansR += a[r][0][0];
for (int s = 1; s <= S; s++) ansS += a[0][s][0];
for (int p = 1; p <= P; p++) ansP += a[0][0][p];
printf("%.12f %.12f %.12f\n", (double)ansR, (double)ansS, (double)ansP);
}
|
540
|
E
|
Infinite Inversions
|
There is an infinite sequence consisting of all positive integers in the increasing order: $p = {1, 2, 3, ...}$. We performed $n$ swap operations with this sequence. A $swap(a, b)$ is an operation of swapping the elements of the sequence on positions $a$ and $b$. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs $(i, j)$, that $i < j$ and $p_{i} > p_{j}$.
|
At first find the position of each element which is used in swap (using map). Now let's find the answer. It consists of the two parts. First part is the number of inversions formed by only whose elements which took part in the swaps. They can be counted by one of the standard ways: mergesort or Fenwick tree. The second part is the number of inversions formed by pairs of elements where one element has been swapped even once, and the other element stayed at his position. Let's consider the following test: The global sequence will look as follows: [1 6 3 8 5 2 7 4 9 ...], and here is the array of swapped elements: [6 8 2 4]. Let's understand with which numbers the number 8 forms the inversions. The only elements that could do that are the elements between the initial position of the number 8 (where the number 4 is now) and its current position: [5 2 7]. There are two numbers on this segment which didn't take part in swaps: 5 and 7. The number 2 should not be counted as it took part in the swaps and we have already counted it in the first part of the solution. So we should take the count of numbers between 8's indices in the global sequence ($8 - 4 - 1 = 3$) and subtract the count of numbers between its indices in the swaps array ($4 - 2 - 1 = 1$). We'll get the number of inversions formed by the element 8 and the elements which haven't moved at all, it's 2. Counting this value for all elements which have been swapped at least once, we get the second part of the answer. All operations in the second part of the solution can be performed using sorts and binary searches. +103 dalex 10 years ago 69
|
[
"binary search",
"data structures",
"implementation",
"sortings",
"trees"
] | 2,100
|
class E {
static class Item implements Comparable<Item> {
int pos, val;
public Item(int pos, int val) {
this.pos = pos;
this.val = val;
}
public int compareTo(Item o) {
if (pos != o.pos) {
return Integer.compare(pos, o.pos);
}
return Integer.compare(val, o.val);
}
}
static class FenwickTree {
int n;
int[] a;
public FenwickTree(int n) {
this.n = n;
a = new int[n];
}
private int sum(int r) {
int res = 0;
for (int i = r; i >= 0; i = (i & (i + 1)) - 1) {
res += a[i];
}
return res;
}
private int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
private void inc(int i) {
for (; i < n; i |= i + 1) {
a[i]++;
}
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int q = in.readInt();
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int i = 0; i < q; i++) {
int pos1 = in.readInt() - 1;
int pos2 = in.readInt() - 1;
int num1 = map.containsKey(pos1) ? map.get(pos1) : pos1;
int num2 = map.containsKey(pos2) ? map.get(pos2) : pos2;
map.put(pos1, num2);
map.put(pos2, num1);
}
Item[] a = new Item[map.size()];
int n = 0;
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
a[n++] = new Item(e.getKey(), e.getValue());
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = a[i].val;
}
compress(b);
long ans = 0;
FenwickTree tree = new FenwickTree(n);
for (int i = 0; i < n; i++) {
ans += tree.sum(b[i], n - 1);
tree.inc(b[i]);
}
for (int idxAfter = 0; idxAfter < n; idxAfter++) {
int idxBefore = ~Arrays.binarySearch(a, new Item(a[idxAfter].val, -1));
ans += Math.abs(a[idxAfter].pos - a[idxBefore].pos);
ans -= Math.abs(idxAfter - idxBefore);
}
out.printLine(ans);
}
private void compress(int[] a) {
TreeSet<Integer> set = new TreeSet<Integer>();
for (int x : a) {
set.add(x);
}
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int x : set) {
int id = map.size();
map.put(x, id);
}
for (int i = 0; i < a.length; i++) {
a[i] = map.get(a[i]);
}
}
}
|
542
|
A
|
Place Your Ad Here
|
Ivan Anatolyevich's agency is starting to become famous in the town.
They have already ordered and made $n$ TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the $i$-th video can only be shown within the time range of $[l_{i}, r_{i}]$ (it is not necessary to use the whole segment but the broadcast time should be within this segment).
Now it's time to choose a TV channel to broadcast the commercial. Overall, there are $m$ TV channels broadcasting in the city, the $j$-th one has $c_{j}$ viewers, and is ready to sell time $[a_{j}, b_{j}]$ to broadcast the commercial.
Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video $i$ and exactly one TV channel $j$ to broadcast this video and also a time range to broadcast $[x, y]$. At that the time range should be chosen so that it is both within range $[l_{i}, r_{i}]$ and within range $[a_{j}, b_{j}]$.
Let's define the efficiency of the broadcast as value $(y - x)·c_{j}$ — the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!
|
Let's fix the TV channel window and look for a commerical having the largest intersection with it. There are four types of commercials: lying inside the window, overlapping the window and partially intersecting the window from the left and from the right. It's easy to determine if there is overlapping commercial: it's enough to sort commercials in increasing order of the left end and then while iterating over them from left to right, keep the minimum value of a right end of a commercial. If when we pass the window $j$ and see that current value of the maximum right end is no less than $b_{j}$ then there exists a commercial overlapping our window and the value is equal to the $(r_{i} - l_{i}) \cdot c_{i}$. Among all commercials that lie inside our window we need the longest one. It can be done by similar but a bit harder manner. Let's use sweepline method. While passing through the end of the commercial $r_{i}$, let's assign in some data structure (like segment tree) the value $r_{i} - l_{i}$ in point $l_{i}$. While passing through the end of a window, let's calculate answer for it as a maximum on segment $[a_{j}, b_{j}]$. By doing this, we consider all commercials inside the window. We can process partially intersecting commercials in the similar way. While passing the right end of the commercial $r_{i}$ let's put the value $r_{i}$ in the point $l_{i}$ in our data structure. While passing through the right end of a window $b_{j}$ let's calculate the answer for it as a maximum on the segment $[a_{j}, b_{j}]$ minus $a_{j}$. Among all answers for all commercials we need to choose the largest one. So we have the solution in $O(n\log n)$.
|
[
"data structures",
"sortings"
] | 2,400
| null |
542
|
B
|
Duck Hunt
|
A duck hunter is doing his favorite thing, hunting. He lives in a two dimensional world and is located at point $(0, 0)$. As he doesn't like walking for his prey, he prefers to shoot only vertically up (because in this case, the ducks fall straight into his hands). The hunter doesn't reload the gun immediately — $r$ or more seconds must pass between the shots. When the hunter shoots up, the bullet immediately hits all the ducks who are directly above the hunter.
In a two dimensional world each duck is a horizontal segment that moves horizontally in the negative direction of the $Ox$ axis at the speed $1$ length unit per second. For each duck we know the values $h_{i}$ and $t_{i}$ — the $x$-coordinates of its head (the left end of the segment) and its tail (the right end of the segment) at time $0$. The height where the duck is flying isn't important as the gun shoots vertically up to the infinite height and hits all the ducks on its way.
\begin{center}
{\small The figure to the first sample.}
\end{center}
What maximum number of ducks can the hunter shoot? The duck is considered shot by the hunter if at the moment of the shot at least one of its point intersects the $Oy$ axis. After the hunter shoots the duck, it falls and it can't be shot anymore. The hunter cannot make shots before the moment of time 0.
|
First of all, let's say that ducks stay still and the one that moves is the hunter. Let's define the value $F[x][s]$ as the minimum number of ducks among having the right end no further than $x$, that we can't shot if the last shot was in the point $s$. In particular, the value $F[x][s]$ includes all ducks located inside the segment $[s + 1, x]$. Values $F[x][s]$ for $s > x$ let's consider as undefined. Let's look on $F[x]$ as on a function of $s$. This function is defined on all $s$ from $0$ to $x$ inclusive. The key idea is in investigating how $F[x + 1][ \cdot ]$ differs from $F[x][ \cdot ]$. Let's first suppose that in point $x + 1$ there is no end of the duck. Then in definition of $F[x + 1][ \cdot ]$ we consider the same set of the ducks as for the definition f $F[x][ \cdot ]$. That means that all values $F[x][s]$ for $s \le x$ are the same for $F[x + 1]$. Let's understand what happens with $F[x + 1][x + 1]$. It's easy to see that the shot in point $x + 1$ can't kill any of the ducks that end no further than $x + 1$ (since we just supposed that there are no ducks ending in exactly $x + 1$). So, $F[x + 1][x + 1] = min F[x + 1][0... x + 1 - r] = min F[x][0... x + 1 - r]$. Now let's suppose that in point $x + 1$ the duck $[l, x + 1]$ ends. In this case we can say that all values of $F[x + 1][0... l - 1]$ should be increased by $1$ (since at the moment of shot in point $s < l$ the duck $[l, x + 1]$ can't be killed yet). From the other hand, all values $F[x + 1][l... x + 1]$ remain the same since the last shot kills the newly added duck. Now let's understand how to implement all this stuff. Function $F[x][ \cdot ]$ is piecewise constant, so it can be stored in a Cartesian tree as a sequence of pairs (beginning of segment, value on segment). Such storage allows us to easily add $1$ on prefix and take minimum on prefix of a function. Now let's think that $F[x][ \cdot ]$ is defined on all posistive values but the values $F[x][s]$ for $s > x$ do not satisfy the definition of $F[x][s]$ above. In other words, let's just suppose that the lats segment in structure $F[x]$ is infinite in right direction. Let's sweep with the variable $x$. The function $F[x + 1][ \cdot ]$ changes in comparsion to $F[x][ \cdot ]$ very rarely For example, the value $F[x + 1][x + 1]$ is almost always the same as $F[x][x + 1]$ (that is equal to $F[x][x]$ as said above). Indeed, if we suppose that there is no duck ending in $x + 1$ then $F[x][x] = min(F[x][0... x - r])$ and $F[x + 1][x + 1] = min(F[x + 1][0... x + 1 - r]) = min(F[x][0... x + 1 - r]) \le min(F[x][0... x - r])$. So, there is an interesting event only if value $F[x][x - r + 1]$ is smaller than the whole prefix before it. On the other hand, the value $min(F[x][0... x - r])$ can't increase more than $n$ times by $1$ (each time when we pass through the right end of the duck) and so, it also can't decrease more then $n$ times (since it is a non-negative value). So, the events "we passed through the right end of the duck" and "we should non-trivially calculate $F[x][x]$" are in total linear. Each of them can be processed in $O(1)$ operation with Cartesian tree, that gives as totally an $O(n\log n)$ solution. Whooray!
|
[
"data structures"
] | 3,100
| null |
542
|
C
|
Idempotent functions
|
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set ${1, 2, ..., n}$ is such function $g:\{1,2,\cdot\cdot,n\}\to\{1,2,\cdot\cdot,n\}$, that for any $x\in\{1,2,\cdot\cdot,n\}$ the formula $g(g(x)) = g(x)$ holds.
Let's denote as $f^{(k)}(x)$ the function $f$ applied $k$ times to the value $x$. More formally, $f^{(1)}(x) = f(x)$, $f^{(k)}(x) = f(f^{(k - 1)}(x))$ for each $k > 1$.
You are given some function $f:\{1,2,\cdot\cdot,n\}\to\{1,2,\cdot\cdot,n\}$. Your task is to find minimum positive integer $k$ such that function $f^{(k)}(x)$ is idempotent.
|
In order to solve this task it's good to understand how does the graph corresponding the function from ${1, ..., n}$ to itself looks. Let's consider a graph on vertices $1, ..., n$ with edges from vertex $i$ to the vertex $f(i)$. Such graph always looks like a set of cycles with several trees leading to that cycles. How should the graph look like for function to be the idempotent? It's easy to see that in such graph all cycles should be of length $1$ and all vertex that are not cycles of length $1$ (i. e. all not fixed points) should immediatly lead to some fixed point. So, we should satisfy two conditions. First, all cycles should become of length $1$ - in order to do that $k$ should be divisible by $lcm(c_{1}, c_{2}, ..., c_{m})$ where $c_{i}$ are the lengths of all cycles. Second, all vertices not lying on cycles should become leading to the vertices lying on cycles. In other words, $k$ should be no less than the distance from any vertex $x$ to the cycle it goes into (or, that the same, the length of pre-period in the sequence $f(x), f(f(x)), f(f(f(x))), ...$). So, are task is about finding the smallest number $k$ divisible by $A$ that is no less than $B$, it is not hard at all.
|
[
"constructive algorithms",
"graphs",
"math"
] | 2,000
| null |
542
|
D
|
Superhero's Job
|
It's tough to be a superhero. And it's twice as tough to resist the supervillain who is cool at math. Suppose that you're an ordinary Batman in an ordinary city of Gotham. Your enemy Joker mined the building of the city administration and you only have several minutes to neutralize the charge. To do that you should enter the cancel code on the bomb control panel.
However, that mad man decided to give you a hint. This morning the mayor found a playing card under his pillow. There was a line written on the card:
\[
\begin{array}{c}{{J(x)=\displaystyle}}\\ {{\qquad\sum_{k=k=x}\sum_{k=1}\sum_{k=1}}}\\ {{\qquad\operatorname*{gcd}(k,x/k)=1}}\end{array}
\]
The bomb has a note saying "$J(x) = A$", where $A$ is some positive integer. You suspect that the cancel code is some integer $x$ that meets the equation $J(x) = A$. Now in order to decide whether you should neutralize the bomb or run for your life, you've got to count how many distinct positive integers $x$ meet this equation.
|
First step is to understand the properties of a Joker function. It's important property is that it is multiplicative: $J(ab) = J(a)J(b)$ for $(a, b) = 1$, so we can write the value of function knowing the factorization of an argument: $J(p_{1}^{k1}p_{2}^{k2}... p_{m}^{km}) = J(p_{1}^{k1})J(p_{2}^{k2})... J(p_{m}^{km}) = (p_{1}^{k1} + 1)(p_{2}^{k2} + 1)... (p_{m}^{km} + 1)$. Let's use this knowledge in order to solve the task with dynamic programming. Let's denote as $P$ the set of prime $p$ such that the multiple including it may appear in $A = J(x)$. There are not that many such primes: each divisor $d$ of number $A$ can correspond no more than one such prime, namely, the one whose power the number $d - 1$ is (if it is a prime power at all). Let's calculate the set $P$ and also remember for each prime number $p$ in it in which powers $k$ the value $(p^{k} + 1)$ divides $A$. Now we can calculate value $D[p][d]$ that is equal to the number of ways to get a divisor $d$ of a number $A$ as a product of brackets of first $p$ primes in set $P$. Such value can be caluclated by using dynamic programming in time $O(\tau(A)^{2})$ where ${\boldsymbol{\tau}}(A)$ is the number of divisors of $A$ (as it was shown above that $\left|P\right|=O(\tau(A))$). So, overall complexity of the solution is $O({\sqrt{A}}+\tau(A)^{2})$.
|
[
"dfs and similar",
"dp",
"hashing",
"math",
"number theory"
] | 2,600
| null |
542
|
E
|
Playing on Graph
|
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.
Vova has a non-directed graph consisting of $n$ vertices and $m$ edges without loops and multiple edges. Let's define the operation of contraction two vertices $a$ and $b$ that are \textbf{not connected by an edge}. As a result of this operation vertices $a$ and $b$ are deleted and instead of them a new vertex $x$ is added into the graph, and also edges are drawn from it to all vertices that were connected with $a$ or with $b$ (specifically, if the vertex was connected with both $a$ and $b$, then also exactly one edge is added from $x$ to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains $(n - 1)$ vertices.
Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length $k$ ($k ≥ 0$) is a connected graph whose vertices can be numbered with integers from $1$ to $k + 1$ so that the edges of the graph connect all pairs of vertices $(i, i + 1)$ ($1 ≤ i ≤ k$) and only them. Specifically, the graph that consists of one vertex is a chain of length $0$. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.
\begin{center}
{\small The picture illustrates the contraction of two vertices marked by red.}
\end{center}
Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.
|
First, if the original graph isn't bipartite then the answer is (-1). Indeed, any odd cycle, while being contracted by the pair of vertices, always produces an odd cycle of smaller size, so at some point we will get a triangle that blocks us from doing anything. From the other way, each bipartite component can be contracted in order to get a chain whose length is a diameter of the component. Suppose that the pair of vertices $(a, b)$ is a diamater of some connected component. Then, by contracting all vertices located on the same distance from $a$ we can achieve the chain we want. The last step is that the answer fror the original graph is the sum of the answers for all the connected components since we can attach all of them together. So, the answer is the sum of diameters of all connected components if all of them are bipartite, otherwise answer is -1. Solution has the complexity $O(E + VE)$ (The first summand is checking for being bipartite, the second one is calculation diameters by running BFS from each vertex).
|
[
"graphs",
"shortest paths"
] | 2,600
| null |
542
|
F
|
Quest
|
Polycarp is making a quest for his friends. He has already made $n$ tasks, for each task the boy evaluated how interesting it is as an integer $q_{i}$, and the time $t_{i}$ in minutes needed to complete the task.
An interesting feature of his quest is: each participant should get the task that is best suited for him, depending on his preferences. The task is chosen based on an interactive quiz that consists of some questions. The player should answer these questions with "yes" or "no". Depending on the answer to the question, the participant either moves to another question or goes to one of the tasks that are in the quest. In other words, the quest is a binary tree, its nodes contain questions and its leaves contain tasks.
We know that answering any of the questions that are asked before getting a task takes exactly one minute from the quest player. Polycarp knows that his friends are busy people and they can't participate in the quest for more than $T$ minutes. Polycarp wants to choose some of the $n$ tasks he made, invent the corresponding set of questions for them and use them to form an interactive quiz as a binary tree so that no matter how the player answers quiz questions, he spends at most $T$ minutes on completing the whole quest (that is, answering all the questions and completing the task). Specifically, the quest can contain zero questions and go straight to the task. Each task can only be used once (i.e., the people who give different answers to questions should get different tasks).
Polycarp wants the total "interest" value of the tasks involved in the quest to be as large as possible. Help him determine the maximum possible total interest value of the task considering that the quest should be completed in $T$ minutes at any variant of answering questions.
|
This task can be solved in lot of ways. The most straightforward is DP. The task can be seen in the following way. We want some set of vertices as leaves and for each potential leaf we know the upper bound for its depth and its cost. Let's sweep over the tree from down to up. Let's calculate the value $D[h][c]$ that is the maximum possible cost that we can achieve if we stay on the level $h$ and have $c$ vertices on it. For transition let's fix how many leaves of the deepness exactly $h$ we will take (it's easy to see that among them we should task several greatest). Suppose we will take $k$ of them. Then from this state we can move to $D[h - 1][ \lceil (c + k) / 2 \rceil ]$. The answer will be located in $D[0][1]$ because when we are on the level $0$ we should have the only vertex that is the root of the tree. The complexity of such solution is $O(n^{2}T)$.
|
[
"dp",
"greedy"
] | 2,100
| null |
543
|
A
|
Writing Code
|
Programmers working on a large project have just received a task to write exactly $m$ lines of code. There are $n$ programmers working on a project, the $i$-th of them makes exactly $a_{i}$ bugs in every line of code that he writes.
Let's call a sequence of non-negative integers $v_{1}, v_{2}, ..., v_{n}$ a plan, if $v_{1} + v_{2} + ... + v_{n} = m$. The programmers follow the plan like that: in the beginning the first programmer writes the first $v_{1}$ lines of the given task, then the second programmer writes $v_{2}$ more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most $b$ bugs in total.
Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer $mod$.
|
Let's create the solution, which will work too slow, but after that we will improve it. Let's calculate the following dynamic programming $z[i][j][k]$ - answer to the problem, if we already used exactly $i$ programmers, writed exactly $j$ lines of code, and there are exactly $k$ bugs. How we can do transitions in such dp? We can suppose that we $i$-th programmer will write $r$ lines of code, then we should add to $z[i][j][k]$ value $z[i - 1][j - r][k - ra[i]]$ But let's look at transitions from the other side. It's clear, that there are exactly 2 cases. The first case, we will give any task for $i$-th programmer. So, we should add to $z[i][j][k]$ value $z[i - 1][j][k]$. The second case, is to give at least one task to $i$-th programmer. So, this value will be included in that state: $z[i][j - 1][k - a[i]]$. In that solution we use same idea, which is used to calculate binomial coefficients using Pascal's triangle. So overall solution will have complexity: $O(n^{3})$
|
[
"dp"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int N = 505;
int a[N];
int z[2][N][N];
int main() {
int n, bl, bugs, md;
scanf("%d %d %d %d", &n, &bl, &bugs, &md);
forn(i, n) scanf("%d", &a[i]);
z[0][0][0] = 1;
for(int it = 1; it <= n; it++){
int i = it & 1;
for(int j = 0; j <= bl; j++) {
for(int k = 0; k <= bugs; k++) {
z[i][j][k] = z[i ^ 1][j][k];
if (j > 0 && k >= a[it - 1])
z[i][j][k] += z[i][j - 1][k - a[it - 1]];
while (z[i][j][k] >= md) z[i][j][k] -= md;
}
}
}
int ans = 0;
for(int i = 0; i <= bugs; i++) {
ans += z[n & 1][bl][i];
while (ans >= md) ans -= md;
}
printf("%d\n", ans);
}
|
543
|
B
|
Destroying Roads
|
In some country there are exactly $n$ cities and $m$ bidirectional roads connecting the cities. Cities are numbered with integers from $1$ to $n$. If cities $a$ and $b$ are connected by a road, then in an hour you can go along this road either from city $a$ to city $b$, or from city $b$ to city $a$. The road network is such that from any city you can get to any other one by moving along the roads.
You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city $s_{1}$ to city $t_{1}$ in at most $l_{1}$ hours and get from city $s_{2}$ to city $t_{2}$ in at most $l_{2}$ hours.
Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.
|
Let's solve easiest task. We have only one pair of vertices, and we need to calculate smallest amout of edges, such that there is a path from first of vertex to the second. It's clear, that the answer for that problem equals to shortest distance from first vertex to the second. Let's come back to initial task. Let's $d[i][j]$ - shortest distance between $i$ and $j$. You can calculate such matrix using bfs from each vertex. Now we need to handle two cases: Paths doesn't intersects. In such way we can update the answer with the following value: $m - d[s_{0}][t_{0}] - d[s_{1}][t_{1}]$ (just in case wheh conditions on the paths lengths fullfills). Otherwise paths are intersecting, and the correct answer looks like a letter 'H'. More formally, at the start two paths will consists wiht different edges, after that paths will consists with same edges, and will finish with different edges. Let's iterate over pairs $(i, j)$ - the start and the finish vertices of the same part of paths. Then we can update answer with the following value: $m - d[s_{0}][i] - d[i][j] - d[j][t_{0}] - d[s_{1}][i] - d[j][t_{1}]$ (just in case wheh conditions on the paths lengths fullfills). Please note, that we need to swap vertices $s_{0}$ and $t_{0}$, and recheck the second case, because in some situations it's better to connect vertex $t_{0}$ with vertex $i$ and $s_{0}$ with vertex $j$. Solutions, which didn't handle that case failed system test on testcase 11.
|
[
"constructive algorithms",
"graphs",
"shortest paths"
] | 2,100
|
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int N = 5005;
int d[N][N];
vector < int > g[N];
int main() {
memset(d, -1, sizeof d);
int n, m;
scanf("%d %d", &n, &m);
for(int i = 0; i < m; i++) {
int a, b;
scanf("%d %d", &a, &b);
a--, b--;
g[a].push_back(b);
g[b].push_back(a);
}
for(int i = 0; i < n; i++) {
queue < int > q;
q.push(i);
d[i][i] = 0;
while (!q.empty()) {
int s = q.front();
q.pop();
for(int j = 0; j < int(g[s].size()); j++) {
int to = g[s][j];
if (d[i][to] == -1) {
d[i][to] = d[i][s] + 1;
q.push(to);
}
}
}
}
int s[2], t[2], l[2];
scanf("%d %d %d", &s[0], &t[0], &l[0]);
scanf("%d %d %d", &s[1], &t[1], &l[1]);
s[0]--, t[0]--, s[1]--, t[1]--;
int ans = m + 1;
for(int iter = 0; iter < 2; iter++){
swap(s[0], t[0]);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int v[] = {d[s[0]][i] + d[i][j] + d[j][t[0]], d[s[1]][i] + d[i][j] + d[j][t[1]]};
if (v[0] <= l[0] && v[1] <= l[1]) {
ans = min(ans, v[0] + v[1] - d[i][j]);
}
}
}
}
if (d[s[0]][t[0]] <= l[0] && d[s[1]][t[1]] <= l[1]) {
ans = min(ans, d[s[0]][t[0]] + d[s[1]][t[1]]);
}
if (ans > m) {
ans = -1;
} else {
ans = m - ans;
}
printf("%d\n", ans);
}
|
543
|
C
|
Remembering Strings
|
You have multiset of $n$ strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position $i$ and some letter $c$ of the English alphabet, such that this string is the only string in the multiset that has letter $c$ in position $i$.
For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because:
- the first string is the only string that has character $c$ in position $3$;
- the second string is the only string that has character $d$ in position $2$;
- the third string is the only string that has character $s$ in position $2$.
You want to change your multiset a little so that it is easy to remember. For $a_{ij}$ coins, you can change character in the $j$-th position of the $i$-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.
|
First that we need to notice, that is amout of strings is smaller then alphabet size. It means, that we can always change some character to another, because at least one character is not used by some string. After that we need handle two cases: We can change exactly one character to another. The cost of such operation equals to $a[i][j]$ (which depends on chosed column) After that we can remember string very easy. We can choose some column, and choose some set of strings, that have same character in that column, By one move we can make all these strings are easy to remember.The cost of such move equals to cost of all characters, except most expensive. As the result, we will have following solution: d[mask] - answer to the problem, when we make all strings from set $mask$ easy to remember. We can calculate this dp in following way: let $lowbit$ - smallest element of set $mask$. It's clear, that we can do this string easy to remember using first or second move. So we need just iterate over possible columns, and try first or second move (in second move we should choose set that contain string $lowbit$) Overall complexity is $O(m2^{n})$, where $m$ - is length of strings.
|
[
"bitmasks",
"dp"
] | 2,500
|
#include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
using namespace std;
const int N = 20;
const int leng = 300;
string s[N];
int cost[N][leng], c[N][leng], sv[N][leng], a[N][leng];
int d[1 << N];
int main() {
int n, m;
cin >> n >> m;
forn(i, n) cin >> s[i];
forn(i, n) forn(j, m) cin >> a[i][j];
forn(i, n) {
forn(j, m) {
int curv = 0;
forn(k, n) {
if (s[i][j] == s[k][j]) {
sv[i][j] |= (1 << k);
c[i][j] += a[k][j];
curv = max(curv, a[k][j]);
}
}
c[i][j] -= curv;
}
}
forn(i, 1 << n) d[i] = 1000000000;
d[0] = 0;
forn(mask, 1 << n) {
if (mask == 0) continue;
int lowbit = -1;
forn(i, n) {
if ((mask >> i) & 1) {
lowbit = i;
break;
}
}
forn(i, m) {
d[mask] = min(d[mask], d[mask & (mask ^ sv[lowbit][i])] + c[lowbit][i]);
d[mask] = min(d[mask], d[mask ^ (1 << lowbit)] + a[lowbit][i]);
}
}
printf("%d\n", d[(1 << n) - 1]);
}
|
543
|
D
|
Road Improvement
|
The country has $n$ cities and $n - 1$ bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from $1$ to $n$ inclusive.
All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city $x$ to any other city contains at most one bad road.
Your task is — for every possible $x$ determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo $1 000 000 007$ ($10^{9} + 7$).
|
Let's suppose $i$ is a root of tree. Let's calculate extra dynamic programming $d[i]$ - answer to the problem for sub-tree with root $i$ We can understand, that d[i] equals to the following value: $d[i]=\prod_{i}(d[j]+1)$ - where $j$ is a child of the vertex $i$. It's nice. After that answer to problem for first vertex equal to $d[1]$. After that let's study how to make child $j$ of current root $i$ as new root of tree. We need to recalculate only two values $d[i]$ and $d[j]$. First value we can recalculate using following formula $d[i]$: $suf[i][j] * pref[i][j] * d[parent]$, where $parent$ - is the parent of vertex $i$, (for vertex $1$ $d[parent] = 1$), and array $suf[i][j]$ - is the product of values $d[k]$, for all childs of vertex $i$ and $k < j$ ($pref[i][j]$ have same definition, but $k > j$). And after we can calculate $d[j]$ as $d[j] * (d[i] + 1)$. That is all, $j$ is root now, and answer to vertex $j$ equals to current value $d[j]$
|
[
"dp",
"trees"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define ford(i, n) for(int i = int(n) - 1; i >= 0; i--)
#define sz(a) int((a).size())
const int N = 200000 + 300;
const int md = 1000000007;
vector < int > g[N], pref[N], suf[N];
int ans[N], d[N];
void dfs(int s){
d[s] = 1;
forn(i, sz(g[s])) {
int to = g[s][i];
dfs(to);
d[s] = d[s] * 1ll * (d[to] + 1) % md;
}
int curp = 1, curs = 1;
forn(i, sz(g[s])) {
int to = g[s][i], rto = g[s][sz(g[s]) - i - 1];
pref[s].push_back(curp);
suf[s].push_back(curs);
curp = curp * 1ll * (d[to] + 1) % md;
curs = curs * 1ll * (d[rto] + 1) % md;
}
reverse(suf[s].begin(), suf[s].end());
}
void tdfs(int s, int par = -1) {
ans[s] = d[s];
forn(i, sz(g[s])) {
int to = g[s][i], olds = d[s], oldto = d[to];
d[s] = pref[s][i] * 1ll * suf[s][i] % md;
if (par != -1) d[s] = d[s] * 1ll * (d[par] + 1) % md;
d[to] = d[to] * 1ll * (d[s] + 1) % md;
tdfs(to, s);
d[s] = olds;
d[to] = oldto;
}
}
int main() {
#ifdef gridnevvvit
freopen("input.txt", "rt", stdin);
#endif
int n;
scanf("%d", &n);
for(int i = 0; i < n - 1; i++) {
int par;
scanf("%d", &par);
g[par - 1].push_back(i + 1);
}
dfs(0);
tdfs(0);
forn(i, n) {
if (i > 0) printf(" ");
printf("%d", ans[i]);
}
}
|
543
|
E
|
Listening to Music
|
Please note that the memory limit differs from the standard.
You really love to listen to music. During the each of next $s$ days you will listen to exactly $m$ songs from the playlist that consists of exactly $n$ songs. Let's number the songs from the playlist with numbers from $1$ to $n$, inclusive. The quality of song number $i$ is $a_{i}$.
On the $i$-th day you choose some integer $v$ ($l_{i} ≤ v ≤ r_{i}$) and listen to songs number $v, v + 1, ..., v + m - 1$. On the $i$-th day listening to one song with quality less than $q_{i}$ increases your displeasure by exactly one.
Determine what minimum displeasure you can get on each of the $s$ next days.
|
Let's sort all songs in decreasing order. We will iterate over songs, and each time we will say, that now current song will fully satisfy our conditions. So, let's $s_{i} = 0$, is song $i$ was not processed yet and $s_{i} = 1$ otherwise. Let $v_{i}=\sum_{i=i}^{j=i+m-1}s_{j}$. It's clear, when we add new song in position $idx$ then we should do $+ 1$ for all on segment $[max(0, idx - m + 1), idx]$ in our array $v$. So, when we need to implement some data structure, which can restore our array $v$ to the position when all strings have quality $ \ge q$. It also should use very small amout of memory. So, answer to the query will be $m - max(v_{i})$, $l_{j} \le i \le r_{j}$. We will store this data structure in the following way. Let's beat all positions of songs in blocks of length $\sqrt{n}$. Each time, when we added about $\sqrt{n}$ songs as good, we will store three arrays: first array will contain value $v_{i}$ of first element of the block of indices. second array will contain maximum value of $v$ on each block and also we will keep about $2{\sqrt{n}}$ of ''small'' updates which doesn't cover full block. Using this information array $v$ will be restored and we process current query in easy way.
|
[
"constructive algorithms",
"data structures"
] | 3,200
|
#include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define sz(a) int((a).size())
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define mp make_pair
#define sc second
#define ft first
using namespace std;
const int M = 512;
const int N = M * M;
int blvalue[M][M];
int ftvalue[M][M];
int exvalue[M][2 * M];
int a[N];
pair<int, int> na[N];
int va[N];
int push[M];
int bl[M];
int n, m;
int blcount;
const int mult = 9;
const int blsz = (1 << mult);
inline bool is_first(int idx) {
return (idx & (blsz - 1)) == 0;
}
inline int bl_idx(int idx) {
if (idx >= n) {
return (idx >> mult) + 1;
}
return idx >> mult;
}
inline int first_idx(int blid) {
return blid << mult;
}
inline int last_idx(int blid) {
return min(n - 1, first_idx(blid) + blsz - 1);
}
const int INF = 1000 * 1000 * 1000;
int main()
{
#ifdef gridnevvvit
freopen("input.txt", "rt", stdin);
#endif
scanf("%d %d", &n, &m);
blcount = (n + blsz - 1) / blsz;
forn(i, n) scanf("%d", &a[i]);
forn(i, n)
na[i] = mp(-a[i], i);
sort(na, na + n);
forn(iter, n) {
if (is_first(iter)){
int curbl = bl_idx(iter);
forn(i, n)
va[i] = va[i] + push[bl_idx(i)];
forn(i, blcount) {
bl[i] += push[i];
blvalue[curbl][i] = bl[i];
ftvalue[curbl][i] = va[first_idx(i)];
push[i] = 0;
}
}
int r = na[iter].sc;
int l = max(0, r - m + 1);
int blocks[] = {blcount, blcount};
int szb = 0;
for(int i = l; i <= r; ) {
int curbl = bl_idx(i);
if (is_first(i) && last_idx(curbl) <= r) {
push[curbl] ++;
i = last_idx(curbl) + 1;
} else {
va[i]++;
bl[curbl] = max(bl[curbl], va[i]);
if (szb == 0 || blocks[szb - 1] != curbl) {
blocks[szb++] = curbl;
}
i++;
}
}
szb = 2;
int curbl = bl_idx(iter);
int idx = iter - first_idx(curbl);
forn(i, szb) {
exvalue[curbl][2 * idx + i] = (bl[blocks[i]] << mult) + blocks[i];
}
}
int query;
scanf("%d", &query);
int last_ans = 0;
forn(it, query) {
int l, r, q;
scanf("%d %d %d", &l, &r, &q); l--, r--;
q ^= last_ans;
int idx = upper_bound(na, na + n, mp(-q, INF)) - na;
idx--;
if (idx < 0) {
printf("%d\n", m);
last_ans = m;
continue;
}
int curbl = bl_idx(idx);
forn(i, blcount) {
bl[i] = blvalue[curbl][i];
push[i] = 0;
}
int ft = first_idx(curbl);
for(int i = ft; i <= idx; i++) {
int nr = na[i].sc;
int nl = max(0, nr - m + 1);
if (nl != first_idx(bl_idx(nl))) {
nl = last_idx(bl_idx(nl)) + 1;
}
if (nr == last_idx(bl_idx(nr))){
nr++;
}
if (bl_idx(nl) <= bl_idx(nr)) {
push[bl_idx(nl)] ++;
push[bl_idx(nr)] --;
}
forn(j, 2) {
int blid = exvalue[curbl][2 * (i - ft) + j];
int vt = blid >> mult;
blid &= (blsz - 1);
bl[blid] = vt;
}
}
forn(i, blcount) {
if (i > 0) push[i] += push[i - 1];
}
int maxAns = 0;
int pv = -1;
for(int i = l; i <= r; ) {
int blid = bl_idx(i);
if (is_first(i) && last_idx(blid) <= r) {
maxAns = max(maxAns, bl[blid] + push[blid]);
i = last_idx(blid) + 1;
pv = -1;
} else {
if (pv == -1) {
pv = ftvalue[curbl][blid];
int ftp = first_idx(blid);
for(int j = ft; j <= idx; j++) {
if (ftp <= na[j].sc && ftp >= max(na[j].sc - m + 1, 0)) {
pv++;
}
}
while (ftp != i) {
pv -= (a[ftp] >= q);
pv += (a[ftp + m] >= q);
ftp++;
}
}
maxAns = max(maxAns, pv);
pv -= (a[i] >= q);
pv += (a[i + m] >= q);
i++;
}
}
maxAns = m - maxAns;
printf("%d\n", maxAns);
last_ans = maxAns;
}
}
|
544
|
A
|
Set of Strings
|
You are given a string $q$. A sequence of $k$ strings $s_{1}, s_{2}, ..., s_{k}$ is called beautiful, if the concatenation of these strings is string $q$ (formally, $s_{1} + s_{2} + ... + s_{k} = q$) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
|
In that task you need to implement what was written in the statements. Let's iterate over all characters of string and keep array $used$. Also let's keep current string. If current character was not used previously, then let's put current string to the answer and after that we need to clear current string. Otherwise, let's append current character to the current string. If array, that contain answer will have more then $k$ elements, we will concatenate few last strings.
|
[
"implementation",
"strings"
] | 1,100
|
k = input()
s = raw_input()
ans = []
cur = ""
used = set()
for i in range(len(s)):
if s[i] not in used:
if len(cur) > 0:
ans.append(cur)
cur = ""
cur += s[i]
used.add(s[i])
else:
cur += s[i]
ans.append(cur)
if len(ans) < k:
print("NO")
else:
print("YES")
for i in range(k, len(ans)):
ans[k - 1] += ans[i]
for i in range(k):
print(ans[i])
|
544
|
B
|
Sea and Islands
|
A map of some object is a rectangular field consisting of $n$ rows and $n$ columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly $k$ islands appear on the map. We will call a set of sand cells to be \textbf{island} if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).
Find a way to cover some cells with sand so that exactly $k$ islands appear on the $n × n$ map, or determine that no such way exists.
|
It's clear to understand, that optimal answer will consists of simple cells, for which following condition fullfills: the sum of indices of row and column is even. We will try to put $k$ islands in such way, and if it's impossible, we will report that answer is NO. Try to prove that this solution is optimal.
|
[
"constructive algorithms",
"implementation"
] | 1,400
|
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
int main() {
int n, k;
scanf("%d %d", &n, &k);
if (n == 5 && k == 2) {
puts("YES");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if (i & 1) printf("L");
else printf("S");
}
puts("");
}
return 0;
}
vector < string > ans(n, "");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++) {
int sum = (i + j) & 1;
if (sum == 0 && k > 0) {
ans[i] += "L";
k --;
} else {
ans[i] += "S";
}
}
}
if (k == 0) {
puts("YES");
for(int i = 0; i < n; i++)
puts(ans[i].c_str());
} else {
puts("NO");
}
}
|
545
|
A
|
Toy Cars
|
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are $n$ toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an $n × n$ matrix $А$: there is a number on the intersection of the $і$-th row and $j$-th column that describes the result of the collision of the $і$-th and the $j$-th car:
- $ - 1$: if this pair of cars never collided. $ - 1$ occurs only on the main diagonal of the matrix.
- $0$: if no car turned over during the collision.
- $1$: if only the $i$-th car turned over during the collision.
- $2$: if only the $j$-th car turned over during the collision.
- $3$: if both cars turned over during the collision.
Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?
|
We can find all information about $i$-th car collisions in the $i$-th row of the matrix $A$. More specific, if there is at least one 1 or 3 at $i$-th row, then $i$-th car isn't good (it was turned over in at least one collision). Otherwise, $i$-th car is good. We just need to check this condition for each car.
|
[
"implementation"
] | 900
| null |
545
|
B
|
Equidistant String
|
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:
We will define the distance between two strings $s$ and $t$ of the same length consisting of digits zero and one as the number of positions $i$, such that $s_{i}$ isn't equal to $t_{i}$.
As besides everything else Susie loves symmetry, she wants to find for two strings $s$ and $t$ of length $n$ such string $p$ of length $n$, that the distance from $p$ to $s$ was equal to the distance from $p$ to $t$.
It's time for Susie to go to bed, help her find such string $p$ or state that it is impossible.
|
One can see, that if $s_{i} = t_{i}$ for some $i$, then the value of $p_{i}$ isn't important for us. Really, if we make $p_{i}$ equal to $s_{i}$ then it also be equal to $t_{i}$. And if we make $p_{i}$ not equal to $s_{i}$ then it also be not equal to $t_{i}$. So, we have an answer that is closer or further to both of s and t. So we interested about such position $i$ that $s_{i} \neq t_{i}$. If we make $p_{i}$ equal to $s_{i}$ we make $p$ further from $t$. If we make $p_{i}$ equal to $t_{i}$ we make $p$ further from $s$. It means that we need to divide these positions into two equal parts to have equidistant string. For example, we can make first of these positions closer to $s$, second closer to $t$ and so on. If the number of these positions is even, we find an answer, if it is odd, answer doesn't exist. Time complexity - $O(n)$.
|
[
"greedy"
] | 1,100
| null |
545
|
C
|
Woodcutters
|
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are $n$ trees located along the road at points with coordinates $x_{1}, x_{2}, ..., x_{n}$. Each tree has its height $h_{i}$. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments $[x_{i} - h_{i}, x_{i}]$ or $[x_{i};x_{i} + h_{i}]$. The tree that is not cut down occupies a single point with coordinate $x_{i}$. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
|
One can solve this problem using dynamic programming or greedy algorithm. Start with DP solution. Define $stay_{i}$, $left_{i}$ and $right_{i}$ as maximal count of trees that woodcutters can fell, if only trees with number from $1$ to $i$ exist, and $i$-th tree isn't cutted down, $i$-th tree is cutted down and fallen left, $i$-th tree is cutted down and fallen right correspondingly. Now we can compute this values for each $i$ from $1$ to $n$ by $O(n)$ time because for each next we need only two previous value. Answer is maximum of $stay_{n}$, $left_{n}$, $right_{n}$. Also this problem can be solved by the next greedy algoritm. Let's fell leftmost tree to the left (it always doesn't make an answer worse). After that, try to fell the next tree. If we can fell it to the left, let's do it (because it also always doesn't make an answer worse). If we can't, then try to fell it to the right. If it is possible, let's do it. Last step is correct because felling some tree to the right may only prevent the next tree's fallen. So we may "exchange" one tree to another without worsing an answer. Time complexity - $O(n)$.
|
[
"dp",
"greedy"
] | 1,500
| null |
545
|
D
|
Queue
|
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are $n$ people in the queue. For each person we know time $t_{i}$ needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
|
We can solve this problem by greedy algorithm. Let's prove that it is always possible find an answer (queue with the maximal number of not disappointed people), where all not disappointed people are at the begin of queue. Assume the contrary - there are two position $i$ and $j$ such that $i < j$, persons at position from $i$ to $j - 1$ are disappointed, but $j$-th person isn't. Then just swap persons at positions $i$ and $j$. After that all persons from $i$ to $j - 1$ will be still disappointed (or become not disappointed) and $j$-th person will be still not disappointed. So the answer isn't maked worse. So, we need to find person with minimal $t_{i}$, that can be served now and will be not disappointed. We can do that by sorting all the people by time $t_{i}$ and try to serve them one by one. If somebody will be disappointed, we may send he to the end of queue, and doesn't add his serve time to the waiting time. Time complexity - $O(n + sort)$.
|
[
"greedy",
"implementation",
"sortings"
] | 1,300
| null |
545
|
E
|
Paths and Trees
|
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.
Let's assume that we are given a \textbf{connected} weighted undirected graph $G = (V, E)$ (here $V$ is the set of vertices, $E$ is the set of edges). The shortest-path tree from vertex $u$ is such graph $G_{1} = (V, E_{1})$ that is a tree with the set of edges $E_{1}$ that is the subset of the set of edges of the initial graph $E$, and the lengths of the shortest paths from $u$ to any vertex to $G$ and to $G_{1}$ are the same.
You are given a \textbf{connected} weighted undirected graph $G$ and vertex $u$. Your task is to find the shortest-path tree of the given graph from vertex $u$, the total weight of whose edges is minimum possible.
|
It's true, that Dijkstra modification, where in case of equal distances we take one with shorter last edge, find an answer. For prove that let's do some transformation with graph. At first, find all shortest paths from $u$ to other vertices. Define $d_{i}$ as the length of shortest path from $u$ to $i$. After that, we can delete some edges. Specifically, we can delete an edge with ends in $x$ and $y$ and weight $w$ if $|d_{x} - d_{y}| \neq w$, because it isn't contained in any shortest path, so it isn't contained in shortest path tree. After that, we can direct all edges from vertices with less distance to vertices with greater distance (because of all weight are positive). It's easy to prove, that if we take one edge that entering each vertex, we have a shortest path tree. Then we only need to take for each vertex minimal egde, that entering this vertex. Why? Because we have to take at least one edge, that entering each vertex to make a graph connected. We can't take edges with less weights than minimal. And if we take minimal edges, that entering each vertex we will have an shortest path tree. So that is minimal possible total wieght of shortest path tree. You can see, that Dijkstra with modification do exactly the same things. Time complexity - $O(m\log n)$
|
[
"graphs",
"greedy",
"shortest paths"
] | 2,000
| null |
546
|
A
|
Soldier and Bananas
|
A soldier wants to buy $w$ bananas in the shop. He has to pay $k$ dollars for the first banana, $2k$ dollars for the second one and so on (in other words, he has to pay $i·k$ dollars for the $i$-th banana).
He has $n$ dollars. How many dollars does he have to borrow from his friend soldier to buy $w$ bananas?
|
We can easily calculate the sum of money that we need to buy all the bananas that we want, let's name it x. If n > = x the answer is 0, because we don't need to borrow anything. Otherwise the answer is x - n.
|
[
"brute force",
"implementation",
"math"
] | 800
| null |
546
|
B
|
Soldier and Badges
|
Colonel has $n$ badges. He wants to give one badge to every of his $n$ soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors.
Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.
|
Let's count the number of badges with coolness factor 1, 2 and so on. Then, let's look at the number of badges with value equal to 1. If it's greater than 1, we have to increase a value of every of them except for one. Then, we look at number of badges with value 2, 3 and so on up to 2n - 2 (because maximum value of badge which we can achieve is 2n - 1). It is easy to see that this is the correct solution. We can implement it in O(n), but solutions that work in complexity O(n^2) also passed.
|
[
"brute force",
"greedy",
"implementation",
"sortings"
] | 1,200
| null |
546
|
C
|
Soldier and Cards
|
Two bored soldiers are playing card war. Their card deck consists of exactly $n$ cards, numbered from $1$ to $n$, \textbf{all values are different}. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins.
You have to calculate how many fights will happen and who will win the game, or state that game won't end.
|
It's easy to count who wins and after how many "fights", but it's harder to say, that game won't end. How to do it? Firstly let's count a number of different states that we can have in the game. Cards can be arranged in any one of n! ways. In every of this combination, we must separate first soldier's cards from the second one's. We can separate it in n + 1 places (because we can count the before and after deck case too). So war has (n + 1)! states. If we'd do (n + 1)! "fights" and we have not finished the game yes, then we'll be sure that there is a state, that we passed at least twice. That means that we have a cycle, and game won't end. After checking this game more accurately I can say that the longest path in the state-graph for n = 10 has length 106, so it is enough to do 106 fights, but solutions that did about 40 millions also passed. Alternative solution is to map states that we already passed. If we know, that we longest time needed to return to state is about 100, then we know that this solution is correct and fast.
|
[
"brute force",
"dfs and similar",
"games"
] | 1,400
| null |
546
|
D
|
Soldier and Number Game
|
Two soldiers are playing a game. At the beginning first of them chooses a positive integer $n$ and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer $x > 1$, such that $n$ is divisible by $x$ and replacing $n$ with $n / x$. When $n$ becomes equal to $1$ and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.
To make the game more interesting, first soldier chooses $n$ of form $a! / b!$ for some positive integer $a$ and $b$ ($a ≥ b$). Here by $k!$ we denote the factorial of $k$ that is defined as a product of all positive integers not large than $k$.
What is the maximum possible score of the second soldier?
|
Firstly we have to note, that second soldier should choose only prime numbers. If he choose a composite number x that is equal to p * q, he can choose first p, then q and get better score. So our task is to find a number of prime factors in factorization of n. Now we have to note that factorization of number a! / b! is this same as factorization of numbers (b + 1)*(b + 2)*...*(a - 1)*a. Let's count number of prime factor in factorization of every number from 2 to 5000000. First, we use Sieve of Eratosthenes to find a prime diviser of each of these numbers. Then we can calculate a number of prime factors in factorization of a using the formula: primefactors[a] = primefactors[a / primediviser[a]] + 1 When we know all these numbers, we can use a prefix sums, and then answer for sum on interval.
|
[
"constructive algorithms",
"dp",
"math",
"number theory"
] | 1,700
| null |
546
|
E
|
Soldier and Traveling
|
In the country there are $n$ cities and $m$ bidirectional roads between them. Each city has an army. Army of the $i$-th city consists of $a_{i}$ soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at \textbf{moving along at most one road}.
Check if is it possible that after roaming there will be exactly $b_{i}$ soldiers in the $i$-th city.
|
There are few ways to solve this task, but I'll describe the simplest (in my opinion) one. Let's build a flow network in following way: Make a source. Make a first group of vertices consisting of n vertices, each of them for one city. Connect a source with ith vertex in first group with edge that has capacity ai. Make a sink and second group of vertices in the same way, but use bi except for ai. If there is a road between cities i and j or i = j. Make two edges, first should be connecting ith vertex from first group, and jth vertex from second group, and has infinity capacity. Second should be similar, but connect jth from first group and ith from second group. Then find a maxflow, in any complexity. If maxflow is equal to sum of ai and is equal to sum of bi, then there exists an answer. How can we get it? We just have to check how many units are we pushing through edge connecting two vertices from different groups. I told about many solutions, because every solution, which doesn't use greedy strategy, can undo it's previous pushes, and does it in reasonable complexity should pass.
|
[
"flows",
"graphs",
"math"
] | 2,100
| null |
547
|
A
|
Mike and Frog
|
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time $0$), height of Xaniar is $h_{1}$ and height of Abol is $h_{2}$. Each second, Mike waters Abol and Xaniar.
So, if height of Xaniar is $h_{1}$ and height of Abol is $h_{2}$, after one second height of Xaniar will become $(x_{1}h_{1}+y_{1})\bmod m$ and height of Abol will become $(x_{2}h_{2}+y_{2})\bmod m$ where $x_{1}, y_{1}, x_{2}$ and $y_{2}$ are some integer numbers and $a\,\mathrm{mod}\,b$ denotes the remainder of $a$ modulo $b$.
Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is $a_{1}$ and height of Abol is $a_{2}$.
Mike has asked you for your help. Calculate the minimum time or say it will never happen.
|
In this editorial, consider $p = m$, $a = h_{1}$, $a' = a_{1}$, $b = h_{2}$ and $b' = a_{2}$, $x = x_{1}$, $y = y_{1}$, $X = x_{2}$ and $Y = y_{2}$. First of all, find the number of seconds it takes until height of Xaniar becomes $a'$ (starting from $a$) and call it $q$. Please note that $q \le p$ and if we don't reach $a'$ after $p$ seconds, then answer is $- 1$. If after $q$ seconds also height of Abol will become equal to $b'$ then answer if $q$. Otherwise, find the height of Abdol after $q$ seconds and call it $e$. Then find the number of seconds it takes until height of Xaniar becomes $a'$ (starting from $a'$) and call it $c$. Please note that $c \le p$ and if we don't reach $a'$ after $p$ seconds, then answer is $- 1$. if $g(x) = Xx + Y$, then find $f(x) = g(g(...(g(x))))$ ($c$ times). It is really easy: Then, Actually, if height of Abol is $x$ then, after $c$ seconds it will be $f(x)$. Then, starting from $e$, find the minimum number of steps of performing e = f(e) it takes to reach $b'$ and call it $o$. Please note that $o \le p$ and if we don't reach $b'$ after $p$ seconds, then answer is $- 1$. Then answer is $x + c \times o$. Time Complexity: ${\cal O}(p)$
|
[
"brute force",
"greedy",
"implementation",
"math"
] | 2,200
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
int a[2], b[2], x[3], y[3], p;
inline int nex(int c, int w){
return (1LL * c * x[w] + y[w])%p;
}
int main(){
iOS;
cin >> p;
For(i,0,2){
if(!i)
cin >> a[0] >> a[1];
else
cin >> b[0] >> b[1];
cin >> x[i] >> y[i];
}
ll ans = 0LL;
while(a[0] != a[1] && ans < p + 20){
++ ans;
a[0] = nex(a[0], 0);
b[0] = nex(b[0], 1);
}
if(a[0] != a[1]){
cout << -1 << endl;
return 0;
}
if(a[0] == a[1] && b[0] == b[1]){
cout << ans << endl;
return 0;
}
int o = 0;
int cur = a[0];
x[2] = x[1], y[2] = y[1];
x[1] = 1, y[1] = 0;
do{
cur = nex(cur, 0);
++ o;
x[1] = (1LL * x[1] * x[2]) % p;
y[1] = (1LL * y[1] * x[2]) % p;
y[1] = (1LL * y[1] + y[2]) % p;
}while(o < p + 10 && cur != a[1]);
if(cur != a[1]){
cout << -1 << endl;
return 0;
}
int O = 0;
cur = b[0];
do{
cur = nex(cur, 1);
++ O;
}while(O < p + 10 && cur != b[1]);
if(cur != b[1]){
cout << -1 << endl;
return 0;
}
ans += 1LL * o * O;
cout << ans << endl;
}
|
547
|
B
|
Mike and Feet
|
Mike is the president of country What-The-Fatherland. There are $n$ bears living in this country besides Mike. All of them are standing in a line and they are numbered from $1$ to $n$ from left to right. $i$-th bear is exactly $a_{i}$ feet high.
A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.
Mike is a curious to know for each $x$ such that $1 ≤ x ≤ n$ the maximum strength among all groups of size $x$.
|
For each $i$, find the largest $j$ that $a_{j} < a_{i}$ and show it by $l_{i}$ (if there is no such $j$, then $l_{i} = 0$). Also, find the smallest $j$ that $a_{j} < a_{i}$ and show it by $r_{i}$ (if there is no such $j$, then $r_{i} = n + 1$). This can be done in $O(n)$ with a stack. Pseudo code of the first part (second part is also like that) : Consider that you are asked to print $n$ integers, $ans_{1}, ans_{2}, ..., ans_{n}$. Obviously, $ans_{1} \ge ans_{2} \ge ... \ge ans_{n}$. For each $i$, we know that $a_{i}$ can be minimum element in groups of size $1, 2, ..., r_{i} - l_{i} - 1$. Se we need a data structure for us to do this: We have array $ans_{1}, ans_{2}, ..., ans_{n}$ and all its elements are initially equal to $0$. Also, $n$ queries. Each query gives $x, val$ and want us to perform $ans_{1} = max(ans_{1}, val), ans_{2} = max(ans_{2}, val), ..., ans_{x} = max(ans_{x}, val)$. We want the final array. This can be done in $O(n)$ with a maximum partial sum (keeping maximum instead of sum), read here for more information about partial sum. Time complexity: ${\mathcal{O}}(n)$.
|
[
"binary search",
"data structures",
"dp",
"dsu"
] | 1,900
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 1e6 + 100;
int a[maxn], n, l[maxn], r[maxn], ans[maxn];
stack<int> s;
int main(){
scanf("%d", &n);
For(i,0,n)
scanf("%d", a + i);
fill(l, l + maxn, -1);
fill(r, r + maxn, n);
For(i,0,n){
while(!s.empty() && a[s.top()] >= a[i])
s.pop();
if(!s.empty())
l[i] = s.top();
s.push(i);
}
while(!s.empty())
s.pop();
rof(i,n-1,-1){
while(!s.empty() && a[s.top()] >= a[i])
s.pop();
if(!s.empty())
r[i] = s.top();
s.push(i);
}
For(i,0,n){
int len = r[i] - l[i] - 1;
smax(ans[len], a[i]);
}
rof(i,n,-1)
smax(ans[i], ans[i+1]);
For(i,1,n+1)
printf("%d ", ans[i]);
cout << endl;
return 0;
}
|
547
|
C
|
Mike and Foam
|
Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are $n$ kinds of beer at Rico's numbered from $1$ to $n$. $i$-th kind of beer has $a_{i}$ milliliters of foam on it.
Maxim is Mike's boss. Today he told Mike to perform $q$ queries. Initially the shelf is empty. In each request, Maxim gives him a number $x$. If beer number $x$ is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf.
After each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs $(i, j)$ of glasses in the shelf such that $i < j$ and $\operatorname*{gcd}(a_{i},a_{j})=1$ where $\operatorname*{gcd}(a,b)$ is the greatest common divisor of numbers $a$ and $b$.
Mike is tired. So he asked you to help him in performing these requests.
|
We define that a number $x$ is good if and only if there is no $y > 1$ that $y^{2}$ is a divisor of $x$. Also, we define function $f(x)$ as follow: Consider $x = p_{1}^{a1} \times p_{2}^{a2} \times ... \times p_{k}^{ak}$ where all $p_{i}$s are prime. Then, $f(x) = a_{1} + a_{2} + ... + a_{n}$. Use simple inclusion. Consider all the primes from $1$ to $5 \times 10^{5}$ are $p_{1}, p_{2}, ..., p_{k}$. So, after each query, if $d(x)$ is the set of beers like $i$ in the shelf that $x$ is a divisor of $a_{i}$, then number of pairs with $gcd$ equal to 1 is: $\begin{array}{c}{{|d(1)|-|d(p_{1})\cap d(p_{2})|-|d(p_{3})|\neg|d(p_{3})|-...-|d(p_{k-1})\cap d(p_{3})|+|d(p_{1})\cap d(p_{2})\Gamma.}}\\ {{d(p_{3})|+...=|d(p_{1})|-|d(p_{1}p_{2})|-|d(p_{1}p_{3})|-...-|d(p_{k-1}p_{k})|+|d(p_{1}p_{2}p_{3})|+...}}\end{array}$ Consider good numbers from $1$ to $5 \times 10^{5}$ are $b_{1}, b_{2}, ..., b_{m}$. The above phrase can be written in some other way: $|d(b_{1})| \times ( - 1)^{f(b1)} + |d(b_{2})| \times ( - 1)^{f(b2)} + ... + |d(b_{m})| \times ( - 1)^{f(bm)}$. So, for each query if we can find all good numbers that $a_{i}$ is divisible by them in a fast way, we can solve the rest of the problem easily (for each good number $x$, we can store $|d(x)|$ in an array and just update this array and update the answer). Since all numbers are less than $2 \times 3 \times 5 \times 7 \times 11 \times 13 \times 17$, then there are at most $6$ primes divisible buy $a_{i}$. With a simple preprocesses, we can find their maximum and so easily we can find these (at most 6) primes fast. If their amount is $x$, then there are exactly $2^{x}$ good numbers that $a_{i}$ is divisible by them (power of each prime should be either $0$ or $1$). So we can perform each query in $O(2^{6})$ Time complexity: $O(q\times2^{6})$.
|
[
"bitmasks",
"combinatorics",
"dp",
"math",
"number theory"
] | 2,300
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 1e6 + 10;
int lsp[maxn], cnt[maxn];
ll ans = 0LL;
int a[maxn], p[10], nx, bp[256], dp[256], lb[256], tp[256];
inline void upd(int x, int sgn){
nx = 0;
int a;
while(x > 1){
a = lsp[x];
p[nx ++] = a;
while(x % a == 0)
x /= a;
}
For(mask,0,tp[nx]){
if(mask)
dp[mask] = p[lb[mask]] * dp[mask ^ tp[lb[mask]]];
else
dp[mask] = 1;
if(sgn < 0)
cnt[dp[mask]] += sgn;
if(bp[mask] % 2)
ans += -1LL * sgn * cnt[dp[mask]];
else
ans += +1LL * sgn * cnt[dp[mask]];
if(sgn > 0)
cnt[dp[mask]] += sgn;
}
}
bool in[maxn];
int n, q;
int main(){
memset(lsp, -1, sizeof lsp);
For(i,0,256){
tp[i] = (1 << i);
bp[i] = __builtin_popcount(i);
lb[i] = __builtin_ctz(i);
}
For(i,2,maxn)
if(lsp[i] == -1)
for(int j = i;j < maxn;j += i)
lsp[j] = i;
scanf("%d %d", &n, &q);
For(i,0,n)
scanf("%d", a + i);
while(q--){
int i;
scanf("%d", &i);
-- i;
if(!in[i])
upd(a[i], +1);
else
upd(a[i], -1);
in[i] = !in[i];
printf("%lld\n", ans);
}
}
|
547
|
D
|
Mike and Fish
|
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.
He has marked $n$ distinct points in the plane. $i$-th point is point $(x_{i}, y_{i})$. He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.
He can't find a way to perform that! Please help him.
|
Consider a bipartite graph. In each part (we call them first and second part) there are $L = 2 \times 10^{5}$ vertices numbered from $1$ to $L$. For each point $(x, y)$ add an edge between vertex number $x$ from the first part and vertex number $y$ from the second part. In this problem, we want to color edges with two colors so that the difference between the number of blue edges connected to a vertex and the number of red edges connected to it be at most 1. Doing such thing is always possible. We prove this and solve the problem at the same time with induction on the number of edges : If all vertices have even degree, then for each component there is an Eulerian circuit, find it and color the edges alternatively_ with blue and red. Because graph is bipartite, then our circuit is an even walk and so, the difference between the number of blue and red edges connected to a vertex will be 0. Otherwise, if a vertex like $v$ has odd degree, consider a vertex like $u$ that there is and edge between $v$ and $u$. Delete this edge and solve the problem for the rest of the edges (with the induction definition) and then add this edge and if the number of red edges connected to $u$ is more than the blue ones, then color this edge with blue, otherwise with red. You can handle this add/delete edge requests and find odd vertices with a simple set. So, Time complexity: $O((n+L)\log(L+n))$
|
[
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,600
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 2e5 + 10;
vi adj[maxn * 2];
int x[maxn * 2];
map <pii, int> mp;
map <pii, bool> del;
vector<int> eu;
set<int> d[2];
int deg[maxn * 2];
vector<pii> edges;
inline void euler(int v){
while(!adj[v].empty()){
int u = adj[v].back();
adj[v].PB;
if(!del[{v, u}]){
del[{v, u}] = del[{u, v}] = true;
euler(u);
}
}
eu.pb(v);
}
inline void deledge(int v,int u){
del[{v, u}] = true;
del[{u, v}] = true;
d[deg[v]].erase(v);
deg[v] = !deg[v];
d[deg[v]].insert(v);
d[deg[u]].erase(u);
deg[u] = !deg[u];
d[deg[u]].insert(u);
}
inline void solve(){
if(d[1].empty()){
For(i,0,maxn * 2){
eu.clear();
euler(i);
For(j,1,eu.size())
mp[{eu[j], eu[j-1]}] = mp[{eu[j-1], eu[j]}] = j % 2;
}
}
else{
int v = *d[1].begin();
while(!adj[v].empty() && del[{v, adj[v].back()}])
adj[v].PB;
int u = adj[v].back();
deledge(v, u);
solve();
int c = 0;
if(x[u] > 0)
c = 1;
if(c == 1)
x[u] --, x[v] --;
else
x[u] ++, x[v] ++;
mp[{v, u}] = mp[{u, v}] = c;
}
}
int n;
string s = "rb";
int main(){
scanf("%d", &n);
For(i,0,n){
int x, y;
scanf("%d %d", &x, &y);
-- x, -- y;
x = 2 * x + 1;
y = 2 * y;
edges.pb({x, y});
adj[x].pb(y);
adj[y].pb(x);
}
For(i,0,2*maxn)
d[(int)adj[i].size() % 2].insert(i), deg[i] = adj[i].size() % 2;
solve();
rep(e, edges)
printf("%c", (char)s[mp[{e.x, e.y}]]);
puts("");
}
|
547
|
E
|
Mike and Friends
|
What-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears!
In that country there is a rock band called CF consisting of $n$ bears (including Mike) numbered from $1$ to $n$.
Phone number of $i$-th member of CF is $s_{i}$. May 17th is a holiday named Phone Calls day. In the last Phone Calls day, everyone called all the numbers that are substrings of his/her number (one may call some number several times). In particular, everyone called himself (that was really strange country).
Denote as $call(i, j)$ the number of times that $i$-th member of CF called the $j$-th member of CF.
The geek Mike has $q$ questions that he wants to ask you. In each question he gives you numbers $l, r$ and $k$ and you should tell him the number
\[
\sum_{i=1}^{r}c a l l(i,k)
\]
|
$call(i, j) = match(s_{jins}_{i})$ which $match(tins)$ is the number of occurrences of $t$ in $s$. Concatenate all strings together in order (an put null character between them) and call it string $S$. We know that $|S|=\sum_{i=1}^{n}|s_{i}|+n-1$. Consider $N = 5 \times 10^{5}$. Consider Consider for each $i$, $S_{xi}s_{xi + 1}...s_{yi} = s_{i}$ ($x_{i + 1} = y_{i} + 2$). Also, for $i - th$ character of $S$ which is not a null character, consider it belongs to $s_{wi}$. Calculate the suffix array of $S$ in $(O(|S|\log(|S|))=O(N\log(N))$ and show it by $f_{1}, f_{2}, ..., f_{|S|}$ (we show each suffix by the index of its beginning). For each query, we want to know the number of occurrences of $s_{k}$ in $S_{xl}...s_{yr}$. For this propose, we can use this suffix array. Consider that we show suffix of $S$ starting from index $x$ by $S(x)$. Also, for each $i < |S|$, calculate $lcp(S(f_{i}), S(f_{i + 1}))$ totally in $O(N\log(N))$ and show it by $lc_{i}$. For each query, consider $f_{i} = x_{k}$, also find minimum number $a$ and maximum number $b$ (using binary search and sparse table on sequence $lc$) such that $a \le i \le b$ and $min(lc_{a}, lc_{a + 1}, ..., lc_{i - 1}) \ge |s_{k}|$ and $min(lc_{i}, lc_{i + 1}, ..., lc_{b - 1}) \ge |s_{k}|$. Finally answer of this query is the number of elements in $w_{a}, w_{a + 1}, ..., w_{b}$ that are in the interval $[l, r]$. This problem is just like KQUERY. You can read my offline approach for KQUERY here. It uses segment tree, but you can also use Fenwick instead of segment tree. This wasn't my main approach. My main approach uses aho-corasick and a data structure I invented and named it C-Tree. Time complexity: $O(n\log(n))$
|
[
"data structures",
"string suffix structures",
"strings",
"trees"
] | 2,800
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 5e5 + 100;
int TRIE[maxn][26];
string s[maxn];
int f[maxn], aut[maxn][26], root, nx = 1;
vi tof[maxn];
vi adj[maxn];
int end[maxn];
inline void build(int x){
int v = root;
rep(ch, s[x]){
int c = ch - 'a';
if(TRIE[v][c] == -1){
TRIE[v][c] = nx;
++ nx;
}
v = TRIE[v][c];
}
::end[x] = v;
}
inline void ahoc(){
f[root] = root;
queue<int> q;
q.push(root);
while(!q.empty()){
int v = q.front();
q.pop();
For(c,0,26){
if(TRIE[v][c] != -1){
aut[v][c] = TRIE[v][c];
if(v != root)
f[aut[v][c]] = aut[f[v]][c];
else
f[aut[v][c]] = root;
q.push(TRIE[v][c]);
}
else{
if(v == root)
aut[v][c] = root;
else
aut[v][c] = aut[f[v]][c];
}
}
}
}
inline void go(int x){
int v = root;
rep(ch, s[x]){
int c = ch - 'a';
v = aut[v][c];
tof[v].pb(x);
}
}
int par[maxn];
int st[maxn], ft[maxn];
int a[maxn], nex = 0;
inline void dfs(int v){
st[v] = nex;
rep(x, tof[v])
a[nex ++] = x;
rep(u, adj[v])
dfs(u);
ft[v] = nex;
}
struct query{
int l, r, k, ind, sgn;
query(){
l = r = k = 0;
}
query(int L,int R,int K,int IND,int SGN){l = L, r = R, k = K, ind = IND, sgn = SGN;}
bool operator < (const query &a) const{
if(k != a.k)
return k < a.k;
return pii(l, r) < pii(a.l, a.r);
}
};
pii p[maxn];
int fen[maxn];
inline void add(int x){
++ x;
for(int i = x;i < maxn;i += i & -i)
fen[i] ++;
}
inline int ask(int x){
++ x;
int res = 0;
for(int i = x;i > 0;i -= i & -i)
res += fen[i];
return res;
}
inline int ask(int l, int r){
return max(0, ask(r) - ask(l-1));
}
int answ[maxn];
vector<query> quer;
int lq[maxn], rq[maxn], kq[maxn];
char ch[maxn];
int main(){
memset(TRIE, -1, sizeof TRIE);
memset(par, -1, sizeof par);
int n, q;
scanf("%d %d", &n, &q);
For(i,0,n){
scanf("%s", ch);
s[i] = (string)ch;
build(i);
}
ahoc();
For(i,0,n)
go(i);
For(i,1,nx){
par[i] = f[i];
adj[par[i]].pb(i);
}
dfs(root);
For(i,0,q){
scanf("%d %d %d", lq + i, rq + i, kq + i);
-- kq[i];
kq[i] = ::end[kq[i]];
lq[i] --;
rq[i] --;
quer.pb(query(st[kq[i]], ft[kq[i]] - 1, lq[i] - 1, i, -1));
quer.pb(query(st[kq[i]], ft[kq[i]] - 1, rq[i], i, 1));
}
sort(all(quer));
For(i,0,nex)
p[i] = {a[i], i};
sort(p, p + nex);
int po = 0;
rep(q, quer){
int l = q.l;
int r = q.r;
int k = q.k;
while(po < nex && p[po].x <= k){
add(p[po].y);
po ++;
}
int ans = ask(l, r);
int ind = q.ind;
answ[ind] += q.sgn * ans;
}
For(i,0,q)
printf("%d\n", answ[i] );
}
|
548
|
A
|
Mike and Fax
|
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string $s$.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly $k$ messages in his own bag, each was a palindrome string and all those strings had the same length.
He asked you to help him and tell him if he has worn his own back-bag. Check if the given string $s$ is a concatenation of $k$ palindromes of the same length.
|
Consider characters of this string are number 0-based from left to right. If $|s|$ is not a multiply of $k$, then answer is "NO". Otherwise, let $l e n={\frac{\log}{\frac{\langle\pi\rangle}{k}}}$. Then answer is "Yes" if and only if for each $i$ that $0 \le i < |s|$, $s_{i} = s_{(i / len) * len + len - 1 - (i%len)}$ where $a%b$ is the remainder of dividing $a$ by $b$. Time complexity: $O(|s|)$.
|
[
"brute force",
"implementation",
"strings"
] | 1,100
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
int n, k;
string s;
int main(){
iOS;
cin >> s >> k;
n = s.size();
int len = n/k;
For(i,0,n)
if(n % k or s[i] != s[(i/len) * len + len - 1 - (i % len)]){
cout << "NO" << endl;
return 0;
}
cout << "YES" << endl;
return 0;
}
|
548
|
B
|
Mike and Fun
|
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an $n × m$ grid, there's exactly one bear in each cell. We denote the bear standing in column number $j$ of row number $i$ by $(i, j)$. Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.
They play for $q$ rounds. In each round, Mike chooses a bear $(i, j)$ and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.
Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.
Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
|
Consider this problem: We have a binary sequence $s$ and want to find the maximum number of consecutive 1s in it. How to solve this? Easily: Finally, answer to this problem is ans. For each row $r$ of the table, let $ans_{r}$ be the maximum number of consecutive 1s in it (we know how to calculate it in $O(m)$ right ?). So after each query, update $ans_{i}$ in $O(m)$ and then find $max(ans_{1}, ans_{2}, ..., ans_{n})$ in $O(n)$. Time complexity: ${\cal O}((n+m)q)$
|
[
"brute force",
"dp",
"greedy",
"implementation"
] | 1,400
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 500 + 10;
bool a[maxn][maxn];
int n, m, q;
int mx[maxn];
inline void calc(int i){
int cur = 0;
mx[i] = 0;
For(j,0,m){
if(a[i][j])
cur ++;
else
cur = 0;
smax(mx[i], cur);
}
}
int main(){
iOS;
cin >> n >> m >> q;
For(i,0,n)
For(j,0,m)
cin >> a[i][j];
For(i,0,n)
calc(i);
while(q--){
int i, j;
cin >> i >> j;
-- i, -- j;
a[i][j] = !a[i][j];
calc(i);
int ans = 0;
For(i,0,n)
smax(ans, mx[i]);
cout << ans << '\n';
}
}
|
549
|
A
|
Face Detection
|
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a $2 × 2$ square, such that from the four letters of this square you can make word "face".
You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.
|
One should iterate through each 2x2 square and check if it is possible to rearrange letters in such way they they form the word "face". It could be done i.e. by sorting all letters from the square in alphabetic order and comparing the result with the word "acef"(sorted letters of word "face").
|
[
"implementation",
"strings"
] | 900
| null |
549
|
B
|
Looksery Party
|
The Looksery company, consisting of $n$ staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message \textbf{to himself or herself}.
Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates $n$ numbers, the $i$-th of which indicates how many messages, in his view, the $i$-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.
You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.
|
In any cases there is such set of people that if they come on party and send messages to their contacts then each employee receives the number of messages that is different from what Igor pointed. Let's show how to build such set. There are 2 cases. There are no zeros among Igor's numbers. So if nobody comes on party then each employee receives 0 messages and, therefore, the desired set is empty. There is at least one zero. Suppose Igor thinks that i-th employee will receive 0 messages. Then we should add i-th employee in the desired set. He will send messages to his contacts and will receive 1 message from himself. If we add other employees in the desired set then the number of messages that i-th employee will receive will not decrease so we can remove him from considering. Igor pointed some numbers for people from contact list of i-th employee and because they have already received one message we need to decrease these numbers by one. After that we can consider the same problem but with number of employees equals to n - 1. If the remaining number of employees is equal to 0 then the desired set is built.
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | 2,300
| null |
549
|
C
|
The Game Of Parity
|
There are $n$ cities in Westeros. The $i$-th city is inhabited by $a_{i}$ people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly $k$ cities left.
The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.
Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.
|
If n = k no moves may be done. The winner is determined with starting parity of citizens' number. Otherwise let's see that the player making the last move may guarantee his victory, if there are both odd and even cities when he makes the move. He just selects the city of which parity he should burn to obtain required parity. So, his enemy's target is to destroy all the cities of some one type. Sometimes the type does matter, sometimes doesn't. It depends on the player's name and the parity of k. So the problem's solution consists in checking if "non-last" player's moves number (n - k) / 2 is enough to destroy all the odd or even cities. If Stannis makes the last move and k is even, Daenerys should burn all the odd or all the even cities. If k is odd, Daenerys should burn all the odd cities. If Daenerys makes the last move and k is even, Stannis has no chance to win. If k is odd, Stannis should burn all the even cities.
|
[
"games"
] | 2,200
| null |
549
|
D
|
Haar Features
|
The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.
Let's consider a rectangular image that is represented with a table of size $n × m$. The table elements are integers that specify the brightness of each pixel in the image.
A feature also is a rectangular table of size $n × m$. Each cell of a feature is painted black or white.
To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of $W - B$, where $W$ is the total brightness of the pixels in the image, covered with white feature cells, and $B$ is the total brightness of the pixels covered with black feature cells.
Some examples of the most popular Haar features are given below.
Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.
A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.
You have a variable $value$, whose value is initially zero. In one operation you can count the sum of pixel values at any prefix rectangle, multiply it by any integer and add to variable $value$.
You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.
|
This problem had a complicated statement but it is very similar to the real description of the features. Assume that we have a solution. It means we have a sequence of prefix-rectangles and coefficients to multiply. We can sort that sequence by the bottom-right corner of the rectangle and feature's value wouldn't be changed. Now we could apply our operations from the last one to the first. To calculate the minimum number of operations we will iterate through each pixel starting from the bottom-right in any of the column-major or raw-major order. For each pixel we will maintain the coefficient with which it appears in the feature's value. Initially it is 0 for all. If the coefficient of the current cell is not equal to + 1 for W and - 1 for B we increment the required amount of operations. Now we should make coefficient to have a proper value. Assume that it has to be X( - 1 or + 1 depends on the color) but current coefficient of this pixel is C. Then we should anyway add this pixel's value to the feature's value with the coefficient X - C. But the only way to add this pixel's value now(after skipping all pixels that have not smaller index of both row and column) is to get sum on the prefix rectangle with the bottom-left corner in this pixel. Doing this addition we also add X - C to the coefficient of all pixels in prefix-rectangle. This solution could be implemented as I describe above in $O(n^{2}m^{2})$ or $O(nm)$. Also I want to notice that in real Haar-like features one applies them not to the whole image but to the part of the image. Anyway, the minimum amount of operations could be calculated in the same way.
|
[
"greedy",
"implementation"
] | 1,900
| null |
549
|
E
|
Sasha Circle
|
Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has $n$ points, Sasha — $m$. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that the points of trade of one businessman are strictly inside a circle, and points of the other one are strictly outside. It doesn't matter which of the two gentlemen will have his trade points inside the circle.
Determine whether they can build a fence or not.
|
Author's solution has complexity $O((|A|+|B|)C^{\frac{2}{3}}+|A|l o g|A|+|B|l o g|B|)$, where $C$ is a maximum absolute value of the coordinates of all given points. Let's call a set of points $A$ and $B$ separable if there's a circle inside or on the boundary of which lie all the points of one set. When there're no points neither inside nor on the boundary of the circle we call this circle separating. Let points of the set $A$ lie inside or on the boundary of the circle and points of the set $B$ lie outside the circle. Points from set $A$ are allowed to be on the boundary of the separative circle as after increasing radius a little we're getting set $A$ strictly inside and set $B$ strictly outside the circle. Let $A$ contain at least two points. Separating circle can be compressed in such a way that it'll pass at least through two points of the set $A$. It's possible to look over all the pairs of points $p,q\in A$ and try to pass each pair through the separating circle. The centre of the desired circle lies on the medial perpendicular of the segment $pq$. Let's designate the points of the medial perpendicular as $l(t)$ where $t\in\mathbb{R}$ is a parameter. All the points that don't lie on the straight line $pq$ make parameter $t$ bounded above or below. All the points that lie on the straight line $pq$ have to lie outside the limits of the segment $pq$. E.g. a picture below displays a blue point which bounds the centre of separating circle from the left side and red points - from the right side. That's why the centre has to lie inside a segment $cd$. Let's look over all the points to make sure that a value $t$ which satisfies all the bounds exists. This provides us with the problem solving for $O((|A|^{2} + |B|^{2})(|A| + |B|))$. Let's examine paraboloid $z = x^{2} + y^{2}$ and draw arbitrary non-vertical plane $ax + by + z = c$. The intersection of the paraboloid and the plane satysfies the equation $ax + by + x^{2} + y^{2} = c$, or $\left(x+{\textstyle{\frac{1}{2}}}a\right)^{2}+\left(y+{\textstyle{\frac{1}{2}}}b\right)^{2}=c+{\textstyle{\frac{1}{4}}}(a^{2}+b^{2})$. If project points of the paraboloid $(x, y, x^{2} + y^{2})$ onto the plane $(x,y,x^{2}+y^{2})\mapsto(x,y)$ the cross-section of the paraboloid formed by the plane projects onto a circle, the paraboloid points below the plane projects onto internal points of the circle, those above the plane projects onto points outside the circle. As $(x,y,x^{2}+y^{2})\mapsto(x,y)$ is one-to-one correspondence the opposite is also true: when points of the plane project onto the paraboloid $(x,y)\mapsto(x,y,x^{2}+y^{2})$ the plane projects onto the cross-section of the paraboloid formed by the plane, the internal points - onto the paraboloid below the cross-section and external points - above the cross-section. So, projection of points onto paraboloid assigns one-to-one correspondence between circles and planes (non-vertical). partitioning of sets of points $A$ and $B$ of plane by circle can be done by means of partitioning of their three-dimensional projections into paraboloid $A'$ and $B'$ by non-vertical plane. Let's call such a plane separating (like separating circle, separating plane can include points from $A'$). By analogy with separating, circle separating plane can be passed through two points of set $A'$. All the other points of $A'$ will lie below or on the plane. In other words separating plane will pass through the edge of the upper convex hull of the set $A'$. The projection of edges of the upper convex hull $A'$ onto the plane $xOy$ will produce some sort of a set flat convex hull partitioning into $A$ by non-intersecting edges. In this case separating plane corresponds separating circle passing through the edge partition. Let's designate the convex hull $A$ as $coA$. In case when none of $4$ vertices $coA$ lies within one circle all the edges of the upper convex hull are triangles and the derived partitioning is triangulation. Otherwise the derived partitioning should be completed to be triangulation. To construct a separating circle look over triangulation edges and check the possibility of drawing a circle though an edge as it is described above. The derived triangulation has the following feature: circle drawn around any triangle contains the whole polygon $coA$ as the corresponding bound of three-dimensional convex hull is higher than all three-dimensional points $A'$. The described triangulation is "opposite" to the Delaunay triangulation according to which circle drawn around any triangle doesn't contain any points of the original set. This triangulation is commonly known as the Anti-Delaunay triangulation. Using the characterizing feature the Anti-Delaunay triangulation can be constructed by means of the method "divide and conquer" without transferring into three-dimensional space and working with points of plane and circles only. Let us triangulate polygon created by the vertices $coA$ when moving counter-clock-wise from $i$ to $j$. Let us find the third point of triangle, that will contain edge $(i, j)$. I.e such point $k$, that circumscribed circle over triangle $(i, j, k)$ contains the whole current polygon. For this purpose let's iterate through all polygon's vertices and select the one, that gives the extreme position of the center of the circumscribed circle lied on the mid-perpendicular of $(i, j)$. The circle will contain the whole polygon $coA$ as the edge $(i, j)$ is included in the Anti-Delaunay triangulation. Recursively triangulate polygons with vertices from $i$ to $k$ and from $k$ to $j$. The base of recursion is a segment, that shouldn't be triangulated. To solve the original problem one should swap $A$ and $B$ and perform the above procedure once more. Complexity of the algorithm is $O(|A|log|A| + |coA|(|coA| + |B|) + |B|log|B| + |coB|(|coB| + |A|)$=$O((|A|+|B|)C^{\frac{2}{3}}+|A|l o g|A|+|B|l o g|B|)$, where $C$ is a maximum absolute value of the coordinates of all given points. Actually, $O(C^{3 / 2})$ is an estimation of the number of points at a convex hull with no three points in a line.
|
[
"geometry",
"math"
] | 2,700
| null |
549
|
F
|
Yura and Developers
|
Yura has a team of $k$ developers and a list of $n$ tasks numbered from $1$ to $n$. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing \textbf{no less than 2 numbers}, i. e. a sequence of form $l, l + 1, ..., r$ for some $1 ≤ l < r ≤ n$.
Every task $i$ has an integer number $a_{i}$ associated with it denoting how many man-hours are required to complete the $i$-th task. Developers are not self-confident at all, and they are actually afraid of difficult tasks. Knowing that, Yura decided to pick up a hardest task (the one that takes the biggest number of man-hours to be completed, among several hardest tasks with same difficulty level he chooses arbitrary one) and complete it on his own. So, if tasks with numbers $[l, r]$ are chosen then the developers are left with $r - l$ tasks to be done by themselves.
Every developer can spend any integer amount of hours over any task, but when they are done with the whole assignment there should be exactly $a_{i}$ man-hours spent over the $i$-th task.
The last, but not the least problem with developers is that one gets angry if he works more than another developer. A set of tasks $[l, r]$ is considered good if it is possible to find such a distribution of work that allows to complete all the tasks and to have every developer working for the same amount of time (amount of work performed by Yura doesn't matter for other workers as well as for him).
For example, let's suppose that Yura have chosen tasks with following difficulties: $a = [1, 2, 3, 4]$, and he has three developers in his disposal. He takes the hardest fourth task to finish by himself, and the developers are left with tasks with difficulties $[1, 2, 3]$. If the first one spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours and every task has been worked over for the required amount of time. As another example, if the first task required two hours instead of one to be completed then it would be impossible to assign the tasks in a way described above.
Besides work, Yura is fond of problem solving. He wonders how many pairs $(l, r)$ ($1 ≤ l < r ≤ n$) exists such that a segment $[l, r]$ is good? Yura has already solved this problem, but he has no time to write the code. Please, help Yura and implement the solution for this problem.
|
Let's consider following solution: Let $f(l, r)$ be the solution for $[l, r]$ subarray. It's easy to see that $f(1, n)$ is the answer for the given problem. How should one count $f(l, r)$? Let $m$ be an index of the maximum value over subarray $[l, r]$. All the $good$ segments can be divided into two non-intersecting sets: those that contain $m$ and those that don't. To count the latter we can call $f(l, m - 1)$ and $f(m + 1, r)$. We are left with counting the number of subarrays that contain $m$, i.e. the number of pairs $(i, j)$ such that $l \le i < m < j \le r$ and $g(i, m - 1) + g(m + 1, j)%k = 0$ ($g(s, t)$ defines $a_{s} + a_{s + 1} + ... + a_{t})$. Let $s$ be the sequence of partial sums of the given array, i.e. $s_{i} = a_{1} + a_{2} + ... + a_{i}$. For every $j$ we are interested in the number of such $i$ that $s_{j} - s_{i} - a_{m}%k = 0$, so if we iterate over every possible $j$, then we are interested in number of $i$ that $s_{i} = s_{j} - a_{m}(modk)$ and $l \le i < m$. So we are left with simple query over the segment problem of form "how many numbers equal to $x$ and belong to a given segment $(l, r)$". It can be done in $O(q + k)$ time and memory, where $q$ is the number of generated queries. Model solution processes all the queries in offline mode, using frequency array. One can notice that in the worst case we can generate $O(n^{2})$ queries which doesn't fit into TL or ML. However, we can choose which is faster: iterate over all possible $j$ or $i$. In both cases we get an easy congruence which ends up as a query described above. If we iterate only over the smaller segment, every time we "look at" the element $w$ it moves to a smaller segment which is at least two times smaller than the previous one. So, every element will end up in 1-element length segment where recursion will meet it's base in $O(log(n))$ "looking at" this element. The overall complexity is $O(n \times log(n) + k)$.
|
[
"data structures",
"divide and conquer"
] | 2,800
| null |
549
|
G
|
Happy Line
|
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of $n$ Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person $a$ stands just behind person $b$, then person $a$ can pay person $b$ 1 dollar, then $a$ and $b$ get swapped. Of course, if person $a$ has zero dollars, he can not swap places with person $b$.
Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.
Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.
|
Let's reformulate the condition in terms of a certain height the towers, which will be on the stairs. Then an appropriate amount of money of a person in the queue is equal to the height of the tower with the height of the step at which the tower stands. And the process of moving in the queue will be equivalent to raising a tower on the top step, and the one in whose place it came up - down. As shown in the illustrations. Then, it becomes apparent that to make all of the tower on the steps to be sorted, it is enough to sort the tower without the height of step it stays. Total complexity of sorting is O(nlog(n)).
|
[
"constructive algorithms",
"greedy",
"sortings"
] | 2,200
| null |
549
|
H
|
Degenerate Matrix
|
The determinant of a matrix $2 × 2$ is defined as follows:
\[
\operatorname*{det}\left(\begin{array}{c c}{{a}}&{{b}}\\ {{c}}&{{d\rangle}}=a d-b c
\]
A matrix is called degenerate if its determinant is equal to zero.
The norm $||A||$ of a matrix $A$ is defined as a maximum of absolute values of its elements.
You are given a matrix $A={\binom{a}{c}}{\binom{b}{d}}$. Consider any degenerate matrix $B$ such that norm $||A - B||$ is minimum possible. Determine $||A - B||$.
|
The rows of degenerate matrix are linear dependent so the matrix B can be written in the following way: Suppose Let's assume that elements of the first row of matrix $A$ are coordinates of point $a_{0}$ on two-dimensional plane and the elements of the second row are coordinates of point $a_{1}$. Assume that the rows of matrix $B$ are also coordinates of points $b_{0}$ and $b_{1}$. Let's note that in this case the line that is passing through points $b_{0}$ and $b_{1}$ is also passing through point $(0, 0)$. Let's find the answer - the number $d$ - by using binary search. Suppose we are considering some number $d_{0}$. We need to check if there is such matrix $B$ that In geometric interpretation it means that point $b_{0}$ are inside the square which center is point $a_{0}$ and length of side is $2 \cdot d_{0}$. In the same way the point $b_{1}$ are inside the square which center is point $a_{1}$ and length of side is $2 \cdot d_{0}$. So we need to check if there is a line that is passing through point $(0, 0)$ and is crossing these squares. In order to do this we should consider every vertex of the first square, build the line that is passing through the chosen vertex and the center of coordinate plane and check if it cross any side of the other square. Afterwards we should swap the squares and check again. Finally if there is a desired line we need to reduce the search area and to expand otherwise.
|
[
"binary search",
"math"
] | 2,100
| null |
550
|
A
|
Two Substrings
|
You are given string $s$. Your task is to determine if the given string $s$ contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
There are many ways to solve this problem. Author solution does the following: check if substring "AB" goes before "BA", and then vice versa, if "BA" goes before "AB". You can do it in the following way: find the first occurence of "AB" then check all substrings of length two to the right of it to check if substring "BA" also exists. Then do it vice versa. Complexity of the solution is $O(n)$, where $n$ is the length of the given string.
|
[
"brute force",
"dp",
"greedy",
"implementation",
"strings"
] | 1,500
| null |
550
|
B
|
Preparing Olympiad
|
You have $n$ problems. You have estimated the difficulty of the $i$-th one as integer $c_{i}$. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least $l$ and at most $r$. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least $x$.
Find the number of ways to choose a problemset for the contest.
|
Because of the low constraints, this problem can be solved by complete search over all problem sets (there are $2^{n}$ of them). For every potential problem set (which can be conviniently expressed as bit mask) we need to check if it satisfies all needed criteria. We can simply find the sum of problem complexities and also the difference between the most difficult and the easiest problems in linear time, iterating over the problems that we included in our current set/bitmask. If this problem set can be used, we increase the answer by one. Complexity of this solution is $O(2^{n} \cdot n)$.
|
[
"bitmasks",
"brute force"
] | 1,400
| null |
550
|
C
|
Divisibility by Eight
|
You are given a non-negative integer $n$, its decimal representation consists of at most $100$ digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.
If a solution exists, you should print it.
|
This problem can be solved with at least two different approaches. The first one is based on the "school" property of the divisibility by eight - number can be divided by eight if and only if its last three digits form a number that can be divided by eight. Thus, it is enough to test only numbers that can be obtained from the original one by crossing out and that contain at most three digits (so we check only all one-digit, two-digit and three-digit numbers). This can be done in $O(len^{3})$ with three nested loops (here $len$ is the length of the original number). Second approach uses dynamic programming. Let's calculate $dp[i][j]$, $1 \le i \le n$, $0 \le j < 8$. The value of dp is true if we can cross out some digits from the prefix of length $i$ such that the remaining number gives $j$ modulo eight, and false otherwise. This dp can be calculated in the following way: let $a_{i}$ be $i$th digit of the given number. Then $dp[i][a_{i}mod8] = true$ (just this number). For all $0 \le j < 8$ such that $dp[i - 1][j] = true$, $dp[i][(j * 10 + a_{i})mod8] = true$ (we add current digit to some previous result), $dp[i][j] = true$ (we cross out current digit). Answer is "YES" if $dp[i][0] = true$ for some position $i$. For restoring the answer we need to keep additional array $prev[i][j]$, which will say from where current value was calculated. Complexity of such solution is $O(8 \cdot len) = O(len)$ (again $len$ is the length of the original number).
|
[
"brute force",
"dp",
"math"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
#define sz(x) (int) x.size()
#define all(a) a.begin(), a.end()
#define prev sadasdjksgjkasjdklaj
const int MAXN = 105;
string s;
int n;
bool dp[MAXN][8];
int prev[MAXN][8];
int main() {
getline(cin, s);
n = sz(s);
memset(prev, -1, sizeof(prev));
dp[0][(s[0] - '0') % 8] = true;
for (int i = 1; i < n; i++) {
dp[i][(s[i] - '0') % 8] = true;
for (int j = 0; j < 8; j++) {
if (dp[i - 1][j]) {
dp[i][(j * 10 + s[i] - '0') % 8] = true;
prev[i][(j * 10 + s[i] - '0') % 8] = j;
dp[i][j] = true;
prev[i][j] = j;
}
}
}
for (int i = 0; i < n; i++) {
if (dp[i][0]) {
string ans = "";
int curI = i, curJ = 0;
while (true) {
if (prev[curI][curJ] == -1 || prev[curI][curJ] != curJ) {
ans.append(1, s[curI]);
}
if (prev[curI][curJ] == -1) break;
curJ = prev[curI][curJ];
curI--;
}
puts("YES");
reverse(all(ans));
cout << ans << endl;
return 0;
}
}
puts("NO");
return 0;
}
|
550
|
D
|
Regular Bridge
|
An undirected graph is called $k$-regular, if the degrees of all its vertices are equal $k$. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected $k$-regular graph containing at least one bridge, or else state that such graph doesn't exist.
|
Let's prove that there is no solution for even $k$. Suppose our graph contains some bridges, $k = 2s$ (even), all degrees are $k$. Then there always exists strongly connected component that is connected to other part of the graph with exactly one bridge. Consider this component. Let's remove bridge that connects it to the remaining graph. Then it has one vertex with degree $k - 1 = 2s - 1$ and some vertices with degrees $k = 2s$. But then the graph consisting of this component will contain only one vertex with odd degree, which is impossible by Handshaking Lemma. Let's construct the answer for odd $k$. Let $k = 2s - 1$. For $k = 1$ graph consisting of two nodes connected by edge works. For $k \ge 3$ let's construct graph with $2k + 4$ nodes. Let it consist of two strongly connected components connected by bridge. Enumerate nodes of first component from $1$ to $k + 2$, second component will be the same as the first one. Let vertex $1$ be connected to the second component by bridge. Also connect it with $k - 1$ edges to vertices $2, 3, ..., k$. Connect vertices $2, 3, ..., k$ to each other (add all possible edges between them), and then remove edges between every neighbouring pair, for example edges $2 - 3$, $4 - 5$, ..., $(k - 1) - k$. Then we connect vertices $2, 3, ..., k$ with vertices $k + 1$ and $k + 2$. And finally add an edge between nodes $k + 1$ and $k + 2$. Build the second component in the similar manner, and add a bridge between components. Constructed graph has one bridge, all degrees of $k$ and consists of $O(k)$ nodes and $O(k^{2})$ edges. Complexity of the solution - $O(k^{2})$.
|
[
"constructive algorithms",
"graphs",
"implementation"
] | 1,900
| null |
550
|
E
|
Brackets in Implications
|
Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false.
Implication is written by using character '$\to$', and the arguments and the result of the implication are written as '0' ($false$) and '1' ($true$). According to the definition of the implication:
\begin{center}
$0\rightarrow0=1$
$0\rightarrow1=1\qquad$
$1\to0=0$
$1\to1=1$
\end{center}
When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,
$0\rightarrow0\rightarrow0=(0\rightarrow0)\rightarrow0=1\rightarrow0=0=0$.
When there are brackets, we first calculate the expression in brackets. For example,
$0\rightarrow(0\rightarrow0)=0\rightarrow1=1$.
For the given logical expression $a_{1}\longrightarrow a_{2}\to a_{3}\to\cdot\cdot\cdot\to a_{n}$ determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.
|
Let input consists of $a_{1}\longrightarrow a_{2}\longrightarrow\cdot\cdot\cdot\longrightarrow a_{n}$, $a_{i}$ is $0$ or $1$ for all $i$. Let's show that there is no solution in only two cases: 1) $a_{n} = 1$. $x\to1=1$, for all $x$, and no parentheses can change last $1$ to $0$. 2) Input has the form $1\to1\to1\to\cdots\cdots\to1\to0\to0$ or its suffix with at least two arguments. This can be proven by induction. For input $0\to0$ there is no solution, for longer inputs any attempt to put parentheses will decrease the number of $1$s in the beginning by one, or will introduce $1$ in the last position (which will lead to case one). Let's construct solution for all other cases. 1) For input $0$ we don't need to do anything. 2) For input of the form $\cdot\cdot\rightarrow1\rightarrow0$ we don't need any parentheses, the value of this expression is always 3) Expression in the form $\cdot\cdot\cdot\rightarrow0\rightarrow\cdot\cdot\cdot\rightarrow0\rightarrow0$ (where second missed part consists of ones only). Then $\cdot\cdot\cdot\rightarrow(0\to(1\to1\to\cdot\cdot\cdot\rightarrow1\to0))\to0=0$. Complexity of the solution is $O(n)$.
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 2,200
| null |
551
|
A
|
GukiZ and Contest
|
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, $n$ students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from $1$ to $n$. Let's denote the rating of $i$-th student as $a_{i}$. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.
He thinks that each student will take place equal to $\mathrm{i}+(\mathrm{number~of~students~with~strictly~higher~rating~than~his~or~her})$. In particular, if student $A$ has rating strictly lower then student $B$, $A$ will get the strictly better position than $B$, and if two students have equal ratings, they will share the same position.
GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
|
Very simple implementation problem. Just implement what is written in the statement: for every element of array, find the number of array elements greater than it, and add one to the sum. This can be easily done with two nested loops. Total complexity $O(n^{2})$.
|
[
"brute force",
"implementation",
"sortings"
] | 800
|
import java.util.Scanner;
public class Main {
private Scanner scanner;
private Main(Scanner scanner) {
this.scanner = scanner;
}
public static void main(String[] args) {
Main main = new Main(new Scanner(System.in));
main.solve();
}
private void solve() {
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = scanner.nextInt();
for (int i = 0; i < n; i++) {
int s = 1;
for (int j = 0; j < n; j++) if (a[j] > a[i]) s++;
System.out.print(s);
if (i < n - 1) System.out.print(" ");
else
System.out.println();
}
}
}
|
551
|
B
|
ZgukistringZ
|
Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.
GukiZ has strings $a$, $b$, and $c$. He wants to obtain string $k$ by swapping some letters in $a$, so that $k$ should contain as many non-overlapping substrings equal either to $b$ or $c$ as possible. Substring of string $x$ is a string formed by consecutive segment of characters from $x$. Two substrings of string $x$ overlap if there is position $i$ in string $x$ occupied by both of them.
GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings $k$?
|
First, calculate the number of occurences of every English letter in strings $a$, $b$, and $c$. We can now iterate by number of non-overlapping substrings of the resulting string equal to $b$, then we can calculate in constant time how many substrings equal to $c$ can be formed (by simple operations on the number of occurences of English letters in $c$). In every iteration, maximise the sum of numbers of $b$ and $c$. Number of iterations is not greater than $|a|$. At the end, we can easily build the resulting string by concatenating previously calculated number of strings $b$ and $c$, and add the rest of the letters to get the string obtainable from $a$. Total complexity is $O(|a| + |b| + |c|)$.
|
[
"brute force",
"constructive algorithms",
"implementation",
"strings"
] | 1,800
|
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, m, k, ba[26], bb[26], bs[26];
int d, res, prvi, drugi;
char s[N], a[N], b[N], resenje[N];
int main()
{
scanf("%s %s %s", s + 1, a + 1, b + 1);
n = strlen(s + 1);
m = strlen(a + 1);
k = strlen(b + 1);
for (int i = 1; i <= n; i++) bs[s[i] - 'a']++;
for (int i = 1; i <= m; i++) ba[a[i] - 'a']++;
for (int i = 1; i <= k; i++) bb[b[i] - 'a']++;
for (int i = 0; ; i++)
{
int x = n;
for (int j = 0; j < 26; j++) if (bb[j]) x = min(x, bs[j] / bb[j]);
if (x + i > res)
{
res = x + i;
prvi = i;
drugi = x;
}
bool f = false;
for (int j = 0; j < 26; j++) if (bs[j] < ba[j])
{
f = true;
break;
} else
bs[j] -= ba[j];
if (f) break;
}
for (int i = 1; i <= prvi; i++)
for (int j = 1; j <= m; j++) resenje[++d] = a[j];
for (int i = 1; i <= drugi; i++)
for (int j = 1; j <= k; j++) resenje[++d] = b[j];
for (int i = 0; i < 26; i++) bs[i] = -ba[i] * prvi - bb[i] * drugi;
for (int i = 1; i <= n; i++) bs[s[i] - 'a']++;
for (int i = 0; i < 26; i++)
for (int j = 1; j <= bs[i]; j++) resenje[++d] = 'a' + i;
for (int i = 1; i <= n; i++) printf("%c", resenje[i]);
return 0;
}
|
551
|
C
|
GukiZ hates Boxes
|
Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way.
In total there are $n$ piles of boxes, arranged in a line, from left to right, $i$-th pile ($1 ≤ i ≤ n$) containing $a_{i}$ boxes. Luckily, $m$ students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time $0$, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are:
- If $i ≠ n$, move from pile $i$ to pile $i + 1$;
- If pile located at the position of student is not empty, remove one box from it.
GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time $t$ in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after $t$ seconds, but all the boxes must be removed.
|
Problem solution (complete work time) can be binary searched, because if the work can be done for some amount of time, it can certainly be done for greater amount of time. Let the current search time be $k$. We can determine if we can complete work for this time by folowing greedy algorithm: find last non-zero pile of boxes and calculate the time needed to get there (which is equal to it's index in array) and take with first man as much boxes as we can. If he can take even more boxes, find next non-zero (to the left) pile, and get as much boxes from it, and repete untill no time is left. When the first man does the job, repete the algorithm for next man, and when all $m$ men did their maximum, if all boxes are removed we can decrease upper bound in binary search. Otherwise, we must increase lower bound. Total compexity is $O((n+m)\cdot\log_{2}(n+\sum a))$.
|
[
"binary search",
"greedy"
] | 2,200
|
import java.util.Scanner;
public class Main {
private Scanner scanner;
private Main(Scanner scanner) {
this.scanner = scanner;
}
public static void main(String[] args) {
Main main = new Main(new Scanner(System.in));
main.solve();
}
private void solve() {
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] a = new int[n];
long s = 0;
for (int i = 0; i < n; i++) s += a[i] = scanner.nextInt();
long l = 2, r = s + n;
while (l < r) {
long z = l + r >> 1;
int[] b = a.clone();
int p = n - 1;
for (int i = 0; i < m; i++) {
while (p >= 0 && b[p] == 0) p--;
long t = z - p - 1;
if (t <= 0) break;
while (p >= 0 && b[p] <= t) t -= b[p--];
if (p >= 0) b[p] -= t;
}
if (p < 0) r = z;
else
l = z + 1;
}
System.out.println(r);
}
}
|
551
|
D
|
GukiZ and Binary Operations
|
We all know that GukiZ often plays with arrays.
Now he is thinking about this problem: how many arrays $a$, of length $n$, with non-negative elements \textbf{strictly less} then $2^{l}$ meet the following condition: $(a_{1}\operatorname{and}a_{2})\operatorname{or}(a_{2}\operatorname{and}a_{3})\operatorname{or}\cdot\cdot\cdot\operatorname{or}(a_{n-1}\operatorname{and}a_{n})=k$? Here operation $\mathrm{and}$ means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &), operation $\mathrm{or}$ means bitwise OR (in Pascal it is equivalent to $\mathrm{or}$, in C/C++/Java/Python it is equivalent to |).
Because the answer can be quite large, calculate it modulo $m$. This time GukiZ hasn't come up with solution, and needs you to help him!
|
First convert number $k$ into binary number system. If some bit of $k$ is $0$ than the result of $or$ opertion applied for every adjacent pair of those bits in array $a$ must be $0$, that is no two adjacent those bits in array $a$ are $1$. We should count how many times this is fulfilled. If the values were smaller we could count it with simply $dp_{i} = dp_{i - 1} + dp_{i - 2}$, where $dp_{i}$ is equal to number of ways to make array od i bits where no two are adjacent ones. With first values $dp_{1} = 2$ and $dp_{2} = 3$, we can see that this is ordinary Fibonacci number. We can calculate Fibonacci numbers up to $10^{18}$ easily by fast matrix multiplication. If some bit at $k$ is $1$ than number of ways is $2^{n}$ - \t{(number of ways bit is 0)}, which is also easy to calculate. We must be cearful for cases when $2^{l}$ smaller than $k$ (solution is $0$ then) and when $l = 63$ or $l = 64$. Total complexity is $O(\log_{2}n+\log_{2}k)$.
|
[
"combinatorics",
"implementation",
"math",
"matrices",
"number theory"
] | 2,100
|
import java.util.Scanner;
public class Main {
private Scanner scanner;
private int mod;
private Main(Scanner scanner) {
this.scanner = scanner;
}
public static void main(String[] args) {
Main main = new Main(new Scanner(System.in));
main.solve();
}
private void solve() {
long n = scanner.nextLong();
long k = scanner.nextLong();
int l = scanner.nextInt();
mod = scanner.nextInt();
if (mod == 1 || l < 63 && 1l << l <= k) {
System.out.println(0);
return;
}
if (l == 0) {
if (k == 0) System.out.println(1);
else
System.out.println(0);
return;
}
long pow2 = fastPower(2, n);
long fib = fibonacci(n + 1);
long res = 1;
for (int i = 0; i < l; i++)
if (((k >> i) & 1) == 0) res = res * fib % mod;
else
res = res * (pow2 - fib) % mod;
if (res < 0) res += mod;
System.out.println(res);
}
private long fibonacci(long n) {
Matrix matrix = new Matrix(new long[][]{{1, 1}, {1, 0}});
matrix = fastPower(matrix, n);
return matrix.matrix[0][0];
}
private long fastPower(long base, long exponent) {
if (exponent == 0) return 1;
long x = fastPower(base, exponent >> 1);
x = x * x % mod;
if ((exponent & 1) != 0) x = x * base % mod;
return x;
}
private Matrix fastPower(Matrix base, long exponent) {
if (exponent == 1) return base;
Matrix x = fastPower(base, exponent >> 1);
x = multiplyMatrix(x, x);
if ((exponent & 1) != 0) x = multiplyMatrix(x, base);
return x;
}
private Matrix multiplyMatrix(Matrix a, Matrix b) {
Matrix matrix = new Matrix();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
matrix.matrix[i][k] = (matrix.matrix[i][k] + a.matrix[i][j] * b.matrix[j][k]) % mod;
return matrix;
}
private class Matrix {
private long[][] matrix;
public Matrix() {
matrix = new long[2][2];
}
public Matrix(long[][] c) {
matrix = c.clone();
}
}
}
|
551
|
E
|
GukiZ and GukiZiana
|
Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called $GukiZiana$. For given array $a$, indexed with integers from $1$ to $n$, and number $y$, $GukiZiana(a, y)$ represents maximum value of $j - i$, such that $a_{j} = a_{i} = y$. If there is no $y$ as an element in $a$, then $GukiZiana(a, y)$ is equal to $ - 1$. GukiZ also prepared a problem for you. This time, you have two types of queries:
- First type has form $1$ $l$ $r$ $x$ and asks you to increase values of all $a_{i}$ such that $l ≤ i ≤ r$ by the non-negative integer $x$.
- Second type has form $2$ $y$ and asks you to find value of $GukiZiana(a, y)$.
For each query of type $2$, print the answer and make GukiZ happy!
|
First we divide array $a$ in $\sqrt{n}$ groups with $\sqrt{n}$ numbers. Every group in each moment will be kept sorted. For type $1$ query, If we update some interval, for each group, which is whole packed in the interval, we will add the number it is being increased to it's current increasing value (this means all the elements are increased by this number). If some part of group is covered by interval, update these elements and resort them. Now, let's handle with type $2$ queries. When we want find $GukiZiana(a, j)$, we search for the first and the last occurence of $j$ by groups. One group can be binary searched in $O(\log_{2}{\sqrt{n}})$, because of sorted values, and most $\sqrt{n}$ groups will be searched. Of course, for the first occurence we search for minimum index of value of $j$, and for the last occurence maximum index of value of $j$ in array. When we find these $2$ indexes, we must restore their original positions in array $a$ and print their difference. If there is no occurence of $j$, print $- 1$. Total complexity is $O(n\cdot\log_{2}{\sqrt{n}}+q\cdot{\sqrt{n}}\cdot\log_{2}{\sqrt{n}})$.
|
[
"binary search",
"data structures",
"implementation"
] | 2,500
|
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 500010, G = 1010;
int n, q, koren;
ll a[N], d[N];
pair<ll, int> pa[G][G];
int grupa(int x)
{
return 1 + (x - 1) / koren;
}
void sortirajgrupu(int grp, int neki)
{
int vel = 0;
for (int i = neki; i && grupa(i) == grp; i--) pa[grp][++vel] = {a[i], i};
for (int i = neki + 1; i <= n && grupa(i) == grp; i++) pa[grp][++vel] = {a[i], i};
sort(pa[grp] + 1, pa[grp] + vel + 1);
}
int main()
{
scanf("%d %d", &n, &q);
koren = sqrt(n);
for (int i = 1; i <= n; i++) scanf("%I64d", &a[i]);
for (int i = 1, g = 1; g <= n; i++, g += koren) sortirajgrupu(i, g);
while (q--)
{
int t;
scanf("%d", &t);
if (t == 1)
{
int l, r, x;
scanf("%d %d %d", &l, &r, &x);
int p = grupa(l), q = grupa(r);
if (p == q)
{
for (int i = l; i <= r; i++) a[i] += x;
sortirajgrupu(p, l);
continue;
}
for (int i = l; i <= n && grupa(i) == p; i++) a[i] += x;
for (int i = r; i && grupa(i) == q; i--) a[i] += x;
sortirajgrupu(p, l);
sortirajgrupu(q, r);
for (int i = p + 1; i < q; i++) d[i] += x;
} else
{
int x, mi = 0, ma;
scanf("%d", &x);
for (int i = 1, g = 1; g <= n; i++, g += koren)
{
int gor = min(n, g + koren - 1), vel = gor - g + 1;
int pos = lower_bound(pa[i] + 1, pa[i] + vel + 1, pair<ll, int>(x - d[i], 1)) - pa[i];
if (pos <= vel && pa[i][pos].first == x - d[i])
{
mi = pa[i][pos].second;
break;
}
}
for (int i = (n + koren - 1) / koren, g = (i - 1) * koren + 1; i; i--, g -= koren)
{
int gor = min(n, g + koren - 1), vel = gor - g + 1;
int pos = lower_bound(pa[i] + 1, pa[i] + vel + 1, pair<ll, int>(x - d[i] + 1, 1)) - pa[i] - 1;
if (pos && pa[i][pos].first == x - d[i])
{
ma = pa[i][pos].second;
break;
}
}
if (mi) printf("%d\n", ma - mi); else
printf("-1\n");
}
}
return 0;
}
|
552
|
A
|
Vanya and Table
|
Vanya has a table consisting of $100$ rows, each row contains $100$ cells. The rows are numbered by integers from $1$ to $100$ from bottom to top, the columns are numbered from $1$ to $100$ from left to right.
In this table, Vanya chose $n$ rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.
|
In this problem we can get AC with many solutions: 1) With every new rectangle we will add his area to the result, so for each line $x_{1}, y_{1}, x_{2}, y_{2}$ we will add to answer $(x_{2} - x_{1} + 1) * (y_{2} - y_{1} + 1)$ Time complexity $O(n)$. 2) We can just do all, that is written in the statement: create an array and with each new rectangle we can just increment every element inside rectangle. In the end we can just add all elements inside this array. Time complexity $O(n * x * y)$
|
[
"implementation",
"math"
] | 1,000
|
"#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI 3.14159265358979323846\n#define MOD 1000000007\n#define INF ((ll)1e+15)\n#define x1 fldgjdflgjhrthrl\n#define x2 fldgjdflgrtyrtyjl\n#define y1 fldggfhfghjdflgjl\n#define y2 ffgfldgjdflgjl\ntypedef long long ll;\nusing namespace std;\nll i,n,m,x1,y1,x2,y2;\n\nint main()\n{\n ll ans = 0;\n\tcin >> n;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\t\tans += (x2-x1+1)*(y2-y1+1);\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}\n"
|
552
|
B
|
Vanya and Books
|
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the $n$ books should be assigned with a number from $1$ to $n$. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the books.
|
We can find out a formula for this problem: for $n < 10$ answer will be $n = n - 1 + 1 = 1 * (n + 1) - 1$; for $n < 100$ answer will be $2 * (n - 9) + 9 = 2 * n - 9 = 2 * n - 10 - 1 + 2 = 2 * (n + 1) - 11$; for $n < 1000$ answer will be $3 * (n - 99) + 2 * (99 - 9) + 9 = 3 * n - 99 - 9 = 3 * n - 100 - 10 - 1 + 3 = 3 * (n + 1) - 111$; so for $n < 10^{sz}$ answer will be $s z\ast(n+1)-\sum_{i=0}^{s_{z}-1}10^{s_{i}}$; Time complexity $O(sz)$, where $sz$ is the length of n. We also could just try $10$ options $n < 10, n < 100, ..., n < 10^{9}, n = 10^{9}$ and solve problem for each option. UPD: Don't use function pow() to find powers of 10, because it doesn't work right sometimes.
|
[
"implementation",
"math"
] | 1,200
|
"#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI 3.14159265358979323846\n#define MOD 1000000007\n#define INF ((ll)1e+15)\n#define x1 fldgjdflgjhrthrl\n#define x2 fldgjdflgrtyrtyjl\n#define y1 fldggfhfghjdflgjl\n#define y2 ffgfldgjdflgjl\ntypedef long long ll;\nusing namespace std;\nll i,n,x,m,k,ans;\nint main()\n{\n cin >> n;\n\tx = n;\n\twhile (x)\n\t{\n\t\tx /= 10;\n\t\tm++;\n\t}\n\tans = n*m + m - 1;\n\tk = 1;\n\tfor (i = 0; i < m-1; i++)\n\t{\n\t\tk *= 10;\n\t\tans -=k;\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}\n"
|
552
|
C
|
Vanya and Scales
|
Vanya has a scales for weighing loads and weights of masses $w^{0}, w^{1}, w^{2}, ..., w^{100}$ grams where $w$ is some integer not less than $2$ (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass $m$ using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass $m$ and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.
|
Convert $m$ to number system of base $w$. If all digits of number - $0$ or $1$, then we can measure the weight of the item with putting weights, that have digits equal to $1$, on one pan, and our item on another one. If this condition isn't satisfied, then we should iterate from lower digit to high and if digit is not equal to $0$ or $1$, we try to substract $w$ from it and increment higher digit. If it becomes equal to $- 1$, then we can put weight with number of this digit on the same pan with our item, if it becomes equal to $0$, then we don't put weight, in another case we can't measure the weight of our item and answer is $\mathrm{No}$. Time complexity $O(logm)$.
|
[
"brute force",
"dp",
"greedy",
"math",
"meet-in-the-middle",
"number theory"
] | 1,900
|
"#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI 3.14159265358979323846\n#define MOD 1000000007\n#define INF ((ll)1e+15)\n#define x1 fldgjdflgjhrthrl\n#define x2 fldgjdflgrtyrtyjl\n#define y1 fldggfhfghjdflgjl\n#define y2 ffgfldgjdflgjl\ntypedef long long ll;\nusing namespace std;\nll w,m,sz,i;\nll a[40];\n\nint main()\n{\n\tll flag = 1;\n cin >> w >> m;\n while (m)\n {\n \ta[sz++] = m%w;\n \tm /= w;\n }\n\tfor (i = 0; i <= sz; i++)\n\t\tif (a[i] != 0 && a[i] != 1 && a[i] != w-1 && a[i] != w)\n\t\t{\n\t\t flag = 0;\n\t\t break;\n }\n else\n {\n\t\t\tif (a[i] == w-1 || a[i] == w)\n\t\t\t a[i+1]++;\n }\n\tif (flag)\n\t cout << \"YES\" << endl;\n\telse\n\t\tcout << \"NO\" << endl;\n\treturn 0;\n}\n"
|
552
|
D
|
Vanya and Triangles
|
Vanya got bored and he painted $n$ distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the \textbf{non-zero} area.
|
We can look through all pair of points, draw line through each pair and write, that this line includes these 2 points. We can do it with map. If some line includes $x$ points, then in fact we counted, that it has $2 * x * (x - 1)$ points, because we included each point 2*(x-1) times in this line. We can create an array and add to him values $b[2 * x * (x - 1)] = x$, so we can define, how many points is on the line. Then we can iterate through all lanes and for each line with $x$ points we will loose $x * (x - 1) * (x - 2) / 6$ possible triangles from all possible $n * (n - 1) * (n - 2) / 6$ triangles. Decide, that at first $ans = n * (n - 1) * (n - 2) / 6$. So for every line, that includes $x$ points, we will substract $x * (x - 1) * (x - 2) / 6$ from $ans$. Time complexity $O(n^{2} * logn)$.
|
[
"brute force",
"combinatorics",
"data structures",
"geometry",
"math",
"sortings"
] | 1,900
|
"#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#include <unordered_map>\n#define mp make_pair\n#define pb push_back\n#define PI 3.14159265358979323846\n#define MOD 1000000007\n#define INF ((ll)1e+15)\n#define x1 fldgjdflgjhrthrl\n#define x2 fldgjdflgrtyrtyjl\n#define y1 fldggfhfghjdflgjl\n#define y2 ffgfldgjdflgjl\ntypedef long long ll;\nusing namespace std;\nint i,j,n,m,x[3005],y[3005],a[4500000],b[20005][205];\nunordered_map <ll, int> f;\nunordered_map <ll, int>::iterator itr;\nll Abs(int a)\n{\n\treturn a>0?a:-a;\n}\nll gcd(int a, int b)\n{\n\tif (b == 0)\n\t return a;\n\treturn gcd(b,a%b);\n}\nint main()\n{\n\tfor (i = 1; i <= 20000; i++)\n for (j = 1; j <= 200; j++)\n b[i][j] = gcd(i,j);\n\tfor (i = 1; i <= 20000; i++)\n\t\tb[i][0] = i;\n\tfor (i = 1; i <= 200; i++)\n\t\tb[0][i] = i;\n \tcin >> n;\n \tfor (i = 2; i <= 2000; i++)\n\t\ta[i*i-i] = i;\n \tfor (i = 0; i < n; i++)\n\t\tcin >> x[i] >> y[i];\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tfor (j = 0; j < n; j++)\n\t\tif (i != j)\n\t\t{\n\t\t\tint kc = y[j] - y[i];\n\t\t\tint kz = x[j] - x[i];\n\t\t\tint bc = y[i]*(x[j] - x[i]) - x[i]*(y[j]-y[i]);\n\t\t\tint bz = x[j] - x[i];\n\t\t\tif (kz != 0)\n\t\t\t{\n\t\t\tint tmp = b[Abs(kc)][Abs(kz)];\n\t\t\tkc /= tmp; kz /= tmp;\n\t\t\tif (kc < 0)\n\t\t\t kc = -kc, kz = -kz;\n\t\t\tif (kc == 0)\n\t\t\t kz = 1;\n tmp = b[Abs(bc)][Abs(bz)];\n\t\t\tbc /= tmp; bz /= tmp;\n\t\t\tif (bc < 0)\n\t\t\t bc = -bc, bz = -bz;\n\t\t\tif (bc == 0)\n\t\t\t bz = 1;\n }\n else\n kc = bc = x[i];\n ll hsh = bc*27000000000LL + bz*9000000LL + kc*300 + kz;\n\t\t\t\tf[hsh]+=2;\n\t\t}\n\t}\n\tll ans = ((ll)n*(n-1)*(n-2))/6;\n\tfor (itr = f.begin(); itr != f.end(); itr++)\n\t{\n\t\tint tmp = (*itr).second;\n\t\ttmp = a[tmp/2];\n\t\tans -= ((ll)tmp*(tmp-1)*(tmp-2))/6;\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}"
|
552
|
E
|
Vanya and Brackets
|
Vanya is doing his maths homework. He has an expression of form $x_{1}\otimes x_{2}\otimes x_{3}\otimes\cdot\cdot\otimes x_{n}$, where $x_{1}, x_{2}, ..., x_{n}$ are digits from $1$ to $9$, and sign $\quad\quad\quad\quad\quad\quad\quad\quad\quad{}$ represents either a plus '+' or the multiplication sign '*'. Vanya needs to add \textbf{one} pair of brackets in this expression so that to maximize the value of the resulting expression.
|
We can see, that we can reach maximal answer, when brackets will be between two signs $*$, or between one sign $*$ and the end of expression. For convenience we will add in the begin of expression $1 *$, and in the end of expression $* 1$. After that we can iterate all possible pairs of signs $*$ and count the expression with putting brackets between two signs $*$ for each pair. We can use two variables $x$ and $y$ to count the value of expression, in the begin $x = 0, y = firstnumber$, where $firstnumber$ is first digit of expression, then if next sign is $+$, then $x = y, y = nextnumber$, and if next sign is $*$, then $x = x, y = y * nextnumber$. The value of expression will be $x + y$, we can create function, like that, to count expressions inside and outside the brackets. Time complexity $O(|s| * 17^{2})$.
|
[
"brute force",
"dp",
"expression parsing",
"greedy",
"implementation",
"strings"
] | 2,100
|
"#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <cstring>\n#include <deque>\n#include <time.h>\n#include <stack>\n#include <stdio.h>\n#include <map>\n#include <set>\n#include <string>\n#include <fstream>\n#include <queue>\n#define mp make_pair\n#define pb push_back\n#define PI 3.14159265358979323846\n#define MOD 1000000007\n#define INF ((ll)1e+15)\n#define x1 fldgjdflgjhrthrl\n#define x2 fldgjdflgrtyrtyjl\n#define y1 fldggfhfghjdflgjl\n#define y2 ffgfldgjdflgjl\ntypedef long long ll;\nusing namespace std;\nll i,j,n,x,y,m,k,ans,a[6000],b[6000];\nvector <ll> f;\nstring s,t;\npair<ll,ll> solve(ll l, ll r)\n{\n\tll x = 0, y = a[l];\n\tfor (int i = l; i < r; i++)\n\t\tif (b[i] == 1)\n\t\t x += y, y = a[i+1];\n\t\telse\n\t\t\ty *= a[i+1];\n\treturn mp(x,y);\n}\nint main()\n{\n\tcin >> s;\n\tt = \"1*\";\n\tt.append(s);\n\tt.append(\"*1\");\n\ts = t;\n\tn = s.size();\n\tm = n/2;\n\tfor (i = 0; i < n; i+=2)\n\t\ta[i/2] = s[i] - '0';\n\tfor (i = 1; i < n; i+=2)\n\t\tif (s[i] == '+')\n\t\t b[i/2] = 1;\n\t\telse\n\t\t{\n\t\t\tb[i/2] = 2;\n\t\t\tf.push_back(i/2);\n\t\t}\n\tll max1 = 0;\n\tfor (i = 0; i < f.size(); i++)\n\t\tfor (j = i+1; j < f.size(); j++)\n\t\t{\n\t\t pair <ll,ll> tmp = solve(0,f[i]);\n\t\t x = tmp.first, y = tmp.second;\n\t\t tmp = solve(f[i]+1,f[j]);\n\t\t y *= tmp.first + tmp.second;\n\t\t ll xx = a[f[j]];\n\t\t a[f[j]] = y;\n\t\t tmp = solve(f[j],m);\n\t\t max1 = max(max1, x+tmp.first+tmp.second);\n\t\t a[f[j]] = xx;\n\t\t}\n\tcout << max1 << endl;\n\treturn 0;\n}\n\n"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.