contestId
int64
0
1.01k
name
stringlengths
2
58
tags
listlengths
0
11
title
stringclasses
523 values
time-limit
stringclasses
8 values
memory-limit
stringclasses
8 values
problem-description
stringlengths
0
7.15k
input-specification
stringlengths
0
2.05k
output-specification
stringlengths
0
1.5k
demo-input
listlengths
0
7
demo-output
listlengths
0
7
note
stringlengths
0
5.24k
test_cases
listlengths
0
402
timeConsumedMillis
int64
0
8k
memoryConsumedBytes
int64
0
537M
score
float64
-1
3.99
__index_level_0__
int64
0
621k
0
none
[ "none" ]
null
null
For an array $b$ of length $m$ we define the function $f$ as where $\oplus$ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$.
The first line contains a single integer $n$ ($1 \le n \le 5000$)Β β€” the length of $a$. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$)Β β€” the elements of the array. The third line contains a single integer $q$ ($1 \le q \le 100\,000$)Β β€” the number of queries. Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$).
Print $q$ linesΒ β€” the answers for the queries.
[ "3\n8 4 1\n2\n2 3\n1 2\n", "6\n1 2 4 8 16 32\n4\n1 6\n2 5\n3 4\n1 2\n" ]
[ "5\n12\n", "60\n30\n12\n3\n" ]
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment. In second sample, optimal segment for first query are $[3,6]$, for second query β€” $[2,5]$, for third β€” $[3,4]$, for fourth β€” $[1,2]$.
[ { "input": "3\n8 4 1\n2\n2 3\n1 2", "output": "5\n12" }, { "input": "6\n1 2 4 8 16 32\n4\n1 6\n2 5\n3 4\n1 2", "output": "60\n30\n12\n3" } ]
2,000
94,617,600
0
4,573
792
Counting-out Rhyme
[ "implementation" ]
null
null
*n* children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to *n*. In the beginning, the first child is considered the leader. The game is played in *k* steps. In the *i*-th step the leader counts out *a**i* people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader. For example, if there are children with numbers [8,<=10,<=13,<=14,<=16] currently in the circle, the leader is child 13 and *a**i*<==<=12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader. You have to write a program which prints the number of the child to be eliminated on every step.
The first line contains two integer numbers *n* and *k* (2<=≀<=*n*<=≀<=100, 1<=≀<=*k*<=≀<=*n*<=-<=1). The next line contains *k* integer numbers *a*1,<=*a*2,<=...,<=*a**k* (1<=≀<=*a**i*<=≀<=109).
Print *k* numbers, the *i*-th one corresponds to the number of child to be eliminated at the *i*-th step.
[ "7 5\n10 4 11 4 1\n", "3 2\n2 5\n" ]
[ "4 2 5 6 1 \n", "3 2 \n" ]
Let's consider first example: - In the first step child 4 is eliminated, child 5 becomes the leader. - In the second step child 2 is eliminated, child 3 becomes the leader. - In the third step child 5 is eliminated, child 6 becomes the leader. - In the fourth step child 6 is eliminated, child 7 becomes the leader. - In the final step child 1 is eliminated, child 3 becomes the leader.
[ { "input": "7 5\n10 4 11 4 1", "output": "4 2 5 6 1 " }, { "input": "3 2\n2 5", "output": "3 2 " }, { "input": "2 1\n1", "output": "2 " }, { "input": "2 1\n2", "output": "1 " }, { "input": "2 1\n3", "output": "2 " }, { "input": "10 7\n5 10 4 3 8 10 6",...
62
4,608,000
3
4,583
981
Useful Decomposition
[ "implementation", "trees" ]
null
null
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer $n$ ($2 \leq n \leq 10^{5}$) the number of nodes in the tree. Each of the next $n<=-<=1$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$)Β β€” the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $m$. Each of the next $m$ lines should contain two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \neq v_i$) denoting that one of the paths in the decomposition is the simple path between nodes $u_i$ and $v_i$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
[ "4\n1 2\n2 3\n3 4\n", "6\n1 2\n2 3\n3 4\n2 5\n3 6\n", "5\n1 2\n1 3\n1 4\n1 5\n" ]
[ "Yes\n1\n1 4\n", "No\n", "Yes\n4\n1 2\n1 3\n1 4\n1 5\n" ]
The tree from the first example is shown on the picture below: <img class="tex-graphics" src="https://espresso.codeforces.com/9eb4b4c143d3ad267ae05d1e43341bd368b3088b.png" style="max-width: 100.0%;max-height: 100.0%;"/> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. The tree from the second example is shown on the picture below: <img class="tex-graphics" src="https://espresso.codeforces.com/20704b97182d9bcde3321c00a16edcae4d772d93.png" style="max-width: 100.0%;max-height: 100.0%;"/> We can show that there are no valid decompositions of this tree. The tree from the third example is shown on the picture below: <img class="tex-graphics" src="https://espresso.codeforces.com/357ff9496a4ed4746401160ee6ee63f5d57d81b9.png" style="max-width: 100.0%;max-height: 100.0%;"/> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
[ { "input": "4\n1 2\n2 3\n3 4", "output": "Yes\n1\n1 4" }, { "input": "6\n1 2\n2 3\n3 4\n2 5\n3 6", "output": "No" }, { "input": "5\n1 2\n1 3\n1 4\n1 5", "output": "Yes\n4\n1 2\n1 3\n1 4\n1 5" }, { "input": "2\n1 2", "output": "Yes\n1\n1 2" }, { "input": "8\n1 2\n1...
483
8,089,600
3
4,584
0
none
[ "none" ]
null
null
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but *n* different heads that can read data in parallel. When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the *i*-th reading head is above the track number *h**i*. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered *h*1, *h*2, ..., *h**n* have been read at the beginning of the operation. Mike needs to read the data on *m* distinct tracks with numbers *p*1, *p*2, ..., *p**m*. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.
The first line of the input contains two space-separated integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the number of disk heads and the number of tracks to read, accordingly. The second line contains *n* distinct integers *h**i* in ascending order (1<=≀<=*h**i*<=≀<=1010, *h**i*<=&lt;<=*h**i*<=+<=1) β€” the initial positions of the heads. The third line contains *m* distinct integers *p**i* in ascending order (1<=≀<=*p**i*<=≀<=1010, *p**i*<=&lt;<=*p**i*<=+<=1) - the numbers of tracks to read. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Print a single number β€” the minimum time required, in seconds, to read all the needed tracks.
[ "3 4\n2 5 6\n1 3 6 8\n", "3 3\n1 2 3\n1 2 3\n", "1 2\n165\n142 200\n" ]
[ "2\n", "0\n", "81\n" ]
The first test coincides with the figure. In this case the given tracks can be read in 2 seconds in the following way: 1. during the first second move the 1-st head to the left and let it stay there; 1. move the second head to the left twice; 1. move the third head to the right twice (note that the 6-th track has already been read at the beginning). One cannot read the tracks in 1 second as the 3-rd head is at distance 2 from the 8-th track.
[ { "input": "3 4\n2 5 6\n1 3 6 8", "output": "2" }, { "input": "3 3\n1 2 3\n1 2 3", "output": "0" }, { "input": "1 2\n165\n142 200", "output": "81" }, { "input": "1 2\n5000000000\n1 10000000000", "output": "14999999998" }, { "input": "2 4\n3 12\n1 7 8 14", "out...
233
21,708,800
3
4,586
8
Obsession with Robots
[ "constructive algorithms", "graphs", "implementation" ]
B. Obsession with Robots
2
64
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug β€” the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in.
The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100.
In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist).
[ "LLUUUR\n", "RRUULLDD\n" ]
[ "OK\n", "BUG\n" ]
none
[ { "input": "LLUUUR", "output": "OK" }, { "input": "RRUULLDD", "output": "BUG" }, { "input": "L", "output": "OK" }, { "input": "R", "output": "OK" }, { "input": "R", "output": "OK" }, { "input": "RR", "output": "OK" }, { "input": "DL", "...
312
0
0
4,592
137
History
[ "sortings" ]
null
null
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the World history encompasses exactly *n* events: the *i*-th event had continued from the year *a**i* to the year *b**i* inclusive (*a**i*<=&lt;<=*b**i*). Polycarpus easily learned the dates when each of *n* events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event *j* includes an event *i* if *a**j*<=&lt;<=*a**i* and *b**i*<=&lt;<=*b**j*. Your task is simpler: find the number of events that are included in some other event.
The first input line contains integer *n* (1<=≀<=*n*<=≀<=105) which represents the number of events. Next *n* lines contain descriptions of the historical events, one event per line. The *i*<=+<=1 line contains two integers *a**i* and *b**i* (1<=≀<=*a**i*<=&lt;<=*b**i*<=≀<=109) β€” the beginning and the end of the *i*-th event. No two events start or finish in the same year, that is, *a**i*<=β‰ <=*a**j*,<=*a**i*<=β‰ <=*b**j*,<=*b**i*<=β‰ <=*a**j*,<=*b**i*<=β‰ <=*b**j* for all *i*, *j* (where *i*<=β‰ <=*j*). Events are given in arbitrary order.
Print the only integer β€” the answer to the problem.
[ "5\n1 10\n2 9\n3 8\n4 7\n5 6\n", "5\n1 100\n2 50\n51 99\n52 98\n10 60\n", "1\n1 1000000000\n" ]
[ "4\n", "4\n", "0\n" ]
In the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third β€” in the second and the second β€” in the first. In the second example all events except the first one are contained in the first. In the third example only one event, so the answer is 0.
[ { "input": "5\n1 10\n2 9\n3 8\n4 7\n5 6", "output": "4" }, { "input": "5\n1 100\n2 50\n51 99\n52 98\n10 60", "output": "4" }, { "input": "1\n1 1000000000", "output": "0" }, { "input": "2\n100 1000\n500 1500", "output": "0" }, { "input": "4\n1 100\n50 150\n120 200\...
2,000
9,523,200
0
4,595
429
Tricky Function
[ "data structures", "divide and conquer", "geometry" ]
null
null
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task. You're given an (1-based) array *a* with *n* elements. Let's define function *f*(*i*,<=*j*) (1<=≀<=*i*,<=*j*<=≀<=*n*) as (*i*<=-<=*j*)2<=+<=*g*(*i*,<=*j*)2. Function g is calculated by the following pseudo-code: Find a value *min**i*<=β‰ <=*j*Β Β *f*(*i*,<=*j*). Probably by now Iahub already figured out the solution to this problem. Can you?
The first line of input contains a single integer *n* (2<=≀<=*n*<=≀<=100000). Next line contains *n* integers *a*[1], *a*[2], ..., *a*[*n*] (<=-<=104<=≀<=*a*[*i*]<=≀<=104).
Output a single integer β€” the value of *min**i*<=β‰ <=*j*Β Β *f*(*i*,<=*j*).
[ "4\n1 0 0 -1\n", "2\n1 -1\n" ]
[ "1\n", "2\n" ]
none
[ { "input": "4\n1 0 0 -1", "output": "1" }, { "input": "2\n1 -1", "output": "2" }, { "input": "100\n-57 -64 83 76 80 27 60 76 -80 -56 52 72 -17 92 -96 87 41 -88 94 89 12 42 36 34 -100 -43 -42 62 3 87 -69 -6 -27 -59 -7 5 -90 -23 63 -87 -60 -92 -40 54 -16 -47 67 -64 10 33 -19 53 -7 -62 16 -...
77
4,198,400
-1
4,596
478
Red-Green Towers
[ "dp" ]
null
null
There are *r* red and *g* green blocks for construction of the red-green tower. Red-green tower can be built following next rules: - Red-green tower is consisting of some number of levels; - Let the red-green tower consist of *n* levels, then the first level of this tower should consist of *n* blocks, second level β€” of *n*<=-<=1 blocks, the third one β€” of *n*<=-<=2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; - Each level of the red-green tower should contain blocks of the same color. Let *h* be the maximum possible number of levels of red-green tower, that can be built out of *r* red and *g* green blocks meeting the rules above. The task is to determine how many different red-green towers having *h* levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height *h* moduloΒ 109<=+<=7.
The only line of input contains two integers *r* and *g*, separated by a single space β€” the number of available red and green blocks respectively (0<=≀<=*r*,<=*g*<=≀<=2Β·105, *r*<=+<=*g*<=β‰₯<=1).
Output the only integer β€” the number of different possible red-green towers of height *h* moduloΒ 109<=+<=7.
[ "4 6\n", "9 7\n", "1 1\n" ]
[ "2\n", "6\n", "2\n" ]
The image in the problem statement shows all possible red-green towers for the first sample.
[ { "input": "4 6", "output": "2" }, { "input": "9 7", "output": "6" }, { "input": "1 1", "output": "2" }, { "input": "3 3", "output": "2" }, { "input": "2 19", "output": "1" }, { "input": "18 3", "output": "2" }, { "input": "100000 1", "...
62
614,400
-1
4,611
53
Physical Education
[ "sortings" ]
D. Physical Education
2
256
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the height of the *i*-th student in the line and *n* is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: *b*1,<=*b*2,<=...,<=*b**n*, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: *a*1,<=*a*2,<=...,<=*a**n*. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=300) which is the number of students. The second line contains *n* space-separated integers *a**i* (1<=≀<=*a**i*<=≀<=109) which represent the height of the student occupying the *i*-th place must possess. The third line contains *n* space-separated integers *b**i* (1<=≀<=*b**i*<=≀<=109) which represent the height of the student occupying the *i*-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. *a* and *b* coincide as multisets.
In the first line print an integer *k* (0<=≀<=*k*<=≀<=106) which is the number of moves. It is not required to minimize *k* but it must not exceed 106. Then print *k* lines each containing two space-separated integers. Line *p**i*, *p**i*<=+<=1 (1<=≀<=*p**i*<=≀<=*n*<=-<=1) means that Vasya should swap students occupying places *p**i* and *p**i*<=+<=1.
[ "4\n1 2 3 2\n3 2 1 2\n", "2\n1 100500\n1 100500\n" ]
[ "4\n2 3\n1 2\n3 4\n2 3\n", "0\n" ]
none
[ { "input": "4\n1 2 3 2\n3 2 1 2", "output": "4\n2 3\n1 2\n3 4\n2 3" }, { "input": "2\n1 100500\n1 100500", "output": "0" }, { "input": "3\n652586118 652586118 652586118\n652586118 652586118 652586118", "output": "3\n2 3\n1 2\n2 3" }, { "input": "4\n681106577 681106577 6750771...
216
6,963,200
0
4,613
612
The Union of k-Segments
[ "greedy", "sortings" ]
null
null
You are given *n* segments on the coordinate axis Ox and the number *k*. The point is satisfied if it belongs to at least *k* segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.
The first line contains two integers *n* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=106) β€” the number of segments and the value of *k*. The next *n* lines contain two integers *l**i*,<=*r**i* (<=-<=109<=≀<=*l**i*<=≀<=*r**i*<=≀<=109) each β€” the endpoints of the *i*-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.
First line contains integer *m* β€” the smallest number of segments. Next *m* lines contain two integers *a**j*,<=*b**j* (*a**j*<=≀<=*b**j*) β€” the ends of *j*-th segment in the answer. The segments should be listed in the order from left to right.
[ "3 2\n0 5\n-3 2\n3 8\n", "3 2\n0 5\n-3 3\n3 8\n" ]
[ "2\n0 2\n3 5\n", "1\n0 5\n" ]
none
[ { "input": "3 2\n0 5\n-3 2\n3 8", "output": "2\n0 2\n3 5" }, { "input": "3 2\n0 5\n-3 3\n3 8", "output": "1\n0 5" }, { "input": "1 1\n-1 1", "output": "1\n-1 1" }, { "input": "10 2\n27 96\n-22 45\n-68 26\n46 69\n-91 86\n12 73\n-89 76\n-11 33\n17 47\n-57 78", "output": "1\...
62
5,632,000
0
4,627
0
none
[ "none" ]
null
null
In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process $q$ queries. Each query is a question "what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?"
The first line contains five integers $n, m, c_l, c_e, v$ ($2 \leq n, m \leq 10^8$, $0 \leq c_l, c_e \leq 10^5$, $1 \leq c_l + c_e \leq m - 1$, $1 \leq v \leq n - 1$)Β β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains $c_l$ integers $l_1, \ldots, l_{c_l}$ in increasing order ($1 \leq l_i \leq m$), denoting the positions of the stairs. If $c_l = 0$, the second line is empty. The third line contains $c_e$ integers $e_1, \ldots, e_{c_e}$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $l_i$ and $e_i$ are distinct. The fourth line contains a single integer $q$ ($1 \leq q \leq 10^5$)Β β€” the number of queries. The next $q$ lines describe queries. Each of these lines contains four integers $x_1, y_1, x_2, y_2$ ($1 \leq x_1, x_2 \leq n$, $1 \leq y_1, y_2 \leq m$)Β β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i.Β e. $y_1$ and $y_2$ are not among $l_i$ and $e_i$.
Print $q$ integers, one per lineΒ β€” the answers for the queries.
[ "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n" ]
[ "7\n5\n4\n" ]
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
[ { "input": "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3", "output": "7\n5\n4" }, { "input": "2 2 0 1 1\n\n1\n1\n1 2 2 2", "output": "3" }, { "input": "4 4 1 0 1\n4\n\n5\n1 1 2 2\n1 3 2 2\n3 3 4 3\n3 2 2 2\n1 2 2 3", "output": "6\n4\n3\n5\n4" }, { "input": "10 10 1 8 4\n10\n...
46
0
0
4,634
364
Free Market
[ "dp", "greedy" ]
null
null
John Doe has recently found a "Free Market" in his city β€” that is the place where you can exchange some of your possessions for other things for free. John knows that his city has *n* items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that each item is one of a kind and that means that you cannot exchange set {*a*,<=*b*} for set {*v*,<=*a*}. However, you can always exchange set *x* for any set *y*, unless there is item *p*, such that *p* occurs in *x* and *p* occurs in *y*. For each item, John knows its value *c**i*. John's sense of justice doesn't let him exchange a set of items *x* for a set of items *y*, if *s*(*x*)<=+<=*d*<=&lt;<=*s*(*y*) (*s*(*x*) is the total price of items in the set *x*). During one day John can exchange only one set of items for something else. Initially, he has no items. John wants to get a set of items with the maximum total price. Find the cost of such set and the minimum number of days John can get it in.
The first line contains two space-separated integers *n*, *d* (1<=≀<=*n*<=≀<=50, 1<=≀<=*d*<=≀<=104) β€” the number of items on the market and John's sense of justice value, correspondingly. The second line contains *n* space-separated integers *c**i* (1<=≀<=*c**i*<=≀<=104).
Print two space-separated integers: the maximum possible price in the set of items John can get and the minimum number of days needed to get such set.
[ "3 2\n1 3 10\n", "3 5\n1 2 3\n", "10 10000\n10000 9999 1 10000 10000 10000 1 2 3 4\n" ]
[ "4 3\n", "6 2\n", "50010 6\n" ]
In the first sample John can act like this: - Take the first item (1 - 0 ≀ 2). - Exchange the first item for the second one (3 - 1 ≀ 2). - Take the first item (1 - 0 ≀ 2).
[]
1,000
0
0
4,639
876
Divisiblity of Differences
[ "implementation", "math", "number theory" ]
null
null
You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
First line contains three integers *n*, *k* and *m* (2<=≀<=*k*<=≀<=*n*<=≀<=100<=000, 1<=≀<=*m*<=≀<=100<=000)Β β€” number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109)Β β€” the numbers in the multiset.
If it is not possible to select *k* numbers in the desired way, output Β«NoΒ» (without the quotes). Otherwise, in the first line of output print Β«YesΒ» (without the quotes). In the second line print *k* integers *b*1,<=*b*2,<=...,<=*b**k*Β β€” the selected numbers. If there are multiple possible solutions, print any of them.
[ "3 2 3\n1 8 4\n", "3 3 3\n1 8 4\n", "4 3 5\n2 7 7 7\n" ]
[ "Yes\n1 4 ", "No", "Yes\n2 7 7 " ]
none
[ { "input": "3 2 3\n1 8 4", "output": "Yes\n1 4 " }, { "input": "3 3 3\n1 8 4", "output": "No" }, { "input": "4 3 5\n2 7 7 7", "output": "Yes\n2 7 7 " }, { "input": "9 9 5\n389149775 833127990 969340400 364457730 48649145 316121525 640054660 924273385 973207825", "output":...
1,000
5,529,600
0
4,642
859
Lazy Security Guard
[ "brute force", "geometry", "math" ]
null
null
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
Input will consist of a single integer *N* (1<=≀<=*N*<=≀<=106), the number of city blocks that must be enclosed by the route.
Print the minimum perimeter that can be achieved.
[ "4\n", "11\n", "22\n" ]
[ "8\n", "14\n", "20\n" ]
Here are some possible shapes for the examples: <img class="tex-graphics" src="https://espresso.codeforces.com/e11bef2cf82b55dd583cfc97d12b5aee5e483a65.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "4", "output": "8" }, { "input": "11", "output": "14" }, { "input": "22", "output": "20" }, { "input": "3", "output": "8" }, { "input": "1024", "output": "128" }, { "input": "101", "output": "42" }, { "input": "30", "output":...
62
0
3
4,644
778
Peterson Polyglot
[ "brute force", "dfs and similar", "dsu", "hashing", "strings", "trees" ]
null
null
Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters. Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his languages which is called broom. Broom is rooted tree with edges marked with letters. Initially broom is represented by the only vertexΒ β€” the root of the broom. When Peterson wants to add new word to the language he stands at the root and processes the letters of new word one by one. Consider that Peterson stands at the vertex *u*. If there is an edge from *u* marked with current letter, Peterson goes through this edge. Otherwise Peterson adds new edge from *u* to the new vertex *v*, marks it with the current letter and goes through the new edge. Size of broom is the number of vertices in it. In the evening after working day Peterson can't understand the language he made this morning. It is too difficult for bored Peterson and he tries to make it simpler. Simplification of the language is the process of erasing some letters from some words of this language. Formally, Peterson takes some positive integer *p* and erases *p*-th letter from all the words of this language having length at least *p*. Letters in words are indexed starting by 1. Peterson considers that simplification should change at least one word, i.e. there has to be at least one word of length at least *p*. Peterson tries to make his language as simple as possible, so he wants to choose *p* such that the size of the broom for his simplified language is as small as possible. Peterson is pretty annoyed with this task so he asks you for help. Write a program to find the smallest possible size of the broom and integer *p*.
The first line of input contains integer *n* (2<=≀<=*n*<=≀<=3Β·105)Β β€” the size of the broom. Next *n*<=-<=1 lines describe the broom: *i*-th of them contains integers *u**i*, *v**i* and letter *x**i*Β β€” describing the edge from *u**i* to *v**i* marked with letter *x**i*. Vertices are numbered from 1 to *n*. All *x**i* are lowercase latin letters. Vertex 1 is the root of the broom. Edges describe correct broom which is made from Peterson's language.
The first line of output should contain the minimum possible size of the broom after its simplification. The second line of output should contain integer *p* to choose. If there are several suitable *p* values, print the smallest one.
[ "5\n1 2 c\n2 3 a\n3 4 t\n2 5 t\n", "16\n1 2 o\n2 3 f\n1 4 p\n4 5 i\n5 6 e\n6 7 c\n7 8 e\n4 9 r\n9 10 e\n10 11 t\n11 12 t\n12 13 y\n10 14 f\n14 15 i\n15 16 x\n" ]
[ "3\n2\n", "12\n2\n" ]
<img class="tex-graphics" src="https://espresso.codeforces.com/4b46644a485274790bd64830c23320ae20be3097.png" style="max-width: 100.0%;max-height: 100.0%;"/> Broom from the second sample test can be built using language "piece", "of", "pie", "pretty", "prefix". Its simplification with *p* = 2 obtains the language of words "pece", "o", "pe", "petty", "pefix". This language gives us the broom with minimum possible size.
[ { "input": "5\n1 2 c\n2 3 a\n3 4 t\n2 5 t", "output": "3\n2" }, { "input": "16\n1 2 o\n2 3 f\n1 4 p\n4 5 i\n5 6 e\n6 7 c\n7 8 e\n4 9 r\n9 10 e\n10 11 t\n11 12 t\n12 13 y\n10 14 f\n14 15 i\n15 16 x", "output": "12\n2" }, { "input": "2\n1 2 o", "output": "1\n1" }, { "input": "3...
30
0
0
4,655
159
Matchmaker
[ "*special", "greedy", "sortings" ]
null
null
Polycarpus has *n* markers and *m* marker caps. Each marker is described by two numbers: *x**i* is the color and *y**i* is the diameter. Correspondingly, each cap is described by two numbers: *a**j* is the color and *b**j* is the diameter. Cap (*a**j*,<=*b**j*) can close marker (*x**i*,<=*y**i*) only if their diameters match, that is, *b**j*<==<=*y**i*. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, *a**j*<==<=*x**i*. Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.
The first input line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the number of markers and the number of caps, correspondingly. Next *n* lines describe the markers. The *i*-th line contains two space-separated integers *x**i*, *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=1000) β€” the *i*-th marker's color and diameter, correspondingly. Next *m* lines describe the caps. The *j*-th line contains two space-separated integers *a**j*, *b**j* (1<=≀<=*a**j*,<=*b**j*<=≀<=1000) β€” the color and diameter of the *j*-th cap, correspondingly.
Print two space-separated integers *u*,<=*v*, where *u* is the number of closed markers and *v* is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.
[ "3 4\n1 2\n3 4\n2 4\n5 4\n2 4\n1 1\n1 2\n", "2 2\n1 2\n2 1\n3 4\n5 1\n" ]
[ "3 2\n", "1 0\n" ]
In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed β€” the first and the third markers.
[ { "input": "3 4\n1 2\n3 4\n2 4\n5 4\n2 4\n1 1\n1 2", "output": "3 2" }, { "input": "2 2\n1 2\n2 1\n3 4\n5 1", "output": "1 0" }, { "input": "6 7\n2 1\n2 2\n2 1\n1 1\n2 1\n1 2\n2 2\n2 2\n2 2\n1 2\n2 2\n1 1\n1 2", "output": "3 3" }, { "input": "6 7\n2 1\n1 1\n2 2\n1 2\n1 1\n1 2...
2,870
24,883,200
3
4,671
437
The Child and Homework
[ "implementation" ]
null
null
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct. Fortunately the child knows how to solve such complicated test. The child will follow the algorithm: - If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great. - If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice). You are given a multiple-choice questions, can you predict child's choose?
The first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length. Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_".
Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes).
[ "A.VFleaKing_is_the_author_of_this_problem\nB.Picks_is_the_author_of_this_problem\nC.Picking_is_the_author_of_this_problem\nD.Ftiasch_is_cute\n", "A.ab\nB.abcde\nC.ab\nD.abc\n", "A.c\nB.cc\nC.c\nD.c\n" ]
[ "D\n", "C\n", "B\n" ]
In the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D. In the second sample, no choice is great, so the child will choose the luckiest choice C. In the third sample, the choice B (length 2) is twice longer than all other choices', so it is great choice. There is no other great choices so the child will choose B.
[ { "input": "A.VFleaKing_is_the_author_of_this_problem\nB.Picks_is_the_author_of_this_problem\nC.Picking_is_the_author_of_this_problem\nD.Ftiasch_is_cute", "output": "D" }, { "input": "A.ab\nB.abcde\nC.ab\nD.abc", "output": "C" }, { "input": "A.c\nB.cc\nC.c\nD.c", "output": "B" }, ...
108
6,963,200
0
4,688
631
Report
[ "data structures", "sortings" ]
null
null
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are *n* commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of *m* managers. Each of them may reorder the elements in some order. Namely, the *i*-th manager either sorts first *r**i* numbers in non-descending or non-ascending order and then passes the report to the manager *i*<=+<=1, or directly to Blake (if this manager has number *i*<==<=*m*). Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence *a**i* of length *n* and the description of each manager, that is value *r**i* and his favourite order. You are asked to speed up the process and determine how the final report will look like.
The first line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=200<=000)Β β€” the number of commodities in the report and the number of managers, respectively. The second line contains *n* integers *a**i* (|*a**i*|<=≀<=109)Β β€” the initial report before it gets to the first manager. Then follow *m* lines with the descriptions of the operations managers are going to perform. The *i*-th of these lines contains two integers *t**i* and *r**i* (, 1<=≀<=*r**i*<=≀<=*n*), meaning that the *i*-th manager sorts the first *r**i* numbers either in the non-descending (if *t**i*<==<=1) or non-ascending (if *t**i*<==<=2) order.
Print *n* integersΒ β€” the final report, which will be passed to Blake by manager number *m*.
[ "3 1\n1 2 3\n2 2\n", "4 2\n1 2 4 3\n2 3\n1 2\n" ]
[ "2 1 3 ", "2 4 1 3 " ]
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form. In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
[ { "input": "3 1\n1 2 3\n2 2", "output": "2 1 3 " }, { "input": "4 2\n1 2 4 3\n2 3\n1 2", "output": "2 4 1 3 " }, { "input": "4 1\n4 3 2 1\n1 4", "output": "1 2 3 4 " }, { "input": "5 1\n1 2 3 4 5\n2 5", "output": "5 4 3 2 1 " }, { "input": "6 2\n3 1 2 6 4 5\n1 6\n...
2,000
30,515,200
0
4,697
898
Proper Nutrition
[ "brute force", "implementation", "number theory" ]
null
null
Vasya has *n* burles. One bottle of Ber-Cola costs *a* burles and one Bars bar costs *b* burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly *n* burles. In other words, you should find two non-negative integers *x* and *y* such that Vasya can buy *x* bottles of Ber-Cola and *y* Bars bars and *x*Β·*a*<=+<=*y*Β·*b*<==<=*n* or tell that it's impossible.
First line contains single integer *n* (1<=≀<=*n*<=≀<=10<=000<=000)Β β€” amount of money, that Vasya has. Second line contains single integer *a* (1<=≀<=*a*<=≀<=10<=000<=000)Β β€” cost of one bottle of Ber-Cola. Third line contains single integer *b* (1<=≀<=*b*<=≀<=10<=000<=000)Β β€” cost of one Bars bar.
If Vasya can't buy Bars and Ber-Cola in such a way to spend exactly *n* burles print Β«NOΒ» (without quotes). Otherwise in first line print Β«YESΒ» (without quotes). In second line print two non-negative integers *x* and *y*Β β€” number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly *n* burles, i.e. *x*Β·*a*<=+<=*y*Β·*b*<==<=*n*. If there are multiple answers print any of them. Any of numbers *x* and *y* can be equal 0.
[ "7\n2\n3\n", "100\n25\n10\n", "15\n4\n8\n", "9960594\n2551\n2557\n" ]
[ "YES\n2 1\n", "YES\n0 10\n", "NO\n", "YES\n1951 1949\n" ]
In first example Vasya can buy two bottles of Ber-Cola and one Bars bar. He will spend exactly 2Β·2 + 1Β·3 = 7 burles. In second example Vasya can spend exactly *n* burles multiple ways: - buy two bottles of Ber-Cola and five Bars bars; - buy four bottles of Ber-Cola and don't buy Bars bars; - don't buy Ber-Cola and buy 10 Bars bars. In third example it's impossible to but Ber-Cola and Bars bars in order to spend exactly *n* burles.
[ { "input": "7\n2\n3", "output": "YES\n2 1" }, { "input": "100\n25\n10", "output": "YES\n0 10" }, { "input": "15\n4\n8", "output": "NO" }, { "input": "9960594\n2551\n2557", "output": "YES\n1951 1949" }, { "input": "10000000\n1\n1", "output": "YES\n0 10000000" ...
670
1,638,400
0
4,714
558
A Simple Task
[ "data structures", "sortings", "strings" ]
null
null
This task is very simple. Given a string *S* of length *n* and *q* queries each query is on the format *i* *j* *k* which means sort the substring consisting of the characters from *i* to *j* in non-decreasing order if *k*<==<=1 or in non-increasing order if *k*<==<=0. Output the final string after applying the queries.
The first line will contain two integers *n*,<=*q* (1<=≀<=*n*<=≀<=105, 0<=≀<=*q*<=≀<=50<=000), the length of the string and the number of queries respectively. Next line contains a string *S* itself. It contains only lowercase English letters. Next *q* lines will contain three integers each *i*,<=*j*,<=*k* (1<=≀<=*i*<=≀<=*j*<=≀<=*n*, ).
Output one line, the string *S* after applying the queries.
[ "10 5\nabacdabcda\n7 10 0\n5 8 1\n1 4 0\n3 6 0\n7 10 1\n", "10 1\nagjucbvdfk\n1 10 1\n" ]
[ "cbcaaaabdd", "abcdfgjkuv" ]
First sample test explanation: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3ac4e8cc7e335675a4a2b7b4758bfb3865377cea.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a90b5b03cf59288d8861f0142ecbdf6b12f69e5c.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1f482a91a275b6bce07eaed85312eac0cfcc6ccf.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/33b1a4a924f4bd562551ba4e40309f180dbe22e0.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bddc77fd5b02858eb2ff29819cd16a93dbd241e6.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "10 5\nabacdabcda\n7 10 0\n5 8 1\n1 4 0\n3 6 0\n7 10 1", "output": "cbcaaaabdd" }, { "input": "10 1\nagjucbvdfk\n1 10 1", "output": "abcdfgjkuv" }, { "input": "10 6\nrmaahmdmuo\n1 3 1\n4 6 0\n5 6 1\n7 8 0\n8 10 0\n8 9 1", "output": "amrmahmoud" }, { "input": "10 5\...
5,000
2,560,000
0
4,715
630
Selection of Personnel
[ "combinatorics", "math" ]
null
null
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received *n* resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
The only line of the input contains one integer *n* (7<=≀<=*n*<=≀<=777) β€” the number of potential employees that sent resumes.
Output one integer β€” the number of different variants of group composition.
[ "7\n" ]
[ "29" ]
none
[ { "input": "7", "output": "29" }, { "input": "8", "output": "92" }, { "input": "9", "output": "246" }, { "input": "10", "output": "582" }, { "input": "321", "output": "66715035255088" }, { "input": "624", "output": "7147161340917624" }, { "...
46
0
3
4,732
578
"Or" Game
[ "brute force", "greedy" ]
null
null
You are given *n* numbers *a*1,<=*a*2,<=...,<=*a**n*. You can perform at most *k* operations. For each operation you can multiply one of the numbers by *x*. We want to make as large as possible, where denotes the bitwise OR. Find the maximum possible value of after performing at most *k* operations optimally.
The first line contains three integers *n*, *k* and *x* (1<=≀<=*n*<=≀<=200<=000, 1<=≀<=*k*<=≀<=10, 2<=≀<=*x*<=≀<=8). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109).
Output the maximum value of a bitwise OR of sequence elements after performing operations.
[ "3 1 2\n1 1 1\n", "4 2 3\n1 2 4 8\n" ]
[ "3\n", "79\n" ]
For the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1ee73b671ed4bc53f2f96ed1a85fd98388e1712b.png" style="max-width: 100.0%;max-height: 100.0%;"/>. For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.
[ { "input": "3 1 2\n1 1 1", "output": "3" }, { "input": "4 2 3\n1 2 4 8", "output": "79" }, { "input": "2 1 2\n12 9", "output": "30" }, { "input": "2 1 2\n12 7", "output": "31" }, { "input": "3 1 3\n3 2 0", "output": "11" }, { "input": "5 10 8\n10000000...
124
0
0
4,738
268
Beautiful Sets of Points
[ "constructive algorithms", "implementation" ]
null
null
Manao has invented a new mathematical term β€” a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 1. For any two points from the set, the distance between them is a non-integer. Consider all points (*x*,<=*y*) which satisfy the inequations: 0<=≀<=*x*<=≀<=*n*; 0<=≀<=*y*<=≀<=*m*; *x*<=+<=*y*<=&gt;<=0. Choose their subset of maximum size such that it is also a beautiful set of points.
The single line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100).
In the first line print a single integer β€” the size *k* of the found beautiful set. In each of the next *k* lines print a pair of space-separated integers β€” the *x*- and *y*- coordinates, respectively, of a point from the set. If there are several optimal solutions, you may print any of them.
[ "2 2\n", "4 3\n" ]
[ "3\n0 1\n1 2\n2 0\n", "4\n0 3\n2 1\n3 0\n4 2\n" ]
Consider the first sample. The distance between points (0, 1) and (1, 2) equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bfe16f27ebc966df6f10ba356a1547b6e7242dd7.png" style="max-width: 100.0%;max-height: 100.0%;"/>, between (0, 1) and (2, 0) β€” <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/23d63d8a57cddda72562a512c05111054cd85870.png" style="max-width: 100.0%;max-height: 100.0%;"/>, between (1, 2) and (2, 0) β€” <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/23d63d8a57cddda72562a512c05111054cd85870.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.
[ { "input": "2 2", "output": "3\n0 1\n1 2\n2 0" }, { "input": "4 3", "output": "4\n0 3\n2 1\n3 0\n4 2" }, { "input": "21 21", "output": "22\n21 0\n20 1\n19 2\n18 3\n17 4\n16 5\n15 6\n14 7\n13 8\n12 9\n11 10\n10 11\n9 12\n8 13\n7 14\n6 15\n5 16\n4 17\n3 18\n2 19\n1 20\n0 21" }, { ...
122
1,638,400
0
4,757
746
Green and Black Tea
[ "constructive algorithms", "greedy", "math" ]
null
null
Innokentiy likes tea very much and today he wants to drink exactly *n* cups of tea. He would be happy to drink more but he had exactly *n* tea bags, *a* of them are green and *b* are black. Innokentiy doesn't like to drink the same tea (green or black) more than *k* times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink *n* cups of tea, without drinking the same tea more than *k* times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.
The first line contains four integers *n*, *k*, *a* and *b* (1<=≀<=*k*<=≀<=*n*<=≀<=105, 0<=≀<=*a*,<=*b*<=≀<=*n*)Β β€” the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that *a*<=+<=*b*<==<=*n*.
If it is impossible to drink *n* cups of tea, print "NO" (without quotes). Otherwise, print the string of the length *n*, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them.
[ "5 1 3 2\n", "7 2 2 5\n", "4 3 4 0\n" ]
[ "GBGBG\n", "BBGBGBB", "NO\n" ]
none
[ { "input": "5 1 3 2", "output": "GBGBG" }, { "input": "7 2 2 5", "output": "BBGBBGB" }, { "input": "4 3 4 0", "output": "NO" }, { "input": "2 2 0 2", "output": "BB" }, { "input": "3 2 0 3", "output": "NO" }, { "input": "1 1 0 1", "output": "B" },...
46
0
0
4,763
0
none
[ "none" ]
null
null
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of *n* players, all of which are GUC students. However, the team might have players belonging to different departments. There are *m* departments in GUC, numbered from 1 to *m*. Herr Wafa's department has number *h*. For each department *i*, Herr Wafa knows number *s**i* β€” how many students who play basketball belong to this department. Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.
The first line contains three integers *n*, *m* and *h* (1<=≀<=*n*<=≀<=100,<=1<=≀<=*m*<=≀<=1000,<=1<=≀<=*h*<=≀<=*m*) β€” the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly. The second line contains a single-space-separated list of *m* integers *s**i* (1<=≀<=*s**i*<=≀<=100), denoting the number of students in the *i*-th department. Note that *s**h* includes Herr Wafa.
Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10<=-<=6.
[ "3 2 1\n2 1\n", "3 2 1\n1 1\n", "3 2 1\n2 2\n" ]
[ "1\n", "-1\n", "0.666667\n" ]
In the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department. In the second example, there are not enough players. In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team.
[ { "input": "3 2 1\n2 1", "output": "1" }, { "input": "3 2 1\n1 1", "output": "-1" }, { "input": "3 2 1\n2 2", "output": "0.666667" }, { "input": "3 2 1\n1 2", "output": "0.000000" }, { "input": "6 5 3\n5 2 3 10 5", "output": "0.380435" }, { "input": "7...
0
0
-1
4,778
789
Masha and geometric depression
[ "brute force", "implementation", "math" ]
null
null
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression *b* defined by two integers *b*1 and *q*. Remind that a geometric progression is a sequence of integers *b*1,<=*b*2,<=*b*3,<=..., where for each *i*<=&gt;<=1 the respective term satisfies the condition *b**i*<==<=*b**i*<=-<=1Β·*q*, where *q* is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both *b*1 and *q* can equal 0. Also, Dvastan gave Masha *m* "bad" integers *a*1,<=*a*2,<=...,<=*a**m*, and an integer *l*. Masha writes all progression terms one by one onto the board (including repetitive) while condition |*b**i*|<=≀<=*l* is satisfied (|*x*| means absolute value of *x*). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term. But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
The first line of input contains four integers *b*1, *q*, *l*, *m* (-109<=≀<=*b*1,<=*q*<=≀<=109, 1<=≀<=*l*<=≀<=109, 1<=≀<=*m*<=≀<=105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains *m* distinct integers *a*1,<=*a*2,<=...,<=*a**m* (-109<=≀<=*a**i*<=≀<=109)Β β€” numbers that will never be written on the board.
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
[ "3 2 30 4\n6 14 25 48\n", "123 1 2143435 4\n123 11 -5453 141245\n", "123 1 2143435 4\n54343 -13 6 124\n" ]
[ "3", "0", "inf" ]
In the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed *l* by absolute value. In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer. In the third case, Masha will write infinitely integers 123.
[ { "input": "3 2 30 4\n6 14 25 48", "output": "3" }, { "input": "123 1 2143435 4\n123 11 -5453 141245", "output": "0" }, { "input": "123 1 2143435 4\n54343 -13 6 124", "output": "inf" }, { "input": "3 2 25 2\n379195692 -69874783", "output": "4" }, { "input": "3 2 3...
46
4,608,000
0
4,779
868
Race Against Time
[ "implementation" ]
null
null
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with three handsΒ β€” hour, minute, and second. Time froze, and clocks now show the time *h* hours, *m* minutes, *s* seconds. Last time Misha talked with the coordinator at *t*1 o'clock, so now he stands on the number *t*1 on the clock face. The contest should be ready by *t*2 o'clock. In the terms of paradox it means that Misha has to go to number *t*2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction. Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way). Given the hands' positions, *t*1, and *t*2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from *t*1 to *t*2 by the clock face.
Five integers *h*, *m*, *s*, *t*1, *t*2 (1<=≀<=*h*<=≀<=12, 0<=≀<=*m*,<=*s*<=≀<=59, 1<=≀<=*t*1,<=*t*2<=≀<=12, *t*1<=β‰ <=*t*2). Misha's position and the target time do not coincide with the position of any hand.
Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").
[ "12 30 45 3 11\n", "12 0 1 12 1\n", "3 47 0 4 9\n" ]
[ "NO\n", "YES\n", "YES\n" ]
The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same.
[ { "input": "12 30 45 3 11", "output": "NO" }, { "input": "12 0 1 12 1", "output": "YES" }, { "input": "3 47 0 4 9", "output": "YES" }, { "input": "10 22 59 6 10", "output": "YES" }, { "input": "3 1 13 12 3", "output": "NO" }, { "input": "11 19 28 9 10"...
62
0
0
4,803
825
Suitable Replacement
[ "binary search", "greedy", "implementation" ]
null
null
You are given two strings *s* and *t* consisting of small Latin letters, string *s* can also contain '?' characters. Suitability of string *s* is calculated by following metric: Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings *s*, you choose the one with the largest number of non-intersecting occurrences of string *t*. Suitability is this number of occurrences. You should replace all '?' characters with small Latin letters in such a way that the suitability of string *s* is maximal.
The first line contains string *s* (1<=≀<=|*s*|<=≀<=106). The second line contains string *t* (1<=≀<=|*t*|<=≀<=106).
Print string *s* with '?' replaced with small Latin letters in such a way that suitability of that string is maximal. If there are multiple strings with maximal suitability then print any of them.
[ "?aa?\nab\n", "??b?\nza\n", "abcd\nabacaba\n" ]
[ "baab\n", "azbz\n", "abcd\n" ]
In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2. In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them. In the third example there are no '?' characters and the suitability of the string is 0.
[ { "input": "?aa?\nab", "output": "baab" }, { "input": "??b?\nza", "output": "azbz" }, { "input": "abcd\nabacaba", "output": "abcd" }, { "input": "mqwstphetbfrsyxuzdww\nrutseqtsbh", "output": "mqwstphetbfrsyxuzdww" }, { "input": "????????????????????\nxwkxsxlrre", ...
514
60,006,400
3
4,816
429
Working out
[ "dp" ]
null
null
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix *a* with *n* lines and *m* columns. Let number *a*[*i*][*j*] represents the calories burned by performing workout at the cell of gym in the *i*-th line and the *j*-th column. Iahub starts with workout located at line 1 and column 1. He needs to finish with workout *a*[*n*][*m*]. After finishing workout *a*[*i*][*j*], he can go to workout *a*[*i*<=+<=1][*j*] or *a*[*i*][*j*<=+<=1]. Similarly, Iahubina starts with workout *a*[*n*][1] and she needs to finish with workout *a*[1][*m*]. After finishing workout from cell *a*[*i*][*j*], she goes to either *a*[*i*][*j*<=+<=1] or *a*[*i*<=-<=1][*j*]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout. If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.
The first line of the input contains two integers *n* and *m* (3<=≀<=*n*,<=*m*<=≀<=1000). Each of the next *n* lines contains *m* integers: *j*-th number from *i*-th line denotes element *a*[*i*][*j*] (0<=≀<=*a*[*i*][*j*]<=≀<=105).
The output contains a single number β€” the maximum total gain possible.
[ "3 3\n100 100 100\n100 1 100\n100 100 100\n" ]
[ "800" ]
Iahub will choose exercises *a*[1][1] → *a*[1][2] → *a*[2][2] → *a*[3][2] → *a*[3][3]. Iahubina will choose exercises *a*[3][1] → *a*[2][1] → *a*[2][2] → *a*[2][3] → *a*[1][3].
[ { "input": "3 3\n100 100 100\n100 1 100\n100 100 100", "output": "800" }, { "input": "4 5\n87882 40786 3691 85313 46694\n28884 16067 3242 97367 78518\n4250 35501 9780 14435 19004\n64673 65438 56977 64495 27280", "output": "747898" }, { "input": "3 3\n3 1 2\n3 2 0\n2 3 2", "output": "...
312
10,035,200
0
4,847
267
Subtractions
[ "math", "number theory" ]
null
null
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5). You've got some number of pairs (*a**i*,<=*b**i*). How many operations will be performed for each of them?
The first line contains the number of pairs *n* (1<=<=≀<=<=*n*<=<=≀<=<=1000). Then follow *n* lines, each line contains a pair of positive integers *a**i*,<=*b**i* (1<=<=≀<=<=*a**i*,<=<=*b**i*<=<=≀<=<=109).
Print the sought number of operations for each pair on a single line.
[ "2\n4 17\n7 987654321\n" ]
[ "8\n141093479\n" ]
none
[ { "input": "2\n4 17\n7 987654321", "output": "8\n141093479" }, { "input": "10\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321\n7 987654321", "output": "141093479\n141093479\n141093479\n141093479\n141093479\n141093479\n141093479...
30
0
0
4,848
940
Cashback
[ "data structures", "dp", "greedy", "math" ]
null
null
Since you are the best Wraith King, Nizhniy Magazin Β«MirΒ» at the centre of Vinnytsia is offering you a discount. You are given an array *a* of length *n* and an integer *c*. The value of some array *b* of length *k* is the sum of its elements except for the smallest. For example, the value of the array [3,<=1,<=6,<=5,<=2] with *c*<==<=2 is 3<=+<=6<=+<=5<==<=14. Among all possible partitions of *a* into contiguous subarrays output the smallest possible sum of the values of these subarrays.
The first line contains integers *n* and *c* (1<=≀<=*n*,<=*c*<=≀<=100<=000). The second line contains *n* integers *a**i* (1<=≀<=*a**i*<=≀<=109)Β β€” elements of *a*.
Output a single integer Β β€” the smallest possible sum of values of these subarrays of some partition of *a*.
[ "3 5\n1 2 3\n", "12 10\n1 1 10 10 10 10 10 10 9 10 10 10\n", "7 2\n2 3 6 4 5 7 1\n", "8 4\n1 3 4 5 5 3 4 1\n" ]
[ "6\n", "92\n", "17\n", "23\n" ]
In the first example any partition yields 6 as the sum. In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively. In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively. In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.
[ { "input": "3 5\n1 2 3", "output": "6" }, { "input": "12 10\n1 1 10 10 10 10 10 10 9 10 10 10", "output": "92" }, { "input": "7 2\n2 3 6 4 5 7 1", "output": "17" }, { "input": "8 4\n1 3 4 5 5 3 4 1", "output": "23" }, { "input": "15 5\n11 15 16 24 24 28 36 40 49 4...
436
18,432,000
3
4,849
46
Ball Game
[ "brute force", "implementation" ]
A. Ball Game
2
256
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to *n* clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if *n*<==<=5, then after the third throw the child number 2 has the ball again. Overall, *n*<=-<=1 throws are made, and the game ends. The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
The first line contains integer *n* (2<=≀<=*n*<=≀<=100) which indicates the number of kids in the circle.
In the single line print *n*<=-<=1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.
[ "10\n", "3\n" ]
[ "2 4 7 1 6 2 9 7 6\n", "2 1\n" ]
none
[ { "input": "10", "output": "2 4 7 1 6 2 9 7 6" }, { "input": "3", "output": "2 1" }, { "input": "4", "output": "2 4 3" }, { "input": "5", "output": "2 4 2 1" }, { "input": "6", "output": "2 4 1 5 4" }, { "input": "7", "output": "2 4 7 4 2 1" }, ...
92
0
0
4,851
0
none
[ "none" ]
null
null
The mobile application store has a new game called "Subway Roller". The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and *n* columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field. All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel. Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.
Each test contains from one to ten sets of the input data. The first line of the test contains a single integer *t* (1<=≀<=*t*<=≀<=10 for pretests and tests or *t*<==<=1 for hacks; see the Notes section for details) β€” the number of sets. Then follows the description of *t* sets of the input data. The first line of the description of each set contains two integers *n*,<=*k* (2<=≀<=*n*<=≀<=100,<=1<=≀<=*k*<=≀<=26) β€” the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of *n* character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the *k* trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.
For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.
[ "2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....\n", "2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY...\n" ]
[ "YES\nNO\n", "YES\nNO\n" ]
In the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel. Note that in this problem the challenges are restricted to tests that contain only one testset.
[]
77
512,000
3
4,854
847
Weather Tomorrow
[ "implementation", "math" ]
null
null
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last *n* days. Assume that the average air temperature for each day is integral. Vasya believes that if the average temperatures over the last *n* days form an arithmetic progression, where the first term equals to the average temperature on the first day, the second term equals to the average temperature on the second day and so on, then the average temperature of the next (*n*<=+<=1)-th day will be equal to the next term of the arithmetic progression. Otherwise, according to Vasya's method, the temperature of the (*n*<=+<=1)-th day will be equal to the temperature of the *n*-th day. Your task is to help Vasya predict the average temperature for tomorrow, i. e. for the (*n*<=+<=1)-th day.
The first line contains a single integer *n* (2<=≀<=*n*<=≀<=100) β€” the number of days for which the average air temperature is known. The second line contains a sequence of integers *t*1,<=*t*2,<=...,<=*t**n* (<=-<=1000<=≀<=*t**i*<=≀<=1000)Β β€” where *t**i* is the average temperature in the *i*-th day.
Print the average air temperature in the (*n*<=+<=1)-th day, which Vasya predicts according to his method. Note that the absolute value of the predicted temperature can exceed 1000.
[ "5\n10 5 0 -5 -10\n", "4\n1 1 1 1\n", "3\n5 1 -5\n", "2\n900 1000\n" ]
[ "-15\n", "1\n", "-5\n", "1100\n" ]
In the first example the sequence of the average temperatures is an arithmetic progression where the first term is 10 and each following terms decreases by 5. So the predicted average temperature for the sixth day is  - 10 - 5 =  - 15. In the second example the sequence of the average temperatures is an arithmetic progression where the first term is 1 and each following terms equals to the previous one. So the predicted average temperature in the fifth day is 1. In the third example the average temperatures do not form an arithmetic progression, so the average temperature of the fourth day equals to the temperature of the third day and equals to  - 5. In the fourth example the sequence of the average temperatures is an arithmetic progression where the first term is 900 and each the following terms increase by 100. So predicted average temperature in the third day is 1000 + 100 = 1100.
[ { "input": "5\n10 5 0 -5 -10", "output": "-15" }, { "input": "4\n1 1 1 1", "output": "1" }, { "input": "3\n5 1 -5", "output": "-5" }, { "input": "2\n900 1000", "output": "1100" }, { "input": "2\n1 2", "output": "3" }, { "input": "3\n2 5 8", "output...
46
0
3
4,865
0
none
[ "none" ]
null
null
On vacations *n* pupils decided to go on excursion and gather all together. They need to overcome the path with the length *l* meters. Each of the pupils will go with the speed equal to *v*1. To get to the excursion quickly, it was decided to rent a bus, which has seats for *k* people (it means that it can't fit more than *k* people at the same time) and the speed equal to *v*2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all *n* pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
The first line of the input contains five positive integers *n*, *l*, *v*1, *v*2 and *k* (1<=≀<=*n*<=≀<=10<=000, 1<=≀<=*l*<=≀<=109, 1<=≀<=*v*1<=&lt;<=*v*2<=≀<=109, 1<=≀<=*k*<=≀<=*n*)Β β€” the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Print the real numberΒ β€” the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10<=-<=6.
[ "5 10 1 2 5\n", "3 6 1 2 1\n" ]
[ "5.0000000000\n", "4.7142857143\n" ]
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
[ { "input": "5 10 1 2 5", "output": "5.0000000000" }, { "input": "3 6 1 2 1", "output": "4.7142857143" }, { "input": "39 252 51 98 26", "output": "3.5344336938" }, { "input": "59 96 75 98 9", "output": "1.2315651330" }, { "input": "87 237 3 21 40", "output": "3...
124
0
0
4,869
621
Wet Shark and Bishops
[ "combinatorics", "implementation" ]
null
null
Today, Wet Shark is given *n* bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right. Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
The first line of the input contains *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the number of bishops. Each of next *n* lines contains two space separated integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=1000)Β β€” the number of row and the number of column where *i*-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output one integerΒ β€” the number of pairs of bishops which attack each other.
[ "5\n1 1\n1 5\n3 3\n5 1\n5 5\n", "3\n1 1\n2 3\n3 5\n" ]
[ "6\n", "0\n" ]
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
[ { "input": "5\n1 1\n1 5\n3 3\n5 1\n5 5", "output": "6" }, { "input": "3\n1 1\n2 3\n3 5", "output": "0" }, { "input": "3\n859 96\n634 248\n808 72", "output": "0" }, { "input": "3\n987 237\n891 429\n358 145", "output": "0" }, { "input": "3\n411 81\n149 907\n611 114"...
1,185
11,468,800
3
4,876
0
none
[ "none" ]
null
null
Old MacDonald has a farm and a large potato field, (1010<=+<=1)<=Γ—<=(1010<=+<=1) square meters in size. The field is divided into square garden beds, each bed takes up one square meter. Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Old McDonald wants to spray some beds with insecticides. So Old McDonald went to the field, stood at the center of the central field bed and sprayed this bed with insecticides. Now he's going to make a series of movements and spray a few more beds. During each movement Old McDonald moves left, right, up or down the field some integer number of meters. As Old McDonald moves, he sprays all the beds he steps on. In other words, the beds that have any intersection at all with Old McDonald's trajectory, are sprayed with insecticides. When Old McDonald finished spraying, he wrote out all his movements on a piece of paper. Now he wants to know how many beds won't be infected after the invasion of the Colorado beetles. It is known that the invasion of the Colorado beetles goes as follows. First some bed on the field border gets infected. Than any bed that hasn't been infected, hasn't been sprayed with insecticides and has a common side with an infected bed, gets infected as well. Help Old McDonald and determine the number of beds that won't be infected by the Colorado potato beetle.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=1000) β€” the number of Old McDonald's movements. Next *n* lines contain the description of Old McDonald's movements. The *i*-th of these lines describes the *i*-th movement. Each movement is given in the format "*d**i* *x**i*", where *d**i* is the character that determines the direction of the movement ("L", "R", "U" or "D" for directions "left", "right", "up" and "down", correspondingly), and *x**i* (1<=≀<=*x**i*<=≀<=106) is an integer that determines the number of meters in the movement.
Print a single integer β€” the number of beds that won't be infected by the Colorado potato beetle. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "5\nR 8\nU 9\nL 9\nD 8\nL 2\n", "7\nR 10\nD 2\nL 7\nU 9\nD 2\nR 3\nD 10\n" ]
[ "101", "52" ]
none
[]
62
0
0
4,880
0
none
[ "none" ]
null
null
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence. When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every *a* minutes, but a train goes to Masha's direction every *b* minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample). We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously. Help Vasya count to which girlfriend he will go more often.
The first line contains two integers *a* and *b* (*a*<=β‰ <=*b*,<=1<=≀<=*a*,<=*b*<=≀<=106).
Print "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency.
[ "3 7\n", "5 3\n", "2 3\n" ]
[ "Dasha\n", "Masha\n", "Equal\n" ]
Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0, 6], he will go to both girls equally often. If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute. If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute. If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute. If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction. In sum Masha and Dasha get equal time β€” three minutes for each one, thus, Vasya will go to both girlfriends equally often.
[ { "input": "3 7", "output": "Dasha" }, { "input": "5 3", "output": "Masha" }, { "input": "2 3", "output": "Equal" }, { "input": "31 88", "output": "Dasha" }, { "input": "8 75", "output": "Dasha" }, { "input": "32 99", "output": "Dasha" }, { ...
62
0
0
4,883
549
Haar Features
[ "greedy", "implementation" ]
null
null
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.
The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100) β€” the number of rows and columns in the feature. Next *n* lines contain the description of the feature. Each line consists of *m* characters, the *j*-th character of the *i*-th line equals to "W", if this element of the feature is white and "B" if it is black.
Print a single number β€” the minimum number of operations that you need to make to calculate the value of the feature.
[ "6 8\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\n", "3 3\nWBW\nBWW\nWWW\n", "3 6\nWWBBWW\nWWBBWW\nWWBBWW\n", "4 4\nBBBB\nBBBB\nBBBB\nBBBW\n" ]
[ "2\n", "4\n", "3\n", "4\n" ]
The first sample corresponds to feature *B*, the one shown in the picture. The value of this feature in an image of size 6 × 8 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations: 1. add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable *value* (the rectangle is indicated by a red frame); <img class="tex-graphics" src="https://espresso.codeforces.com/59e6d843dfb74d53c1bdfa004d277d661dbfb8fc.png" style="max-width: 100.0%;max-height: 100.0%;"/>1. add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient  - 2 and variable *value*. <img class="tex-graphics" src="https://espresso.codeforces.com/91d79402e81fce528454fd33ea193676082cf259.png" style="max-width: 100.0%;max-height: 100.0%;"/> Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1 - 2 =  - 1, as required.
[ { "input": "6 8\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW", "output": "2" }, { "input": "3 3\nWBW\nBWW\nWWW", "output": "4" }, { "input": "3 6\nWWBBWW\nWWBBWW\nWWBBWW", "output": "3" }, { "input": "4 4\nBBBB\nBBBB\nBBBB\nBBBW", "output": "4" }, { ...
124
0
3
4,898
173
Chamber of Secrets
[ "dfs and similar", "shortest paths" ]
null
null
"The Chamber of Secrets has been opened again" β€” this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an *n*<=Γ—<=*m* rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.
The first line of the input contains two integer numbers *n* and *m* (2<=≀<=*n*,<=*m*<=≀<=1000). Each of the next *n* lines contains *m* characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.
Print the minimum number of columns to make magic or -1 if it's impossible to do.
[ "3 3\n.#.\n...\n.#.\n", "4 3\n##.\n...\n.#.\n.#.\n" ]
[ "2\n", "2\n" ]
The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.
[ { "input": "3 3\n.#.\n...\n.#.", "output": "2" }, { "input": "4 3\n##.\n...\n.#.\n.#.", "output": "2" }, { "input": "3 3\n###\n###\n###", "output": "2" }, { "input": "3 4\n..##\n....\n..#.", "output": "2" }, { "input": "4 3\n#.#\n...\n...\n.##", "output": "2" ...
2,000
1,843,200
0
4,900
978
Almost Arithmetic Progression
[ "brute force", "implementation", "math" ]
null
null
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i &lt; n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not. It follows from the definition that any sequence of length one or two is an arithmetic progression. Polycarp found some sequence of positive integers $[b_1, b_2, \dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged. Determine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible. It is possible that the resulting sequence contains element equals $0$.
The first line contains a single integer $n$ $(1 \le n \le 100\,000)$ β€” the number of elements in $b$. The second line contains a sequence $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 10^{9})$.
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer β€” the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
[ "4\n24 21 14 10\n", "2\n500 500\n", "3\n14 5 1\n", "5\n1 3 6 9 12\n" ]
[ "3\n", "0\n", "-1\n", "1\n" ]
In the first example Polycarp should increase the first number on $1$, decrease the second number on $1$, increase the third number on $1$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $[25, 20, 15, 10]$, which is an arithmetic progression. In the second example Polycarp should not change anything, because his sequence is an arithmetic progression. In the third example it is impossible to make an arithmetic progression. In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $[0, 3, 6, 9, 12]$, which is an arithmetic progression.
[ { "input": "4\n24 21 14 10", "output": "3" }, { "input": "2\n500 500", "output": "0" }, { "input": "3\n14 5 1", "output": "-1" }, { "input": "5\n1 3 6 9 12", "output": "1" }, { "input": "1\n1000000000", "output": "0" }, { "input": "2\n1000000000 1", ...
108
14,745,600
3
4,902
233
Non-square Equation
[ "binary search", "brute force", "math" ]
null
null
Let's consider equation: where *x*,<=*n* are positive integers, *s*(*x*) is the function, equal to the sum of digits of number *x* in the decimal number system. You are given an integer *n*, find the smallest positive integer root of equation *x*, or else determine that there are no such roots.
A single line contains integer *n* (1<=≀<=*n*<=≀<=1018) β€” the equation parameter. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Print -1, if the equation doesn't have integer positive roots. Otherwise print such smallest integer *x* (*x*<=&gt;<=0), that the equation given in the statement holds.
[ "2\n", "110\n", "4\n" ]
[ "1\n", "10\n", "-1\n" ]
In the first test case *x* = 1 is the minimum root. As *s*(1) = 1 and 1<sup class="upper-index">2</sup> + 1Β·1 - 2 = 0. In the second test case *x* = 10 is the minimum root. As *s*(10) = 1 + 0 = 1 and 10<sup class="upper-index">2</sup> + 1Β·10 - 110 = 0. In the third test case the equation has no roots.
[ { "input": "2", "output": "1" }, { "input": "110", "output": "10" }, { "input": "4", "output": "-1" }, { "input": "8", "output": "2" }, { "input": "10000000100000000", "output": "100000000" }, { "input": "10000006999999929", "output": "99999999" ...
92
0
0
4,904
0
none
[ "none" ]
null
null
Π•ΡΡ‚ΡŒ *n*-ΠΏΠΎΠ΄ΡŠΠ΅Π·Π΄Π½Ρ‹ΠΉ Π΄ΠΎΠΌ, Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ подъСздС ΠΏΠΎ *m* этаТСй, ΠΈ Π½Π° ΠΊΠ°ΠΆΠ΄ΠΎΠΌ этаТС ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ подъСзда Ρ€ΠΎΠ²Π½ΠΎ *k* ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€. Π’Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ, Π² Π΄ΠΎΠΌΠ΅ всСго *n*Β·*m*Β·*k* ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€. Они ΠΏΡ€ΠΎΠ½ΡƒΠΌΠ΅Ρ€ΠΎΠ²Π°Π½Ρ‹ СстСствСнным ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ ΠΎΡ‚ 1 Π΄ΠΎ *n*Β·*m*Β·*k*, Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ пСрвая ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π° Π½Π° ΠΏΠ΅Ρ€Π²ΠΎΠΌ этаТС Π² ΠΏΠ΅Ρ€Π²ΠΎΠΌ подъСздС ΠΈΠΌΠ΅Π΅Ρ‚ Π½ΠΎΠΌΠ΅Ρ€ 1, пСрвая ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π° Π½Π° Π²Ρ‚ΠΎΡ€ΠΎΠΌ этаТС ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ подъСзда ΠΈΠΌΠ΅Π΅Ρ‚ Π½ΠΎΠΌΠ΅Ρ€ *k*<=+<=1 ΠΈ Ρ‚Π°ΠΊ Π΄Π°Π»Π΅Π΅. ΠžΡΠΎΠ±Π΅Π½Π½ΠΎΡΡ‚ΡŒ этого Π΄ΠΎΠΌΠ° состоит Π² Ρ‚ΠΎΠΌ, Ρ‡Ρ‚ΠΎ ΠΎΠ½ ΠΊΡ€ΡƒΠ³Π»Ρ‹ΠΉ. Π’ΠΎ Π΅ΡΡ‚ΡŒ Ссли ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΡ‚ΡŒ Π΅Π³ΠΎ ΠΏΠΎ часовой стрСлкС, Ρ‚ΠΎ послС подъСзда Π½ΠΎΠΌΠ΅Ρ€ 1 слСдуСт подъСзд Π½ΠΎΠΌΠ΅Ρ€ 2, Π·Π°Ρ‚Π΅ΠΌ подъСзд Π½ΠΎΠΌΠ΅Ρ€ 3 ΠΈ Ρ‚Π°ΠΊ Π΄Π°Π»Π΅Π΅ Π΄ΠΎ подъСзда Π½ΠΎΠΌΠ΅Ρ€ *n*. ПослС подъСзда Π½ΠΎΠΌΠ΅Ρ€ *n* снова ΠΈΠ΄Ρ‘Ρ‚ подъСзд Π½ΠΎΠΌΠ΅Ρ€ 1. Π­Π΄Π²Π°Ρ€Π΄ ΠΆΠΈΠ²Ρ‘Ρ‚ Π² ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π΅ Π½ΠΎΠΌΠ΅Ρ€ *a*, Π° ΠΠ°Ρ‚Π°ΡˆΠ°Β β€” Π² ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π΅ Π½ΠΎΠΌΠ΅Ρ€ *b*. ΠŸΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ Π½Π° 1 этаТ Π²Π²Π΅Ρ€Ρ… ΠΈΠ»ΠΈ Π²Π½ΠΈΠ· ΠΏΠΎ лСстницС Π·Π°Π½ΠΈΠΌΠ°Π΅Ρ‚ 5 сСкунд, ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ ΠΎΡ‚ Π΄Π²Π΅Ρ€ΠΈ подъСзда ΠΊ Π΄Π²Π΅Ρ€ΠΈ сосСднСго ΠΏΠΎΠ΄ΡŠΠ΅Π·Π΄Π°Β β€” 15 сСкунд, Π° ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ Π² ΠΏΡ€Π΅Π΄Π΅Π»Π°Ρ… ΠΎΠ΄Π½ΠΎΠ³ΠΎ этаТа ΠΎΠ΄Π½ΠΎΠ³ΠΎ подъСзда происходит ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ. Π’Π°ΠΊΠΆΠ΅ Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ подъСздС Π΄ΠΎΠΌΠ° Π΅ΡΡ‚ΡŒ Π»ΠΈΡ„Ρ‚. Он устроСн ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ: ΠΎΠ½ всСгда ΠΏΡ€ΠΈΠ΅Π·ΠΆΠ°Π΅Ρ‚ Ρ€ΠΎΠ²Π½ΠΎ Ρ‡Π΅Ρ€Π΅Π· 10 сСкунд послС Π²Ρ‹Π·ΠΎΠ²Π°, Π° Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅ΡΡ‚ΠΈΡ‚ΡŒ пассаТира Π½Π° ΠΎΠ΄ΠΈΠ½ этаТ Π²Π²Π΅Ρ€Ρ… ΠΈΠ»ΠΈ Π²Π½ΠΈΠ·, Π»ΠΈΡ„Ρ‚ Ρ‚Ρ€Π°Ρ‚ΠΈΡ‚ Ρ€ΠΎΠ²Π½ΠΎ 1 сСкунду. Посадка ΠΈ высадка происходят ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ. ΠŸΠΎΠΌΠΎΠ³ΠΈΡ‚Π΅ Π­Π΄Π²Π°Ρ€Π΄Ρƒ Π½Π°ΠΉΡ‚ΠΈ минимальноС врСмя, Π·Π° ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ ΠΎΠ½ смоТСт Π΄ΠΎΠ±Ρ€Π°Ρ‚ΡŒΡΡ Π΄ΠΎ ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ ΠΠ°Ρ‚Π°ΡˆΠΈ. Π‘Ρ‡ΠΈΡ‚Π°ΠΉΡ‚Π΅, Ρ‡Ρ‚ΠΎ Π­Π΄Π²Π°Ρ€Π΄ ΠΌΠΎΠΆΠ΅Ρ‚ Π²Ρ‹ΠΉΡ‚ΠΈ ΠΈΠ· подъСзда Ρ‚ΠΎΠ»ΡŒΠΊΠΎ с ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ этаТа ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰Π΅Π³ΠΎ подъСзда (это происходит ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ). Если Π­Π΄Π²Π°Ρ€Π΄ стоит ΠΏΠ΅Ρ€Π΅Π΄ Π΄Π²Π΅Ρ€ΡŒΡŽ ΠΊΠ°ΠΊΠΎΠ³ΠΎ-Ρ‚ΠΎ подъСзда, ΠΎΠ½ ΠΌΠΎΠΆΠ΅Ρ‚ Π·Π°ΠΉΡ‚ΠΈ Π² Π½Π΅Π³ΠΎ ΠΈ сразу окаТСтся Π½Π° ΠΏΠ΅Ρ€Π²ΠΎΠΌ этаТС этого подъСзда (это Ρ‚Π°ΠΊΠΆΠ΅ происходит ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ). Π­Π΄Π²Π°Ρ€Π΄ ΠΌΠΎΠΆΠ΅Ρ‚ Π²Ρ‹Π±ΠΈΡ€Π°Ρ‚ΡŒ, Π² ΠΊΠ°ΠΊΠΎΠΌ Π½Π°ΠΏΡ€Π°Π²Π»Π΅Π½ΠΈΠΈ ΠΈΠ΄Ρ‚ΠΈ Π²ΠΎΠΊΡ€ΡƒΠ³ Π΄ΠΎΠΌΠ°.
Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… ΡΠ»Π΅Π΄ΡƒΡŽΡ‚ Ρ‚Ρ€ΠΈ числа *n*, *m*, *k* (1<=≀<=*n*,<=*m*,<=*k*<=≀<=1000)Β β€” количСство подъСздов Π² Π΄ΠΎΠΌΠ΅, количСство этаТСй Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ подъСздС ΠΈ количСство ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€ Π½Π° ΠΊΠ°ΠΆΠ΄ΠΎΠΌ этаТС ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ подъСзда соотвСтствСнно. Π’ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΉ строкС Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… записаны Π΄Π²Π° числа *a* ΠΈ *b* (1<=≀<=*a*,<=*b*<=≀<=*n*Β·*m*Β·*k*)Β β€” Π½ΠΎΠΌΠ΅Ρ€Π° ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€, Π² ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… ΠΆΠΈΠ²ΡƒΡ‚ Π­Π΄Π²Π°Ρ€Π΄ ΠΈ ΠΠ°Ρ‚Π°ΡˆΠ°, соотвСтствСнно. ГарантируСтся, Ρ‡Ρ‚ΠΎ эти Π½ΠΎΠΌΠ΅Ρ€Π° Ρ€Π°Π·Π»ΠΈΡ‡Π½Ρ‹.
Π’Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ СдинствСнноС Ρ†Π΅Π»ΠΎΠ΅ число — минимальноС врСмя (Π² сСкундах), Π·Π° ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ Π­Π΄Π²Π°Ρ€Π΄ смоТСт Π΄ΠΎΠ±Ρ€Π°Ρ‚ΡŒΡΡ ΠΎΡ‚ своСй ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ Π΄ΠΎ ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ ΠΠ°Ρ‚Π°ΡˆΠΈ.
[ "4 10 5\n200 6\n", "3 1 5\n7 2\n" ]
[ "39\n", "15\n" ]
Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΌ тСстовом ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ Π­Π΄Π²Π°Ρ€Π΄ находится Π² 4 подъСздС Π½Π° 10 этаТС, Π° ΠΠ°Ρ‚Π°ΡˆΠ° находится Π² 1 подъСздС Π½Π° 2 этаТС. ΠŸΠΎΡΡ‚ΠΎΠΌΡƒ Π­Π΄Π²Π°Ρ€Π΄Ρƒ Π²Ρ‹Π³ΠΎΠ΄Π½ΠΎ сначала ΡΠΏΡƒΡΡ‚ΠΈΡ‚ΡŒΡΡ Π½Π° Π»ΠΈΡ„Ρ‚Π΅ Π½Π° ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ этаТ (Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 19 сСкунд, ΠΈΠ· ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… 10Β β€” Π½Π° ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠ΅ ΠΈ 9Β β€” Π½Π° ΠΏΠΎΠ΅Π·Π΄ΠΊΡƒ Π½Π° Π»ΠΈΡ„Ρ‚Π΅), Π·Π°Ρ‚Π΅ΠΌ ΠΎΠ±ΠΎΠΉΡ‚ΠΈ Π΄ΠΎΠΌ ΠΏΡ€ΠΎΡ‚ΠΈΠ² часовой стрСлки Π΄ΠΎ подъСзда Π½ΠΎΠΌΠ΅Ρ€ 1 (Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 15 сСкунд), ΠΈ Π½Π°ΠΊΠΎΠ½Π΅Ρ† ΠΏΠΎΠ΄Π½ΡΡ‚ΡŒΡΡ ΠΏΠΎ лСстницС Π½Π° этаТ Π½ΠΎΠΌΠ΅Ρ€ 2 (Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 5 сСкунд). Π’Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ, ΠΎΡ‚Π²Π΅Ρ‚ Ρ€Π°Π²Π΅Π½ 19 + 15 + 5 = 39. Π’ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΌ тСстовом ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ Π­Π΄Π²Π°Ρ€Π΄ ΠΆΠΈΠ²Ρ‘Ρ‚ Π² подъСздС 2 Π½Π° этаТС 1, Π° ΠΠ°Ρ‚Π°ΡˆΠ° находится Π² подъСздС 1 Π½Π° этаТС 1. ΠŸΠΎΡΡ‚ΠΎΠΌΡƒ Π­Π΄Π²Π°Ρ€Π΄Ρƒ Π²Ρ‹Π³ΠΎΠ΄Π½ΠΎ просто ΠΎΠ±ΠΎΠΉΡ‚ΠΈ Π΄ΠΎΠΌ ΠΏΠΎ часовой стрСлкС Π΄ΠΎ подъСзда 1, Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 15 сСкунд.
[ { "input": "4 10 5\n200 6", "output": "39" }, { "input": "3 1 5\n7 2", "output": "15" }, { "input": "100 100 100\n1 1000000", "output": "124" }, { "input": "1000 1000 1000\n1 1000000000", "output": "1024" }, { "input": "125 577 124\n7716799 6501425", "output":...
62
4,608,000
-1
4,906
612
HDD is Outdated Technology
[ "implementation", "math" ]
null
null
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order. One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file. Find the time need to read file split to *n* fragments. The *i*-th sector contains the *f**i*-th fragment of the file (1<=≀<=*f**i*<=≀<=*n*). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the *n*-th fragment is read. The fragments are read in the order from the first to the *n*-th. It takes |*a*<=-<=*b*| time units to move the magnetic head from the sector *a* to the sector *b*. Reading a fragment takes no time.
The first line contains a positive integer *n* (1<=≀<=*n*<=≀<=2Β·105) β€” the number of fragments. The second line contains *n* different integers *f**i* (1<=≀<=*f**i*<=≀<=*n*) β€” the number of the fragment written in the *i*-th sector.
Print the only integer β€” the number of time units needed to read the file.
[ "3\n3 1 2\n", "5\n1 3 5 4 2\n" ]
[ "3\n", "10\n" ]
In the second example the head moves in the following way: - 1-&gt;2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units - 2-&gt;3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units - 3-&gt;4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units - 4-&gt;5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4 + 3 + 2 + 1 = 10.
[ { "input": "3\n3 1 2", "output": "3" }, { "input": "5\n1 3 5 4 2", "output": "10" }, { "input": "1\n1", "output": "0" }, { "input": "1\n1", "output": "0" }, { "input": "1\n1", "output": "0" }, { "input": "10\n8 2 10 3 4 6 1 7 9 5", "output": "40" ...
155
57,446,400
3
4,908
494
Treasure
[ "greedy" ]
null
null
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string *s* written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each *i* (1<=≀<=*i*<=≀<=|*s*|) there are no more ')' characters than '(' characters among the first *i* characters of *s* and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.
The first line of the input contains a string *s* (1<=≀<=|*s*|<=≀<=105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that *s* contains at least one '#' character.
If there is no way of replacing '#' characters which leads to a beautiful string print <=-<=1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.
[ "(((#)((#)\n", "()((#((#(#()\n", "#\n", "(#)\n" ]
[ "1\n2\n", "2\n2\n1", "-1\n", "-1\n" ]
|*s*| denotes the length of the string *s*.
[ { "input": "(((#)((#)", "output": "1\n2" }, { "input": "()((#((#(#()", "output": "1\n1\n3" }, { "input": "#", "output": "-1" }, { "input": "(#)", "output": "-1" }, { "input": "(((((#(#(#(#()", "output": "1\n1\n1\n5" }, { "input": "#))))", "output":...
77
307,200
0
4,922
741
Arpa’s overnight party and Mehrdad’s silent entering
[ "constructive algorithms", "dfs and similar", "graphs" ]
null
null
Note that girls in Arpa’s land are really attractive. Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw *n* pairs of friends sitting around a table. *i*-th pair consisted of a boy, sitting on the *a**i*-th chair, and his girlfriend, sitting on the *b**i*-th chair. The chairs were numbered 1 through 2*n* in clockwise direction. There was exactly one person sitting on each chair. There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: - Each person had exactly one type of food, - No boy had the same type of food as his girlfriend, - Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2*n* and 1 are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
The first line contains an integer *n* (1<=<=≀<=<=*n*<=<=≀<=<=105)Β β€” the number of pairs of guests. The *i*-th of the next *n* lines contains a pair of integers *a**i* and *b**i* (1<=<=≀<=*a**i*,<=*b**i*<=≀<=<=2*n*)Β β€” the number of chair on which the boy in the *i*-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
If there is no solution, print -1. Otherwise print *n* lines, the *i*-th of them should contain two integers which represent the type of food for the *i*-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2. If there are multiple solutions, print any of them.
[ "3\n1 4\n2 5\n3 6\n" ]
[ "1 2\n2 1\n1 2\n" ]
none
[ { "input": "3\n1 4\n2 5\n3 6", "output": "1 2\n2 1\n1 2" }, { "input": "6\n3 2\n5 11\n7 12\n6 9\n8 4\n1 10", "output": "1 2\n1 2\n2 1\n2 1\n1 2\n1 2" }, { "input": "19\n30 27\n6 38\n10 28\n20 5\n14 18\n32 2\n36 29\n12 1\n31 24\n15 4\n35 11\n3 7\n21 17\n25 19\n16 8\n23 22\n37 33\n13 9\n34...
327
40,755,200
-1
4,931
50
Choosing Symbol Pairs
[ "strings" ]
B. Choosing Symbol Pairs
2
256
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that 1. 1<=≀<=*i*,<=*j*<=≀<=*N* 2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
The single input line contains *S*, consisting of lowercase Latin letters and digits. It is guaranteed that string *S* in not empty and its length does not exceed 105.
Print a single number which represents the number of pairs *i* and *j* with the needed property. Pairs (*x*,<=*y*) and (*y*,<=*x*) should be considered different, i.e. the ordered pairs count.
[ "great10\n", "aaaaaaaaaa\n" ]
[ "7\n", "100\n" ]
none
[ { "input": "great10", "output": "7" }, { "input": "aaaaaaaaaa", "output": "100" }, { "input": "great10", "output": "7" }, { "input": "aaaaaaaaaa", "output": "100" }, { "input": "aabb", "output": "8" }, { "input": "w", "output": "1" }, { "in...
2,000
2,252,800
0
4,935
818
Diplomas and Certificates
[ "implementation", "math" ]
null
null
There are *n* students who have taken part in an olympiad. Now it's time to award the students. Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be exactly *k* times greater than the number of diplomas. The number of winners must not be greater than half of the number of all students (i.e. not be greater than half of *n*). It's possible that there are no winners. You have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners.
The first (and the only) line of input contains two integers *n* and *k* (1<=≀<=*n*,<=*k*<=≀<=1012), where *n* is the number of students and *k* is the ratio between the number of certificates and the number of diplomas.
Output three numbers: the number of students with diplomas, the number of students with certificates and the number of students who are not winners in case when the number of winners is maximum possible. It's possible that there are no winners.
[ "18 2\n", "9 10\n", "1000000000000 5\n", "1000000000000 499999999999\n" ]
[ "3 6 9\n", "0 0 9\n", "83333333333 416666666665 500000000002\n", "1 499999999999 500000000000\n" ]
none
[ { "input": "18 2", "output": "3 6 9" }, { "input": "9 10", "output": "0 0 9" }, { "input": "1000000000000 5", "output": "83333333333 416666666665 500000000002" }, { "input": "1000000000000 499999999999", "output": "1 499999999999 500000000000" }, { "input": "1 1",...
155
0
3
4,957
832
Petya and Exam
[ "implementation", "strings" ]
null
null
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one.. There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern. Also, *n* query strings are given, it is required to determine for each of them if the pattern matches it or not. Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning. A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string. The good letters are given to Petya. All the others are bad.
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad. The second line contains the patternΒ β€” a string *s* of lowercase English letters, characters "?" and "*" (1<=≀<=|*s*|<=≀<=105). It is guaranteed that character "*" occurs in *s* no more than once. The third line contains integer *n* (1<=≀<=*n*<=≀<=105)Β β€” the number of query strings. *n* lines follow, each of them contains single non-empty string consisting of lowercase English lettersΒ β€” a query string. It is guaranteed that the total length of all query strings is not greater than 105.
Print *n* lines: in the *i*-th of them print "YES" if the pattern matches the *i*-th query string, and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrary.
[ "ab\na?a\n2\naaa\naab\n", "abc\na?a?a*\n4\nabacaba\nabaca\napapa\naaaaax\n" ]
[ "YES\nNO\n", "NO\nYES\nNO\nYES\n" ]
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter. Explanation of the second example. - The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good. - The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide. - The third query: "NO", because characters "?" can't be replaced with bad letters. - The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
[ { "input": "ab\na?a\n2\naaa\naab", "output": "YES\nNO" }, { "input": "abc\na?a?a*\n4\nabacaba\nabaca\napapa\naaaaax", "output": "NO\nYES\nNO\nYES" }, { "input": "s\nc*?cb\n26\nbbaa\nb\ncc\ncbaab\nacacc\nca\na\nc\ncb\nabb\nba\nb\nba\ncac\nccccb\nccb\nbbbc\nabbcb\na\nbc\nc\na\nabb\nca\ncac...
374
8,806,400
0
4,966
209
Multicolored Marbles
[ "dp", "math" ]
null
null
Polycarpus plays with red and blue marbles. He put *n* marbles from the left to the right in a row. As it turned out, the marbles form a zebroid. A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebroids and sequence (red; red) is not a zebroid. Now Polycarpus wonders, how many ways there are to pick a zebroid subsequence from this sequence. Help him solve the problem, find the number of ways modulo 1000000007 (109<=+<=7).
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=106) β€” the number of marbles in Polycarpus's sequence.
Print a single number β€” the answer to the problem modulo 1000000007 (109<=+<=7).
[ "3\n", "4\n" ]
[ "6\n", "11\n" ]
Let's consider the first test sample. Let's assume that Polycarpus initially had sequence (red; blue; red), so there are six ways to pick a zebroid: - pick the first marble; - pick the second marble; - pick the third marble; - pick the first and second marbles; - pick the second and third marbles; - pick the first, second and third marbles. It can be proven that if Polycarpus picks (blue; red; blue) as the initial sequence, the number of ways won't change.
[ { "input": "3", "output": "6" }, { "input": "4", "output": "11" }, { "input": "1", "output": "1" }, { "input": "2", "output": "3" }, { "input": "5", "output": "19" }, { "input": "6", "output": "32" }, { "input": "7", "output": "53" },...
2,000
13,516,800
0
4,971
670
Cinema
[ "implementation", "sortings" ]
null
null
Moscow is hosting a major international conference, which is attended by *n* scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109. In the evening after the conference, all *n* scientists decided to go to the cinema. There are *m* movies in the cinema they came to. Each of the movies is characterized by two distinct numbersΒ β€” the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different). Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.
The first line of the input contains a positive integer *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the number of scientists. The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109), where *a**i* is the index of a language, which the *i*-th scientist knows. The third line contains a positive integer *m* (1<=≀<=*m*<=≀<=200<=000)Β β€” the number of movies in the cinema. The fourth line contains *m* positive integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≀<=*b**j*<=≀<=109), where *b**j* is the index of the audio language of the *j*-th movie. The fifth line contains *m* positive integers *c*1,<=*c*2,<=...,<=*c**m* (1<=≀<=*c**j*<=≀<=109), where *c**j* is the index of subtitles language of the *j*-th movie. It is guaranteed that audio languages and subtitles language are different for each movie, that is *b**j*<=β‰ <=*c**j*.
Print the single integerΒ β€” the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists. If there are several possible answers print any of them.
[ "3\n2 3 2\n2\n3 2\n2 3\n", "6\n6 3 1 1 3 7\n5\n1 2 3 4 5\n2 3 4 5 1\n" ]
[ "2\n", "1\n" ]
In the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied. In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied.
[ { "input": "3\n2 3 2\n2\n3 2\n2 3", "output": "2" }, { "input": "6\n6 3 1 1 3 7\n5\n1 2 3 4 5\n2 3 4 5 1", "output": "1" }, { "input": "1\n10\n1\n10\n3", "output": "1" }, { "input": "2\n1 6\n1\n6\n1", "output": "1" }, { "input": "1\n5\n2\n2 2\n5 5", "output": ...
623
31,539,200
3
4,975
0
none
[ "none" ]
null
null
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: 1. the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", 1. or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club *x* the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club *x*. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name. Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the number of clubs in the league. Each of the next *n* lines contains two wordsΒ β€” the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.
It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print *n* lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them.
[ "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n", "2\nDINAMO BYTECITY\nDINAMO BITECITY\n", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n", "3\nABC DEF\nABC EFG\nABD OOO\n" ]
[ "YES\nDIN\nFOO\n", "NO\n", "YES\nPLM\nPLS\nGOG\n", "YES\nABD\nABE\nABO\n" ]
In the first sample Innokenty can choose first option for both clubs. In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs. In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club. In the fourth example note that it is possible that the chosen short name for some club *x* is the same as the first option of another club *y* if the first options of *x* and *y* are different.
[ { "input": "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "output": "YES\nDIN\nFOO" }, { "input": "2\nDINAMO BYTECITY\nDINAMO BITECITY", "output": "NO" }, { "input": "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "output": "YES\nPLM\nPLS\nGOG" }, { "input": "3\nABC DEF...
62
5,120,000
0
4,978
444
DZY Loves Colors
[ "data structures" ]
null
null
DZY loves colors, and he enjoys painting. On a colorful day, DZY gets a colorful ribbon, which consists of *n* units (they are numbered from 1 to *n* from left to right). The color of the *i*-th unit of the ribbon is *i* at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first. DZY loves painting, we know. He takes up a paintbrush with color *x* and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit *i* currently is *y*. When it is painted by this paintbrush, the color of the unit becomes *x*, and the colorfulness of the unit increases by |*x*<=-<=*y*|. DZY wants to perform *m* operations, each operation can be one of the following: 1. Paint all the units with numbers between *l* and *r* (both inclusive) with color *x*. 1. Ask the sum of colorfulness of the units between *l* and *r* (both inclusive). Can you help DZY?
The first line contains two space-separated integers *n*,<=*m*Β (1<=≀<=*n*,<=*m*<=≀<=105). Each of the next *m* lines begins with a integer *type*Β (1<=≀<=*type*<=≀<=2), which represents the type of this operation. If *type*<==<=1, there will be 3 more integers *l*,<=*r*,<=*x*Β (1<=≀<=*l*<=≀<=*r*<=≀<=*n*;Β 1<=≀<=*x*<=≀<=108) in this line, describing an operation 1. If *type*<==<=2, there will be 2 more integers *l*,<=*r*Β (1<=≀<=*l*<=≀<=*r*<=≀<=*n*) in this line, describing an operation 2.
For each operation 2, print a line containing the answer β€” sum of colorfulness.
[ "3 3\n1 1 2 4\n1 2 3 5\n2 1 3\n", "3 4\n1 1 3 4\n2 1 1\n2 2 2\n2 3 3\n", "10 6\n1 1 5 3\n1 2 7 9\n1 10 10 11\n1 3 8 12\n1 1 10 3\n2 1 10\n" ]
[ "8\n", "3\n2\n1\n", "129\n" ]
In the first sample, the color of each unit is initially [1, 2, 3], and the colorfulness is [0, 0, 0]. After the first operation, colors become [4, 4, 3], colorfulness become [3, 2, 0]. After the second operation, colors become [4, 5, 5], colorfulness become [3, 3, 2]. So the answer to the only operation of type 2 is 8.
[ { "input": "3 3\n1 1 2 4\n1 2 3 5\n2 1 3", "output": "8" }, { "input": "3 4\n1 1 3 4\n2 1 1\n2 2 2\n2 3 3", "output": "3\n2\n1" }, { "input": "10 6\n1 1 5 3\n1 2 7 9\n1 10 10 11\n1 3 8 12\n1 1 10 3\n2 1 10", "output": "129" }, { "input": "3 3\n1 2 2 31844623\n1 1 2 37662529\n...
2,000
4,403,200
0
4,979
662
International Olympiad
[ "constructive algorithms", "greedy", "implementation", "math" ]
null
null
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where *y* stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string *y* that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition. For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995. You are given a list of abbreviations. For each of them determine the year it stands for.
The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the number of abbreviations to process. Then *n* lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.
For each abbreviation given in the input, find the year of the corresponding Olympiad.
[ "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0\n", "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999\n" ]
[ "2015\n12015\n1991\n1989\n1990\n", "1989\n1999\n2999\n9999\n" ]
none
[ { "input": "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0", "output": "2015\n12015\n1991\n1989\n1990" }, { "input": "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999", "output": "1989\n1999\n2999\n9999" }, { "input": "1\nIAO'111110", "output": "1111110" }, { "input": "2\nIAO'0\nIAO'00", "o...
46
0
3
4,984
222
Reducing Fractions
[ "implementation", "math", "number theory", "sortings" ]
null
null
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.
The first input line contains two space-separated integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=107) β€” the numbers that are multiplied to produce the numerator. The third line contains *m* space-separated integers: *b*1,<=*b*2,<=...,<=*b**m* (1<=≀<=*b**i*<=≀<=107) β€” the numbers that are multiplied to produce the denominator.
Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print *n**out*,<=*m**out* must satisfy the inequality 1<=≀<=*n**out*,<=*m**out*<=≀<=105, and the actual values in the sets *a**out*,<=*i* and *b**out*,<=*i* must satisfy the inequality 1<=≀<=*a**out*,<=*i*,<=*b**out*,<=*i*<=≀<=107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer *x* (*x*<=&gt;<=1), that the numerator and the denominator of the printed fraction are divisible by *x*. If there are several matching answers, print any of them.
[ "3 2\n100 5 2\n50 10\n", "4 3\n2 5 10 20\n100 1 3\n" ]
[ "2 3\n2 1\n1 1 1\n", "1 1\n20\n3\n" ]
In the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1. In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3.
[ { "input": "3 2\n100 5 2\n50 10", "output": "2 3\n2 1\n1 1 1" }, { "input": "4 3\n2 5 10 20\n100 1 3", "output": "1 1\n20\n3" }, { "input": "2 3\n50 10\n100 5 2", "output": "2 3\n1 1 \n2 1 1 " }, { "input": "1 1\n1\n1", "output": "1 1\n1 \n1 " }, { "input": "3 2\n...
904
135,577,600
0
4,988
359
Prime Number
[ "math", "number theory" ]
null
null
Simon has a prime number *x* and an array of non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number *t* equals *x**a*1<=+<=*a*2<=+<=...<=+<=*a**n*. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers *s* and *t*. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109<=+<=7).
The first line contains two positive integers *n* and *x* (1<=≀<=*n*<=≀<=105, 2<=≀<=*x*<=≀<=109) β€” the size of the array and the prime number. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a*1<=≀<=*a*2<=≀<=...<=≀<=*a**n*<=≀<=109).
Print a single number β€” the answer to the problem modulo 1000000007 (109<=+<=7).
[ "2 2\n2 2\n", "3 3\n1 2 3\n", "2 2\n29 29\n", "4 5\n0 0 0 0\n" ]
[ "8\n", "27\n", "73741817\n", "1\n" ]
In the first sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7745f7cc87c6c5f753e3414fad9baa3b1e3fea48.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Thus, the answer to the problem is 8. In the second sample, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/acb3d7990f024100be499bcb59828fa6e23a867d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. The answer to the problem is 27, as 351 = 13Β·27, 729 = 27Β·27. In the third sample the answer to the problem is 1073741824Β *mod*Β 1000000007 = 73741817. In the fourth sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/05a5fca3fb4690369838ff6dfeda521c959aa937.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Thus, the answer to the problem is 1.
[ { "input": "2 2\n2 2", "output": "8" }, { "input": "3 3\n1 2 3", "output": "27" }, { "input": "2 2\n29 29", "output": "73741817" }, { "input": "4 5\n0 0 0 0", "output": "1" }, { "input": "1 2\n1000000000", "output": "1" }, { "input": "26 2\n0 0 0 0 0 0...
234
31,129,600
0
4,993
22
Scheme
[ "dfs and similar", "graphs", "trees" ]
E. Scheme
2
256
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index *i* got a person with index *f**i*, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes β€” there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (*x**i*,<=*y**i*), which mean that person *x**i* has to call person *y**i* as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?
The first input line contains number *n* (2<=≀<=*n*<=≀<=105) β€” amount of BolgenOS community members. The second line contains *n* space-separated integer numbers *f**i* (1<=≀<=*f**i*<=≀<=*n*,<=*i*<=β‰ <=*f**i*) β€” index of a person, to whom calls a person with index *i*.
In the first line output one number β€” the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any.
[ "3\n3 3 2\n", "7\n2 3 1 3 4 4 1\n" ]
[ "1\n3 1\n", "3\n2 5\n2 6\n3 7\n" ]
none
[ { "input": "3\n3 3 2", "output": "1\n3 1" }, { "input": "7\n2 3 1 3 4 4 1", "output": "3\n1 5\n1 6\n1 7" }, { "input": "2\n2 1", "output": "0" }, { "input": "3\n2 3 1", "output": "0" }, { "input": "4\n2 4 4 3", "output": "1\n4 1" }, { "input": "5\n5 3 ...
248
56,934,400
-1
4,994
722
Generating Sets
[ "binary search", "data structures", "dfs and similar", "greedy", "strings", "trees" ]
null
null
You are given a set *Y* of *n* distinct positive integers *y*1,<=*y*2,<=...,<=*y**n*. Set *X* of *n* distinct positive integers *x*1,<=*x*2,<=...,<=*x**n* is said to generate set *Y* if one can transform *X* to *Y* by applying some number of the following two operation to integers in *X*: 1. Take any integer *x**i* and multiply it by two, i.e. replace *x**i* with 2Β·*x**i*. 1. Take any integer *x**i*, multiply it by two and add one, i.e. replace *x**i* with 2Β·*x**i*<=+<=1. Note that integers in *X* are not required to be distinct after each operation. Two sets of distinct integers *X* and *Y* are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set *Y* and have to find a set *X* that generates *Y* and the maximum element of *X* is mininum possible.
The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=50<=000)Β β€” the number of elements in *Y*. The second line contains *n* integers *y*1,<=...,<=*y**n* (1<=≀<=*y**i*<=≀<=109), that are guaranteed to be distinct.
Print *n* integersΒ β€” set of distinct integers that generate *Y* and the maximum element of which is minimum possible. If there are several such sets, print any of them.
[ "5\n1 2 3 4 5\n", "6\n15 14 3 13 1 12\n", "6\n9 7 13 17 5 11\n" ]
[ "4 5 2 3 1 \n", "12 13 14 7 3 1 \n", "4 5 2 6 3 1 \n" ]
none
[ { "input": "5\n1 2 3 4 5", "output": "4 5 2 3 1 " }, { "input": "6\n15 14 3 13 1 12", "output": "12 13 14 7 3 1 " }, { "input": "6\n9 7 13 17 5 11", "output": "4 5 2 6 3 1 " }, { "input": "10\n18 14 19 17 11 7 20 10 4 12", "output": "8 9 4 10 5 2 6 7 3 1 " }, { "i...
733
27,136,000
3
5,005
253
Text Editor
[ "data structures", "dfs and similar", "graphs", "greedy", "shortest paths" ]
null
null
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β€” in writing a composition. As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one? Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written *n* lines, the *i*-th line contains *a**i* characters (including spaces). If some line contains *k* characters, then this line overall contains (*k*<=+<=1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (*r*,<=*c*), where *r* is the number of the line and *c* is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line). Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (*r*,<=*c*), then Vasya pushed key: - "Up": if the cursor was located in the first line (*r*<==<=1), then it does not move. Otherwise, it moves to the previous line (with number *r*<=-<=1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position *c* there, the cursor moves to the last position of the line with number *r*<=-<=1;- "Down": if the cursor was located in the last line (*r*<==<=*n*), then it does not move. Otherwise, it moves to the next line (with number *r*<=+<=1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position *c* there, the cursor moves to the last position of the line with number *r*<=+<=1;- "Right": if the cursor can move to the right in this line (*c*<=&lt;<=*a**r*<=+<=1), then it moves to the right (to position *c*<=+<=1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key;- "Left": if the cursor can move to the left in this line (*c*<=&gt;<=1), then it moves to the left (to position *c*<=-<=1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key. You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (*r*1,<=*c*1) to position (*r*2,<=*c*2).
The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=100) β€” the number of lines in the file. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=105), separated by single spaces. The third line contains four integers *r*1,<=*c*1,<=*r*2,<=*c*2 (1<=≀<=*r*1,<=*r*2<=≀<=*n*,<=1<=≀<=*c*1<=≀<=*a**r*1<=+<=1,<=1<=≀<=*c*2<=≀<=*a**r*2<=+<=1).
Print a single integer β€” the minimum number of times Vasya should push a key to move the cursor from position (*r*1,<=*c*1) to position (*r*2,<=*c*2).
[ "4\n2 1 6 4\n3 4 4 2\n", "4\n10 5 6 4\n1 11 4 2\n", "3\n10 1 10\n1 10 1 1\n" ]
[ "3\n", "6\n", "3\n" ]
In the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter *s* represents the cursor's initial position, letter *t* represents the last one. Then all possible positions of the cursor in the text editor are described by the following table. 123 12 123s567 1t345 One of the possible answers in the given sample is: "Left", "Down", "Left".
[ { "input": "4\n2 1 6 4\n3 4 4 2", "output": "3" }, { "input": "4\n10 5 6 4\n1 11 4 2", "output": "6" }, { "input": "3\n10 1 10\n1 10 1 1", "output": "3" }, { "input": "4\n2 1 6 4\n4 2 3 5", "output": "4" }, { "input": "3\n20 3 20\n1 20 1 1", "output": "5" },...
122
2,867,200
-1
5,007
819
Mister B and Flight to the Moon
[ "constructive algorithms", "graphs" ]
null
null
In order to fly to the Moon Mister B just needs to solve the following problem. There is a complete indirected graph with *n* vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles. We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?
The only line contains single integer *n* (3<=≀<=*n*<=≀<=300).
If there is no answer, print -1. Otherwise, in the first line print *k* (1<=≀<=*k*<=≀<=*n*2)Β β€” the number of cycles in your solution. In each of the next *k* lines print description of one cycle in the following format: first print integer *m* (3<=≀<=*m*<=≀<=4)Β β€” the length of the cycle, then print *m* integers *v*1,<=*v*2,<=...,<=*v**m* (1<=≀<=*v**i*<=≀<=*n*)Β β€” the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.
[ "3\n", "5\n" ]
[ "2\n3 1 2 3\n3 1 2 3\n", "6\n3 5 4 2\n3 3 1 5\n4 4 5 2 3\n4 4 3 2 1\n3 4 2 1\n3 3 1 5\n" ]
none
[ { "input": "3", "output": "2\n3 1 2 3\n3 1 2 3" }, { "input": "5", "output": "6\n3 1 2 3\n3 2 3 4\n3 3 4 5\n3 4 5 1\n4 2 1 3 5\n4 5 1 4 2" }, { "input": "299", "output": "22350\n4 2 3 1 4\n4 1 4 299 5\n4 299 5 298 6\n4 298 6 297 7\n4 297 7 296 8\n4 296 8 295 9\n4 295 9 294 10\n4 294 ...
46
0
0
5,013
525
Pasha and String
[ "constructive algorithms", "greedy", "math", "strings" ]
null
null
Pasha got a very beautiful string *s* for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |*s*| from left to right, where |*s*| is the length of the given string. Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent *m* days performing the following transformations on his stringΒ β€”Β each day he chose integer *a**i* and reversed a piece of string (a segment) from position *a**i* to position |*s*|<=-<=*a**i*<=+<=1. It is guaranteed that 2Β·*a**i*<=≀<=|*s*|. You face the following task: determine what Pasha's string will look like after *m* days.
The first line of the input contains Pasha's string *s* of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer *m* (1<=≀<=*m*<=≀<=105)Β β€”Β  the number of days when Pasha changed his string. The third line contains *m* space-separated elements *a**i* (1<=≀<=*a**i*; 2Β·*a**i*<=≀<=|*s*|)Β β€”Β the position from which Pasha started transforming the string on the *i*-th day.
In the first line of the output print what Pasha's string *s* will look like after *m* days.
[ "abcdef\n1\n2\n", "vwxyz\n2\n2 2\n", "abcdef\n3\n1 2 3\n" ]
[ "aedcbf\n", "vwxyz\n", "fbdcea\n" ]
none
[ { "input": "abcdef\n1\n2", "output": "aedcbf" }, { "input": "vwxyz\n2\n2 2", "output": "vwxyz" }, { "input": "abcdef\n3\n1 2 3", "output": "fbdcea" }, { "input": "jc\n5\n1 1 1 1 1", "output": "cj" }, { "input": "wljqgdlxyc\n13\n3 4 3 3 5 4 4 2 4 4 5 3 3", "out...
2,000
7,372,800
0
5,022
183
Zoo
[ "brute force", "geometry" ]
null
null
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has *n* observation binoculars located at the *OX* axis. For each *i* between 1 and *n*, inclusive, there exists a single binocular located at the point with coordinates (*i*,<=0). There are *m* flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move. In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line. Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.
The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*<=≀<=106,<=1<=≀<=*m*<=≀<=250), denoting the number of binoculars and the number of flamingos, respectively. Then *m* lines follow, the *i*-th line will contain two space-separated integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=109), which means that the *i*-th flamingo is located at point (*x**i*,<=*y**i*). All flamingos will be located at distinct points.
Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.
[ "5 5\n2 1\n4 1\n3 2\n4 3\n4 4\n" ]
[ "11\n" ]
This picture shows the answer to the example test case.
[ { "input": "5 5\n2 1\n4 1\n3 2\n4 3\n4 4", "output": "11" }, { "input": "3 3\n1 1\n2 10\n3 100", "output": "3" }, { "input": "1 2\n450000001 500000000\n900000001 1000000000", "output": "2" }, { "input": "3 6\n1 1\n1 2\n1 3\n2 1\n2 2\n3 1", "output": "7" }, { "inpu...
2,000
253,132,800
0
5,030
17
Palisection
[ "strings" ]
E. Palisection
2
128
In an English class Nick had nothing to do at all, and remembered about wonderful strings called palindromes. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: Β«eyeΒ», Β«popΒ», Β«levelΒ», Β«abaΒ», Β«deedΒ», Β«racecarΒ», Β«rotorΒ», Β«madamΒ». Nick started to look carefully for all palindromes in the text that they were reading in the class. For each occurrence of each palindrome in the text he wrote a pair β€” the position of the beginning and the position of the ending of this occurrence in the text. Nick called each occurrence of each palindrome he found in the text subpalindrome. When he found all the subpalindromes, he decided to find out how many different pairs among these subpalindromes cross. Two subpalindromes cross if they cover common positions in the text. No palindrome can cross itself. Let's look at the actions, performed by Nick, by the example of text Β«babbΒ». At first he wrote out all subpalindromes: Then Nick counted the amount of different pairs among these subpalindromes that cross. These pairs were six: Since it's very exhausting to perform all the described actions manually, Nick asked you to help him and write a program that can find out the amount of different subpalindrome pairs that cross. Two subpalindrome pairs are regarded as different if one of the pairs contains a subpalindrome that the other does not.
The first input line contains integer *n* (1<=≀<=*n*<=≀<=2Β·106) β€” length of the text. The following line contains *n* lower-case Latin letters (from a to z).
In the only line output the amount of different pairs of two subpalindromes that cross each other. Output the answer modulo 51123987.
[ "4\nbabb\n", "2\naa\n" ]
[ "6\n", "2\n" ]
none
[]
60
0
0
5,033
55
Pie or die
[ "games" ]
C. Pie or die
2
256
Volodya and Vlad play the following game. There are *k* pies at the cells of *n*<=<=Γ—<=<=*m* board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.
First line contains 3 integers, separated by space: 1<=≀<=*n*,<=*m*<=≀<=100 β€” dimensions of the board and 0<=≀<=*k*<=≀<=100 β€” the number of pies. Each of the next *k* lines contains 2 integers, separated by space: 1<=≀<=*x*<=≀<=*n*, 1<=≀<=*y*<=≀<=*m* β€” coordinates of the corresponding pie. There could be more than one pie at a cell.
Output only one word: "YES" β€” if Volodya wins, "NO" β€” otherwise.
[ "2 2 1\n1 2\n", "3 4 0\n", "100 50 2\n50 25\n50 25\n" ]
[ "YES", "NO", "NO" ]
none
[ { "input": "2 2 1\n1 2", "output": "YES" }, { "input": "3 4 0", "output": "NO" }, { "input": "100 50 2\n50 25\n50 25", "output": "NO" }, { "input": "20 20 4\n10 10\n10 10\n10 10\n10 10", "output": "NO" }, { "input": "15 15 1\n8 8", "output": "NO" }, { ...
124
0
0
5,048
711
Coloring Trees
[ "dp" ]
null
null
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where *n* trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to *n* from left to right. Initially, tree *i* has color *c**i*. ZS the Coder and Chris the Baboon recognizes only *m* different colors, so 0<=≀<=*c**i*<=≀<=*m*, where *c**i*<==<=0 means that tree *i* is uncolored. ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with *c**i*<==<=0. They can color each of them them in any of the *m* colors from 1 to *m*. Coloring the *i*-th tree with color *j* requires exactly *p**i*,<=*j* litres of paint. The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the *n* trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2,<=1,<=1,<=1,<=3,<=2,<=2,<=3,<=1,<=3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2},<={1,<=1,<=1},<={3},<={2,<=2},<={3},<={1},<={3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly *k*. They need your help to determine the minimum amount of paint (in litres) needed to finish the job. Please note that the friends can't color the trees that are already colored.
The first line contains three integers, *n*, *m* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=100, 1<=≀<=*m*<=≀<=100)Β β€” the number of trees, number of colors and beauty of the resulting coloring respectively. The second line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (0<=≀<=*c**i*<=≀<=*m*), the initial colors of the trees. *c**i* equals to 0 if the tree number *i* is uncolored, otherwise the *i*-th tree has color *c**i*. Then *n* lines follow. Each of them contains *m* integers. The *j*-th number on the *i*-th of them line denotes *p**i*,<=*j* (1<=≀<=*p**i*,<=*j*<=≀<=109)Β β€” the amount of litres the friends need to color *i*-th tree with color *j*. *p**i*,<=*j*'s are specified even for the initially colored trees, but such trees still can't be colored.
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty *k*, print <=-<=1.
[ "3 2 2\n0 0 0\n1 2\n3 4\n5 6\n", "3 2 2\n2 1 2\n1 3\n2 4\n3 5\n", "3 2 2\n2 0 0\n1 3\n2 4\n3 5\n", "3 2 3\n2 1 2\n1 3\n2 4\n3 5\n" ]
[ "10", "-1", "5", "0" ]
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color). In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is  - 1. In the last sample case, all the trees are colored and the beauty of the coloring matches *k*, so no paint is used and the answer is 0.
[ { "input": "3 2 2\n0 0 0\n1 2\n3 4\n5 6", "output": "10" }, { "input": "3 2 2\n2 1 2\n1 3\n2 4\n3 5", "output": "-1" }, { "input": "3 2 2\n2 0 0\n1 3\n2 4\n3 5", "output": "5" }, { "input": "3 2 3\n2 1 2\n1 3\n2 4\n3 5", "output": "0" }, { "input": "3 2 3\n0 0 0\n...
2,000
37,478,400
0
5,052
883
Automatic Door
[ "implementation" ]
null
null
There is an automatic door at the entrance of a factory. The door works in the following way: - when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, - when one or several people come to the door and it is open, all people immediately come inside, - opened door immediately closes in *d* seconds after its opening, - if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close. For example, if *d*<==<=3 and four people are coming at four different moments of time *t*1<==<=4, *t*2<==<=7, *t*3<==<=9 and *t*4<==<=13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12. It is known that *n* employees will enter at moments *a*,<=2Β·*a*,<=3Β·*a*,<=...,<=*n*Β·*a* (the value *a* is positive integer). Also *m* clients will enter at moments *t*1,<=*t*2,<=...,<=*t**m*. Write program to find the number of times the automatic door will open. Assume that the door is initially closed.
The first line contains four integers *n*, *m*, *a* and *d* (1<=≀<=*n*,<=*a*<=≀<=109, 1<=≀<=*m*<=≀<=105, 1<=≀<=*d*<=≀<=1018) β€” the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes. The second line contains integer sequence *t*1,<=*t*2,<=...,<=*t**m* (1<=≀<=*t**i*<=≀<=1018) β€” moments of time when clients will come. The values *t**i* are given in non-decreasing order.
Print the number of times the door will open.
[ "1 1 3 4\n7\n", "4 3 4 2\n7 9 11\n" ]
[ "1\n", "4\n" ]
In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time.
[ { "input": "1 1 3 4\n7", "output": "1" }, { "input": "4 3 4 2\n7 9 11", "output": "4" }, { "input": "10 10 51 69\n154 170 170 183 251 337 412 426 445 452", "output": "6" }, { "input": "70 10 26 17\n361 371 579 585 629 872 944 1017 1048 1541", "output": "70" }, { "...
61
5,529,600
0
5,054
572
Order Book
[ "data structures", "greedy", "implementation", "sortings" ]
null
null
In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number *i* has price *p**i*, direction *d**i* β€” buy or sell, and integer *q**i*. This means that the participant is ready to buy or sell *q**i* stocks at price *p**i* for one stock. A value *q**i* is also known as a volume of an order. All orders with the same price *p* and direction *d* are merged into one aggregated order with price *p* and direction *d*. The volume of such order is a sum of volumes of the initial orders. An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order. An order book of depth *s* contains *s* best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than *s* aggregated orders for some direction then all of them will be in the final order book. You are given *n* stock exhange orders. Your task is to print order book of depth *s* for these orders.
The input starts with two positive integers *n* and *s* (1<=≀<=*n*<=≀<=1000,<=1<=≀<=*s*<=≀<=50), the number of orders and the book depth. Next *n* lines contains a letter *d**i* (either 'B' or 'S'), an integer *p**i* (0<=≀<=*p**i*<=≀<=105) and an integer *q**i* (1<=≀<=*q**i*<=≀<=104) β€” direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
Print no more than 2*s* lines with aggregated orders from order book of depth *s*. The output format for orders should be the same as in input.
[ "6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10\n" ]
[ "S 50 8\nS 40 1\nB 25 10\nB 20 4\n" ]
Denote (x, y) an order with price *x* and volume *y*. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample. You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
[ { "input": "6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10", "output": "S 50 8\nS 40 1\nB 25 10\nB 20 4" }, { "input": "2 1\nB 7523 5589\nS 69799 1711", "output": "S 69799 1711\nB 7523 5589" }, { "input": "1 1\nB 48259 991", "output": "B 48259 991" }, { "input": "1 50\n...
61
307,200
0
5,058
300
Coach
[ "brute force", "dfs and similar", "graphs" ]
null
null
A programming coach has *n* students to teach. We know that *n* is divisible by 3. Let's assume that all students are numbered from 1 to *n*, inclusive. Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the *i*-th student wants to be on the same team with the *j*-th one, then the *j*-th student wants to be on the same team with the *i*-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the *i*-th student wants to be on the same team with the *j*-th, then the *i*-th and the *j*-th students must be on the same team. Also, it is obvious that each student must be on exactly one team. Help the coach and divide the teams the way he wants.
The first line of the input contains integers *n* and *m* (3<=≀<=*n*<=≀<=48, . Then follow *m* lines, each contains a pair of integers *a**i*,<=*b**i* (1<=≀<=*a**i*<=&lt;<=*b**i*<=≀<=*n*) β€” the pair *a**i*,<=*b**i* means that students with numbers *a**i* and *b**i* want to be on the same team. It is guaranteed that *n* is divisible by 3. It is guaranteed that each pair *a**i*,<=*b**i* occurs in the input at most once.
If the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers *x**i*, *y**i*, *z**i* (1<=≀<=*x**i*,<=*y**i*,<=*z**i*<=≀<=*n*) β€” the *i*-th team. If there are multiple answers, you are allowed to print any of them.
[ "3 0\n", "6 4\n1 2\n2 3\n3 4\n5 6\n", "3 3\n1 2\n2 3\n1 3\n" ]
[ "3 2 1 \n", "-1\n", "3 2 1 \n" ]
none
[ { "input": "3 0", "output": "3 2 1 " }, { "input": "6 4\n1 2\n2 3\n3 4\n5 6", "output": "-1" }, { "input": "3 3\n1 2\n2 3\n1 3", "output": "3 2 1 " }, { "input": "6 3\n1 2\n3 4\n5 6", "output": "-1" }, { "input": "15 9\n1 4\n1 6\n2 7\n2 11\n4 6\n5 12\n7 11\n9 14\n...
218
7,065,600
0
5,068
88
Keyboard
[ "implementation" ]
B. Keyboard
1
256
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has *n* rows of keys containing *m* keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase. Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed *x*. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys. Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than *x*. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips. You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
The first line contains three integers *n*, *m*, *x* (1<=≀<=*n*,<=*m*<=≀<=30,<=1<=≀<=*x*<=≀<=50). Next *n* lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly *m* keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol. Then follow the length of the text *q* (1<=≀<=*q*<=≀<=5Β·105). The last line contains the text *T*, which consists of *q* symbols, which are uppercase and lowercase Latin letters.
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
[ "2 2 1\nab\ncd\n1\nA\n", "2 2 1\nab\ncd\n1\ne\n", "2 2 1\nab\ncS\n5\nabcBA\n", "3 9 4\nqwertyuio\nasdfghjkl\nSzxcvbnmS\n35\nTheQuIcKbRoWnFOXjummsovertHeLazYDOG\n" ]
[ "-1\n", "-1\n", "1\n", "2\n" ]
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard. In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard. In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
[ { "input": "2 2 1\nab\ncd\n1\nA", "output": "-1" }, { "input": "2 2 1\nab\ncd\n1\ne", "output": "-1" }, { "input": "2 2 1\nab\ncS\n5\nabcBA", "output": "1" }, { "input": "3 9 4\nqwertyuio\nasdfghjkl\nSzxcvbnmS\n35\nTheQuIcKbRoWnFOXjummsovertHeLazYDOG", "output": "2" }, ...
46
0
0
5,093
328
IQ Test
[ "implementation" ]
null
null
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions. Arithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 and *d* are any numbers. Geometric progression is a sequence *b*1, *b*2<==<=*b*1*q*, ..., *b**n*<==<=*b**n*<=-<=1*q*, where *b*1<=β‰ <=0, *q*<=β‰ <=0, *q*<=β‰ <=1. Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.
The first line contains exactly four integer numbers between 1 and 1000, inclusively.
Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element. Print 42 if the given sequence is not an arithmetic or geometric progression.
[ "836 624 412 200\n", "1 334 667 1000\n" ]
[ "-12\n", "1333\n" ]
This problem contains very weak pretests!
[ { "input": "836 624 412 200", "output": "-12" }, { "input": "1 334 667 1000", "output": "1333" }, { "input": "501 451 400 350", "output": "42" }, { "input": "836 624 412 200", "output": "-12" }, { "input": "1 334 667 1000", "output": "1333" }, { "input...
92
0
0
5,110
793
Igor and his way to work
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
null
null
Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank. Bankopolis looks like a grid of *n* rows and *m* columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.
The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=1000)Β β€” the number of rows and the number of columns in the grid. Each of the next *n* lines contains *m* characters denoting the corresponding row of the grid. The following characters can occur: - "." β€” an empty cell; - "*" β€” a cell with road works; - "S" β€” the cell where Igor's home is located; - "T" β€” the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each.
In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.
[ "5 5\n..S..\n****.\nT....\n****.\n.....\n", "5 5\nS....\n****.\n.....\n.****\n..T..\n" ]
[ "YES", "NO" ]
The first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:
[ { "input": "5 5\nS....\n****.\n.....\n.****\n..T..", "output": "NO" }, { "input": "1 2\nST", "output": "YES" }, { "input": "3 1\nS\n*\nT", "output": "NO" }, { "input": "3 3\n*..\n...\nTS.", "output": "YES" }, { "input": "3 3\nT.*\n*.*\n*S*", "output": "YES" ...
46
5,529,600
-1
5,118
375
Divisible by Seven
[ "math", "number theory" ]
null
null
You have number *a*, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7. Number *a* doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
The first line contains positive integer *a* in the decimal record. It is guaranteed that the record of number *a* contains digits: 1, 6, 8, 9. Number *a* doesn't contain any leading zeroes. The decimal representation of number *a* contains at least 4 and at most 106 characters.
Print a number in the decimal notation without leading zeroes β€” the result of the permutation. If it is impossible to rearrange the digits of the number *a* in the required manner, print 0.
[ "1689\n", "18906\n" ]
[ "1869\n", "18690\n" ]
none
[ { "input": "1689", "output": "1869" }, { "input": "18906", "output": "18690" }, { "input": "2419323689", "output": "2432391689" }, { "input": "8589157262", "output": "5857221986" }, { "input": "2717172350336955863014903670481525170997949309274087058935108848979319...
1,000
12,902,400
0
5,119
766
Mahmoud and a Triangle
[ "constructive algorithms", "geometry", "greedy", "math", "number theory", "sortings" ]
null
null
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle. Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
The first line contains single integer *n* (3<=≀<=*n*<=≀<=105)Β β€” the number of line segments Mahmoud has. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109)Β β€” the lengths of line segments Mahmoud has.
In the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise.
[ "5\n1 5 3 2 4\n", "3\n4 1 2\n" ]
[ "YES\n", "NO\n" ]
For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle.
[ { "input": "5\n1 5 3 2 4", "output": "YES" }, { "input": "3\n4 1 2", "output": "NO" }, { "input": "30\n197 75 517 39724 7906061 1153471 3 15166 168284 3019844 272293 316 16 24548 42 118 5792 5 9373 1866366 4886214 24 2206 712886 104005 1363 836 64273 440585 3576", "output": "NO" },...
2,000
20,172,800
0
5,147
958
Maximum Control (easy)
[ "implementation" ]
null
null
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them. The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel. How much work is there left to be done: that is, how many remote planets are there?
The first line of the input contains an integer *N* (2<=≀<=*N*<=≀<=1000) – the number of planets in the galaxy. The next *N*<=-<=1 lines describe the hyperspace tunnels between the planets. Each of the *N*<=-<=1 lines contains two space-separated integers *u* and *v* (1<=≀<=*u*,<=*v*<=≀<=*N*) indicating that there is a bidirectional hyperspace tunnel between the planets *u* and *v*. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
A single integer denoting the number of remote planets.
[ "5\n4 1\n4 2\n1 3\n1 5\n", "4\n1 2\n4 3\n1 4\n" ]
[ "3\n", "2\n" ]
In the first example, only planets 2, 3 and 5 are connected by a single tunnel. In the second example, the remote planets are 2 and 3. Note that this problem has only two versions – easy and medium.
[ { "input": "5\n4 1\n4 2\n1 3\n1 5", "output": "3" }, { "input": "4\n1 2\n4 3\n1 4", "output": "2" }, { "input": "10\n4 3\n2 6\n10 1\n5 7\n5 8\n10 6\n5 9\n9 3\n2 9", "output": "4" } ]
46
0
3
5,151
587
Duff and Weight Lifting
[ "greedy" ]
null
null
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of *i*-th of them is 2*w**i* pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2*a*1,<=...,<=2*a**k* if and only if there exists a non-negative integer *x* such that 2*a*1<=+<=2*a*2<=+<=...<=+<=2*a**k*<==<=2*x*, i. e. the sum of those numbers is a power of two. Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.
The first line of input contains integer *n* (1<=≀<=*n*<=≀<=106), the number of weights. The second line contains *n* integers *w*1,<=...,<=*w**n* separated by spaces (0<=≀<=*w**i*<=≀<=106 for each 1<=≀<=*i*<=≀<=*n*), the powers of two forming the weights values.
Print the minimum number of steps in a single line.
[ "5\n1 1 2 3 3\n", "4\n0 1 2 3\n" ]
[ "2\n", "4\n" ]
In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two. In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.
[ { "input": "5\n1 1 2 3 3", "output": "2" }, { "input": "4\n0 1 2 3", "output": "4" }, { "input": "1\n120287", "output": "1" }, { "input": "2\n28288 0", "output": "2" }, { "input": "2\n95745 95745", "output": "1" }, { "input": "13\n92 194 580495 0 10855...
1,000
69,427,200
0
5,172
771
Bear and Different Names
[ "constructive algorithms", "greedy" ]
null
null
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?). A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't. You are a spy in the enemy's camp. You noticed *n* soldiers standing in a row, numbered 1 through *n*. The general wants to choose a group of *k* consecutive soldiers. For every *k* consecutive soldiers, the general wrote down whether they would be an effective group or not. You managed to steal the general's notes, with *n*<=-<=*k*<=+<=1 strings *s*1,<=*s*2,<=...,<=*s**n*<=-<=*k*<=+<=1, each either "YES" or "NO". - The string *s*1 describes a group of soldiers 1 through *k* ("YES" if the group is effective, and "NO" otherwise). - The string *s*2 describes a group of soldiers 2 through *k*<=+<=1. - And so on, till the string *s**n*<=-<=*k*<=+<=1 that describes a group of soldiers *n*<=-<=*k*<=+<=1 through *n*. Your task is to find possible names of *n* soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β€” it's allowed to print "Xyzzzdj" or "T" for example. Find and print any solution. It can be proved that there always exists at least one solution.
The first line of the input contains two integers *n* and *k* (2<=≀<=*k*<=≀<=*n*<=≀<=50)Β β€” the number of soldiers and the size of a group respectively. The second line contains *n*<=-<=*k*<=+<=1 strings *s*1,<=*s*2,<=...,<=*s**n*<=-<=*k*<=+<=1. The string *s**i* is "YES" if the group of soldiers *i* through *i*<=+<=*k*<=-<=1 is effective, and "NO" otherwise.
Find any solution satisfying all given conditions. In one line print *n* space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them.
[ "8 3\nNO NO YES YES YES NO\n", "9 8\nYES NO\n", "3 2\nNO NO\n" ]
[ "Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na" ]
In the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: - First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string *s*<sub class="lower-index">1</sub> is "NO". - Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string *s*<sub class="lower-index">2</sub> is "NO". - Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string *s*<sub class="lower-index">3</sub> is "YES". - ..., - Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string *s*<sub class="lower-index">6</sub> is "NO".
[ { "input": "8 3\nNO NO YES YES YES NO", "output": "Ab Ac Ab Ac Af Ag Ah Ag " }, { "input": "9 8\nYES NO", "output": "Ab Ac Ad Ae Af Ag Ah Ai Ac " }, { "input": "3 2\nNO NO", "output": "Ab Ab Ab " }, { "input": "2 2\nYES", "output": "Ab Ac " }, { "input": "2 2\nNO"...
202
2,662,400
-1
5,189
160
Unlucky Ticket
[ "greedy", "sortings" ]
null
null
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half. But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half. For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2<=&gt;<=1 and 4<=&gt;<=2), ticket 0135 also meets the criterion (the sought correspondence is 0<=&lt;<=3 and 1<=&lt;<=5), and ticket 3754 does not meet the criterion. You have a ticket in your hands, it contains 2*n* digits. Your task is to check whether it meets the unluckiness criterion.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=100). The second line contains a string that consists of 2*n* digits and defines your ticket.
In the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes).
[ "2\n2421\n", "2\n0135\n", "2\n3754\n" ]
[ "YES\n", "YES\n", "NO\n" ]
none
[ { "input": "2\n2421", "output": "YES" }, { "input": "2\n0135", "output": "YES" }, { "input": "2\n3754", "output": "NO" }, { "input": "1\n33", "output": "NO" }, { "input": "2\n3444", "output": "NO" }, { "input": "3\n221323", "output": "YES" }, {...
62
0
0
5,192
797
Broken BST
[ "data structures", "dfs and similar" ]
null
null
Let *T* be arbitrary binary tree β€” tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent β€” it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree *T*: 1. Set pointer to the root of a tree. 1. Return success if the value in the current vertex is equal to the number you are looking for 1. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for 1. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for 1. Return fail if you try to go to the vertex that doesn't exist Here is the pseudo-code of the described algorithm: The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree. Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree. If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
First line contains integer number *n* (1<=≀<=*n*<=≀<=105) β€” number of vertices in the tree. Each of the next *n* lines contains 3 numbers *v*, *l*, *r* (0<=≀<=*v*<=≀<=109) β€” value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number <=-<=1 is set instead. Note that different vertices of the tree may contain the same values.
Print number of times when search algorithm will fail.
[ "3\n15 -1 -1\n10 1 3\n5 -1 -1\n", "8\n6 2 3\n3 4 5\n12 6 7\n1 -1 8\n4 -1 -1\n5 -1 -1\n14 -1 -1\n2 -1 -1\n" ]
[ "2\n", "1\n" ]
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
[ { "input": "3\n15 -1 -1\n10 1 3\n5 -1 -1", "output": "2" }, { "input": "8\n6 2 3\n3 4 5\n12 6 7\n1 -1 8\n4 -1 -1\n5 -1 -1\n14 -1 -1\n2 -1 -1", "output": "1" }, { "input": "1\n493041212 -1 -1", "output": "0" }, { "input": "10\n921294733 5 9\n341281094 -1 -1\n35060484 10 -1\n36...
982
96,153,600
3
5,196
266
Queue at the School
[ "constructive algorithms", "graph matchings", "implementation", "shortest paths" ]
null
null
During the break the schoolchildren, boys and girls, formed a queue of *n* people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second. Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to *n*, at that the person in the position number 1 is served first. Then, if at time *x* a boy stands on the *i*-th position and a girl stands on the (*i*<=+<=1)-th position, then at time *x*<=+<=1 the *i*-th position will have a girl and the (*i*<=+<=1)-th position will have a boy. The time is given in seconds. You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after *t* seconds.
The first line contains two integers *n* and *t* (1<=≀<=*n*,<=*t*<=≀<=50), which represent the number of children in the queue and the time after which the queue will transform into the arrangement you need to find. The next line contains string *s*, which represents the schoolchildren's initial arrangement. If the *i*-th position in the queue contains a boy, then the *i*-th character of string *s* equals "B", otherwise the *i*-th character equals "G".
Print string *a*, which describes the arrangement after *t* seconds. If the *i*-th position has a boy after the needed time, then the *i*-th character *a* must equal "B", otherwise it must equal "G".
[ "5 1\nBGGBG\n", "5 2\nBGGBG\n", "4 1\nGGGB\n" ]
[ "GBGGB\n", "GGBGB\n", "GGGB\n" ]
none
[ { "input": "5 1\nBGGBG", "output": "GBGGB" }, { "input": "5 2\nBGGBG", "output": "GGBGB" }, { "input": "4 1\nGGGB", "output": "GGGB" }, { "input": "2 1\nBB", "output": "BB" }, { "input": "2 1\nBG", "output": "GB" }, { "input": "6 2\nBBGBBG", "outpu...
62
0
0
5,201
604
More Cowbell
[ "binary search", "greedy" ]
null
null
Kevin Sun wants to move his precious collection of *n* cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into *k* boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his *i*-th (1<=≀<=*i*<=≀<=*n*) cowbell is an integer *s**i*. In fact, he keeps his cowbells sorted by size, so *s**i*<=-<=1<=≀<=*s**i* for any *i*<=&gt;<=1. Also an expert packer, Kevin can fit one or two cowbells into a box of size *s* if and only if the sum of their sizes does not exceed *s*. Given this information, help Kevin determine the smallest *s* for which it is possible to put all of his cowbells into *k* boxes of size *s*.
The first line of the input contains two space-separated integers *n* and *k* (1<=≀<=*n*<=≀<=2Β·*k*<=≀<=100<=000), denoting the number of cowbells and the number of boxes, respectively. The next line contains *n* space-separated integers *s*1,<=*s*2,<=...,<=*s**n* (1<=≀<=*s*1<=≀<=*s*2<=≀<=...<=≀<=*s**n*<=≀<=1<=000<=000), the sizes of Kevin's cowbells. It is guaranteed that the sizes *s**i* are given in non-decreasing order.
Print a single integer, the smallest *s* for which it is possible for Kevin to put all of his cowbells into *k* boxes of size *s*.
[ "2 1\n2 5\n", "4 3\n2 3 5 9\n", "3 2\n3 5 7\n" ]
[ "7\n", "9\n", "8\n" ]
In the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}. In the third sample, the optimal solution is {3, 5} and {7}.
[ { "input": "2 1\n2 5", "output": "7" }, { "input": "4 3\n2 3 5 9", "output": "9" }, { "input": "3 2\n3 5 7", "output": "8" }, { "input": "20 11\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "output": "2" }, { "input": "10 10\n3 15 31 61 63 63 68 94 98 100", "outp...
62
7,065,600
0
5,214
0
none
[ "none" ]
null
null
Arpa has found a list containing *n* numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1. Arpa can perform two types of operations: - Choose a number and delete it with cost *x*. - Choose a number and increase it by 1 with cost *y*. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number. Help Arpa to find the minimum possible cost to make the list good.
First line contains three integers *n*, *x* and *y* (1<=≀<=*n*<=≀<=5Β·105, 1<=≀<=*x*,<=*y*<=≀<=109)Β β€” the number of elements in the list and the integers *x* and *y*. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=106)Β β€” the elements of the list.
Print a single integer: the minimum possible cost to make the list good.
[ "4 23 17\n1 17 17 16\n", "10 6 2\n100 49 71 73 66 96 8 60 41 63\n" ]
[ "40\n", "10\n" ]
In example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17). A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd [here](https://en.wikipedia.org/wiki/Greatest_common_divisor).
[]
0
0
-1
5,217
125
Measuring Lengths in Baden
[ "math" ]
null
null
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches. You are given a length equal to *n* centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches. Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
The only line contains an integer *n* (1<=≀<=*n*<=≀<=10000).
Print two non-negative space-separated integers *a* and *b*, where *a* is the numbers of feet and *b* is the number of inches.
[ "42\n", "5\n" ]
[ "1 2\n", "0 2\n" ]
none
[ { "input": "42", "output": "1 2" }, { "input": "5", "output": "0 2" }, { "input": "24", "output": "0 8" }, { "input": "1", "output": "0 0" }, { "input": "2", "output": "0 1" }, { "input": "3", "output": "0 1" }, { "input": "4", "output"...
218
0
0
5,224
441
Valera and Swaps
[ "constructive algorithms", "dsu", "graphs", "implementation", "math", "string suffix structures" ]
null
null
A permutation *p* of length *n* is a sequence of distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≀<=*p**i*<=≀<=*n*). A permutation is an identity permutation, if for any *i* the following equation holds *p**i*<==<=*i*. A swap (*i*,<=*j*) is the operation that swaps elements *p**i* and *p**j* in the permutation. Let's assume that *f*(*p*) is the minimum number of swaps that you need to make the permutation *p* an identity permutation. Valera wonders, how he can transform permutation *p* into any permutation *q*, such that *f*(*q*)<==<=*m*, using the minimum number of swaps. Help him do that.
The first line contains integer *n* (1<=≀<=*n*<=≀<=3000) β€” the length of permutation *p*. The second line contains *n* distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≀<=*p**i*<=≀<=*n*) β€” Valera's initial permutation. The last line contains integer *m* (0<=≀<=*m*<=&lt;<=*n*).
In the first line, print integer *k* β€” the minimum number of swaps. In the second line, print 2*k* integers *x*1,<=*x*2,<=...,<=*x*2*k* β€” the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (*x*1,<=*x*2), (*x*3,<=*x*4), ..., (*x*2*k*<=-<=1,<=*x*2*k*). If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.
[ "5\n1 2 3 4 5\n2\n", "5\n2 1 4 5 3\n2\n" ]
[ "2\n1 2 1 3 ", "1\n1 2 " ]
Sequence *x*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub>, ..., *x*<sub class="lower-index">*s*</sub> is lexicographically smaller than sequence *y*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">2</sub>, ..., *y*<sub class="lower-index">*s*</sub>, if there is such integer *r* (1 ≀ *r* ≀ *s*), that *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ..., *x*<sub class="lower-index">*r* - 1</sub> = *y*<sub class="lower-index">*r* - 1</sub> and *x*<sub class="lower-index">*r*</sub> &lt; *y*<sub class="lower-index">*r*</sub>.
[]
0
0
-1
5,233
932
Permutation Cycle
[ "brute force", "constructive algorithms" ]
null
null
For a permutation *P*[1... *N*] of integers from 1 to *N*, function *f* is defined as follows: Let *g*(*i*) be the minimum positive integer *j* such that *f*(*i*,<=*j*)<==<=*i*. We can show such *j* always exists. For given *N*,<=*A*,<=*B*, find a permutation *P* of integers from 1 to *N* such that for 1<=≀<=*i*<=≀<=*N*, *g*(*i*) equals either *A* or *B*.
The only line contains three integers *N*,<=*A*,<=*B* (1<=≀<=*N*<=≀<=106,<=1<=≀<=*A*,<=*B*<=≀<=*N*).
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to *N*.
[ "9 2 5\n", "3 2 1\n" ]
[ "6 5 8 3 4 1 9 2 7", "1 2 3 " ]
In the first example, *g*(1) = *g*(6) = *g*(7) = *g*(9) = 2 and *g*(2) = *g*(3) = *g*(4) = *g*(5) = *g*(8) = 5 In the second example, *g*(1) = *g*(2) = *g*(3) = 1
[ { "input": "9 2 5", "output": "2 1 4 3 6 7 8 9 5 " }, { "input": "3 2 1", "output": "1 2 3 " }, { "input": "7 4 4", "output": "-1" }, { "input": "1000000 999998 3", "output": "-1" }, { "input": "1 1 1", "output": "1 " }, { "input": "993012 997 1001", ...
1,559
30,105,600
3
5,237
962
Students in Railway Carriage
[ "constructive algorithms", "greedy", "implementation" ]
null
null
There are $n$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of $a$ student-programmers and $b$ student-athletes. Determine the largest number of students from all $a+b$ students, which you can put in the railway carriage so that: - no student-programmer is sitting next to the student-programmer; - and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting. Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
The first line contain three integers $n$, $a$ and $b$ ($1 \le n \le 2\cdot10^{5}$, $0 \le a, b \le 2\cdot10^{5}$, $a + b &gt; 0$) β€” total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $n$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
[ "5 1 1\n*...*\n", "6 2 3\n*...*.\n", "11 3 10\n.*....**.*.\n", "3 2 3\n***\n" ]
[ "2\n", "4\n", "7\n", "0\n" ]
In the first example you can put all student, for example, in the following way: *.AB* In the second example you can put four students, for example, in the following way: *BAB*B In the third example you can put seven students, for example, in the following way: B*ABAB**A*B The letter A means a student-programmer, and the letter B β€” student-athlete.
[ { "input": "5 1 1\n*...*", "output": "2" }, { "input": "6 2 3\n*...*.", "output": "4" }, { "input": "11 3 10\n.*....**.*.", "output": "7" }, { "input": "3 2 3\n***", "output": "0" }, { "input": "9 5 3\n*...*...*", "output": "6" }, { "input": "9 2 4\n*....
109
0
0
5,242
355
Vasya and Public Transport
[ "greedy", "implementation" ]
null
null
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has *n* buses and *m* trolleys, the buses are numbered by integers from 1 to *n*, the trolleys are numbered by integers from 1 to *m*. Public transport is not free. There are 4 types of tickets: 1. A ticket for one ride on some bus or trolley. It costs *c*1 burles; 1. A ticket for an unlimited number of rides on some bus or on some trolley. It costs *c*2 burles; 1. A ticket for an unlimited number of rides on all buses or all trolleys. It costs *c*3 burles; 1. A ticket for an unlimited number of rides on all buses and trolleys. It costs *c*4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
The first line contains four integers *c*1,<=*c*2,<=*c*3,<=*c*4 (1<=≀<=*c*1,<=*c*2,<=*c*3,<=*c*4<=≀<=1000) β€” the costs of the tickets. The second line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=1000) β€” the number of buses and trolleys Vasya is going to use. The third line contains *n* integers *a**i* (0<=≀<=*a**i*<=≀<=1000) β€” the number of times Vasya is going to use the bus number *i*. The fourth line contains *m* integers *b**i* (0<=≀<=*b**i*<=≀<=1000) β€” the number of times Vasya is going to use the trolley number *i*.
Print a single number β€” the minimum sum of burles Vasya will have to spend on the tickets.
[ "1 3 7 19\n2 3\n2 5\n4 4 4\n", "4 3 2 1\n1 3\n798\n1 2 3\n", "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42\n" ]
[ "12\n", "1\n", "16\n" ]
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2Β·1) + 3 + 7 = 12 burles. In the second sample the profitable strategy is to buy one ticket of the fourth type. In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
[ { "input": "1 3 7 19\n2 3\n2 5\n4 4 4", "output": "12" }, { "input": "4 3 2 1\n1 3\n798\n1 2 3", "output": "1" }, { "input": "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42", "output": "16" }, { "input": "3 103 945 1000\n7 9\n34 35 34 35 34 35 34\n0 0 0 0 0 0 0 0 0", "output"...
92
0
0
5,262
993
Two Squares
[ "geometry", "implementation" ]
null
null
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
The input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order. The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees. All the values are integer and between $-100$ and $100$.
Print "Yes" if squares intersect, otherwise print "No". You can print each letter in any case (upper or lower).
[ "0 0 6 0 6 6 0 6\n1 3 3 5 5 3 3 1\n", "0 0 6 0 6 6 0 6\n7 3 9 5 11 3 9 1\n", "6 0 6 6 0 6 0 0\n7 4 4 7 7 10 10 7\n" ]
[ "YES\n", "NO\n", "YES\n" ]
In the first example the second square lies entirely within the first square, so they do intersect. In the second sample squares do not have any points in common. Here are images corresponding to the samples:
[ { "input": "0 0 6 0 6 6 0 6\n1 3 3 5 5 3 3 1", "output": "YES" }, { "input": "0 0 6 0 6 6 0 6\n7 3 9 5 11 3 9 1", "output": "NO" }, { "input": "6 0 6 6 0 6 0 0\n7 4 4 7 7 10 10 7", "output": "YES" }, { "input": "0 0 6 0 6 6 0 6\n8 4 4 8 8 12 12 8", "output": "YES" }, ...
62
0
0
5,284
702
Road to Post Office
[ "math" ]
null
null
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to *d* kilometers. Vasiliy's car is not new β€” it breaks after driven every *k* kilometers and Vasiliy needs *t* seconds to repair it. After repairing his car Vasiliy can drive again (but after *k* kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station. To drive one kilometer on car Vasiliy spends *a* seconds, to walk one kilometer on foot he needs *b* seconds (*a*<=&lt;<=*b*). Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.
The first line contains 5 positive integers *d*,<=*k*,<=*a*,<=*b*,<=*t* (1<=≀<=*d*<=≀<=1012; 1<=≀<=*k*,<=*a*,<=*b*,<=*t*<=≀<=106; *a*<=&lt;<=*b*), where: - *d* β€” the distance from home to the post office; - *k* β€” the distance, which car is able to drive before breaking; - *a* β€” the time, which Vasiliy spends to drive 1 kilometer on his car; - *b* β€” the time, which Vasiliy spends to walk 1 kilometer on foot; - *t* β€” the time, which Vasiliy spends to repair his car.
Print the minimal time after which Vasiliy will be able to reach the post office.
[ "5 2 1 4 10\n", "5 2 1 4 5\n" ]
[ "14\n", "13\n" ]
In the first example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds) and then to walk on foot 3 kilometers (in 12 seconds). So the answer equals to 14 seconds. In the second example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds), then repair his car (in 5 seconds) and drive 2 kilometers more on the car (in 2 seconds). After that he needs to walk on foot 1 kilometer (in 4 seconds). So the answer equals to 13 seconds.
[ { "input": "5 2 1 4 10", "output": "14" }, { "input": "5 2 1 4 5", "output": "13" }, { "input": "1 1 1 2 1", "output": "1" }, { "input": "1000000000000 1000000 999999 1000000 1000000", "output": "999999999999000000" }, { "input": "997167959139 199252 232602 952690...
61
0
0
5,288
472
Design Tutorial: Inverse the Problem
[ "dfs and similar", "dsu", "shortest paths", "trees" ]
null
null
There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example. Now let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an *n*<=Γ—<=*n* distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).
The first line contains an integer *n* (1<=≀<=*n*<=≀<=2000) β€” the number of nodes in that graph. Then next *n* lines each contains *n* integers *d**i*,<=*j* (0<=≀<=*d**i*,<=*j*<=≀<=109) β€” the distance between node *i* and node *j*.
If there exists such a tree, output "YES", otherwise output "NO".
[ "3\n0 2 7\n2 0 9\n7 9 0\n", "3\n1 2 7\n2 0 9\n7 9 0\n", "3\n0 2 2\n7 0 9\n7 9 0\n", "3\n0 1 1\n1 0 1\n1 1 0\n", "2\n0 0\n0 0\n" ]
[ "YES\n", "NO\n", "NO\n", "NO\n", "NO\n" ]
In the first example, the required tree exists. It has one edge between nodes 1 and 2 with weight 2, another edge between nodes 1 and 3 with weight 7. In the second example, it is impossible because *d*<sub class="lower-index">1, 1</sub> should be 0, but it is 1. In the third example, it is impossible because *d*<sub class="lower-index">1, 2</sub> should equal *d*<sub class="lower-index">2, 1</sub>.
[ { "input": "3\n0 2 7\n2 0 9\n7 9 0", "output": "YES" }, { "input": "3\n1 2 7\n2 0 9\n7 9 0", "output": "NO" }, { "input": "3\n0 2 2\n7 0 9\n7 9 0", "output": "NO" }, { "input": "3\n0 1 1\n1 0 1\n1 1 0", "output": "NO" }, { "input": "2\n0 0\n0 0", "output": "NO...
30
0
0
5,293
6
Lizards and Basements 2
[ "brute force", "dp" ]
D. Lizards and Basements 2
2
64
This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game Β«Lizards and BasementsΒ». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the *i*-th archer with his fire ball (they are numbered from left to right), the archer loses *a* health points. At the same time the spell damages the archers adjacent to the *i*-th (if any) β€” they lose *b* (1<=≀<=*b*<=&lt;<=*a*<=≀<=10) health points each. As the extreme archers (i.e. archers numbered 1 and *n*) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball. The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies? Polycarp can throw his fire ball into an archer if the latter is already killed.
The first line of the input contains three integers *n*,<=*a*,<=*b* (3<=≀<=*n*<=≀<=10; 1<=≀<=*b*<=&lt;<=*a*<=≀<=10). The second line contains a sequence of *n* integers β€” *h*1,<=*h*2,<=...,<=*h**n* (1<=≀<=*h**i*<=≀<=15), where *h**i* is the amount of health points the *i*-th archer has.
In the first line print *t* β€” the required minimum amount of fire balls. In the second line print *t* numbers β€” indexes of the archers that Polycarp should hit to kill all the archers in *t* shots. All these numbers should be between 2 and *n*<=-<=1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.
[ "3 2 1\n2 2 2\n", "4 3 1\n1 4 1 1\n" ]
[ "3\n2 2 2 ", "4\n2 2 3 3 " ]
none
[ { "input": "3 2 1\n2 2 2", "output": "3\n2 2 2 " }, { "input": "4 3 1\n1 4 1 1", "output": "4\n2 2 3 3 " }, { "input": "3 5 3\n1 2 1", "output": "1\n2 " }, { "input": "3 5 3\n3 2 2", "output": "2\n2 2 " }, { "input": "3 5 3\n3 2 2", "output": "2\n2 2 " }, ...
248
307,200
3.935711
5,309
47
Crossword
[ "implementation" ]
C. Crossword
2
256
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical. The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification. Help Vasya β€” compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots. If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the &lt; operator in the modern programming languages.
[ "NOD\nBAA\nYARD\nAIRWAY\nNEWTON\nBURN\n", "AAA\nAAA\nAAAAA\nAAA\nAAA\nAAAAA\n", "PTC\nJYNYFDSGI\nZGPPC\nIXEJNDOP\nJJFS\nSSXXQOFGJUZ\n" ]
[ "BAA...\nU.I...\nR.R...\nNEWTON\n..A..O\n..YARD\n", "AAA..\nA.A..\nAAAAA\n..A.A\n..AAA\n", "JJFS....\nY..S....\nN..X....\nY..X....\nF..Q....\nD..O....\nS..F....\nG..G....\nIXEJNDOP\n...U...T\n...ZGPPC\n" ]
none
[ { "input": "NOD\nBAA\nYARD\nAIRWAY\nNEWTON\nBURN", "output": "BAA...\nU.I...\nR.R...\nNEWTON\n..A..O\n..YARD" }, { "input": "AAA\nAAA\nAAAAA\nAAA\nAAA\nAAAAA", "output": "AAA..\nA.A..\nAAAAA\n..A.A\n..AAA" }, { "input": "PTC\nJYNYFDSGI\nZGPPC\nIXEJNDOP\nJJFS\nSSXXQOFGJUZ", "output": ...
310
0
3.9225
5,319
157
Game Outcome
[ "brute force" ]
null
null
Sherlock Holmes and Dr. Watson played some game on a checkered board *n*<=Γ—<=*n* in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers. For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8<=+<=3<=+<=6<=+<=7<==<=24, sum of its row numbers equals 9<=+<=5<=+<=3<=+<=2<==<=19, and 24<=&gt;<=19.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=30). Each of the following *n* lines contain *n* space-separated integers. The *j*-th number on the *i*-th line represents the number on the square that belongs to the *j*-th column and the *i*-th row on the board. All number on the board are integers from 1 to 100.
Print the single number β€” the number of the winning squares.
[ "1\n1\n", "2\n1 2\n3 4\n", "4\n5 7 8 4\n9 5 3 2\n1 6 6 4\n9 5 7 3\n" ]
[ "0\n", "2\n", "6\n" ]
In the first example two upper squares are winning. In the third example three left squares in the both middle rows are winning:
[ { "input": "1\n1", "output": "0" }, { "input": "2\n1 2\n3 4", "output": "2" }, { "input": "4\n5 7 8 4\n9 5 3 2\n1 6 6 4\n9 5 7 3", "output": "6" }, { "input": "2\n1 1\n1 1", "output": "0" }, { "input": "3\n1 2 3\n4 5 6\n7 8 9", "output": "4" }, { "inpu...
248
0
3
5,331
359
Permutation
[ "constructive algorithms", "dp", "math" ]
null
null
A permutation *p* is an ordered group of numbers *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*, consisting of *n* distinct positive integers, each is no more than *n*. We'll define number *n* as the length of permutation *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*. Simon has a positive integer *n* and a non-negative integer *k*, such that 2*k*<=≀<=*n*. Help him find permutation *a* of length 2*n*, such that it meets this equation: .
The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=50000, 0<=≀<=2*k*<=≀<=*n*).
Print 2*n* integers *a*1,<=*a*2,<=...,<=*a*2*n* β€” the required permutation *a*. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them.
[ "1 0\n", "2 1\n", "4 0\n" ]
[ "1 2", "3 2 1 4\n", "2 7 4 6 1 3 5 8\n" ]
Record |*x*| represents the absolute value of number *x*. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
[ { "input": "1 0", "output": "1 2" }, { "input": "2 1", "output": "3 2 1 4" }, { "input": "4 0", "output": "2 7 4 6 1 3 5 8" }, { "input": "50000 0", "output": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4...
233
3,891,200
3
5,333
96
Lucky Numbers (easy)
[ "binary search", "bitmasks", "brute force" ]
B. Lucky Numbers (easy)
2
256
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not. One day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*.
The only line contains a positive integer *n* (1<=≀<=*n*<=≀<=109). This number doesn't have leading zeroes.
Output the least super lucky number that is more than or equal to *n*. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
[ "4500\n", "47\n" ]
[ "4747\n", "47\n" ]
none
[ { "input": "4500", "output": "4747" }, { "input": "47", "output": "47" }, { "input": "1", "output": "47" }, { "input": "12", "output": "47" }, { "input": "4587", "output": "4747" }, { "input": "100", "output": "4477" }, { "input": "1007", ...
62
0
0
5,336
362
Two Semiknights Meet
[ "greedy", "math" ]
null
null
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis.
The first line contains number *t* (1<=≀<=*t*<=≀<=50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
[ "2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#\n" ]
[ "YES\nNO\n" ]
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet.
[ { "input": "2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#", "output": "YES\nNO" }, { "input": "3\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n####K#K#\n\n.....
62
307,200
3
5,340
665
Shopping
[ "brute force" ]
null
null
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains *k* items. *n* customers have already used the above service. Each user paid for *m* items. Let *a**ij* denote the *j*-th item in the *i*-th person's order. Due to the space limitations all the items are arranged in one single row. When Ayush receives the *i*-th order he will find one by one all the items *a**ij* (1<=≀<=*j*<=≀<=*m*) in the row. Let *pos*(*x*) denote the position of the item *x* in the row at the moment of its collection. Then Ayush takes time equal to *pos*(*a**i*1)<=+<=*pos*(*a**i*2)<=+<=...<=+<=*pos*(*a**im*) for the *i*-th customer. When Ayush accesses the *x*-th element he keeps a new stock in the front of the row and takes away the *x*-th element. Thus the values are updating. Your task is to calculate the total time it takes for Ayush to process all the orders. You can assume that the market has endless stock.
The first line contains three integers *n*, *m* and *k* (1<=≀<=*n*,<=*k*<=≀<=100,<=1<=≀<=*m*<=≀<=*k*) β€” the number of users, the number of items each user wants to buy and the total number of items at the market. The next line contains *k* distinct integers *p**l* (1<=≀<=*p**l*<=≀<=*k*) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to *k*. Each of the next *n* lines contains *m* distinct integers *a**ij* (1<=≀<=*a**ij*<=≀<=*k*) β€” the order of the *i*-th person.
Print the only integer *t* β€” the total time needed for Ayush to process all the orders.
[ "2 2 5\n3 4 1 2 5\n1 5\n3 1\n" ]
[ "14\n" ]
Customer 1 wants the items 1 and 5. *pos*(1) = 3, so the new positions are: [1, 3, 4, 2, 5]. *pos*(5) = 5, so the new positions are: [5, 1, 3, 4, 2]. Time taken for the first customer is 3 + 5 = 8. Customer 2 wants the items 3 and 1. *pos*(3) = 3, so the new positions are: [3, 5, 1, 4, 2]. *pos*(1) = 3, so the new positions are: [1, 3, 5, 4, 2]. Time taken for the second customer is 3 + 3 = 6. Total time is 8 + 6 = 14. Formally *pos*(*x*) is the index of *x* in the current row.
[ { "input": "2 2 5\n3 4 1 2 5\n1 5\n3 1", "output": "14" }, { "input": "4 4 4\n1 2 3 4\n3 4 2 1\n4 3 2 1\n4 1 2 3\n4 1 2 3", "output": "59" }, { "input": "1 1 1\n1\n1", "output": "1" }, { "input": "10 1 100\n1 55 67 75 40 86 24 84 82 26 81 23 70 79 51 54 21 78 31 98 68 93 66 8...
77
0
0
5,353
534
Covered Path
[ "dp", "greedy", "math" ]
null
null
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.
The first line contains two integers *v*1 and *v*2 (1<=≀<=*v*1,<=*v*2<=≀<=100) β€” the speeds in meters per second at the beginning of the segment and at the end of the segment, respectively. The second line contains two integers *t* (2<=≀<=*t*<=≀<=100) β€” the time when the car moves along the segment in seconds, *d* (0<=≀<=*d*<=≀<=10) β€” the maximum value of the speed change between adjacent seconds. It is guaranteed that there is a way to complete the segment so that: - the speed in the first second equals *v*1, - the speed in the last second equals *v*2, - the absolute value of difference of speeds between any two adjacent seconds doesn't exceed *d*.
Print the maximum possible length of the path segment in meters.
[ "5 6\n4 2\n", "10 10\n10 0\n" ]
[ "26", "100" ]
In the first sample the sequence of speeds of Polycarpus' car can look as follows: 5, 7, 8, 6. Thus, the total path is 5 + 7 + 8 + 6 = 26 meters. In the second sample, as *d* = 0, the car covers the whole segment at constant speed *v* = 10. In *t* = 10 seconds it covers the distance of 100 meters.
[ { "input": "5 6\n4 2", "output": "26" }, { "input": "10 10\n10 0", "output": "100" }, { "input": "87 87\n2 10", "output": "174" }, { "input": "1 11\n6 2", "output": "36" }, { "input": "100 10\n10 10", "output": "550" }, { "input": "1 1\n100 10", "o...
61
0
0
5,359
627
Factory Repairs
[ "data structures" ]
null
null
A factory produces thimbles in bulk. Typically, it can produce up to *a* thimbles a day. However, some of the machinery is defective, so it can currently only produce *b* thimbles each day. The factory intends to choose a *k*-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of *a* thimbles per day after the *k* days are complete. Initially, no orders are pending. The factory receives updates of the form *d**i*, *a**i*, indicating that *a**i* new orders have been placed for the *d**i*-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes. As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day *p**i*. Help the owner answer his questions.
The first line contains five integers *n*, *k*, *a*, *b*, and *q* (1<=≀<=*k*<=≀<=*n*<=≀<=200<=000, 1<=≀<=*b*<=&lt;<=*a*<=≀<=10 000, 1<=≀<=*q*<=≀<=200<=000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next *q* lines contain the descriptions of the queries. Each query is of one of the following two forms: - 1 *d**i* *a**i* (1<=≀<=*d**i*<=≀<=*n*, 1<=≀<=*a**i*<=≀<=10 000), representing an update of *a**i* orders on day *d**i*, or - 2 *p**i* (1<=≀<=*p**i*<=≀<=*n*<=-<=*k*<=+<=1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day *p**i*? It's guaranteed that the input will contain at least one query of the second type.
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all *n* days.
[ "5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3\n", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2\n" ]
[ "3\n6\n4\n", "7\n1\n" ]
Consider the first sample. We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days. For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled. For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
[ { "input": "5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "output": "3\n6\n4" }, { "input": "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2", "output": "7\n1" }, { "input": "1 1 2 1 1\n2 1", "output": "0" } ]
2,995
8,806,400
0
5,373
1,005
Polycarp and Div 3
[ "dp", "greedy", "number theory" ]
null
null
Polycarp likes numbers that are divisible by 3. He has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $3$. For example, if the original number is $s=3121$, then Polycarp can cut it into three parts with two cuts: $3|1|21$. As a result, he will get two numbers that are divisible by $3$. Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid. What is the maximum number of numbers divisible by $3$ that Polycarp can obtain?
The first line of the input contains a positive integer $s$. The number of digits of the number $s$ is between $1$ and $2\cdot10^5$, inclusive. The first (leftmost) digit is not equal to 0.
Print the maximum number of numbers divisible by $3$ that Polycarp can get by making vertical cuts in the given number $s$.
[ "3121\n", "6\n", "1000000000000000000000000000000000\n", "201920181\n" ]
[ "2\n", "1\n", "33\n", "4\n" ]
In the first example, an example set of optimal cuts on the number is 3|1|21. In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $3$. In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $33$ digits 0. Each of the $33$ digits 0 forms a number that is divisible by $3$. In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $0$, $9$, $201$ and $81$ are divisible by $3$.
[ { "input": "3121", "output": "2" }, { "input": "6", "output": "1" }, { "input": "1000000000000000000000000000000000", "output": "33" }, { "input": "201920181", "output": "4" }, { "input": "4", "output": "0" }, { "input": "10", "output": "1" }, ...
187
7,475,200
0
5,380
653
Bear and Forgotten Tree 2
[ "dfs and similar", "dsu", "graphs", "trees" ]
null
null
A tree is a connected undirected graph consisting of *n* vertices and *n*<=<=-<=<=1 edges. Vertices are numbered 1 through *n*. Limak is a little polar bear. He once had a tree with *n* vertices but he lost it. He still remembers something about the lost tree though. You are given *m* pairs of vertices (*a*1,<=*b*1),<=(*a*2,<=*b*2),<=...,<=(*a**m*,<=*b**m*). Limak remembers that for each *i* there was no edge between *a**i* and *b**i*. He also remembers that vertex 1 was incident to exactly *k* edges (its degree was equal to *k*). Is it possible that Limak remembers everything correctly? Check whether there exists a tree satisfying the given conditions.
The first line of the input contains three integers *n*, *m* and *k* ()Β β€” the number of vertices in Limak's tree, the number of forbidden pairs of vertices, and the degree of vertex 1, respectively. The *i*-th of next *m* lines contains two distinct integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*)Β β€” the *i*-th pair that is forbidden. It's guaranteed that each pair of vertices will appear at most once in the input.
Print "possible" (without quotes) if there exists at least one tree satisfying the given conditions. Otherwise, print "impossible" (without quotes).
[ "5 4 2\n1 2\n2 3\n4 2\n4 1\n", "6 5 3\n1 2\n1 3\n1 4\n1 5\n1 6\n" ]
[ "possible\n", "impossible\n" ]
In the first sample, there are *n* = 5 vertices. The degree of vertex 1 should be *k* = 2. All conditions are satisfied for a tree with edges 1 - 5, 5 - 2, 1 - 3 and 3 - 4. In the second sample, Limak remembers that none of the following edges existed: 1 - 2, 1 - 3, 1 - 4, 1 - 5 and 1 - 6. Hence, vertex 1 couldn't be connected to any other vertex and it implies that there is no suitable tree.
[ { "input": "5 4 2\n1 2\n2 3\n4 2\n4 1", "output": "possible" }, { "input": "6 5 3\n1 2\n1 3\n1 4\n1 5\n1 6", "output": "impossible" }, { "input": "4 3 2\n2 3\n2 4\n3 4", "output": "impossible" }, { "input": "4 2 2\n1 2\n1 3", "output": "impossible" }, { "input": "...
436
20,070,400
0
5,381