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
161
Distance in Tree
[ "dfs and similar", "dp", "trees" ]
null
null
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with *n* vertices and a positive number *k*. Find the number of distinct pairs of the vertices which have a distance of exactly *k* between them. Note that pairs (*v*, *u*) and (*u*, *v*) are considered to be the same pair.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=50000, 1<=≤<=*k*<=≤<=500) — the number of vertices and the required distance between the vertices. Next *n*<=-<=1 lines describe the edges as "*a**i* *b**i*" (without the quotes) (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*), where *a**i* and *b**i* are the vertices connected by the *i*-th edge. All given edges are different.
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly *k* between them. 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 2\n1 2\n2 3\n3 4\n2 5\n", "5 3\n1 2\n2 3\n3 4\n4 5\n" ]
[ "4\n", "2\n" ]
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
[ { "input": "5 2\n1 2\n2 3\n3 4\n2 5", "output": "4" }, { "input": "5 3\n1 2\n2 3\n3 4\n4 5", "output": "2" }, { "input": "10 1\n2 1\n3 1\n4 3\n5 4\n6 5\n7 1\n8 6\n9 2\n10 6", "output": "9" }, { "input": "10 2\n2 1\n3 1\n4 3\n5 4\n6 5\n7 1\n8 6\n9 2\n10 6", "output": "10" ...
60
0
0
9,093
38
Let's Go Rolling!
[ "dp", "sortings" ]
E. Let's Go Rolling!
2
256
On a number axis directed from the left rightwards, *n* marbles with coordinates *x*1,<=*x*2,<=...,<=*x**n* are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number *i* is equal to *c**i*, number *c**i* may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: - the sum of the costs of stuck pins; - the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
The first input line contains an integer *n* (1<=≤<=*n*<=≤<=3000) which is the number of marbles. The next *n* lines contain the descriptions of the marbles in pairs of integers *x**i*, *c**i* (<=-<=109<=≤<=*x**i*,<=*c**i*<=≤<=109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output the single number — the least fine you will have to pay.
[ "3\n2 3\n3 4\n1 2\n", "4\n1 7\n3 1\n5 10\n6 1\n" ]
[ "5\n", "11\n" ]
none
[ { "input": "3\n2 3\n3 4\n1 2", "output": "5" }, { "input": "4\n1 7\n3 1\n5 10\n6 1", "output": "11" }, { "input": "1\n-948943148 10", "output": "10" }, { "input": "5\n864449017 54\n864449026 504\n864449027 308\n864449028 284\n864449030 249", "output": "97" }, { "i...
124
3,481,600
-1
9,099
542
Duck Hunt
[ "data structures" ]
null
null
A duck hunter is doing his favorite thing, hunting. He lives in a two dimensional world and is located at point (0,<=0). As he doesn't like walking for his prey, he prefers to shoot only vertically up (because in this case, the ducks fall straight into his hands). The hunter doesn't reload the gun immediately — *r* or more seconds must pass between the shots. When the hunter shoots up, the bullet immediately hits all the ducks who are directly above the hunter. In a two dimensional world each duck is a horizontal segment that moves horizontally in the negative direction of the *Ox* axis at the speed 1 length unit per second. For each duck we know the values *h**i* and *t**i* — the *x*-coordinates of its head (the left end of the segment) and its tail (the right end of the segment) at time 0. The height where the duck is flying isn't important as the gun shoots vertically up to the infinite height and hits all the ducks on its way. What maximum number of ducks can the hunter shoot? The duck is considered shot by the hunter if at the moment of the shot at least one of its point intersects the *Oy* axis. After the hunter shoots the duck, it falls and it can't be shot anymore. The hunter cannot make shots before the moment of time 0.
The first line of the input contains integers *n*, *r* (1<=≤<=*n*<=≤<=200<=000, 1<=≤<=*r*<=≤<=109) — the number of ducks and the minimum time in seconds between the shots. Then *n* lines follow, each of them contains two integers *h**i*,<=*t**i* (<=-<=109<=≤<=*h**i*<=&lt;<=*t**i*<=≤<=109) — the *x*-coordinate of the head and tail of the *i*-th duck at the moment 0.
Print a single integer — the maximum number of ducks that can be shot by the hunter.
[ "3 3\n-3 0\n1 3\n-1 2\n", "4 5\n-1 1\n2 4\n5 9\n6 8\n" ]
[ "3\n", "3\n" ]
In the first sample the hunter must shoot at time 0, this shot kills ducks 1 and 3. Then the hunter needs to reload the gun and shoot again at time 3. His second shot hits the tail of duck 2. In the second sample the hunter can make shots at times 0 and 6 to hit three ducks.
[]
46
0
0
9,109
0
none
[ "none" ]
null
null
There are *n* types of coins in Byteland. Conveniently, the denomination of the coin type *k* divides the denomination of the coin type *k*<=+<=1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types *k*<=+<=1 and *k* equals *a**k*. It is known that for each *x* there are at most 20 coin types of denomination *x*. Byteasar has *b**k* coins of type *k* with him, and he needs to pay exactly *m* tugricks. It is known that Byteasar never has more than 3·105 coins with him. Byteasar want to know how many ways there are to pay exactly *m* tugricks. Two ways are different if there is an integer *k* such that the amount of coins of type *k* differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo 109<=+<=7.
The first line contains single integer *n* (1<=≤<=*n*<=≤<=3·105) — the number of coin types. The second line contains *n*<=-<=1 integers *a*1, *a*2, ..., *a**n*<=-<=1 (1<=≤<=*a**k*<=≤<=109) — the ratios between the coin types denominations. It is guaranteed that for each *x* there are at most 20 coin types of denomination *x*. The third line contains *n* non-negative integers *b*1, *b*2, ..., *b**n* — the number of coins of each type Byteasar has. It is guaranteed that the sum of these integers doesn't exceed 3·105. The fourth line contains single integer *m* (0<=≤<=*m*<=&lt;<=1010000) — the amount in tugricks Byteasar needs to pay.
Print single integer — the number of ways to pay exactly *m* tugricks modulo 109<=+<=7.
[ "1\n\n4\n2\n", "2\n1\n4 4\n2\n", "3\n3 3\n10 10 10\n17\n" ]
[ "1\n", "3\n", "6\n" ]
In the first example Byteasar has 4 coins of denomination 1, and he has to pay 2 tugricks. There is only one way. In the second example Byteasar has 4 coins of each of two different types of denomination 1, he has to pay 2 tugricks. There are 3 ways: pay one coin of the first type and one coin of the other, pay two coins of the first type, and pay two coins of the second type. In the third example the denominations are equal to 1, 3, 9.
[ { "input": "1\n\n4\n2", "output": "1" }, { "input": "2\n1\n4 4\n2", "output": "3" }, { "input": "3\n3 3\n10 10 10\n17", "output": "6" }, { "input": "2\n2\n200000 100000\n34567", "output": "17284" }, { "input": "20\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2\n1 1 1 1 1 ...
30
0
0
9,113
51
Cheaterius's Problem
[ "implementation" ]
A. Cheaterius's Problem
2
256
Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2<=×<=2 which are the Cheaterius' magic amulets! After a hard night Cheaterius made *n* amulets. Everyone of them represents a square 2<=×<=2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets. Write a program that by the given amulets will find the number of piles on Cheaterius' desk.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=1000), where *n* is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.
Print the required number of piles.
[ "4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13\n", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53\n" ]
[ "1\n", "2\n" ]
none
[ { "input": "4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "output": "1" }, { "input": "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53", "output": "2" }, { "input": "4\n56\n61\n**\n31\n31\n**\n33\n11\n**\n11\n33", "output": "2" }, { "input": "4\n36\n44\n**\n32\n46\n**\n66\n41...
342
20,275,200
3.876734
9,120
4
Before an Exam
[ "constructive algorithms", "greedy" ]
B. Before an Exam
0
64
Tomorrow Peter has a Biology exam. He does not like this subject much, but *d* days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than *minTime**i* and not more than *maxTime**i* hours per each *i*-th day. Moreover, they warned Peter that a day before the exam they would check how he has followed their instructions. So, today is the day when Peter's parents ask him to show the timetable of his preparatory studies. But the boy has counted only the sum of hours *sumTime* spent him on preparation, and now he wants to know if he can show his parents a timetable *sсhedule* with *d* numbers, where each number *sсhedule**i* stands for the time in hours spent by Peter each *i*-th day on biology studies, and satisfying the limitations imposed by his parents, and at the same time the sum total of all *schedule**i* should equal to *sumTime*.
The first input line contains two integer numbers *d*,<=*sumTime* (1<=≤<=*d*<=≤<=30,<=0<=≤<=*sumTime*<=≤<=240) — the amount of days, during which Peter studied, and the total amount of hours, spent on preparation. Each of the following *d* lines contains two integer numbers *minTime**i*,<=*maxTime**i* (0<=≤<=*minTime**i*<=≤<=*maxTime**i*<=≤<=8), separated by a space — minimum and maximum amount of hours that Peter could spent in the *i*-th day.
In the first line print YES, and in the second line print *d* numbers (separated by a space), each of the numbers — amount of hours, spent by Peter on preparation in the corresponding day, if he followed his parents' instructions; or print NO in the unique line. If there are many solutions, print any of them.
[ "1 48\n5 7\n", "2 5\n0 1\n3 5\n" ]
[ "NO\n", "YES\n1 4 " ]
none
[ { "input": "1 48\n5 7", "output": "NO" }, { "input": "2 5\n0 1\n3 5", "output": "YES\n1 4 " }, { "input": "1 1\n5 6", "output": "NO" }, { "input": "1 4\n2 4", "output": "YES\n4 " }, { "input": "2 5\n4 6\n0 0", "output": "YES\n5 0 " }, { "input": "27 97...
31
0
3
9,123
219
Choosing Capital for Treeland
[ "dfs and similar", "dp", "graphs", "trees" ]
null
null
The country Treeland consists of *n* cities, some pairs of them are connected with unidirectional roads. Overall there are *n*<=-<=1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one. The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city *a* is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city *a* to any other city. For that some roads may have to be inversed. Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
The first input line contains integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of cities in Treeland. Next *n*<=-<=1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers *s**i*,<=*t**i* (1<=≤<=*s**i*,<=*t**i*<=≤<=*n*; *s**i*<=≠<=*t**i*) — the numbers of cities, connected by that road. The *i*-th road is oriented from city *s**i* to city *t**i*. You can consider cities in Treeland indexed from 1 to *n*.
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
[ "3\n2 1\n2 3\n", "4\n1 4\n2 4\n3 4\n" ]
[ "0\n2 \n", "2\n1 2 3 \n" ]
none
[ { "input": "3\n2 1\n2 3", "output": "0\n2 " }, { "input": "4\n1 4\n2 4\n3 4", "output": "2\n1 2 3 " }, { "input": "2\n1 2", "output": "0\n1 " }, { "input": "8\n1 2\n3 2\n4 3\n4 5\n6 5\n6 7\n8 7", "output": "3\n4 6 8 " }, { "input": "10\n2 3\n1 8\n9 5\n5 4\n6 10\n4...
654
62,464,000
-1
9,152
449
Jzzhu and Squares
[ "dp", "math", "number theory" ]
null
null
Jzzhu has two integers, *n* and *m*. He calls an integer point (*x*,<=*y*) of a plane special if 0<=≤<=*x*<=≤<=*n* and 0<=≤<=*y*<=≤<=*m*. Jzzhu defines a unit square as a square with corners at points (*x*,<=*y*), (*x*<=+<=1,<=*y*), (*x*<=+<=1,<=*y*<=+<=1), (*x*,<=*y*<=+<=1), where *x* and *y* are some integers. Let's look at all the squares (their sides not necessarily parallel to the coordinate axes) with corners at the special points. For each such square Jzzhu paints a dot in every unit square that is fully inside it. After that some unit squares can contain several dots. Now Jzzhu wonders, how many dots he has painted on the plane. Find this number modulo 1000000007 (109<=+<=7).
The first line contains a single integer *t* (1<=≤<=*t*<=≤<=105) — the number of tests. Each of the next *t* lines contains the description of the test: two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=106) — the value of variables for the current test.
For each test output the total number of dots modulo 1000000007 (109<=+<=7).
[ "4\n1 3\n2 2\n2 5\n3 4\n" ]
[ "3\n8\n26\n58\n" ]
none
[]
30
0
0
9,159
822
My pretty girl Noora
[ "brute force", "dp", "greedy", "math", "number theory" ]
null
null
In Pavlopolis University where Noora studies it was decided to hold beauty contest "Miss Pavlopolis University". Let's describe the process of choosing the most beautiful girl in the university in more detail. The contest is held in several stages. Suppose that exactly *n* girls participate in the competition initially. All the participants are divided into equal groups, *x* participants in each group. Furthermore the number *x* is chosen arbitrarily, i. e. on every stage number *x* can be different. Within each group the jury of the contest compares beauty of the girls in the format "each with each". In this way, if group consists of *x* girls, then comparisons occur. Then, from each group, the most beautiful participant is selected. Selected girls enter the next stage of the competition. Thus if *n* girls were divided into groups, *x* participants in each group, then exactly participants will enter the next stage. The contest continues until there is exactly one girl left who will be "Miss Pavlopolis University" But for the jury this contest is a very tedious task. They would like to divide the girls into groups in each stage so that the total number of pairwise comparisons of the girls is as few as possible. Let *f*(*n*) be the minimal total number of comparisons that should be made to select the most beautiful participant, if we admit *n* girls to the first stage. The organizers of the competition are insane. They give Noora three integers *t*, *l* and *r* and ask the poor girl to calculate the value of the following expression: *t*0·*f*(*l*)<=+<=*t*1·*f*(*l*<=+<=1)<=+<=...<=+<=*t**r*<=-<=*l*·*f*(*r*). However, since the value of this expression can be quite large the organizers ask her to calculate it modulo 109<=+<=7. If Noora can calculate the value of this expression the organizers promise her to help during the beauty contest. But the poor girl is not strong in mathematics, so she turned for help to Leha and he turned to you.
The first and single line contains three integers *t*, *l* and *r* (1<=≤<=*t*<=&lt;<=109<=+<=7,<=2<=≤<=*l*<=≤<=*r*<=≤<=5·106).
In the first line print single integer — the value of the expression modulo 109<=+<=7.
[ "2 2 4\n" ]
[ "19\n" ]
Consider the sample. It is necessary to find the value of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3ecc798906ae9e9852061ba2dd5cf6b8fce7753b.png" style="max-width: 100.0%;max-height: 100.0%;"/>. *f*(2) = 1. From two girls you can form only one group of two people, in which there will be one comparison. *f*(3) = 3. From three girls you can form only one group of three people, in which there will be three comparisons. *f*(4) = 3. From four girls you can form two groups of two girls each. Then at the first stage there will be two comparisons, one in each of the two groups. In the second stage there will be two girls and there will be one comparison between them. Total 2 + 1 = 3 comparisons. You can also leave all girls in same group in the first stage. Then <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fcc6c9e72a1525cc01abbfb89094669a9d37d3b1.png" style="max-width: 100.0%;max-height: 100.0%;"/> comparisons will occur. Obviously, it's better to split girls into groups in the first way. Then the value of the expression is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2c5a0f75c9d910ec77b2fe675e690de453060631.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "2 2 4", "output": "19" }, { "input": "7 2444902 2613424", "output": "619309304" }, { "input": "7 2055976 2242066", "output": "231875164" }, { "input": "5 431999 611310", "output": "160643716" }, { "input": "9 1621304 1742530", "output": "797579313"...
30
0
0
9,172
754
Fedor and coupons
[ "binary search", "data structures", "greedy", "sortings" ]
null
null
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has *n* discount coupons, the *i*-th of them can be used with products with ids ranging from *l**i* to *r**i*, inclusive. Today Fedor wants to take exactly *k* coupons with him. Fedor wants to choose the *k* coupons in such a way that the number of such products *x* that all coupons can be used with this product *x* is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=3·105) — the number of coupons Fedor has, and the number of coupons he wants to choose. Each of the next *n* lines contains two integers *l**i* and *r**i* (<=-<=109<=≤<=*l**i*<=≤<=*r**i*<=≤<=109) — the description of the *i*-th coupon. The coupons can be equal.
In the first line print single integer — the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted. In the second line print *k* distinct integers *p*1,<=*p*2,<=...,<=*p**k* (1<=≤<=*p**i*<=≤<=*n*) — the ids of the coupons which Fedor should choose. If there are multiple answers, print any of them.
[ "4 2\n1 100\n40 70\n120 130\n125 180\n", "3 2\n1 12\n15 20\n25 30\n", "5 2\n1 10\n5 15\n14 50\n30 70\n99 100\n" ]
[ "31\n1 2 \n", "0\n1 2 \n", "21\n3 4 \n" ]
In the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total. In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
[ { "input": "4 2\n1 100\n40 70\n120 130\n125 180", "output": "31\n1 2 " }, { "input": "3 2\n1 12\n15 20\n25 30", "output": "0\n1 2 " }, { "input": "5 2\n1 10\n5 15\n14 50\n30 70\n99 100", "output": "21\n3 4 " }, { "input": "7 6\n-8 6\n7 9\n-10 -5\n-6 10\n-7 -3\n5 8\n4 10", ...
31
0
-1
9,189
652
Nested Segments
[ "data structures", "sortings" ]
null
null
You are given *n* segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of segments on a line. Each of the next *n* lines contains two integers *l**i* and *r**i* (<=-<=109<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=109) — the coordinates of the left and the right ends of the *i*-th segment. It is guaranteed that there are no ends of some segments that coincide.
Print *n* lines. The *j*-th of them should contain the only integer *a**j* — the number of segments contained in the *j*-th segment.
[ "4\n1 8\n2 3\n4 7\n5 6\n", "3\n3 4\n1 5\n2 6\n" ]
[ "3\n0\n1\n0\n", "0\n1\n1\n" ]
none
[ { "input": "4\n1 8\n2 3\n4 7\n5 6", "output": "3\n0\n1\n0" }, { "input": "3\n3 4\n1 5\n2 6", "output": "0\n1\n1" }, { "input": "1\n-1000000000 1000000000", "output": "0" }, { "input": "2\n-1000000000 999999999\n-999999999 1000000000", "output": "0\n0" }, { "input"...
1,762
50,688,000
3
9,214
922
Robot Vacuum Cleaner
[ "greedy", "sortings" ]
null
null
Pushok the dog has been chasing Imp for a few hours already. Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string *t* consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string *t* as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (*i*,<=*j*), that *i*<=&lt;<=*j* and and . The robot is off at the moment. Imp knows that it has a sequence of strings *t**i* in its memory, and he can arbitrary change their order. When the robot is started, it generates the string *t* as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation. Help Imp to find the maximum noise he can achieve by changing the order of the strings.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of strings in robot's memory. Next *n* lines contain the strings *t*1,<=*t*2,<=...,<=*t**n*, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
[ "4\nssh\nhs\ns\nhhhs\n", "2\nh\ns\n" ]
[ "18\n", "1\n" ]
The optimal concatenation in the first sample is *ssshhshhhs*.
[ { "input": "4\nssh\nhs\ns\nhhhs", "output": "18" }, { "input": "2\nh\ns", "output": "1" }, { "input": "6\nh\ns\nhhh\nh\nssssss\ns", "output": "40" }, { "input": "1\ns", "output": "0" }, { "input": "10\nsshshss\nhssssssssh\nhhhhhh\nhhhs\nhshhh\nhhhhshsh\nhh\nh\nshs...
31
0
0
9,220
620
Pearls in a Row
[ "greedy" ]
null
null
There are *n* pearls in a row. Let's enumerate them with integers from 1 to *n* from the left to the right. The pearl number *i* has the type *a**i*. Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type. Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105) — the number of pearls in a row. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) – the type of the *i*-th pearl.
On the first line print integer *k* — the maximal number of segments in a partition of the row. Each of the next *k* lines should contain two integers *l**j*,<=*r**j* (1<=≤<=*l**j*<=≤<=*r**j*<=≤<=*n*) — the number of the leftmost and the rightmost pearls in the *j*-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".
[ "5\n1 2 3 4 1\n", "5\n1 2 3 4 5\n", "7\n1 2 1 3 1 2 1\n" ]
[ "1\n1 5\n", "-1\n", "2\n1 3\n4 7\n" ]
none
[ { "input": "5\n1 2 3 4 1", "output": "1\n1 5" }, { "input": "5\n1 2 3 4 5", "output": "-1" }, { "input": "7\n1 2 1 3 1 2 1", "output": "2\n1 3\n4 7" }, { "input": "9\n1 2 1 2 1 2 1 2 1", "output": "3\n1 3\n4 6\n7 9" }, { "input": "11\n1 1 2 1 2 1 2 1 2 1 1", "...
249
268,390,400
0
9,406
549
The Game Of Parity
[ "games" ]
null
null
There are *n* cities in Westeros. The *i*-th city is inhabited by *a**i* people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly *k* cities left. The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way. Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.
The first line contains two positive space-separated integers, *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2·105) — the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains *n* space-separated positive integers *a**i* (1<=≤<=*a**i*<=≤<=106), which represent the population of each city in Westeros.
Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.
[ "3 1\n1 2 1\n", "3 1\n2 2 1\n", "6 3\n5 20 12 7 14 101\n" ]
[ "Stannis\n", "Daenerys\n", "Stannis\n" ]
In the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins. In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.
[ { "input": "3 1\n1 2 1", "output": "Stannis" }, { "input": "3 1\n2 2 1", "output": "Daenerys" }, { "input": "6 3\n5 20 12 7 14 101", "output": "Stannis" }, { "input": "6 3\n346 118 330 1403 5244 480", "output": "Daenerys" }, { "input": "7 4\n11 3532 99 3512 12 8 2...
280
17,203,200
0
9,415
0
none
[ "none" ]
null
null
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most *k* bills from it, and the bills may be of at most two distinct denominations. For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at *k*<==<=20 such ATM can give sums 100<=000 burles and 96<=000 burles, but it cannot give sums 99<=000 and 101<=000 burles. Let's suppose that the country uses bills of *n* distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash *q* times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the *q* of requests for cash withdrawal.
The first line contains two integers *n*, *k* (1<=≤<=*n*<=≤<=5000, 1<=≤<=*k*<=≤<=20). The next line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=107) — the denominations of the bills that are used in the country. Numbers *a**i* follow in the strictly increasing order. The next line contains integer *q* (1<=≤<=*q*<=≤<=20) — the number of requests for cash withdrawal that you will make. The next *q* lines contain numbers *x**i* (1<=≤<=*x**i*<=≤<=2·108) — the sums of money in burles that you are going to withdraw from the ATM.
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print <=-<=1, if it is impossible to get the corresponding sum.
[ "6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950\n", "5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15\n" ]
[ "6\n20\n19\n20\n-1\n3\n-1\n-1\n", "1\n1\n1\n2\n2\n2\n2\n-1\n" ]
none
[ { "input": "6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950", "output": "6\n20\n19\n20\n-1\n3\n-1\n-1" }, { "input": "5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15", "output": "1\n1\n1\n2\n2\n2\n2\n-1" }, { "input": "5 5\n1 2 3 6 102\n10\n1\n4\n30\n1...
498
6,656,000
3
9,420
30
Shooting Gallery
[ "dp", "probabilities" ]
C. Shooting Gallery
2
256
One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him. The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates *x**i*, and *y**i*, by the time of it's appearance *t**i* and by the number *p**i*, which gives the probability that Copa hits this target if he aims at it. A target appears and disappears instantly, so Copa can hit the target only if at the moment *t**i* his gun sight aimed at (*x**i*,<=*y**i*). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0.
The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — amount of targets in the shooting gallery. Then *n* lines follow, each describing one target. Each description consists of four numbers *x**i*, *y**i*, *t**i*, *p**i* (where *x**i*, *y**i*, *t**i* — integers, <=-<=1000<=≤<=*x**i*,<=*y**i*<=≤<=1000,<=0<=≤<=*t**i*<=≤<=109, real number *p**i* is given with no more than 6 digits after the decimal point, 0<=≤<=*p**i*<=≤<=1). No two targets may be at the same point.
Output the maximum expected value of the amount of targets that was shot by the king. Your answer will be accepted if it differs from the correct answer by not more than 10<=-<=6.
[ "1\n0 0 0 0.5\n", "2\n0 0 0 0.6\n5 0 5 0.7\n" ]
[ "0.5000000000\n", "1.3000000000\n" ]
none
[ { "input": "1\n0 0 0 0.5", "output": "0.5000000000" }, { "input": "2\n0 0 0 0.6\n5 0 5 0.7", "output": "1.3000000000" }, { "input": "1\n-5 2 3 0.886986", "output": "0.8869860000" }, { "input": "4\n10 -7 14 0.926305\n-7 -8 12 0.121809\n-7 7 14 0.413446\n3 -8 6 0.859061", "...
218
2,252,800
3.941304
9,431
859
Desk Disorder
[ "combinatorics", "dfs and similar", "dsu", "graphs", "trees" ]
null
null
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement. How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007<==<=109<=+<=7.
Input will begin with a line containing *N* (1<=≤<=*N*<=≤<=100000), the number of engineers. *N* lines follow, each containing exactly two integers. The *i*-th line contains the number of the current desk of the *i*-th engineer and the number of the desk the *i*-th engineer wants to move to. Desks are numbered from 1 to 2·*N*. It is guaranteed that no two engineers sit at the same desk.
Print the number of possible assignments, modulo 1000000007<==<=109<=+<=7.
[ "4\n1 5\n5 2\n3 7\n7 3\n", "5\n1 10\n2 10\n3 10\n4 10\n5 5\n" ]
[ "6\n", "5\n" ]
These are the possible assignments for the first example: - 1 5 3 7 - 1 2 3 7 - 5 2 3 7 - 1 5 7 3 - 1 2 7 3 - 5 2 7 3
[ { "input": "4\n1 5\n5 2\n3 7\n7 3", "output": "6" }, { "input": "5\n1 10\n2 10\n3 10\n4 10\n5 5", "output": "5" }, { "input": "1\n1 2", "output": "2" }, { "input": "30\n22 37\n12 37\n37 58\n29 57\n43 57\n57 58\n58 53\n45 4\n1 4\n4 51\n35 31\n21 31\n31 51\n51 53\n53 48\n60 55\...
764
13,209,600
0
9,434
414
Mashmokh and Reverse Operation
[ "combinatorics", "divide and conquer" ]
null
null
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following. You have an array *a* of length 2*n* and *m* queries on it. The *i*-th query is described by an integer *q**i*. In order to perform the *i*-th query you must: - split the array into 2*n*<=-<=*q**i* parts, where each part is a subarray consisting of 2*q**i* numbers; the *j*-th subarray (1<=≤<=*j*<=≤<=2*n*<=-<=*q**i*) should contain the elements *a*[(*j*<=-<=1)·2*q**i*<=+<=1],<=*a*[(*j*<=-<=1)·2*q**i*<=+<=2],<=...,<=*a*[(*j*<=-<=1)·2*q**i*<=+<=2*q**i*]; - reverse each of the subarrays; - join them into a single array in the same order (this array becomes new array *a*); - output the number of inversions in the new *a*. Given initial array *a* and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
The first line of input contains a single integer *n* (0<=≤<=*n*<=≤<=20). The second line of input contains 2*n* space-separated integers *a*[1],<=*a*[2],<=...,<=*a*[2*n*] (1<=≤<=*a*[*i*]<=≤<=109), the initial array. The third line of input contains a single integer *m* (1<=≤<=*m*<=≤<=106). The fourth line of input contains *m* space-separated integers *q*1,<=*q*2,<=...,<=*q**m* (0<=≤<=*q**i*<=≤<=*n*), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output *m* lines. In the *i*-th line print the answer (the number of inversions) for the *i*-th query.
[ "2\n2 1 4 3\n4\n1 2 0 2\n", "1\n1 2\n3\n0 1 1\n" ]
[ "0\n6\n6\n0\n", "0\n1\n0\n" ]
If we reverse an array *x*[1], *x*[2], ..., *x*[*n*] it becomes new array *y*[1], *y*[2], ..., *y*[*n*], where *y*[*i*] = *x*[*n* - *i* + 1] for each *i*. The number of inversions of an array *x*[1], *x*[2], ..., *x*[*n*] is the number of pairs of indices *i*, *j* such that: *i* &lt; *j* and *x*[*i*] &gt; *x*[*j*].
[]
93
20,172,800
0
9,443
79
Bus Game
[ "greedy" ]
A. Bus Game
2
256
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus. - Initially, there is a pile that contains *x* 100-yen coins and *y* 10-yen coins. - They take turns alternatively. Ciel takes the first turn. - In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins. - If Ciel or Hanako can't take exactly 220 yen from the pile, she loses. Determine the winner of the game.
The first line contains two integers *x* (0<=≤<=*x*<=≤<=106) and *y* (0<=≤<=*y*<=≤<=106), separated by a single space.
If Ciel wins, print "Ciel". Otherwise, print "Hanako".
[ "2 2\n", "3 22\n" ]
[ "Ciel\n", "Hanako\n" ]
In the first turn (Ciel's turn), she will choose 2 100-yen coins and 2 10-yen coins. In the second turn (Hanako's turn), she will choose 1 100-yen coin and 12 10-yen coins. In the third turn (Ciel's turn), she can't pay exactly 220 yen, so Ciel will lose.
[ { "input": "2 2", "output": "Ciel" }, { "input": "3 22", "output": "Hanako" }, { "input": "0 22", "output": "Ciel" }, { "input": "1000 1000", "output": "Ciel" }, { "input": "0 0", "output": "Hanako" }, { "input": "0 21", "output": "Hanako" }, {...
186
307,200
0
9,448
7
Line
[ "math", "number theory" ]
C. Line
1
256
A line on the plane is described by an equation *Ax*<=+<=*By*<=+<=*C*<==<=0. You are to find any point on this line, whose coordinates are integer numbers from <=-<=5·1018 to 5·1018 inclusive, or to find out that such points do not exist.
The first line contains three integers *A*, *B* and *C* (<=-<=2·109<=≤<=*A*,<=*B*,<=*C*<=≤<=2·109) — corresponding coefficients of the line equation. It is guaranteed that *A*2<=+<=*B*2<=&gt;<=0.
If the required point exists, output its coordinates, otherwise output -1.
[ "2 5 3\n" ]
[ "6 -3\n" ]
none
[ { "input": "2 5 3", "output": "6 -3" }, { "input": "0 2 3", "output": "-1" }, { "input": "931480234 -1767614767 -320146190", "output": "-98880374013340920 -52107006370101410" }, { "input": "-1548994394 -1586527767 -1203252104", "output": "-878123061596147680 8573488141506...
186
0
0
9,449
600
Lomsat gelral
[ "data structures", "dfs and similar", "dsu", "trees" ]
null
null
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour. Let's call colour *c* dominating in the subtree of vertex *v* if there are no other colours that appear in the subtree of vertex *v* more times than colour *c*. So it's possible that two or more colours will be dominating in the subtree of some vertex. The subtree of vertex *v* is the vertex *v* and all other vertices that contains vertex *v* in each path to the root. For each vertex *v* find the sum of all dominating colours in the subtree of vertex *v*.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of vertices in the tree. The second line contains *n* integers *c**i* (1<=≤<=*c**i*<=≤<=*n*), *c**i* — the colour of the *i*-th vertex. Each of the next *n*<=-<=1 lines contains two integers *x**j*,<=*y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*) — the edge of the tree. The first vertex is the root of the tree.
Print *n* integers — the sums of dominating colours for each vertex.
[ "4\n1 2 3 4\n1 2\n2 3\n2 4\n", "15\n1 2 3 1 2 3 3 1 1 3 2 2 1 2 3\n1 2\n1 3\n1 4\n1 14\n1 15\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13\n" ]
[ "10 9 3 4\n", "6 5 4 3 2 3 3 1 1 3 2 2 1 2 3\n" ]
none
[ { "input": "4\n1 2 3 4\n1 2\n2 3\n2 4", "output": "10 9 3 4" }, { "input": "15\n1 2 3 1 2 3 3 1 1 3 2 2 1 2 3\n1 2\n1 3\n1 4\n1 14\n1 15\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13", "output": "6 5 4 3 2 3 3 1 1 3 2 2 1 2 3" } ]
2,000
2,662,400
0
9,471
0
none
[ "none" ]
null
null
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer — as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored. Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal). The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. In the given coordinate system you are given: - *y*1, *y*2 — the *y*-coordinates of the side pillars of the goalposts of robo-Wallace's opponents; - *y**w* — the *y*-coordinate of the wall to which Robo-Wallace is aiming; - *x**b*, *y**b* — the coordinates of the ball's position when it is hit; - *r* — the radius of the ball. A goal is scored when the center of the ball crosses the *OY* axis in the given coordinate system between (0, *y*1) and (0, *y*2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius *r*.
The first and the single line contains integers *y*1, *y*2, *y**w*, *x**b*, *y**b*, *r* (1<=≤<=*y*1,<=*y*2,<=*y**w*,<=*x**b*,<=*y**b*<=≤<=106; *y*1<=&lt;<=*y*2<=&lt;<=*y**w*; *y**b*<=+<=*r*<=&lt;<=*y**w*; 2·*r*<=&lt;<=*y*2<=-<=*y*1). It is guaranteed that the ball is positioned correctly in the field, doesn't cross any wall, doesn't touch the wall that Robo-Wallace is aiming at. The goal posts can't be located in the field corners.
If Robo-Wallace can't score a goal in the described manner, print "-1" (without the quotes). Otherwise, print a single number *x**w* — the abscissa of his point of aiming. If there are multiple points of aiming, print the abscissa of any of them. When checking the correctness of the answer, all comparisons are made with the permissible absolute error, equal to 10<=-<=8. It is recommended to print as many characters after the decimal point as possible.
[ "4 10 13 10 3 1\n", "1 4 6 2 2 1\n", "3 10 15 17 9 2\n" ]
[ "4.3750000000\n", "-1\n", "11.3333333333\n" ]
Note that in the first and third samples other correct values of abscissa *x*<sub class="lower-index">*w*</sub> are also possible.
[ { "input": "4 10 13 10 3 1", "output": "4.3750000000" }, { "input": "1 4 6 2 2 1", "output": "-1" }, { "input": "3 10 15 17 9 2", "output": "11.3333333333" }, { "input": "4 9 30 3 3 1", "output": "-1" }, { "input": "4 9 13 2 3 1", "output": "-1" }, { "...
92
0
0
9,481
0
none
[ "none" ]
null
null
You are given an integer *m*, and a list of *n* distinct integers between 0 and *m*<=-<=1. You would like to construct a sequence satisfying the properties: - Each element is an integer between 0 and *m*<=-<=1, inclusive. - All prefix products of the sequence modulo *m* are distinct. - No prefix product modulo *m* appears as an element of the input list. - The length of the sequence is maximized. Construct any sequence satisfying the properties above.
The first line of input contains two integers *n* and *m* (0<=≤<=*n*<=&lt;<=*m*<=≤<=200<=000) — the number of forbidden prefix products and the modulus. If *n* is non-zero, the next line of input contains *n* distinct integers between 0 and *m*<=-<=1, the forbidden prefix products. If *n* is zero, this line doesn't exist.
On the first line, print the number *k*, denoting the length of your sequence. On the second line, print *k* space separated integers, denoting your sequence.
[ "0 5\n", "3 10\n2 9 1\n" ]
[ "5\n1 2 4 3 0\n", "6\n3 9 2 9 8 0\n" ]
For the first case, the prefix products of this sequence modulo *m* are [1, 2, 3, 4, 0]. For the second case, the prefix products of this sequence modulo *m* are [3, 7, 4, 6, 8, 0].
[ { "input": "0 5", "output": "5\n1 2 4 3 0" }, { "input": "3 10\n2 9 1", "output": "6\n3 9 2 9 8 0" }, { "input": "0 1", "output": "1\n0" }, { "input": "0 720", "output": "397\n1 7 413 263 389 467 77 283 299 187 293 563 269 47 677 463 599 367 173 143 149 347 557 643 179 54...
30
102,400
0
9,495
232
Table
[ "bitmasks", "combinatorics", "dp", "math" ]
null
null
John Doe has an *n*<=×<=*m* table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size *n*<=×<=*n* have exactly *k* points. John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by 1000000007 (109<=+<=7). You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.
A single line contains space-separated integers *n*, *m*, *k* (1<=≤<=*n*<=≤<=100; *n*<=≤<=*m*<=≤<=1018; 0<=≤<=*k*<=≤<=*n*2) — the number of rows of the table, the number of columns of the table and the number of points each square must contain. 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.
In a single line print a single integer — the remainder from dividing the described number of ways by 1000000007 (109<=+<=7).
[ "5 6 1\n" ]
[ "45" ]
Let's consider the first test case:
[ { "input": "5 6 1", "output": "45" }, { "input": "1 1000000000000000000 0", "output": "1" }, { "input": "100 1000000 5000", "output": "13662512" }, { "input": "100 1000000000000000000 10000", "output": "1" }, { "input": "2 1791938441 1", "output": "216278738" ...
30
0
0
9,542
1,005
Summarize to the Power of Two
[ "brute force", "greedy", "implementation" ]
null
null
A sequence $a_1, a_2, \dots, a_n$ is called good if, for each element $a_i$, there exists an element $a_j$ ($i \ne j$) such that $a_i+a_j$ is a power of two (that is, $2^d$ for some non-negative integer $d$). For example, the following sequences are good: - $[5, 3, 11]$ (for example, for $a_1=5$ we can choose $a_2=3$. Note that their sum is a power of two. Similarly, such an element can be found for $a_2$ and $a_3$), - $[1, 1, 1, 1023]$, - $[7, 39, 89, 25, 89]$, - $[]$. Note that, by definition, an empty sequence (with a length of $0$) is good. For example, the following sequences are not good: - $[16]$ (for $a_1=16$, it is impossible to find another element $a_j$ such that their sum is a power of two), - $[4, 16]$ (for $a_1=4$, it is impossible to find another element $a_j$ such that their sum is a power of two), - $[1, 3, 2, 8, 8, 8]$ (for $a_3=2$, it is impossible to find another element $a_j$ such that their sum is a power of two). You are given a sequence $a_1, a_2, \dots, a_n$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.
The first line contains the integer $n$ ($1 \le n \le 120000$) — the length of the given sequence. The second line contains the sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $n$ elements, make it empty, and thus get a good sequence.
[ "6\n4 7 1 5 4 9\n", "5\n1 2 3 4 5\n", "1\n16\n", "4\n1 1 1 1023\n" ]
[ "1\n", "2\n", "1\n", "0\n" ]
In the first example, it is enough to delete one element $a_4=5$. The remaining elements form the sequence $[4, 7, 1, 4, 9]$, which is good.
[ { "input": "6\n4 7 1 5 4 9", "output": "1" }, { "input": "5\n1 2 3 4 5", "output": "2" }, { "input": "1\n16", "output": "1" }, { "input": "4\n1 1 1 1023", "output": "0" }, { "input": "10\n2 10 9 1 10 4 7 8 5 4", "output": "5" }, { "input": "2\n1 1", ...
249
28,262,400
3
9,582
906
Power Tower
[ "chinese remainder theorem", "math", "number theory" ]
null
null
Priests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from *k*<=-<=1 rocks, possesses power *p* and we want to add the rock charged with power *w**k* then value of power of a new tower will be {*w**k*}*p*. Rocks are added from the last to the first. That is for sequence *w*1,<=...,<=*w**m* value of power will be After tower is built, its power may be extremely large. But still priests want to get some information about it, namely they want to know a number called cumulative power which is the true value of power taken modulo *m*. Priests have *n* rocks numbered from 1 to *n*. They ask you to calculate which value of cumulative power will the tower possess if they will build it from rocks numbered *l*,<=*l*<=+<=1,<=...,<=*r*.
First line of input contains two integers *n* (1<=≤<=*n*<=≤<=105) and *m* (1<=≤<=*m*<=≤<=109). Second line of input contains *n* integers *w**k* (1<=≤<=*w**k*<=≤<=109) which is the power of rocks that priests have. Third line of input contains single integer *q* (1<=≤<=*q*<=≤<=105) which is amount of queries from priests to you. *k**th* of next *q* lines contains two integers *l**k* and *r**k* (1<=≤<=*l**k*<=≤<=*r**k*<=≤<=*n*).
Output *q* integers. *k*-th of them must be the amount of cumulative power the tower will have if is built from rocks *l**k*,<=*l**k*<=+<=1,<=...,<=*r**k*.
[ "6 1000000000\n1 2 2 3 3 3\n8\n1 1\n1 6\n2 2\n2 3\n2 4\n4 4\n4 5\n4 6\n" ]
[ "1\n1\n2\n4\n256\n3\n27\n597484987\n" ]
3<sup class="upper-index">27</sup> = 7625597484987
[ { "input": "6 1000000000\n1 2 2 3 3 3\n8\n1 1\n1 6\n2 2\n2 3\n2 4\n4 4\n4 5\n4 6", "output": "1\n1\n2\n4\n256\n3\n27\n597484987" }, { "input": "10 20\n792708224 4633945 600798790 384332600 283309209 762285205 750900274 160512987 390669628 205259431\n10\n5 9\n10 10\n8 10\n7 10\n7 10\n10 10\n4 4\n10 1...
31
0
0
9,584
546
Soldier and Number Game
[ "constructive algorithms", "dp", "math", "number theory" ]
null
null
Two soldiers are playing a game. At the beginning first of them chooses a positive integer *n* and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer *x*<=&gt;<=1, such that *n* is divisible by *x* and replacing *n* with *n*<=/<=*x*. When *n* becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed. To make the game more interesting, first soldier chooses *n* of form *a*!<=/<=*b*! for some positive integer *a* and *b* (*a*<=≥<=*b*). Here by *k*! we denote the factorial of *k* that is defined as a product of all positive integers not large than *k*. What is the maximum possible score of the second soldier?
First line of input consists of single integer *t* (1<=≤<=*t*<=≤<=1<=000<=000) denoting number of games soldiers play. Then follow *t* lines, each contains pair of integers *a* and *b* (1<=≤<=*b*<=≤<=*a*<=≤<=5<=000<=000) defining the value of *n* for a game.
For each game output a maximum score that the second soldier can get.
[ "2\n3 1\n6 3\n" ]
[ "2\n5\n" ]
none
[ { "input": "2\n3 1\n6 3", "output": "2\n5" }, { "input": "8\n7 1\n263 262\n1000003 1000002\n5000000 4999995\n2 1\n7 4\n12345 12345\n10 1", "output": "8\n1\n1\n23\n1\n4\n0\n15" }, { "input": "3\n1 1\n5000000 1\n5000000 5000000", "output": "0\n18703742\n0" } ]
1,560
202,854,400
-1
9,629
847
Packmen
[ "binary search", "dp" ]
null
null
A game field is a strip of 1<=×<=*n* square cells. In some cells there are Packmen, in some cells — asterisks, other cells are empty. Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk. In the initial moment of time all Packmen begin to move. Each Packman can change direction of its move unlimited number of times, but it is not allowed to go beyond the boundaries of the game field. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions. Your task is to determine minimum possible time after which Packmen can eat all the asterisks.
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=105) — the length of the game field. The second line contains the description of the game field consisting of *n* symbols. If there is symbol '.' in position *i* — the cell *i* is empty. If there is symbol '*' in position *i* — in the cell *i* contains an asterisk. If there is symbol 'P' in position *i* — Packman is in the cell *i*. It is guaranteed that on the game field there is at least one Packman and at least one asterisk.
Print minimum possible time after which Packmen can eat all asterisks.
[ "7\n*..P*P*\n", "10\n.**PP.*P.*\n" ]
[ "3\n", "2\n" ]
In the first example Packman in position 4 will move to the left and will eat asterisk in position 1. He will spend 3 time units on it. During the same 3 time units Packman in position 6 will eat both of neighboring with it asterisks. For example, it can move to the left and eat asterisk in position 5 (in 1 time unit) and then move from the position 5 to the right and eat asterisk in the position 7 (in 2 time units). So in 3 time units Packmen will eat all asterisks on the game field. In the second example Packman in the position 4 will move to the left and after 2 time units will eat asterisks in positions 3 and 2. Packmen in positions 5 and 8 will move to the right and in 2 time units will eat asterisks in positions 7 and 10, respectively. So 2 time units is enough for Packmen to eat all asterisks on the game field.
[ { "input": "7\n*..P*P*", "output": "3" }, { "input": "10\n.**PP.*P.*", "output": "2" }, { "input": "19\n**P.*..*..P..*.*P**", "output": "7" }, { "input": "12\nP**.*P*P*P**", "output": "3" }, { "input": "58\n..P.P*.P*.P...PPP...P*....*..*.**......*P.*P.....**P...*P...
1,000
3,788,800
0
9,642
774
Stepan and Vowels
[ "*special", "implementation", "strings" ]
null
null
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa". Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y". There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon". Sergey is very busy and asks you to help him and write the required program.
The first line contains the integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of letters in the word written by Stepan. The second line contains the string *s* which has length that equals to *n* and contains only lowercase English letters — the word written by Stepan.
Print the single string — the word written by Stepan converted according to the rules described in the statement.
[ "13\npobeeeedaaaaa\n", "22\niiiimpleeemeentatiioon\n", "18\naeiouyaaeeiioouuyy\n", "24\naaaoooiiiuuuyyyeeeggghhh\n" ]
[ "pobeda\n", "implemeentatioon\n", "aeiouyaeeioouy\n", "aoiuyeggghhh\n" ]
none
[ { "input": "13\npobeeeedaaaaa", "output": "pobeda" }, { "input": "22\niiiimpleeemeentatiioon", "output": "implemeentatioon" }, { "input": "18\naeiouyaaeeiioouuyy", "output": "aeiouyaeeioouy" }, { "input": "24\naaaoooiiiuuuyyyeeeggghhh", "output": "aoiuyeggghhh" }, { ...
78
5,529,600
0
9,644
598
Cut Length
[ "geometry" ]
null
null
Given simple (without self-intersections) *n*-gon. It is not necessary convex. Also you are given *m* lines. For each line find the length of common part of the line and the *n*-gon. The boundary of *n*-gon belongs to polygon. It is possible that *n*-gon contains 180-degree angles.
The first line contains integers *n* and *m* (3<=≤<=*n*<=≤<=1000;1<=≤<=*m*<=≤<=100). The following *n* lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct. The following *m* lines contain line descriptions. Each of them contains two distict points of a line by their coordinates. All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Print *m* lines, the *i*-th line should contain the length of common part of the given *n*-gon and the *i*-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6.
[ "4 3\n0 0\n1 0\n1 1\n0 1\n0 0 1 1\n0 0 0 1\n0 0 1 -1\n" ]
[ "1.41421356237309514547\n1.00000000000000000000\n0.00000000000000000000\n" ]
none
[ { "input": "4 3\n0 0\n1 0\n1 1\n0 1\n0 0 1 1\n0 0 0 1\n0 0 1 -1", "output": "1.41421356237309514547\n1.00000000000000000000\n0.00000000000000000000" }, { "input": "4 9\n0 0\n0 1\n1 1\n1 0\n0 0 1 1\n1 1 0 0\n0 0 1 0\n0 0 0.5 0\n0 0.5 1 0.5\n0 1 1 1\n1 1 1 0\n0.75 0.75 0.75 0.25\n0 0.25 1 0.75", "...
77
2,355,200
-1
9,672
7
Memory Manager
[ "implementation" ]
B. Memory Manager
1
64
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: - alloc n — to allocate *n* bytes of the memory and return the allocated block's identifier *x*; - erase x — to erase the block with the identifier *x*; - defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of *m* bytes, numbered for convenience from the first to the *m*-th. The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of *n* successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL. The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT. The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order. In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration. You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.
The first line of the input data contains two positive integers *t* and *m* (1<=≤<=*t*<=≤<=100;1<=≤<=*m*<=≤<=100), where *t* — the amount of operations given to the memory manager for processing, and *m* — the available memory size in bytes. Then there follow *t* lines where the operations themselves are given. The first operation is alloc n (1<=≤<=*n*<=≤<=100), where *n* is an integer. The second one is erase x, where *x* is an arbitrary 32-bit integer numerical token. The third operation is defragment.
Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.
[ "6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6\n" ]
[ "1\n2\nNULL\n3\n" ]
none
[ { "input": "6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6", "output": "1\n2\nNULL\n3" }, { "input": "6 1\ndefragment\nalloc 10\nalloc 1\nerase -1\nerase 1\nerase 1", "output": "NULL\n1\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT" }, { "input": "14 100\nalloc 99\nalloc...
124
5,222,400
0
9,683
21
Stripe 2
[ "binary search", "dp", "sortings" ]
C. Stripe 2
1
64
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
The first input line contains integer *n* (1<=≤<=*n*<=≤<=105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
[ "4\n1 2 3 3\n", "5\n1 2 3 4 5\n" ]
[ "1\n", "0\n" ]
none
[ { "input": "1\n-3", "output": "0" }, { "input": "2\n0 0", "output": "0" }, { "input": "3\n0 0 0", "output": "1" }, { "input": "4\n-2 3 3 2", "output": "0" }, { "input": "5\n-6 3 -1 2 -7", "output": "0" }, { "input": "6\n2 3 -3 0 -3 1", "output": "0...
109
0
0
9,689
113
Double Happiness
[ "brute force", "math", "number theory" ]
C. Double Happiness
3
128
On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number *t* is his lucky number, if it can be represented as: Now, the boys decided to find out how many days of the interval [*l*,<=*r*] (*l*<=≤<=*r*) are suitable for pair programming. They decided that the day *i* (*l*<=≤<=*i*<=≤<=*r*) is suitable for pair programming if and only if the number *i* is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days.
The first line of the input contains integer numbers *l*,<=*r* (1<=≤<=*l*,<=*r*<=≤<=3·108).
In the only line print the number of days on the segment [*l*,<=*r*], which are lucky for Peter and Bob at the same time.
[ "3 5\n", "6 66\n" ]
[ "1\n", "7\n" ]
none
[]
3,000
7,270,400
0
9,696
837
Two Seals
[ "brute force", "implementation" ]
null
null
One very important person has a piece of paper in the form of a rectangle *a*<=×<=*b*. Also, he has *n* seals. Each seal leaves an impression on the paper in the form of a rectangle of the size *x**i*<=×<=*y**i*. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees). A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?
The first line contains three integer numbers *n*, *a* and *b* (1<=≤<=*n*,<=*a*,<=*b*<=≤<=100). Each of the next *n* lines contain two numbers *x**i*, *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=100).
Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.
[ "2 2 2\n1 2\n2 1\n", "4 10 9\n2 3\n1 1\n5 10\n9 11\n", "3 10 10\n6 6\n7 7\n20 5\n" ]
[ "4\n", "56\n", "0\n" ]
In the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper. In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area. In the third example there is no such pair of seals that they both can fit on a piece of paper.
[ { "input": "2 2 2\n1 2\n2 1", "output": "4" }, { "input": "4 10 9\n2 3\n1 1\n5 10\n9 11", "output": "56" }, { "input": "3 10 10\n6 6\n7 7\n20 5", "output": "0" }, { "input": "2 1 1\n1 1\n1 1", "output": "0" }, { "input": "2 1 2\n1 1\n1 1", "output": "2" }, ...
140
20,172,800
0
9,697
837
Functions On The Segments
[ "data structures" ]
null
null
You have an array *f* of *n* functions.The function *f**i*(*x*) (1<=≤<=*i*<=≤<=*n*) is characterized by parameters: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 and take values: - *y*1, if *x*<=≤<=*x*1. - *a*·*x*<=+<=*b*, if *x*1<=&lt;<=*x*<=≤<=*x*2. - *y*2, if *x*<=&gt;<=*x*2. There are *m* queries. Each query is determined by numbers *l*, *r* and *x*. For a query with number *i* (1<=≤<=*i*<=≤<=*m*), you need to calculate the sum of all *f**j*(*x**i*) where *l*<=≤<=*j*<=≤<=*r*. The value of *x**i* is calculated as follows: *x**i*<==<=(*x*<=+<=*last*) mod 109, where *last* is the answer to the query with number *i*<=-<=1. The value of *last* equals 0 if *i*<==<=1.
First line contains one integer number *n* (1<=≤<=*n*<=≤<=75000). Each of the next *n* lines contains six integer numbers: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 (0<=≤<=*x*1<=&lt;<=*x*2<=≤<=2·105, 0<=≤<=*y*1,<=*y*2<=≤<=109, 0<=≤<=*a*,<=*b*<=≤<=104). Next line contains one integer number *m* (1<=≤<=*m*<=≤<=500000). Each of the next *m* lines contains three integer numbers: *l*, *r* and *x* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, 0<=≤<=*x*<=≤<=109).
none
[ "1\n1 2 1 4 5 10\n1\n1 1 2\n", "3\n2 5 1 1 1 4\n3 6 8 2 5 7\n1 3 5 1 4 10\n3\n1 3 3\n2 3 2\n1 2 5\n" ]
[ "13\n", "19\n17\n11\n" ]
none
[ { "input": "1\n1 2 1 4 5 10\n1\n1 1 2", "output": "13" }, { "input": "3\n2 5 1 1 1 4\n3 6 8 2 5 7\n1 3 5 1 4 10\n3\n1 3 3\n2 3 2\n1 2 5", "output": "19\n17\n11" }, { "input": "7\n4 8 562244866 6 8 140807945\n5 7 415374420 7 6 596093578\n3 4 766370993 3 7 973128805\n4 6 841321398 3 2 8931...
1,403
42,905,600
0
9,701
492
Vanya and Exams
[ "greedy", "sortings" ]
null
null
Vanya wants to pass *n* exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least *avg*. The exam grade cannot exceed *r*. Vanya has passed the exams and got grade *a**i* for the *i*-th exam. To increase the grade for the *i*-th exam by 1 point, Vanya must write *b**i* essays. He can raise the exam grade multiple times. What is the minimum number of essays that Vanya needs to write to get scholarship?
The first line contains three integers *n*, *r*, *avg* (1<=≤<=*n*<=≤<=105, 1<=≤<=*r*<=≤<=109, 1<=≤<=*avg*<=≤<=*min*(*r*,<=106)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following *n* lines contains space-separated integers *a**i* and *b**i* (1<=≤<=*a**i*<=≤<=*r*, 1<=≤<=*b**i*<=≤<=106).
In the first line print the minimum number of essays.
[ "5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5\n", "2 5 4\n5 2\n5 2\n" ]
[ "4\n", "0\n" ]
In the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point. In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.
[ { "input": "5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5", "output": "4" }, { "input": "2 5 4\n5 2\n5 2", "output": "0" }, { "input": "6 5 5\n1 7\n2 4\n3 5\n4 6\n5 6\n4 7", "output": "63" }, { "input": "1 1000000000 1000000\n1 1000000", "output": "999999000000" }, { "input": "1...
795
20,480,000
0
9,707
229
Shifts
[ "brute force", "two pointers" ]
null
null
You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1.
The first line contains two space-separated integers: *n* (1<=≤<=*n*<=≤<=100) — the number of rows in the table and *m* (1<=≤<=*m*<=≤<=104) — the number of columns in the table. Then *n* lines follow, each of them contains *m* characters "0" or "1": the *j*-th character of the *i*-th line describes the contents of the cell in the *i*-th row and in the *j*-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1".
Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.
[ "3 6\n101010\n000100\n100000\n", "2 3\n111\n000\n" ]
[ "3\n", "-1\n" ]
In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s.
[ { "input": "3 6\n101010\n000100\n100000", "output": "3" }, { "input": "2 3\n111\n000", "output": "-1" }, { "input": "1 1\n1", "output": "0" }, { "input": "1 1\n0", "output": "-1" }, { "input": "3 1\n1\n1\n0", "output": "-1" }, { "input": "6 2\n10\n11\n...
310
30,105,600
0
9,711
629
Famil Door and Brackets
[ "dp", "strings" ]
null
null
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length *n* more than any other strings! The sequence of round brackets is called valid if and only if: 1. the total number of opening brackets is equal to the total number of closing brackets; 1. for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string *s* of length *m* (*m*<=≤<=*n*) and want to complete it to obtain a valid sequence of brackets of length *n*. He is going to pick some strings *p* and *q* consisting of round brackets and merge them in a string *p*<=+<=*s*<=+<=*q*, that is add the string *p* at the beginning of the string *s* and string *q* at the end of the string *s*. Now he wonders, how many pairs of strings *p* and *q* exists, such that the string *p*<=+<=*s*<=+<=*q* is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109<=+<=7.
First line contains *n* and *m* (1<=≤<=*m*<=≤<=*n*<=≤<=100<=000,<=*n*<=-<=*m*<=≤<=2000) — the desired length of the string and the length of the string bought by Gabi, respectively. The second line contains string *s* of length *m* consisting of characters '(' and ')' only.
Print the number of pairs of string *p* and *q* such that *p*<=+<=*s*<=+<=*q* is a valid sequence of round brackets modulo 109<=+<=7.
[ "4 1\n(\n", "4 4\n(())\n", "4 3\n(((\n" ]
[ "4\n", "1\n", "0\n" ]
In the first sample there are four different valid pairs: 1. *p* = "(", *q* = "))" 1. *p* = "()", *q* = ")" 1. *p* = "", *q* = "())" 1. *p* = "", *q* = ")()" In the second sample the only way to obtain a desired string is choose empty *p* and *q*. In the third sample there is no way to get a valid sequence of brackets.
[ { "input": "4 1\n(", "output": "4" }, { "input": "4 4\n(())", "output": "1" }, { "input": "4 3\n(((", "output": "0" }, { "input": "875 50\n)))((())()))((()(())))))())))((((((()))))))()(((((", "output": "0" }, { "input": "1980 464\n))(()()))(((((((((()))))))(()((((...
514
7,168,000
0
9,745
1,010
Border
[ "number theory" ]
null
null
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are $n$ banknote denominations on Mars: the value of $i$-th banknote is $a_i$. Natasha has an infinite number of banknotes of each denomination. Martians have $k$ fingers on their hands, so they use a number system with base $k$. In addition, the Martians consider the digit $d$ (in the number system with base $k$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $k$ is $d$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet. Determine for which values $d$ Natasha can make the Martians happy. Natasha can use only her banknotes. Martians don't give her change.
The first line contains two integers $n$ and $k$ ($1 \le n \le 100\,000$, $2 \le k \le 100\,000$) — the number of denominations of banknotes and the base of the number system on Mars. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — denominations of banknotes on Mars. All numbers are given in decimal notation.
On the first line output the number of values $d$ for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation.
[ "2 8\n12 20\n", "3 10\n10 20 30\n" ]
[ "2\n0 4 ", "1\n0 " ]
Consider the first test case. It uses the octal number system. If you take one banknote with the value of $12$, you will get $14_8$ in octal system. The last digit is $4_8$. If you take one banknote with the value of $12$ and one banknote with the value of $20$, the total value will be $32$. In the octal system, it is $40_8$. The last digit is $0_8$. If you take two banknotes with the value of $20$, the total value will be $40$, this is $50_8$ in the octal system. The last digit is $0_8$. No other digits other than $0_8$ and $4_8$ can be obtained. Digits $0_8$ and $4_8$ could also be obtained in other ways. The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
[ { "input": "2 8\n12 20", "output": "2\n0 4 " }, { "input": "3 10\n10 20 30", "output": "1\n0 " }, { "input": "5 10\n20 16 4 16 2", "output": "5\n0 2 4 6 8 " }, { "input": "10 5\n4 6 8 6 4 10 2 10 8 6", "output": "5\n0 1 2 3 4 " }, { "input": "20 25\n15 10 5 20 10 ...
155
0
0
9,756
245
Mishap in Club
[ "greedy", "implementation" ]
null
null
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen. On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended. Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.
The only line of the input contains a sequence of characters "+" and "-", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.
Print the sought minimum number of people
[ "+-+-+\n", "---" ]
[ "1\n", "3" ]
none
[ { "input": "+-+-+", "output": "1" }, { "input": "---", "output": "3" }, { "input": "-", "output": "1" }, { "input": "--", "output": "2" }, { "input": "---", "output": "3" }, { "input": "----", "output": "4" }, { "input": "---+", "output...
216
0
0
9,784
0
none
[ "none" ]
null
null
Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as *n* consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than *t* time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional *k* kilos of sweets. Cindy Lou wants to know the minimum number of *k* kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of *k*.
The first line of the input contains two space-separated integers *n* and *t* (2<=≤<=*n*<=≤<=5·105,<=1<=≤<=*t*<=≤<=109). The second line of the input contains *n* characters, the *i*-th of them equals "H" (if the *i*-th segment contains a house), "S" (if the *i*-th segment contains a shop) or "." (if the *i*-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house.
If there isn't a single value of *k* that makes it possible to give sweets to everybody in at most *t* units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of *k*.
[ "6 6\nHSHSHS\n", "14 100\n...HHHSSS...SH\n", "23 50\nHHSS.......SSHHHHHHHHHH\n" ]
[ "1\n", "0\n", "8\n" ]
In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home.
[]
60
0
0
9,794
288
Polo the Penguin and Lucky Numbers
[ "dp", "implementation", "math" ]
null
null
Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Polo the Penguin have two positive integers *l* and *r* (*l*<=&lt;<=*r*), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other. Let's assume that *n* is the number of distinct lucky numbers, each of them cannot be greater than *r* or less than *l*, and *a**i* is the *i*-th (in increasing order) number of them. Find *a*1·*a*2<=+<=*a*2·*a*3<=+<=...<=+<=*a**n*<=-<=1·*a**n*. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109<=+<=7).
The first line contains a positive integer *l*, and the second line contains a positive integer *r* (1<=≤<=*l*<=&lt;<=*r*<=≤<=10100000). The numbers are given without any leading zeroes. It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers.
In the single line print a single integer — the answer to the problem modulo 1000000007 (109<=+<=7).
[ "4\n7\n", "474\n777\n" ]
[ "28\n", "2316330\n" ]
none
[ { "input": "4\n7", "output": "28" }, { "input": "474\n777", "output": "2316330" }, { "input": "44\n77", "output": "11244" }, { "input": "444\n777", "output": "2726676" }, { "input": "444\n477", "output": "636444" }, { "input": "444\n744", "output":...
2,000
33,177,600
0
9,813
557
Ann and Half-Palindrome
[ "data structures", "dp", "graphs", "string suffix structures", "strings", "trees" ]
null
null
Tomorrow Ann takes the hardest exam of programming where she should get an excellent mark. On the last theoretical class the teacher introduced the notion of a half-palindrome. String *t* is a half-palindrome, if for all the odd positions *i* () the following condition is held: *t**i*<==<=*t*|*t*|<=-<=*i*<=+<=1, where |*t*| is the length of string *t* if positions are indexed from 1. For example, strings "abaa", "a", "bb", "abbbaa" are half-palindromes and strings "ab", "bba" and "aaabaa" are not. Ann knows that on the exam she will get string *s*, consisting only of letters a and b, and number *k*. To get an excellent mark she has to find the *k*-th in the lexicographical order string among all substrings of *s* that are half-palyndromes. Note that each substring in this order is considered as many times as many times it occurs in *s*. The teachers guarantees that the given number *k* doesn't exceed the number of substrings of the given string that are half-palindromes. Can you cope with this problem?
The first line of the input contains string *s* (1<=≤<=|*s*|<=≤<=5000), consisting only of characters 'a' and 'b', where |*s*| is the length of string *s*. The second line contains a positive integer *k* —  the lexicographical number of the requested string among all the half-palindrome substrings of the given string *s*. The strings are numbered starting from one. It is guaranteed that number *k* doesn't exceed the number of substrings of the given string that are half-palindromes.
Print a substring of the given string that is the *k*-th in the lexicographical order of all substrings of the given string that are half-palindromes.
[ "abbabaab\n7\n", "aaaaa\n10\n", "bbaabb\n13\n" ]
[ "abaa\n", "aaa\n", "bbaabb\n" ]
By definition, string *a* = *a*<sub class="lower-index">1</sub>*a*<sub class="lower-index">2</sub>... *a*<sub class="lower-index">*n*</sub> is lexicographically less than string *b* = *b*<sub class="lower-index">1</sub>*b*<sub class="lower-index">2</sub>... *b*<sub class="lower-index">*m*</sub>, if either *a* is a prefix of *b* and doesn't coincide with *b*, or there exists such *i*, that *a*<sub class="lower-index">1</sub> = *b*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub> = *b*<sub class="lower-index">2</sub>, ... *a*<sub class="lower-index">*i* - 1</sub> = *b*<sub class="lower-index">*i* - 1</sub>, *a*<sub class="lower-index">*i*</sub> &lt; *b*<sub class="lower-index">*i*</sub>. In the first sample half-palindrome substrings are the following strings — a, a, a, a, aa, aba, abaa, abba, abbabaa, b, b, b, b, baab, bab, bb, bbab, bbabaab (the list is given in the lexicographical order).
[ { "input": "abbabaab\n7", "output": "abaa" }, { "input": "aaaaa\n10", "output": "aaa" }, { "input": "bbaabb\n13", "output": "bbaabb" }, { "input": "a\n1", "output": "a" }, { "input": "b\n1", "output": "b" }, { "input": "ababbbbbbbaaaaaaaabbbbbb\n23", ...
1,500
51,200,000
0
9,834
128
Statues
[ "dfs and similar" ]
null
null
In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8<=×<=8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone — neither any other statues, nor Anna, nor Maria. Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is — to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared. At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner. Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.
You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one — for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S". It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".
If Maria wins, print string "WIN". If the statues win, print string "LOSE".
[ ".......A\n........\n........\n........\n........\n........\n........\nM.......\n", ".......A\n........\n........\n........\n........\n........\nSS......\nM.......\n", ".......A\n........\n........\n........\n........\n.S......\nS.......\nMS......\n" ]
[ "WIN\n", "LOSE\n", "LOSE\n" ]
none
[ { "input": ".SSSSSSA\n.SSSSSSS\n.SSSSSSS\n.SSSSSSS\n.SSSSSSS\n.SSSSSSS\n.SSSSSSS\nMSSSSSSS", "output": "WIN" }, { "input": "SSSSSSSA\nSSSSSSSS\nSSSSSSSS\nSSSSSSSS\nSSSSSSSS\nSSSSSSSS\nSSSSSSSS\nMSSSSSSS", "output": "LOSE" }, { "input": "SSSSSSSA\n......SS\n.......S\n.......S\n.......S\n....
404
6,656,000
0
9,867
656
Da Vinci Powers
[ "*special" ]
null
null
The input contains a single integer *a* (0<=≤<=*a*<=≤<=35). Output a single integer.
The input contains a single integer *a* (0<=≤<=*a*<=≤<=35).
Output a single integer.
[ "3\n", "10\n" ]
[ "8\n", "1024\n" ]
none
[ { "input": "3", "output": "8" }, { "input": "10", "output": "1024" }, { "input": "35", "output": "33940307968" }, { "input": "0", "output": "1" }, { "input": "1", "output": "2" }, { "input": "2", "output": "4" }, { "input": "4", "output...
46
5,529,600
0
9,881
922
Cave Painting
[ "brute force", "number theory" ]
null
null
Imp is watching a documentary about cave painting. Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number *n* by all integers *i* from 1 to *k*. Unfortunately, there are too many integers to analyze for Imp. Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all , 1<=≤<=*i*<=≤<=*k*, are distinct, i. e. there is no such pair (*i*,<=*j*) that: - 1<=≤<=*i*<=&lt;<=*j*<=≤<=*k*, - , where is the remainder of division *x* by *y*.
The only line contains two integers *n*, *k* (1<=≤<=*n*,<=*k*<=≤<=1018).
Print "Yes", if all the remainders are distinct, and "No" otherwise. You can print each letter in arbitrary case (lower or upper).
[ "4 4\n", "5 3\n" ]
[ "No\n", "Yes\n" ]
In the first sample remainders modulo 1 and 4 coincide.
[ { "input": "4 4", "output": "No" }, { "input": "5 3", "output": "Yes" }, { "input": "1 1", "output": "Yes" }, { "input": "744 18", "output": "No" }, { "input": "47879 10", "output": "Yes" }, { "input": "1000000000000000000 1000000000000000000", "ou...
155
0
3
9,898
108
Datatypes
[ "math", "sortings" ]
B. Datatypes
2
256
Tattah's youngest brother, Tuftuf, is new to programming. Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava. Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has *n* unsigned integer datatypes of sizes (in bits) *a*1,<=*a*2,<=... *a**n*. The *i*-th datatype have size *a**i* bits, so it can represent every integer between 0 and 2*a**i*<=-<=1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer *x*, such that *x* fits in some type *i* (in *a**i* bits) and *x*·*x* does not fit in some other type *j* (in *a**j* bits) where *a**i*<=&lt;<=*a**j*, then Tuftuf will stop using Gava. Your task is to determine Tuftuf's destiny.
The first line contains integer *n* (2<=≤<=*n*<=≤<=105) — the number of Gava's unsigned integer datatypes' sizes. The second line contains a single-space-separated list of *n* integers (1<=≤<=*a**i*<=≤<=109) — sizes of datatypes in bits. Some datatypes may have equal sizes.
Print "YES" if Tuftuf will stop using Gava, and "NO" otherwise.
[ "3\n64 16 32\n", "4\n4 2 1 3\n" ]
[ "NO\n", "YES\n" ]
In the second example, *x* = 7 (111<sub class="lower-index">2</sub>) fits in 3 bits, but *x*<sup class="upper-index">2</sup> = 49 (110001<sub class="lower-index">2</sub>) does not fit in 4 bits.
[ { "input": "3\n64 16 32", "output": "NO" }, { "input": "4\n4 2 1 3", "output": "YES" }, { "input": "5\n1 5 3 3 2", "output": "YES" }, { "input": "52\n474 24 24 954 9 234 474 114 24 114 234 24 114 114 234 9 9 24 9 54 234 54 9 954 474 9 54 54 54 234 9 114 24 54 114 954 954 474 ...
248
0
0
9,900
505
Mr. Kitayuta, the Treasure Hunter
[ "dfs and similar", "dp", "two pointers" ]
null
null
The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are *n* gems in the Shuseki Islands in total, and the *i*-th gem is located on island *p**i*. Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process: - First, he will jump from island 0 to island *d*. - After that, he will continue jumping according to the following rule. Let *l* be the length of the previous jump, that is, if his previous jump was from island *prev* to island *cur*, let *l*<==<=*cur*<=-<=*prev*. He will perform a jump of length *l*<=-<=1, *l* or *l*<=+<=1 to the east. That is, he will jump to island (*cur*<=+<=*l*<=-<=1), (*cur*<=+<=*l*) or (*cur*<=+<=*l*<=+<=1) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when *l*<==<=1. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.
The first line of the input contains two space-separated integers *n* and *d* (1<=≤<=*n*,<=*d*<=≤<=30000), denoting the number of the gems in the Shuseki Islands and the length of the Mr. Kitayuta's first jump, respectively. The next *n* lines describe the location of the gems. The *i*-th of them (1<=≤<=*i*<=≤<=*n*) contains a integer *p**i* (*d*<=≤<=*p*1<=≤<=*p*2<=≤<=...<=≤<=*p**n*<=≤<=30000), denoting the number of the island that contains the *i*-th gem.
Print the maximum number of gems that Mr. Kitayuta can collect.
[ "4 10\n10\n21\n27\n27\n", "8 8\n9\n19\n28\n36\n45\n55\n66\n78\n", "13 7\n8\n8\n9\n16\n17\n17\n18\n21\n23\n24\n24\n26\n30\n" ]
[ "3\n", "6\n", "4\n" ]
In the first sample, the optimal route is 0  →  10 (+1 gem)  →  19  →  27 (+2 gems)  → ... In the second sample, the optimal route is 0  →  8  →  15  →  21 →  28 (+1 gem)  →  36 (+1 gem)  →  45 (+1 gem)  →  55 (+1 gem)  →  66 (+1 gem)  →  78 (+1 gem)  → ... In the third sample, the optimal route is 0  →  7  →  13  →  18 (+1 gem)  →  24 (+2 gems)  →  30 (+1 gem)  → ...
[ { "input": "4 10\n10\n21\n27\n27", "output": "3" }, { "input": "8 8\n9\n19\n28\n36\n45\n55\n66\n78", "output": "6" }, { "input": "13 7\n8\n8\n9\n16\n17\n17\n18\n21\n23\n24\n24\n26\n30", "output": "4" }, { "input": "8 4\n9\n15\n15\n16\n22\n25\n25\n28", "output": "8" }, ...
46
0
0
9,907
985
Isomorphic Strings
[ "hashing", "strings" ]
null
null
You are given a string *s* of length *n* consisting of lowercase English letters. For two given strings *s* and *t*, say *S* is the set of distinct characters of *s* and *T* is the set of distinct characters of *t*. The strings *s* and *t* are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) *f* between *S* and *T* for which *f*(*s**i*)<==<=*t**i*. Formally: 1. *f*(*s**i*)<==<=*t**i* for any index *i*, 1. for any character there is exactly one character that *f*(*x*)<==<=*y*, 1. for any character there is exactly one character that *f*(*x*)<==<=*y*. For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best". You have to handle *m* queries characterized by three integers *x*,<=*y*,<=*len* (1<=≤<=*x*,<=*y*<=≤<=*n*<=-<=*len*<=+<=1). For each query check if two substrings *s*[*x*... *x*<=+<=*len*<=-<=1] and *s*[*y*... *y*<=+<=*len*<=-<=1] are isomorphic.
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=2·105, 1<=≤<=*m*<=≤<=2·105) — the length of the string *s* and the number of queries. The second line contains string *s* consisting of *n* lowercase English letters. The following *m* lines contain a single query on each line: *x**i*, *y**i* and *len**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, 1<=≤<=*len**i*<=≤<=*n*<=-<=*max*(*x**i*,<=*y**i*)<=+<=1) — the description of the pair of the substrings to check.
For each query in a separate line print "YES" if substrings *s*[*x**i*... *x**i*<=+<=*len**i*<=-<=1] and *s*[*y**i*... *y**i*<=+<=*len**i*<=-<=1] are isomorphic and "NO" otherwise.
[ "7 4\nabacaba\n1 1 1\n1 4 2\n2 1 3\n2 4 3\n" ]
[ "YES\nYES\nNO\nYES\n" ]
The queries in the example are following: 1. substrings "a" and "a" are isomorphic: *f*(*a*) = *a*; 1. substrings "ab" and "ca" are isomorphic: *f*(*a*) = *c*, *f*(*b*) = *a*; 1. substrings "bac" and "aba" are not isomorphic since *f*(*b*) and *f*(*c*) must be equal to *a* at same time; 1. substrings "bac" and "cab" are isomorphic: *f*(*b*) = *c*, *f*(*a*) = *a*, *f*(*c*) = *b*.
[ { "input": "7 4\nabacaba\n1 1 1\n1 4 2\n2 1 3\n2 4 3", "output": "YES\nYES\nNO\nYES" }, { "input": "1 2\nz\n1 1 1\n1 1 1", "output": "YES\nYES" }, { "input": "36 4\naababcbbcbczaaawwwwwaaaabbbbtestbest\n1 7 6\n13 18 5\n23 26 3\n29 33 4", "output": "YES\nYES\nNO\nNO" }, { "inp...
92
102,400
0
9,954
730
Bulmart
[ "binary search", "dfs and similar" ]
null
null
A new trade empire is rising in Berland. Bulmart, an emerging trade giant, decided to dominate the market of ... shovels! And now almost every city in Berland has a Bulmart store, and some cities even have several of them! The only problem is, at the moment sales are ... let's say a little below estimates. Some people even say that shovels retail market is too small for such a big company to make a profit. But the company management believes in the future of that market and seeks new ways to increase income. There are *n* cities in Berland connected with *m* bi-directional roads. All roads have equal lengths. It can happen that it is impossible to reach a city from another city using only roads. There is no road which connects a city to itself. Any pair of cities can be connected by at most one road. There are *w* Bulmart stores in Berland. Each of them is described by three numbers: - *c**i* — the number of city where the *i*-th store is located (a city can have no stores at all or have several of them), - *k**i* — the number of shovels in the *i*-th store, - *p**i* — the price of a single shovel in the *i*-th store (in burles). The latest idea of the Bulmart management is to create a program which will help customers get shovels as fast as possible for affordable budget. Formally, the program has to find the minimum amount of time needed to deliver *r**j* shovels to the customer in the city *g**j* for the total cost of no more than *a**j* burles. The delivery time between any two adjacent cities is equal to 1. If shovels are delivered from several cities, the delivery time is equal to the arrival time of the last package. The delivery itself is free of charge. The program needs to find answers to *q* such queries. Each query has to be processed independently from others, i.e. a query does not change number of shovels in stores for the next queries.
The first line contains two integers *n*, *m* (1<=≤<=*n*<=≤<=5000, 0<=≤<=*m*<=≤<=*min*(5000,<=*n*·(*n*<=-<=1)<=/<=2)). Each of the next *m* lines contains two integers *x**e* and *y**e*, meaning that the *e*-th road connects cities *x**e* and *y**e* (1<=≤<=*x**e*,<=*y**e*<=≤<=*n*). The next line contains a single integer *w* (1<=≤<=*w*<=≤<=5000) — the total number of Bulmart stores in Berland. Each of the next *w* lines contains three integers describing the *i*-th store: *c**i*,<=*k**i*,<=*p**i* (1<=≤<=*c**i*<=≤<=*n*,<=1<=≤<=*k**i*,<=*p**i*<=≤<=2·105). The next line contains a single integer *q* (1<=≤<=*q*<=≤<=1000) — the number of queries. Each of the next *q* lines contains three integers describing the *j*-th query: *g**j*,<=*r**j* and *a**j* (1<=≤<=*g**j*<=≤<=*n*, 1<=≤<=*r**j*,<=*a**j*<=≤<=109)
Output *q* lines. On the *j*-th line, print an answer for the *j*-th query — the minimum amount of time needed to deliver *r**j* shovels to the customer in city *g**j* spending no more than *a**j* burles. Print -1 if there is no solution for the *j*-th query.
[ "6 4\n4 2\n5 4\n1 2\n3 2\n2\n4 1 2\n3 2 3\n6\n1 2 6\n2 3 7\n3 1 2\n4 3 8\n5 2 5\n6 1 10\n" ]
[ "2\n-1\n2\n2\n3\n-1\n" ]
none
[]
46
0
0
9,965
241
Old Peykan
[ "greedy" ]
null
null
There are *n* cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as *c*1,<=*c*2,<=...,<=*c**n*. The Old Peykan wants to travel from city *c*1 to *c**n* using roads. There are (*n*<=-<=1) one way roads, the *i*-th road goes from city *c**i* to city *c**i*<=+<=1 and is *d**i* kilometers long. The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time. Each city *c**i* (except for the last city *c**n*) has a supply of *s**i* liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly *k* hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times. Initially (at time zero) the Old Peykan is at city *c*1 and *s*1 liters of fuel is transferred to it's empty tank from *c*1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities. Find the minimum time the Old Peykan needs to reach city *c**n*.
The first line of the input contains two space-separated integers *m* and *k* (1<=≤<=*m*,<=*k*<=≤<=1000). The value *m* specifies the number of roads between cities which is equal to *n*<=-<=1. The next line contains *m* space-separated integers *d*1,<=*d*2,<=...,<=*d**m* (1<=≤<=*d**i*<=≤<=1000) and the following line contains *m* space-separated integers *s*1,<=*s*2,<=...,<=*s**m* (1<=≤<=*s**i*<=≤<=1000).
In the only line of the output print a single integer — the minimum time required for The Old Peykan to reach city *c**n* from city *c*1.
[ "4 6\n1 2 5 2\n2 3 3 4\n", "2 3\n5 6\n5 5\n" ]
[ "10\n", "14\n" ]
In the second sample above, the Old Peykan stays in *c*<sub class="lower-index">1</sub> for 3 hours.
[ { "input": "4 6\n1 2 5 2\n2 3 3 4", "output": "10" }, { "input": "2 3\n5 6\n5 5", "output": "14" }, { "input": "24 3\n11 8 8 12 17 4 4 25 39 37 31 32 38 34 29 29 34 39 39 39 17 9 24 6\n3 5 4 3 3 3 4 3 4 3 3 3 3 4 3 3 4 3 4 3 3 3 3 3", "output": "862" }, { "input": "43 5\n6 7 ...
62
0
0
9,987
488
Candy Boxes
[ "brute force", "constructive algorithms", "math" ]
null
null
There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {*x*1,<=*x*2,<=*x*3,<=*x*4} (*x*1<=≤<=*x*2<=≤<=*x*3<=≤<=*x*4) arithmetic mean is , median is and range is *x*4<=-<=*x*1. The arithmetic mean and median are not necessary integer. It is well-known that if those three numbers are same, boxes will create a "debugging field" and codes in the field will have no bugs. For example, 1,<=1,<=3,<=3 is the example of 4 numbers meeting the condition because their mean, median and range are all equal to 2. Jeff has 4 special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only *n* (0<=≤<=*n*<=≤<=4) boxes remaining. The *i*-th remaining box contains *a**i* candies. Now Jeff wants to know: is there a possible way to find the number of candies of the 4<=-<=*n* missing boxes, meeting the condition above (the mean, median and range are equal)?
The first line of input contains an only integer *n* (0<=≤<=*n*<=≤<=4). The next *n* lines contain integers *a**i*, denoting the number of candies in the *i*-th box (1<=≤<=*a**i*<=≤<=500).
In the first output line, print "YES" if a solution exists, or print "NO" if there is no solution. If a solution exists, you should output 4<=-<=*n* more lines, each line containing an integer *b*, denoting the number of candies in a missing box. All your numbers *b* must satisfy inequality 1<=≤<=*b*<=≤<=106. It is guaranteed that if there exists a positive integer solution, you can always find such *b*'s meeting the condition. If there are multiple answers, you are allowed to print any of them. Given numbers *a**i* may follow in any order in the input, not necessary in non-decreasing. *a**i* may have stood at any positions in the original set, not necessary on lowest *n* first positions.
[ "2\n1\n1\n", "3\n1\n1\n1\n", "4\n1\n2\n2\n3\n" ]
[ "YES\n3\n3\n", "NO\n", "YES\n" ]
For the first sample, the numbers of candies in 4 boxes can be 1, 1, 3, 3. The arithmetic mean, the median and the range of them are all 2. For the second sample, it's impossible to find the missing number of candies. In the third example no box has been lost and numbers satisfy the condition. You may output *b* in any order.
[ { "input": "2\n1\n1", "output": "YES\n3\n3" }, { "input": "3\n1\n1\n1", "output": "NO" }, { "input": "4\n1\n2\n2\n3", "output": "YES" }, { "input": "0", "output": "YES\n1\n1\n3\n3" }, { "input": "1\n125", "output": "YES\n125\n375\n375" }, { "input": "2...
1,000
0
0
10,000
24
Sequence of points
[ "geometry", "implementation", "math" ]
C. Sequence of points
2
256
You are given the following points with integer coordinates on the plane: *M*0,<=*A*0,<=*A*1,<=...,<=*A**n*<=-<=1, where *n* is odd number. Now we define the following infinite sequence of points *M**i*: *M**i* is symmetric to *M**i*<=-<=1 according (for every natural number *i*). Here point *B* is symmetric to *A* according *M*, if *M* is the center of the line segment *AB*. Given index *j* find the point *M**j*.
On the first line you will be given an integer *n* (1<=≤<=*n*<=≤<=105), which will be odd, and *j* (1<=≤<=*j*<=≤<=1018), where *j* is the index of the desired point. The next line contains two space separated integers, the coordinates of *M*0. After that *n* lines follow, where the *i*-th line contain the space separated integer coordinates of the point *A**i*<=-<=1. The absolute values of all input coordinates will not be greater then 1000.
On a single line output the coordinates of *M**j*, space separated.
[ "3 4\n0 0\n1 1\n2 3\n-5 3\n", "3 1\n5 5\n1000 1000\n-1000 1000\n3 100\n" ]
[ "14 0\n", "1995 1995\n" ]
none
[ { "input": "3 4\n0 0\n1 1\n2 3\n-5 3", "output": "14 0" }, { "input": "3 1\n5 5\n1000 1000\n-1000 1000\n3 100", "output": "1995 1995" }, { "input": "1 1\n-1000 -1000\n1000 1000", "output": "3000 3000" }, { "input": "1 1000000000000000000\n-1000 1000\n1000 -1000", "output"...
1,808
8,704,000
3.531788
10,011
628
Magic Numbers
[ "dp" ]
null
null
Consider the decimal presentation of an integer. Let's call a number d-magic if digit *d* appears in decimal presentation of the number on even positions and nowhere else. For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic. Find the number of d-magic numbers in the segment [*a*,<=*b*] that are multiple of *m*. Because the answer can be very huge you should only find its value modulo 109<=+<=7 (so you should find the remainder after dividing by 109<=+<=7).
The first line contains two integers *m*,<=*d* (1<=≤<=*m*<=≤<=2000, 0<=≤<=*d*<=≤<=9) — the parameters from the problem statement. The second line contains positive integer *a* in decimal presentation (without leading zeroes). The third line contains positive integer *b* in decimal presentation (without leading zeroes). It is guaranteed that *a*<=≤<=*b*, the number of digits in *a* and *b* are the same and don't exceed 2000.
Print the only integer *a* — the remainder after dividing by 109<=+<=7 of the number of d-magic numbers in segment [*a*,<=*b*] that are multiple of *m*.
[ "2 6\n10\n99\n", "2 0\n1\n9\n", "19 7\n1000\n9999\n" ]
[ "8\n", "4\n", "6\n" ]
The numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96. The numbers from the answer of the second example are 2, 4, 6 and 8. The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747.
[ { "input": "2 6\n10\n99", "output": "8" }, { "input": "2 0\n1\n9", "output": "4" }, { "input": "19 7\n1000\n9999", "output": "6" }, { "input": "9 4\n33\n52", "output": "0" }, { "input": "10 8\n18\n59", "output": "0" }, { "input": "43 3\n587\n850", ...
124
409,600
0
10,020
260
Ancient Prophesy
[ "brute force", "implementation", "strings" ]
null
null
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012"). The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date. A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it. Notice, that any year between 2013 and 2015 is not a leap year.
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
[ "777-444---21-12-2013-12-2013-12-2013---444-777\n" ]
[ "13-12-2013" ]
none
[ { "input": "777-444---21-12-2013-12-2013-12-2013---444-777", "output": "13-12-2013" }, { "input": "30-12-201429-15-208830-12-2014", "output": "30-12-2014" }, { "input": "14-08-201314-08-201314-08-201381-16-20172406414-08-201314-08-201314-08-20134237014-08-201314-08-2013", "output": "...
77
3,584,000
-1
10,046
776
The Door Problem
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
null
null
Moriarty has trapped *n* people in *n* distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are *m* switches. Each switch control doors of some rooms, but each door is controlled by exactly two switches. You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch 1, which was connected to room 1, 2 and 3 which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked. You need to tell Sherlock, if there exists a way to unlock all doors at the same time.
First line of input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=105, 2<=≤<=*m*<=≤<=105) — the number of rooms and the number of switches. Next line contains *n* space-separated integers *r*1,<=*r*2,<=...,<=*r**n* (0<=≤<=*r**i*<=≤<=1) which tell the status of room doors. The *i*-th room is locked if *r**i*<==<=0, otherwise it is unlocked. The *i*-th of next *m* lines contains an integer *x**i* (0<=≤<=*x**i*<=≤<=*n*) followed by *x**i* distinct integers separated by space, denoting the number of rooms controlled by the *i*-th switch followed by the room numbers that this switch controls. It is guaranteed that the room numbers are in the range from 1 to *n*. It is guaranteed that each door is controlled by exactly two switches.
Output "YES" without quotes, if it is possible to open all doors at the same time, otherwise output "NO" without quotes.
[ "3 3\n1 0 1\n2 1 3\n2 1 2\n2 2 3\n", "3 3\n1 0 1\n3 1 2 3\n1 2\n2 1 3\n", "3 3\n1 0 1\n3 1 2 3\n2 1 2\n1 3\n" ]
[ "NO", "YES", "NO" ]
In the second example input, the initial statuses of the doors are [1, 0, 1] (0 means locked, 1 — unlocked). After toggling switch 3, we get [0, 0, 0] that means all doors are locked. Then, after toggling switch 1, we get [1, 1, 1] that means all doors are unlocked. It can be seen that for the first and for the third example inputs it is not possible to make all doors unlocked.
[ { "input": "3 3\n1 0 1\n2 1 3\n2 1 2\n2 2 3", "output": "NO" }, { "input": "3 3\n1 0 1\n3 1 2 3\n1 2\n2 1 3", "output": "YES" }, { "input": "3 3\n1 0 1\n3 1 2 3\n2 1 2\n1 3", "output": "NO" }, { "input": "11 10\n0 0 1 0 0 0 0 1 1 0 1\n3 2 3 11\n1 3\n2 6 7\n1 5\n1 11\n1 10\n5 ...
31
0
0
10,051
168
Wizards and Minimal Spell
[ "implementation", "strings" ]
null
null
Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells. Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell. You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning. The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden. Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too). For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too). The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.
The input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 (<==<=220) bytes. Newlines are included in this size. In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one. It is guaranteed that the input contains at least one character other than a newline. It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means.
Print the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline. Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter.
[ "# include &lt;cstdio&gt;\n\nusing namespace std;\n\nint main ( ){\nputs(\"Hello # World\"); #\n#\n}\n", "#\n\n#\n" ]
[ "# include &lt;cstdio&gt;\nusingnamespacestd;intmain(){puts(\"Hello#World\");#\n#\n}\n", "#\n\n#\n" ]
In the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them. In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other.
[ { "input": " # include <cstdio>\n\nusing namespace std;\n\nint main ( ){\nputs(\"Hello # World\"); #\n#\n}", "output": " # include <cstdio>\nusingnamespacestd;intmain(){puts(\"Hello#World\");#\n#\n}" }, { "input": "#\n\n#", "output": "#\n\n#" }, { "input": "#\n \n#", "...
156
0
0
10,064
154
Hometask
[ "greedy" ]
null
null
Sergey attends lessons of the *N*-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the *N*-ish language. Sentences of the *N*-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of *N*-ish. The spelling rules state that *N*-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair. Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
The first line contains a non-empty string *s*, consisting of lowercase Latin letters — that's the initial sentence in *N*-ish, written by Sergey. The length of string *s* doesn't exceed 105. The next line contains integer *k* (0<=≤<=*k*<=≤<=13) — the number of forbidden pairs of letters. Next *k* lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Print the single number — the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
[ "ababa\n1\nab\n", "codeforces\n2\ndo\ncs\n" ]
[ "2\n", "1\n" ]
In the first sample you should remove two letters b. In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
[ { "input": "ababa\n1\nab", "output": "2" }, { "input": "codeforces\n2\ndo\ncs", "output": "1" }, { "input": "nllnrlrnll\n1\nrl", "output": "1" }, { "input": "aludfbjtwnkgnfl\n1\noy", "output": "0" }, { "input": "pgpgppgggpbbnnn\n2\npg\nnb", "output": "7" }, ...
154
3,379,200
0
10,089
926
A Vital Problem
[]
null
null
Polycarp has a strict daily schedule. He has *n* alarms set for each day, and the *i*-th alarm rings each day at the same time during exactly one minute. Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of alarms. Each of the next *n* lines contains a description of one alarm. Each description has a format "hh:mm", where *hh* is the hour when the alarm rings, and *mm* is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary. Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i. e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.
Print a line in format "hh:mm", denoting the maximum time Polycarp can sleep continuously. *hh* denotes the number of hours, and *mm* denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.
[ "1\n05:43\n", "4\n22:00\n03:21\n16:03\n09:59\n" ]
[ "23:59\n", "06:37\n" ]
In the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time.
[ { "input": "1\n05:43", "output": "23:59" }, { "input": "4\n22:00\n03:21\n16:03\n09:59", "output": "06:37" }, { "input": "20\n23:59\n00:00\n00:01\n00:02\n00:03\n00:04\n00:05\n00:06\n00:07\n00:08\n00:09\n00:10\n00:11\n00:12\n00:13\n00:14\n00:15\n00:16\n00:17\n00:18", "output": "23:40" ...
109
21,401,600
0
10,112
12
Ball
[ "data structures", "sortings" ]
D. Ball
2
256
*N* ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the *i*-th lady by *B**i*, her intellect by *I**i* and her richness by *R**i*. Then *i*-th lady is a probable self-murderer if there is some *j*-th lady that *B**i*<=&lt;<=*B**j*,<=*I**i*<=&lt;<=*I**j*,<=*R**i*<=&lt;<=*R**j*. Find the number of probable self-murderers.
The first line contains one integer *N* (1<=≤<=*N*<=≤<=500000). The second line contains *N* integer numbers *B**i*, separated by single spaces. The third and the fourth lines contain sequences *I**i* and *R**i* in the same format. It is guaranteed that 0<=≤<=*B**i*,<=*I**i*,<=*R**i*<=≤<=109.
Output the answer to the problem.
[ "3\n1 4 2\n4 3 2\n2 5 3\n" ]
[ "1\n" ]
none
[ { "input": "3\n1 4 2\n4 3 2\n2 5 3", "output": "1" }, { "input": "5\n2 8 10 0 7\n7 7 3 0 10\n2 8 3 2 2", "output": "1" }, { "input": "5\n3 0 0 2 0\n7 10 7 4 0\n9 1 6 1 9", "output": "1" }, { "input": "5\n5 4 0 2 5\n8 3 1 0 10\n4 5 0 0 5", "output": "2" }, { "input...
77
307,200
-1
10,122
392
Blocked Points
[ "math" ]
null
null
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points *A* and *B* on the plane are 4-connected if and only if: - the Euclidean distance between *A* and *B* is one unit and neither *A* nor *B* is blocked; - or there is some integral point *C*, such that *A* is 4-connected with *C*, and *C* is 4-connected with *B*. Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than *n*, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
The first line contains an integer *n* (0<=≤<=*n*<=≤<=4·107).
Print a single integer — the minimum number of points that should be blocked.
[ "1\n", "2\n", "3\n" ]
[ "4\n", "8\n", "16\n" ]
none
[ { "input": "1", "output": "4" }, { "input": "2", "output": "8" }, { "input": "3", "output": "16" }, { "input": "4", "output": "20" }, { "input": "0", "output": "1" }, { "input": "30426905", "output": "172120564" }, { "input": "38450759", ...
93
0
0
10,135
615
Multipliers
[ "math", "number theory" ]
null
null
Ayrat has number *n*, represented as it's prime factorization *p**i* of size *m*, i.e. *n*<==<=*p*1·*p*2·...·*p**m*. Ayrat got secret information that that the product of all divisors of *n* taken modulo 109<=+<=7 is the password to the secret data base. Now he wants to calculate this value.
The first line of the input contains a single integer *m* (1<=≤<=*m*<=≤<=200<=000) — the number of primes in factorization of *n*. The second line contains *m* primes numbers *p**i* (2<=≤<=*p**i*<=≤<=200<=000).
Print one integer — the product of all divisors of *n* modulo 109<=+<=7.
[ "2\n2 3\n", "3\n2 3 2\n" ]
[ "36\n", "1728\n" ]
In the first sample *n* = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36. In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.
[ { "input": "2\n2 3", "output": "36" }, { "input": "3\n2 3 2", "output": "1728" }, { "input": "1\n2017", "output": "2017" }, { "input": "2\n63997 63997", "output": "135893224" }, { "input": "5\n11 7 11 7 11", "output": "750455957" }, { "input": "5\n2 2 ...
280
11,264,000
0
10,158
351
Jeff and Removing Periods
[ "data structures" ]
null
null
Cosider a sequence, consisting of *n* integers: *a*1, *a*2, ..., *a**n*. Jeff can perform the following operation on sequence *a*: - take three integers *v*, *t*, *k* (1<=≤<=*v*,<=*t*<=≤<=*n*; 0<=≤<=*k*; *v*<=+<=*tk*<=≤<=*n*), such that *a**v* = *a**v*<=+<=*t*, *a**v*<=+<=*t* = *a**v*<=+<=2*t*, ..., *a**v*<=+<=*t*(*k*<=-<=1) = *a**v*<=+<=*tk*; - remove elements *a**v*, *a**v*<=+<=*t*, ..., *a**v*<=+<=*t*·*k* from the sequence *a*, the remaining elements should be reindexed *a*1,<=*a*2,<=...,<=*a**n*<=-<=*k*<=-<=1. - permute in some order the remaining elements of sequence *a*. A beauty of a sequence *a* is the minimum number of operations that is needed to delete all elements from sequence *a*. Jeff's written down a sequence of *m* integers *b*1, *b*2, ..., *b**m*. Now he wants to ask *q* questions. Each question can be described with two integers *l**i*,<=*r**i*. The answer to the question is the beauty of sequence *b**l**i*, *b**l**i*<=+<=1, ..., *b**r**i*. You are given the sequence *b* and all questions. Help Jeff, answer all his questions.
The first line contains integer *m* (1<=≤<=*m*<=≤<=105). The next line contains *m* integers *b*1, *b*2, ..., *b**m* (1<=≤<=*b**i*<=≤<=105). The third line contains integer *q* (1<=≤<=*q*<=≤<=105) — the number of questions. The next *q* lines contain pairs of integers, *i*-th of them contains a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*m*) — the description of *i*-th question.
In *q* lines print the answers to Jeff's queries. Print the answers according to the order of questions in input.
[ "5\n2 2 1 1 2\n5\n1 5\n1 1\n2 2\n1 3\n2 3\n", "10\n2 1 3 3 3 3 1 3 1 1\n10\n4 8\n2 10\n1 10\n4 4\n1 3\n2 4\n6 7\n1 9\n2 5\n1 1\n" ]
[ "2\n1\n1\n2\n2\n", "2\n3\n3\n1\n3\n2\n2\n3\n2\n1\n" ]
none
[ { "input": "5\n2 2 1 1 2\n5\n1 5\n1 1\n2 2\n1 3\n2 3", "output": "2\n1\n1\n2\n2" }, { "input": "10\n2 1 3 3 3 3 1 3 1 1\n10\n4 8\n2 10\n1 10\n4 4\n1 3\n2 4\n6 7\n1 9\n2 5\n1 1", "output": "2\n3\n3\n1\n3\n2\n2\n3\n2\n1" }, { "input": "15\n3 3 2 2 1 2 4 1 3 1 1 3 1 4 1\n15\n4 10\n8 9\n12 1...
1,684
9,625,600
0
10,222
0
none
[ "none" ]
null
null
Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is *h*1 and height of Abol is *h*2. Each second, Mike waters Abol and Xaniar. So, if height of Xaniar is *h*1 and height of Abol is *h*2, after one second height of Xaniar will become and height of Abol will become where *x*1,<=*y*1,<=*x*2 and *y*2 are some integer numbers and denotes the remainder of *a* modulo *b*. Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is *a*1 and height of Abol is *a*2. Mike has asked you for your help. Calculate the minimum time or say it will never happen.
The first line of input contains integer *m* (2<=≤<=*m*<=≤<=106). The second line of input contains integers *h*1 and *a*1 (0<=≤<=*h*1,<=*a*1<=&lt;<=*m*). The third line of input contains integers *x*1 and *y*1 (0<=≤<=*x*1,<=*y*1<=&lt;<=*m*). The fourth line of input contains integers *h*2 and *a*2 (0<=≤<=*h*2,<=*a*2<=&lt;<=*m*). The fifth line of input contains integers *x*2 and *y*2 (0<=≤<=*x*2,<=*y*2<=&lt;<=*m*). It is guaranteed that *h*1<=≠<=*a*1 and *h*2<=≠<=*a*2.
Print the minimum number of seconds until Xaniar reaches height *a*1 and Abol reaches height *a*2 or print -1 otherwise.
[ "5\n4 2\n1 1\n0 1\n2 3\n", "1023\n1 2\n1 0\n1 2\n1 1\n" ]
[ "3\n", "-1\n" ]
In the first sample, heights sequences are following: Xaniar: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/85da629b05969e7a8a6636d995b8fe7a0494e8f4.png" style="max-width: 100.0%;max-height: 100.0%;"/> Abol: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ea95da14490864ae8b8bfcd4a8b7c02ad3a666b3.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "5\n4 2\n1 1\n0 1\n2 3", "output": "3" }, { "input": "1023\n1 2\n1 0\n1 2\n1 1", "output": "-1" }, { "input": "1023\n1 2\n1 2\n1 2\n1 2", "output": "512" }, { "input": "2\n0 1\n1 0\n1 0\n0 1", "output": "-1" }, { "input": "17\n15 12\n15 12\n12 14\n1 11"...
124
0
0
10,237
803
Maximal GCD
[ "constructive algorithms", "greedy", "math" ]
null
null
You are given positive integer number *n*. You should create such strictly increasing sequence of *k* positive numbers *a*1,<=*a*2,<=...,<=*a**k*, that their sum is equal to *n* and greatest common divisor is maximal. Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them. If there is no possible sequence then output -1.
The first line consists of two numbers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=1010).
If the answer exists then output *k* numbers — resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
[ "6 3\n", "8 2\n", "5 3\n" ]
[ "1 2 3\n", "2 6\n", "-1\n" ]
none
[ { "input": "6 3", "output": "1 2 3" }, { "input": "8 2", "output": "2 6" }, { "input": "5 3", "output": "-1" }, { "input": "1 1", "output": "1" }, { "input": "1 2", "output": "-1" }, { "input": "2 1", "output": "2" }, { "input": "2 10000000...
124
7,270,400
3
10,278
89
Widget Library
[ "dp", "expression parsing", "graphs", "implementation" ]
B. Widget Library
2
256
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget *a* is packed in the widget *b* if there exists a chain of widgets *a*<==<=*c*1,<=*c*2,<=...,<=*c**k*<==<=*b*, *k*<=≥<=2, for which *c**i* is packed directly to *c**i*<=+<=1 for any 1<=≤<=*i*<=&lt;<=*k*. In Vasya's library the situation when the widget *a* is packed in the widget *a* (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error. Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0<=×<=0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript.
The first line contains an integer *n* — the number of instructions (1<=≤<=*n*<=≤<=100). Next *n* lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below. - "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. - "HBox [name]" — create a new widget [name] of the type HBox. - "VBox [name]" — create a new widget [name] of the type VBox. - "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. - "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. - "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget.
For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator)
[ "12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)\n", "15\nWidget pack(10,10)\nHBox dummy\nHBox x\nVBox y\ny.pack(dum...
[ "brother 30 60\nfather 80 60\nfriend 20 60\ngrandpa 120 120\nme 50 40\nuncle 100 20\n", "dummy 0 0\npack 10 10\nx 40 10\ny 10 10\n" ]
In the first sample the widgets are arranged as follows:
[ { "input": "12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)", "output": "brother 30 60\nfather 80 60\nfriend 2...
92
0
0
10,311
425
Sereja and Swaps
[ "brute force", "sortings" ]
null
null
As usual, Sereja has array *a*, its elements are integers: *a*[1],<=*a*[2],<=...,<=*a*[*n*]. Let's introduce notation: A swap operation is the following sequence of actions: - choose two indexes *i*,<=*j* (*i*<=≠<=*j*); - perform assignments *tmp*<==<=*a*[*i*],<=*a*[*i*]<==<=*a*[*j*],<=*a*[*j*]<==<=*tmp*. What maximum value of function *m*(*a*) can Sereja get if he is allowed to perform at most *k* swap operations?
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=200; 1<=≤<=*k*<=≤<=10). The next line contains *n* integers *a*[1], *a*[2], ..., *a*[*n*] (<=-<=1000<=≤<=*a*[*i*]<=≤<=1000).
In a single line print the maximum value of *m*(*a*) that Sereja can get if he is allowed to perform at most *k* swap operations.
[ "10 2\n10 -1 2 2 2 2 2 2 -1 10\n", "5 10\n-1 -1 -1 -1 -1\n" ]
[ "32\n", "-1\n" ]
none
[ { "input": "10 2\n10 -1 2 2 2 2 2 2 -1 10", "output": "32" }, { "input": "5 10\n-1 -1 -1 -1 -1", "output": "-1" }, { "input": "18 1\n166 788 276 -103 -491 195 -960 389 376 369 630 285 3 575 315 -987 820 466", "output": "5016" }, { "input": "29 6\n-21 486 -630 -433 -123 -387 6...
1,000
102,400
0
10,365
750
New Year and Rating
[ "binary search", "greedy", "math" ]
null
null
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero. Limak competed in *n* contests in the year 2016. He remembers that in the *i*-th contest he competed in the division *d**i* (i.e. he belonged to this division just before the start of this contest) and his rating changed by *c**i* just after the contest. Note that negative *c**i* denotes the loss of rating. What is the maximum possible rating Limak can have right now, after all *n* contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000). The *i*-th of next *n* lines contains two integers *c**i* and *d**i* (<=-<=100<=≤<=*c**i*<=≤<=100, 1<=≤<=*d**i*<=≤<=2), describing Limak's rating change after the *i*-th contest and his division during the *i*-th contest contest.
If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the *n* contests.
[ "3\n-7 1\n5 2\n8 2\n", "2\n57 1\n22 2\n", "1\n-5 1\n", "4\n27 2\n13 1\n-50 1\n8 2\n" ]
[ "1907\n", "Impossible\n", "Infinity\n", "1897\n" ]
In the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating: - Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7. - With rating 1894 Limak is in the division 2. His rating increases by 5. - Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.
[ { "input": "3\n-7 1\n5 2\n8 2", "output": "1907" }, { "input": "2\n57 1\n22 2", "output": "Impossible" }, { "input": "1\n-5 1", "output": "Infinity" }, { "input": "4\n27 2\n13 1\n-50 1\n8 2", "output": "1897" }, { "input": "6\n8 1\n-22 1\n9 2\n-7 2\n85 2\n77 1", ...
156
4,812,800
3
10,371
231
To Add or Not to Add
[ "binary search", "sortings", "two pointers" ]
null
null
A piece of paper contains an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a number that occurs the maximum number of times in this array. However, before looking for such number, you are allowed to perform not more than *k* following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than *k* times (you are allowed to increase the same element of the array multiple times). Your task is to find the maximum number of occurrences of some number in the array after performing no more than *k* allowed operations. If there are several such numbers, your task is to find the minimum one.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105; 0<=≤<=*k*<=≤<=109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=≤<=109) — the initial array. The numbers in the lines are separated by single spaces.
In a single line print two numbers — the maximum number of occurrences of some number in the array after at most *k* allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.
[ "5 3\n6 3 4 0 2\n", "3 4\n5 5 5\n", "5 3\n3 1 2 2 1\n" ]
[ "3 4\n", "3 5\n", "4 2\n" ]
In the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times. In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6. In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.
[ { "input": "5 3\n6 3 4 0 2", "output": "3 4" }, { "input": "3 4\n5 5 5", "output": "3 5" }, { "input": "5 3\n3 1 2 2 1", "output": "4 2" }, { "input": "6 0\n3 2 3 2 3 2", "output": "3 2" }, { "input": "10 15\n1 1 1 4 4 1 4 4 1 4", "output": "10 4" }, { ...
62
0
0
10,408
839
Game of the Rows
[ "brute force", "greedy", "implementation" ]
null
null
Daenerys Targaryen has an army consisting of *k* groups of soldiers, the *i*-th group contains *a**i* soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has *n* rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1,<=2}, {3,<=4}, {4,<=5}, {5,<=6} or {7,<=8}. Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats. Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=10000, 1<=≤<=*k*<=≤<=100) — the number of rows and the number of groups of soldiers, respectively. The second line contains *k* integers *a*1,<=*a*2,<=*a*3,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=10000), where *a**i* denotes the number of soldiers in the *i*-th group. It is guaranteed that *a*1<=+<=*a*2<=+<=...<=+<=*a**k*<=≤<=8·*n*.
If we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes). You can choose the case (lower or upper) for each letter arbitrary.
[ "2 2\n5 8\n", "1 2\n7 1\n", "1 2\n4 4\n", "1 4\n2 2 1 2\n" ]
[ "YES\n", "NO\n", "YES\n", "YES\n" ]
In the first sample, Daenerys can place the soldiers like in the figure below: In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group. In the third example Daenerys can place the first group on seats (1, 2, 7, 8), and the second group an all the remaining seats. In the fourth example she can place the first two groups on seats (1, 2) and (7, 8), the third group on seats (3), and the fourth group on seats (5, 6).
[ { "input": "2 2\n5 8", "output": "YES" }, { "input": "1 2\n7 1", "output": "NO" }, { "input": "1 2\n4 4", "output": "YES" }, { "input": "1 4\n2 2 1 2", "output": "YES" }, { "input": "10000 100\n749 2244 949 2439 2703 44 2394 124 285 3694 3609 717 1413 155 974 1778...
46
0
0
10,409
894
Marco and GCD Sequence
[ "constructive algorithms", "math" ]
null
null
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time. When he woke up, he only remembered that the key was a sequence of positive integers of some length *n*, but forgot the exact sequence. Let the elements of the sequence be *a*1,<=*a*2,<=...,<=*a**n*. He remembered that he calculated *gcd*(*a**i*,<=*a**i*<=+<=1,<=...,<=*a**j*) for every 1<=≤<=*i*<=≤<=*j*<=≤<=*n* and put it into a set *S*. *gcd* here means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Note that even if a number is put into the set *S* twice or more, it only appears once in the set. Now Marco gives you the set *S* and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set *S*, in this case print -1.
The first line contains a single integer *m* (1<=≤<=*m*<=≤<=1000) — the size of the set *S*. The second line contains *m* integers *s*1,<=*s*2,<=...,<=*s**m* (1<=≤<=*s**i*<=≤<=106) — the elements of the set *S*. It's guaranteed that the elements of the set are given in strictly increasing order, that means *s*1<=&lt;<=*s*2<=&lt;<=...<=&lt;<=*s**m*.
If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer *n* denoting the length of the sequence, *n* should not exceed 4000. In the second line print *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the sequence. We can show that if a solution exists, then there is a solution with *n* not exceeding 4000 and *a**i* not exceeding 106. If there are multiple solutions, print any of them.
[ "4\n2 4 6 12\n", "2\n2 3\n" ]
[ "3\n4 6 12", "-1\n" ]
In the first example 2 = *gcd*(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among *gcd*(*a*<sub class="lower-index">*i*</sub>, *a*<sub class="lower-index">*i* + 1</sub>, ..., *a*<sub class="lower-index">*j*</sub>) for every 1 ≤ *i* ≤ *j* ≤ *n*.
[ { "input": "4\n2 4 6 12", "output": "7\n2 2 4 2 6 2 12" }, { "input": "2\n2 3", "output": "-1" }, { "input": "2\n1 6", "output": "3\n1 1 6" }, { "input": "3\n1 2 7", "output": "5\n1 1 2 1 7" }, { "input": "1\n1", "output": "1\n1" }, { "input": "2\n1 10...
155
2,764,800
3
10,414
342
Cupboard and Balloons
[ "geometry" ]
null
null
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius *r* (the cupboard's top) and two walls of height *h* (the cupboard's sides). The cupboard's depth is *r*, that is, it looks like a rectangle with base *r* and height *h*<=+<=*r* from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right). Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius . Help Xenia calculate the maximum number of balloons she can put in her cupboard. You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.
The single line contains two integers *r*,<=*h* (1<=≤<=*r*,<=*h*<=≤<=107).
Print a single integer — the maximum number of balloons Xenia can put in the cupboard.
[ "1 1\n", "1 2\n", "2 1\n" ]
[ "3\n", "5\n", "2\n" ]
none
[ { "input": "1 1", "output": "3" }, { "input": "1 2", "output": "5" }, { "input": "2 1", "output": "2" }, { "input": "2 2", "output": "3" }, { "input": "2 3", "output": "4" }, { "input": "4 1", "output": "1" }, { "input": "5 1", "output"...
92
0
0
10,446
819
Mister B and Boring Game
[ "games", "greedy" ]
null
null
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens. All characters in this game are lowercase English letters. There are two players: Mister B and his competitor. Initially the players have a string *s* consisting of the first *a* English letters in alphabetical order (for example, if *a*<==<=5, then *s* equals to "abcde"). The players take turns appending letters to string *s*. Mister B moves first. Mister B must append exactly *b* letters on each his move. He can arbitrary choose these letters. His opponent adds exactly *a* letters on each move. Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string *s* of length *a* and generates a string *t* of length *a* such that all letters in the string *t* are distinct and don't appear in the considered suffix. From multiple variants of *t* lexicographically minimal is chosen (if *a*<==<=4 and the suffix is "bfdd", the computer chooses string *t* equal to "aceg"). After that the chosen string *t* is appended to the end of *s*. Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string *s* on the segment between positions *l* and *r*, inclusive. Letters of string *s* are numerated starting from 1.
First and only line contains four space-separated integers: *a*, *b*, *l* and *r* (1<=≤<=*a*,<=*b*<=≤<=12, 1<=≤<=*l*<=≤<=*r*<=≤<=109) — the numbers of letters each player appends and the bounds of the segment.
Print one integer — the minimum possible number of different letters in the segment from position *l* to position *r*, inclusive, in string *s*.
[ "1 1 1 8\n", "4 2 2 6\n", "3 7 4 6\n" ]
[ "2", "3", "1" ]
In the first sample test one of optimal strategies generate string *s* = "abababab...", that's why answer is 2. In the second sample test string *s* = "abcdbcaefg..." can be obtained, chosen segment will look like "bcdbc", that's why answer is 3. In the third sample test string *s* = "abczzzacad..." can be obtained, chosen, segment will look like "zzz", that's why answer is 1.
[ { "input": "1 1 1 8", "output": "2" }, { "input": "4 2 2 6", "output": "3" }, { "input": "3 7 4 6", "output": "1" }, { "input": "4 5 1 1", "output": "1" }, { "input": "12 12 1 1000", "output": "13" }, { "input": "12 1 1000 1000", "output": "1" },...
2,000
15,872,000
0
10,451
442
Artem and Array
[ "data structures", "greedy" ]
null
null
Artem has an array of *n* positive integers. Artem decided to play with it. The game consists of *n* moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets *min*(*a*,<=*b*) points, where *a* and *b* are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=5·105) — the number of elements in the array. The next line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the values of the array elements.
In a single line print a single integer — the maximum number of points Artem can get.
[ "5\n3 1 5 2 6\n", "5\n1 2 3 4 5\n", "5\n1 100 101 100 1\n" ]
[ "11\n", "6\n", "102\n" ]
none
[ { "input": "5\n3 1 5 2 6", "output": "11" }, { "input": "5\n1 2 3 4 5", "output": "6" }, { "input": "5\n1 100 101 100 1", "output": "102" }, { "input": "10\n96 66 8 18 30 48 34 11 37 42", "output": "299" }, { "input": "1\n87", "output": "0" }, { "input...
93
0
-1
10,486
913
Logical Expression
[ "bitmasks", "dp", "shortest paths" ]
null
null
You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: - Operation AND ('&amp;', ASCII code 38) - Operation OR ('|', ASCII code 124) - Operation NOT ('!', ASCII code 33) - Variables x, y and z (ASCII codes 120-122) - Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&amp;' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'
The first line contains one integer *n* — the number of functions in the input (1<=≤<=*n*<=≤<=10<=000). The following *n* lines contain descriptions of functions, the *i*-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the *i*-th function. The digit on position *j* (0<=≤<=*j*<=&lt;<=8) equals to the value of the function in case of , and .
You should output *n* lines, the *i*-th line should contain the expression of minimum length which equals to the *i*-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.
[ "4\n00110011\n00000111\n11110000\n00011111\n" ]
[ "y\n(y|z)&amp;x\n!x\nx|y&amp;z\n" ]
The truth table for the second function: <img class="tex-graphics" src="https://espresso.codeforces.com/2b70451f45cd74ee2be475affd7c407d7ed6d5fd.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "4\n00110011\n00000111\n11110000\n00011111", "output": "y\n(y|z)&x\n!x\nx|y&z" }, { "input": "1\n11001110", "output": "!y|!z&x" }, { "input": "2\n11001110\n01001001", "output": "!y|!z&x\n!(!x&!z|x&z|y)|x&y&z" }, { "input": "3\n10001001\n10111011\n10111101", "ou...
30
0
0
10,488
908
New Year and Curling
[ "brute force", "geometry", "implementation", "math" ]
null
null
Carol is currently curling. She has *n* disks each with radius *r* on the 2D plane. Initially she has all these disks above the line *y*<==<=10100. She then will slide the disks towards the line *y*<==<=0 one by one in order from 1 to *n*. When she slides the *i*-th disk, she will place its center at the point (*x**i*,<=10100). She will then push it so the disk’s *y* coordinate continuously decreases, and *x* coordinate stays constant. The disk stops once it touches the line *y*<==<=0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the *y*-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers *n* and *r* (1<=≤<=*n*,<=*r*<=≤<=1<=000), the number of disks, and the radius of the disks, respectively. The next line will contain *n* integers *x*1,<=*x*2,<=...,<=*x**n* (1<=≤<=*x**i*<=≤<=1<=000) — the *x*-coordinates of the disks.
Print a single line with *n* numbers. The *i*-th number denotes the *y*-coordinate of the center of the *i*-th disk. The output will be accepted if it has absolute or relative error at most 10<=-<=6. Namely, let's assume that your answer for a particular value of a coordinate is *a* and the answer of the jury is *b*. The checker program will consider your answer correct if for all coordinates.
[ "6 2\n5 5 6 8 3 12\n" ]
[ "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613\n" ]
The final positions of the disks will look as follows: In particular, note the position of the last disk.
[ { "input": "6 2\n5 5 6 8 3 12", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613" }, { "input": "1 1\n5", "output": "1" }, { "input": "5 300\n939 465 129 611 532", "output": "300 667.864105343 1164.9596696 1522.27745533 2117.05388391" }, { "input": "5 ...
108
0
-1
10,504
923
Primal Sport
[ "math", "number theory" ]
null
null
Alice and Bob begin their day with a quick game. They first choose a starting number *X*0<=≥<=3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the *i*-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number. Formally, he or she selects a prime *p*<=&lt;<=*X**i*<=-<=1 and then finds the minimum *X**i*<=≥<=*X**i*<=-<=1 such that *p* divides *X**i*. Note that if the selected prime *p* already divides *X**i*<=-<=1, then the number does not change. Eve has witnessed the state of the game after two turns. Given *X*2, help her determine what is the smallest possible starting number *X*0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
The input contains a single integer *X*2 (4<=≤<=*X*2<=≤<=106). It is guaranteed that the integer *X*2 is composite, that is, is not prime.
Output a single integer — the minimum possible *X*0.
[ "14\n", "20\n", "8192\n" ]
[ "6\n", "15\n", "8191\n" ]
In the first test, the smallest possible starting number is *X*<sub class="lower-index">0</sub> = 6. One possible course of the game is as follows: - Alice picks prime 5 and announces *X*<sub class="lower-index">1</sub> = 10 - Bob picks prime 7 and announces *X*<sub class="lower-index">2</sub> = 14. In the second case, let *X*<sub class="lower-index">0</sub> = 15. - Alice picks prime 2 and announces *X*<sub class="lower-index">1</sub> = 16 - Bob picks prime 5 and announces *X*<sub class="lower-index">2</sub> = 20.
[ { "input": "14", "output": "6" }, { "input": "20", "output": "15" }, { "input": "8192", "output": "8191" }, { "input": "1000000", "output": "998677" }, { "input": "959806", "output": "239958" }, { "input": "1452", "output": "1206" }, { "inp...
202
1,024,000
-1
10,521
319
Ping-Pong
[ "data structures" ]
null
null
In this problem at each moment you have a set of intervals. You can move from interval (*a*,<=*b*) from our set to interval (*c*,<=*d*) from our set if and only if *c*<=&lt;<=*a*<=&lt;<=*d* or *c*<=&lt;<=*b*<=&lt;<=*d*. Also there is a path from interval *I*1 from our set to interval *I*2 from our set if there is a sequence of successive moves starting from *I*1 so that we can reach *I*2. Your program should handle the queries of the following two types: 1. "1 x y" (*x*<=&lt;<=*y*) — add the new interval (*x*,<=*y*) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.1. "2 a b" (*a*<=≠<=*b*) — answer the question: is there a path from *a*-th (one-based) added interval to *b*-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals.
The first line of the input contains integer *n* denoting the number of queries, (1<=≤<=*n*<=≤<=105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct.
For each query of the second type print "YES" or "NO" on a separate line depending on the answer.
[ "5\n1 1 5\n1 5 11\n2 1 2\n1 2 9\n2 1 2\n" ]
[ "NO\nYES\n" ]
none
[]
122
0
0
10,541
778
Bitwise Formula
[ "bitmasks", "brute force", "dfs and similar", "expression parsing", "implementation" ]
null
null
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer *m*, bit depth of the game, which means that all numbers in the game will consist of *m* bits. Then he asks Peter to choose some *m*-bit number. After that, Bob computes the values of *n* variables. Each variable is assigned either a constant *m*-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.
The first line contains two integers *n* and *m*, the number of variables and bit depth, respectively (1<=≤<=*n*<=≤<=5000; 1<=≤<=*m*<=≤<=1000). The following *n* lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly *m* bits. 1. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.
In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as *m*-bit binary numbers.
[ "3 3\na := 101\nb := 011\nc := ? XOR b\n", "5 1\na := 1\nbb := 0\ncx := ? OR a\nd := ? XOR ?\ne := d AND bb\n" ]
[ "011\n100\n", "0\n0\n" ]
In the first sample if Peter chooses a number 011<sub class="lower-index">2</sub>, then *a* = 101<sub class="lower-index">2</sub>, *b* = 011<sub class="lower-index">2</sub>, *c* = 000<sub class="lower-index">2</sub>, the sum of their values is 8. If he chooses the number 100<sub class="lower-index">2</sub>, then *a* = 101<sub class="lower-index">2</sub>, *b* = 011<sub class="lower-index">2</sub>, *c* = 111<sub class="lower-index">2</sub>, the sum of their values is 15. For the second test, the minimum and maximum sum of variables *a*, *bb*, *cx*, *d* and *e* is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
[ { "input": "3 3\na := 101\nb := 011\nc := ? XOR b", "output": "011\n100" }, { "input": "5 1\na := 1\nbb := 0\ncx := ? OR a\nd := ? XOR ?\ne := d AND bb", "output": "0\n0" }, { "input": "2 10\nb := 0100101101\na := ? XOR b", "output": "0100101101\n1011010010" }, { "input": "1 ...
3,000
7,270,400
0
10,556
301
Yaroslav and Divisors
[ "data structures" ]
null
null
Yaroslav has an array *p*<==<=*p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*), consisting of *n* distinct integers. Also, he has *m* queries: - Query number *i* is represented as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The answer to the query *l**i*,<=*r**i* is the number of pairs of integers *q*, *w* (*l**i*<=≤<=*q*,<=*w*<=≤<=*r**i*) such that *p**q* is the divisor of *p**w*. Help Yaroslav, answer all his queries.
The first line contains the integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*). The following *m* lines contain Yaroslav's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
Print *m* integers — the answers to Yaroslav's queries in the order they appear in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "1 1\n1\n1 1\n", "10 9\n1 2 3 4 5 6 7 8 9 10\n1 10\n2 9\n3 8\n4 7\n5 6\n2 2\n9 10\n5 10\n4 10\n" ]
[ "1\n", "27\n14\n8\n4\n2\n1\n2\n7\n9\n" ]
none
[]
2,000
27,443,200
0
10,563
774
Lie or Truth
[ "*special", "constructive algorithms", "implementation", "sortings" ]
null
null
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to *a*1,<=*a*2,<=...,<=*a**n*. While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to *b*1,<=*b*2,<=...,<=*b**n*. Stepan said that he swapped only cubes which where on the positions between *l* and *r*, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions *l* and *r*, inclusive, in some way). Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.
The first line contains three integers *n*, *l*, *r* (1<=≤<=*n*<=≤<=105, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*) — the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=*n*) — the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.
Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes).
[ "5 2 4\n3 4 2 3 1\n3 2 3 4 1\n", "3 1 2\n1 2 3\n3 1 2\n", "4 2 4\n1 1 1 1\n1 1 1 1\n" ]
[ "TRUTH\n", "LIE\n", "TRUTH\n" ]
In the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]). In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother. In the third example for any values *l* and *r* there is a situation when Stepan said the truth.
[ { "input": "5 2 4\n3 4 2 3 1\n3 2 3 4 1", "output": "TRUTH" }, { "input": "3 1 2\n1 2 3\n3 1 2", "output": "LIE" }, { "input": "4 2 4\n1 1 1 1\n1 1 1 1", "output": "TRUTH" }, { "input": "5 1 3\n2 2 2 1 2\n2 2 2 1 2", "output": "TRUTH" }, { "input": "7 1 4\n2 5 5 5...
62
4,608,000
0
10,566
229
Triangles
[ "combinatorics", "graphs", "math" ]
null
null
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with *n* vertices, chooses some *m* edges and keeps them. Bob gets the remaining edges. Alice and Bob are fond of "triangles" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly?
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=106,<=0<=≤<=*m*<=≤<=106) — the number of vertices in the initial complete graph and the number of edges in Alice's graph, correspondingly. Then *m* lines follow: the *i*-th line contains two space-separated integers *a**i*, *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*), — the numbers of the two vertices connected by the *i*-th edge in Alice's graph. It is guaranteed that Alice's graph contains no multiple edges and self-loops. It is guaranteed that the initial complete graph also contains no multiple edges and self-loops. Consider the graph vertices to be indexed in some way from 1 to *n*.
Print a single number — the total number of cycles of length 3 in Alice and Bob's graphs together. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier.
[ "5 5\n1 2\n1 3\n2 3\n2 4\n3 4\n", "5 3\n1 2\n2 3\n1 3\n" ]
[ "3\n", "4\n" ]
In the first sample Alice has 2 triangles: (1, 2, 3) and (2, 3, 4). Bob's graph has only 1 triangle : (1, 4, 5). That's why the two graphs in total contain 3 triangles. In the second sample Alice's graph has only one triangle: (1, 2, 3). Bob's graph has three triangles: (1, 4, 5), (2, 4, 5) and (3, 4, 5). In this case the answer to the problem is 4.
[]
2,000
3,993,600
0
10,568
24
F1 Champions
[ "implementation" ]
B. F1 Champions
2
256
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places. You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.
The first line contain integer *t* (1<=≤<=*t*<=≤<=20), where *t* is the number of races. After that all races are described one by one. Every race description start with an integer *n* (1<=≤<=*n*<=≤<=50) on a line of itself, where *n* is the number of clasified drivers in the given race. After that *n* lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.
Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.
[ "3\n3\nHamilton\nVettel\nWebber\n2\nWebber\nVettel\n2\nHamilton\nVettel\n", "2\n7\nProst\nSurtees\nNakajima\nSchumacher\nButton\nDeLaRosa\nBuemi\n8\nAlonso\nProst\nNinoFarina\nJimClark\nDeLaRosa\nNakajima\nPatrese\nSurtees\n" ]
[ "Vettel\nHamilton\n", "Prost\nProst\n" ]
It is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.
[ { "input": "3\n3\nHamilton\nVettel\nWebber\n2\nWebber\nVettel\n2\nHamilton\nVettel", "output": "Vettel\nHamilton" }, { "input": "2\n7\nProst\nSurtees\nNakajima\nSchumacher\nButton\nDeLaRosa\nBuemi\n8\nAlonso\nProst\nNinoFarina\nJimClark\nDeLaRosa\nNakajima\nPatrese\nSurtees", "output": "Prost\nP...
436
13,824,000
-1
10,575
128
Games with Rectangle
[ "combinatorics", "dp" ]
null
null
In this task Anna and Maria play the following game. Initially they have a checkered piece of paper with a painted *n*<=×<=*m* rectangle (only the border, no filling). Anna and Maria move in turns and Anna starts. During each move one should paint inside the last-painted rectangle a new lesser rectangle (along the grid lines). The new rectangle should have no common points with the previous one. Note that when we paint a rectangle, we always paint only the border, the rectangles aren't filled. Nobody wins the game — Anna and Maria simply play until they have done *k* moves in total. Count the number of different ways to play this game.
The first and only line contains three integers: *n*,<=*m*,<=*k* (1<=≤<=*n*,<=*m*,<=*k*<=≤<=1000).
Print the single number — the number of the ways to play the game. As this number can be very big, print the value modulo 1000000007 (109<=+<=7).
[ "3 3 1\n", "4 4 1\n", "6 7 2\n" ]
[ "1\n", "9\n", "75\n" ]
Two ways to play the game are considered different if the final pictures are different. In other words, if one way contains a rectangle that is not contained in the other way. In the first sample Anna, who performs her first and only move, has only one possible action plan — insert a 1 × 1 square inside the given 3 × 3 square. In the second sample Anna has as much as 9 variants: 4 ways to paint a 1 × 1 square, 2 ways to insert a 1 × 2 rectangle vertically, 2 more ways to insert it horizontally and one more way is to insert a 2 × 2 square.
[ { "input": "3 3 1", "output": "1" }, { "input": "4 4 1", "output": "9" }, { "input": "6 7 2", "output": "75" }, { "input": "5 5 3", "output": "0" }, { "input": "2 2 1", "output": "0" }, { "input": "999 999 499", "output": "1" }, { "input": ...
1,076
68,096,000
3
10,645
741
Arpa's loud Owf and Mehrdad's evil plan
[ "dfs and similar", "math" ]
null
null
As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to *n*. Everyone has exactly one crush, *i*-th person's crush is person with the number *crush**i*. Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person *x* wants to start a round, he calls *crush**x* and says: "Oww...wwf" (the letter w is repeated *t* times) and cuts off the phone immediately. If *t*<=&gt;<=1 then *crush**x* calls *crush**crush**x* and says: "Oww...wwf" (the letter w is repeated *t*<=-<=1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (*t*<==<=1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest *t* (*t*<=≥<=1) such that for each person *x*, if *x* starts some round and *y* becomes the Joon-Joon of the round, then by starting from *y*, *x* would become the Joon-Joon of the round. Find such *t* for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. *crush**i*<==<=*i*).
The first line of input contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of people in Arpa's land. The second line contains *n* integers, *i*-th of them is *crush**i* (1<=≤<=*crush**i*<=≤<=*n*) — the number of *i*-th person's crush.
If there is no *t* satisfying the condition, print -1. Otherwise print such smallest *t*.
[ "4\n2 3 1 4\n", "4\n4 4 4 4\n", "4\n2 1 4 3\n" ]
[ "3\n", "-1\n", "1\n" ]
In the first sample suppose *t* = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if *x* is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when *x* is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.
[ { "input": "4\n2 3 1 4", "output": "3" }, { "input": "4\n4 4 4 4", "output": "-1" }, { "input": "4\n2 1 4 3", "output": "1" }, { "input": "5\n2 4 3 1 2", "output": "-1" }, { "input": "5\n2 2 4 4 5", "output": "-1" }, { "input": "5\n2 4 5 4 2", "out...
109
21,504,000
3
10,661
468
Tree
[ "graph matchings" ]
null
null
Little X has a tree consisting of *n* nodes (they are numbered from 1 to *n*). Each edge of the tree has a positive length. Let's define the distance between two nodes *v* and *u* (we'll denote it *d*(*v*,<=*u*)) as the sum of the lengths of edges in the shortest path between *v* and *u*. A permutation *p* is a sequence of *n* distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*). Little X wants to find a permutation *p* such that sum is maximal possible. If there are multiple optimal permutations, he wants to find the lexicographically smallest one. Help him with the task!
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105). Each of the next *n*<=-<=1 lines contains three space separated integers *u**i*,<=<=*v**i*,<=*w**i* (1<=≤<=<=*u**i*,<=<=*v**i*<=≤<=<=*n*; 1<=≤<=<=*w**i*<=≤<=<=105), denoting an edge between nodes *u**i* and *v**i* with length equal to *w**i*. It is guaranteed that these edges form a tree.
In the first line print the maximum possible value of the described sum. In the second line print *n* integers, representing the lexicographically smallest permutation.
[ "2\n1 2 3\n", "5\n1 2 2\n1 3 3\n2 4 4\n2 5 5\n" ]
[ "6\n2 1\n", "32\n2 1 4 5 3\n" ]
none
[]
0
0
-1
10,662
57
Square Earth?
[ "dfs and similar", "greedy", "implementation" ]
A. Square Earth?
2
256
Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side *n*. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: (0,<=0), (*n*,<=0), (0,<=*n*) and (*n*,<=*n*).
The single line contains 5 space-separated integers: *n*,<=*x*1,<=*y*1,<=*x*2,<=*y*2 (1<=≤<=*n*<=≤<=1000,<=0<=≤<=*x*1,<=*y*1,<=*x*2,<=*y*2<=≤<=*n*) which correspondingly represent a side of the square, the coordinates of the first point and the coordinates of the second point. It is guaranteed that the points lie on the sides of the square.
You must print on a single line the shortest distance between the points.
[ "2 0 0 1 0\n", "2 0 1 2 1\n", "100 0 0 100 100\n" ]
[ "1\n", "4\n", "200\n" ]
none
[ { "input": "2 0 0 1 0", "output": "1" }, { "input": "2 0 1 2 1", "output": "4" }, { "input": "100 0 0 100 100", "output": "200" }, { "input": "4 0 3 1 4", "output": "2" }, { "input": "10 8 10 10 0", "output": "12" }, { "input": "26 21 0 26 14", "ou...
372
1,740,800
0
10,666
686
Little Robber Girl's Zoo
[ "constructive algorithms", "implementation", "sortings" ]
null
null
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places. The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers *l* and *r* such that *r*<=-<=*l*<=+<=1 is even. After that animals that occupy positions between *l* and *r* inclusively are rearranged as follows: the animal at position *l* swaps places with the animal at position *l*<=+<=1, the animal *l*<=+<=2 swaps with the animal *l*<=+<=3, ..., finally, the animal at position *r*<=-<=1 swaps with the animal *r*. Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20<=000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — number of animals in the robber girl's zoo. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is the height of the animal occupying the *i*-th place.
Print the sequence of operations that will rearrange the animals by non-decreasing height. The output should contain several lines, *i*-th of the lines should contain two space-separated integers *l**i* and *r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=*n*) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed. The number of operations should not exceed 20<=000. If the animals are arranged correctly from the start, you are allowed to output nothing.
[ "4\n2 1 4 3\n", "7\n36 28 57 39 66 69 68\n", "5\n1 2 1 2 1\n" ]
[ "1 4\n", "1 4\n6 7\n", "2 5\n3 4\n1 4\n1 4\n" ]
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
[ { "input": "4\n2 1 4 3", "output": "1 2\n3 4" }, { "input": "7\n36 28 57 39 66 69 68", "output": "1 2\n3 4\n6 7" }, { "input": "5\n1 2 1 2 1", "output": "2 3\n4 5\n3 4" }, { "input": "78\n7 3 8 8 9 8 10 9 12 11 16 14 17 17 18 18 20 20 25 22 27 26 29 27 35 35 36 36 37 37 38 38...
31
0
-1
10,674
946
Timetable
[ "dp" ]
null
null
Ivan is a student at Berland State University (BSU). There are *n* days in Berland week, and each of these days Ivan might have some classes at the university. There are *m* working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during *i*-th hour, and last lesson is during *j*-th hour, then he spends *j*<=-<=*i*<=+<=1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university. Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than *k* lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all. Given *n*, *m*, *k* and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than *k* lessons?
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*k*<=≤<=500) — the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively. Then *n* lines follow, *i*-th line containing a binary string of *m* characters. If *j*-th character in *i*-th line is 1, then Ivan has a lesson on *i*-th day during *j*-th hour (if it is 0, there is no such lesson).
Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than *k* lessons.
[ "2 5 1\n01001\n10110\n", "2 5 0\n01001\n10110\n" ]
[ "5\n", "8\n" ]
In the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day. In the second example Ivan can't skip any lessons, so he spends 4 hours every day.
[ { "input": "2 5 1\n01001\n10110", "output": "5" }, { "input": "2 5 0\n01001\n10110", "output": "8" }, { "input": "3 4 0\n0000\n0000\n0000", "output": "0" }, { "input": "3 4 12\n1111\n1111\n1111", "output": "0" }, { "input": "3 4 6\n1111\n1111\n1111", "output":...
764
7,884,800
3
10,689
41
Email address
[ "expression parsing", "implementation" ]
C. Email address
2
256
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([[email protected]](/cdn-cgi/l/email-protection)). It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots. You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result. Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.
The first line contains the email address description. It is guaranteed that that is a proper email address with all the dots replaced by dot an the at signs replaced by at. The line is not empty and its length does not exceed 100 symbols.
Print the shortest email address, from which the given line could be made by the described above replacements. If there are several solutions to that problem, print the lexicographically minimal one (the lexicographical comparison of the lines are implemented with an operator &lt; in modern programming languages). In the ASCII table the symbols go in this order: . @ ab...z
[ "vasyaatgmaildotcom\n", "dotdotdotatdotdotat\n", "aatt\n" ]
[ "[email protected]\n", "[email protected]\n", "a@t\n" ]
none
[ { "input": "vasyaatgmaildotcom", "output": "vasya@gmail.com" }, { "input": "dotdotdotatdotdotat", "output": "dot..@..at" }, { "input": "aatt", "output": "a@t" }, { "input": "zdotdotatdotz", "output": "z..@.z" }, { "input": "dotdotdotdotatdotatatatdotdotdot", "...
124
0
0
10,693
862
Mahmoud and Ehab and the xor
[ "constructive algorithms" ]
null
null
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets. Dr. Evil has his favorite evil integer *x*. He asks Mahmoud and Ehab to find a set of *n* distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly *x*. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
The only line contains two integers *n* and *x* (1<=≤<=*n*<=≤<=105, 0<=≤<=*x*<=≤<=105) — the number of elements in the set and the desired bitwise-xor, respectively.
If there is no such set, print "NO" (without quotes). Otherwise, on the first line print "YES" (without quotes) and on the second line print *n* distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
[ "5 5\n", "3 6\n" ]
[ "YES\n1 2 4 5 7", "YES\n1 2 5" ]
You can read more about the bitwise-xor operation here: [https://en.wikipedia.org/wiki/Bitwise_operation#XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) For the first sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/eb8ccd05d3a7a41eff93c98f79d158cf85e702f9.png" style="max-width: 100.0%;max-height: 100.0%;"/>. For the second sample <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d05d19f05b03f8ac89b7f86ef830eeccc0050c42.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "5 5", "output": "YES\n1 2 131072 131078 0 " }, { "input": "3 6", "output": "YES\n131072 131078 0 " }, { "input": "3 0", "output": "YES\n393216 131072 262144" }, { "input": "1 0", "output": "YES\n0" }, { "input": "3 3", "output": "YES\n131072 131075...
93
0
0
10,743
718
Efim and Strange Grade
[ "dp", "implementation", "math" ]
null
null
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are *t* seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than *t* seconds. Note, that he can choose to not use all *t* seconds. Moreover, he can even choose to not round the grade at all. In this problem, classic rounding rules are used: while rounding number to the *n*-th digit one has to take a look at the digit *n*<=+<=1. If it is less than 5 than the *n*-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the *n*<=+<=1 digit is greater or equal to 5, the digit at the position *n* is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away. For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.
The first line of the input contains two integers *n* and *t* (1<=≤<=*n*<=≤<=200<=000, 1<=≤<=*t*<=≤<=109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.
Print the maximum grade that Efim can get in *t* seconds. Do not print trailing zeroes.
[ "6 1\n10.245\n", "6 2\n10.245\n", "3 100\n9.2\n" ]
[ "10.25\n", "10.3\n", "9.2\n" ]
In the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect. In the third sample the optimal strategy is to not perform any rounding at all.
[ { "input": "6 1\n10.245", "output": "10.25" }, { "input": "6 2\n10.245", "output": "10.3" }, { "input": "3 100\n9.2", "output": "9.2" }, { "input": "12 5\n872.04488525", "output": "872.1" }, { "input": "35 8\n984227318.2031144444444444494637612", "output": "98...
155
1,024,000
3
10,790
255
Almost Arithmetical Progression
[ "brute force", "dp" ]
null
null
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: - *a*1<==<=*p*, where *p* is some integer; - *a**i*<==<=*a**i*<=-<=1<=+<=(<=-<=1)*i*<=+<=1·*q* (*i*<=&gt;<=1), where *q* is some integer. Right now Gena has a piece of paper with sequence *b*, consisting of *n* integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression. Sequence *s*1,<=<=*s*2,<=<=...,<=<=*s**k* is a subsequence of sequence *b*1,<=<=*b*2,<=<=...,<=<=*b**n*, if there is such increasing sequence of indexes *i*1,<=*i*2,<=...,<=*i**k* (1<=<=≤<=<=*i*1<=<=&lt;<=<=*i*2<=<=&lt;<=... <=<=&lt;<=<=*i**k*<=<=≤<=<=*n*), that *b**i**j*<=<==<=<=*s**j*. In other words, sequence *s* can be obtained from *b* by crossing out some elements.
The first line contains integer *n* (1<=≤<=*n*<=≤<=4000). The next line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=106).
Print a single integer — the length of the required longest subsequence.
[ "2\n3 5\n", "4\n10 20 10 30\n" ]
[ "2\n", "3\n" ]
In the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10.
[ { "input": "2\n3 5", "output": "2" }, { "input": "4\n10 20 10 30", "output": "3" }, { "input": "5\n4 4 3 5 1", "output": "2" }, { "input": "6\n2 3 2 2 1 3", "output": "4" }, { "input": "8\n2 2 5 3 4 3 3 2", "output": "3" }, { "input": "2\n468 335", ...
327
66,560,000
3
10,825
545
Toy Cars
[ "implementation" ]
null
null
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph. There are *n* toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an *n*<=×<=*n* matrix *А*: there is a number on the intersection of the *і*-th row and *j*-th column that describes the result of the collision of the *і*-th and the *j*-th car: - <=-<=1: if this pair of cars never collided. <=-<=1 occurs only on the main diagonal of the matrix. - 0: if no car turned over during the collision. - 1: if only the *i*-th car turned over during the collision. - 2: if only the *j*-th car turned over during the collision. - 3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of cars. Each of the next *n* lines contains *n* space-separated integers that determine matrix *A*. It is guaranteed that on the main diagonal there are <=-<=1, and <=-<=1 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if *A**ij*<==<=1, then *A**ji*<==<=2, if *A**ij*<==<=3, then *A**ji*<==<=3, and if *A**ij*<==<=0, then *A**ji*<==<=0.
Print the number of good cars and in the next line print their space-separated indices in the increasing order.
[ "3\n-1 0 0\n0 -1 1\n0 2 -1\n", "4\n-1 3 3 3\n3 -1 3 3\n3 3 -1 3\n3 3 3 -1\n" ]
[ "2\n1 3 ", "0\n" ]
none
[ { "input": "3\n-1 0 0\n0 -1 1\n0 2 -1", "output": "2\n1 3 " }, { "input": "4\n-1 3 3 3\n3 -1 3 3\n3 3 -1 3\n3 3 3 -1", "output": "0" }, { "input": "1\n-1", "output": "1\n1 " }, { "input": "2\n-1 0\n0 -1", "output": "2\n1 2 " }, { "input": "2\n-1 1\n2 -1", "out...
46
2,867,200
-1
10,828
929
Красивая команда
[ "*special", "combinatorics", "math" ]
null
null
Завтра у хоккейной команды, которой руководит Евгений, важный матч. Евгению нужно выбрать шесть игроков, которые выйдут на лед в стартовом составе: один вратарь, два защитника и три нападающих. Так как это стартовый состав, Евгения больше волнует, насколько красива будет команда на льду, чем способности игроков. А именно, Евгений хочет выбрать такой стартовый состав, чтобы номера любых двух игроков из стартового состава отличались не более, чем в два раза. Например, игроки с номерами 13, 14, 10, 18, 15 и 20 устроят Евгения, а если, например, на лед выйдут игроки с номерами 8 и 17, то это не устроит Евгения. Про каждого из игроков вам известно, на какой позиции он играет (вратарь, защитник или нападающий), а также его номер. В хоккее номера игроков не обязательно идут подряд. Посчитайте число различных стартовых составов из одного вратаря, двух защитников и трех нападающих, которые может выбрать Евгений, чтобы выполнялось его условие красоты.
Первая строка содержит три целых числа *g*, *d* и *f* (1<=≤<=*g*<=≤<=1<=000, 1<=≤<=*d*<=≤<=1<=000, 1<=≤<=*f*<=≤<=1<=000) — число вратарей, защитников и нападающих в команде Евгения. Вторая строка содержит *g* целых чисел, каждое в пределах от 1 до 100<=000 — номера вратарей. Третья строка содержит *d* целых чисел, каждое в пределах от 1 до 100<=000 — номера защитников. Четвертая строка содержит *f* целых чисел, каждое в пределах от 1 до 100<=000 — номера нападающих. Гарантируется, что общее количество игроков не превосходит 1<=000, т. е. *g*<=+<=*d*<=+<=*f*<=≤<=1<=000. Все *g*<=+<=*d*<=+<=*f* номеров игроков различны.
Выведите одно целое число — количество возможных стартовых составов.
[ "1 2 3\n15\n10 19\n20 11 13\n", "2 3 4\n16 40\n20 12 19\n13 21 11 10\n" ]
[ "1\n", "6\n" ]
В первом примере всего один вариант для выбора состава, который удовлетворяет описанным условиям, поэтому ответ 1. Во втором примере подходят следующие игровые сочетания (в порядке вратарь-защитник-защитник-нападающий-нападающий-нападающий): - 16 20 12 13 21 11 - 16 20 12 13 11 10 - 16 20 19 13 21 11 - 16 20 19 13 11 10 - 16 12 19 13 21 11 - 16 12 19 13 11 10 Таким образом, ответ на этот пример — 6.
[ { "input": "1 2 3\n15\n10 19\n20 11 13", "output": "1" }, { "input": "2 3 4\n16 40\n20 12 19\n13 21 11 10", "output": "6" }, { "input": "4 4 5\n15 16 19 6\n8 11 9 18\n5 3 1 12 14", "output": "0" }, { "input": "6 7 7\n32 35 26 33 16 23\n4 40 36 12 28 24 3\n39 11 31 37 1 25 6",...
405
28,467,200
-1
10,846
542
Playing on Graph
[ "graphs", "shortest paths" ]
null
null
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of *n* vertices and *m* edges without loops and multiple edges. Let's define the operation of contraction two vertices *a* and *b* that are not connected by an edge. As a result of this operation vertices *a* and *b* are deleted and instead of them a new vertex *x* is added into the graph, and also edges are drawn from it to all vertices that were connected with *a* or with *b* (specifically, if the vertex was connected with both *a* and *b*, then also exactly one edge is added from *x* to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (*n*<=-<=1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length *k* (*k*<=≥<=0) is a connected graph whose vertices can be numbered with integers from 1 to *k*<=+<=1 so that the edges of the graph connect all pairs of vertices (*i*,<=*i*<=+<=1) (1<=≤<=*i*<=≤<=*k*) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.
The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=1000, 0<=≤<=*m*<=≤<=100<=000) — the number of vertices and the number of edges in the original graph. Next *m* lines contain the descriptions of edges in the format *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*), which means that there is an edge between vertices *a**i* and *b**i*. It is guaranteed that there is at most one edge between each pair of vertexes.
If it is impossible to obtain a chain from the given graph, print <=-<=1. Otherwise, print the maximum possible number of edges in the resulting chain.
[ "5 4\n1 2\n2 3\n3 4\n3 5\n", "4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4\n", "4 2\n1 3\n2 4\n" ]
[ "3\n", "-1\n", "2\n" ]
In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
[ { "input": "5 4\n1 2\n2 3\n3 4\n3 5", "output": "3" }, { "input": "4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4", "output": "-1" }, { "input": "4 2\n1 3\n2 4", "output": "2" }, { "input": "1 0", "output": "0" }, { "input": "1000 0", "output": "0" }, { "input": "1...
155
2,252,800
0
10,849
724
Dense Subsequence
[ "data structures", "greedy", "strings" ]
null
null
You are given a string *s*, consisting of lowercase English letters, and the integer *m*. One should choose some symbols from the given string so that any contiguous subsegment of length *m* has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order. Formally, we choose a subsequence of indices 1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**t*<=≤<=|*s*|. The selected sequence must meet the following condition: for every *j* such that 1<=≤<=*j*<=≤<=|*s*|<=-<=*m*<=+<=1, there must be at least one selected index that belongs to the segment [*j*,<= *j*<=+<=*m*<=-<=1], i.e. there should exist a *k* from 1 to *t*, such that *j*<=≤<=*i**k*<=≤<=*j*<=+<=*m*<=-<=1. Then we take any permutation *p* of the selected indices and form a new string *s**i**p*1*s**i**p*2... *s**i**p**t*. Find the lexicographically smallest string, that can be obtained using this procedure.
The first line of the input contains a single integer *m* (1<=≤<=*m*<=≤<=100<=000). The second line contains the string *s* consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100<=000. It is also guaranteed that the number *m* doesn't exceed the length of the string *s*.
Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.
[ "3\ncbabc\n", "2\nabcab\n", "3\nbcabcbaccba\n" ]
[ "a\n", "aab\n", "aaabb\n" ]
In the first sample, one can choose the subsequence {3} and form a string "a". In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".
[ { "input": "3\ncbabc", "output": "a" }, { "input": "2\nabcab", "output": "aab" }, { "input": "3\nbcabcbaccba", "output": "aaabb" }, { "input": "5\nimmaydobun", "output": "ab" }, { "input": "5\nwjjdqawypvtgrncmqvcsergermprauyevcegjtcrrblkwiugrcjfpjyxngyryxntauxlouv...
62
4,608,000
0
10,894
952
2 + 2 != 4
[]
null
null
One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution...
The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive.
Reproduce the output of the reference solution, including the bug.
[ "8-7+6-5+4-3+2-1-0\n", "2+2\n", "112-37\n" ]
[ "4\n", "-46\n", "375\n" ]
none
[ { "input": "8-7+6-5+4-3+2-1-0", "output": "4" }, { "input": "2+2", "output": "-46" }, { "input": "112-37", "output": "375" }, { "input": "255+255+255+255+255+255+255+255+255+255", "output": "-42450" }, { "input": "0-255-255-255-255-255-255-255-255-255", "outpu...
31
0
0
10,917
351
Jeff and Permutation
[ "greedy" ]
null
null
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence *p*1,<=*p*2,<=...,<=*p**n* for his birthday. Jeff hates inversions in sequences. An inversion in sequence *a*1,<=*a*2,<=...,<=*a**n* is a pair of indexes *i*,<=*j* (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*), such that an inequality *a**i*<=&gt;<=*a**j* holds. Jeff can multiply some numbers of the sequence *p* by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000). The next line contains *n* integers — sequence *p*1, *p*2, ..., *p**n* (|*p**i*|<=≤<=105). The numbers are separated by spaces.
In a single line print the answer to the problem — the minimum number of inversions Jeff can get.
[ "2\n2 1\n", "9\n-2 0 -1 0 -1 2 1 0 -1\n" ]
[ "0\n", "6\n" ]
none
[ { "input": "2\n2 1", "output": "0" }, { "input": "9\n-2 0 -1 0 -1 2 1 0 -1", "output": "6" }, { "input": "9\n0 0 1 1 0 0 1 0 1", "output": "5" }, { "input": "8\n0 1 2 -1 -2 1 -2 2", "output": "3" }, { "input": "24\n-1 -1 2 2 0 -2 2 -1 0 0 2 -2 3 0 2 -3 0 -3 -1 1 0...
60
0
0
10,919
842
Ilya And The Tree
[ "dfs and similar", "graphs", "math", "number theory", "trees" ]
null
null
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex *i* is equal to *a**i*. Ilya believes that the beauty of the vertex *x* is the greatest common divisor of all numbers written on the vertices on the path from the root to *x*, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have. For each vertex the answer must be considered independently. The beauty of the root equals to number written on it.
First line contains one integer number *n* — the number of vertices in tree (1<=≤<=*n*<=≤<=2·105). Next line contains *n* integer numbers *a**i* (1<=≤<=*i*<=≤<=*n*, 1<=≤<=*a**i*<=≤<=2·105). Each of next *n*<=-<=1 lines contains two integer numbers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*, *x*<=≠<=*y*), which means that there is an edge (*x*,<=*y*) in the tree.
Output *n* numbers separated by spaces, where *i*-th number equals to maximum possible beauty of vertex *i*.
[ "2\n6 2\n1 2\n", "3\n6 2 3\n1 2\n1 3\n", "1\n10\n" ]
[ "6 6 \n", "6 6 6 \n", "10 \n" ]
none
[ { "input": "2\n6 2\n1 2", "output": "6 6 " }, { "input": "3\n6 2 3\n1 2\n1 3", "output": "6 6 6 " }, { "input": "1\n10", "output": "10 " }, { "input": "10\n2 3 4 5 6 7 8 9 10 11\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n4 8\n8 9\n9 10", "output": "2 3 2 1 1 1 1 1 1 1 " }, { ...
46
819,200
0
10,933