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
109
Lucky Tree
[ "dp", "dsu", "trees" ]
C. Lucky Tree
2
256
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya encountered a tree with *n* vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with *n* vertexes is an undirected connected graph that has exactly *n*<=-<=1 edges. Petya wondered how many vertex triples (*i*,<=*j*,<=*k*) exists that on the way from *i* to *j*, as well as on the way from *i* to *k* there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,<=2,<=3) is not equal to the triple (2,<=1,<=3) and is not equal to the triple (1,<=3,<=2). Find how many such triples of vertexes exist.
The first line contains the single integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of tree vertexes. Next *n*<=-<=1 lines contain three integers each: *u**i* *v**i* *w**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*,<=1<=≀<=*w**i*<=≀<=109) β€” the pair of vertexes connected by the edge and the edge's weight.
On the single line print the single number β€” the answer. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator.
[ "4\n1 2 4\n3 1 2\n1 4 7\n", "4\n1 2 4\n1 3 47\n1 4 7447\n" ]
[ "16\n", "24\n" ]
The 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2). In the second sample all the triples should be counted: 4Β·3Β·2 = 24.
[ { "input": "4\n1 2 4\n3 1 2\n1 4 7", "output": "16" }, { "input": "4\n1 2 4\n1 3 47\n1 4 7447", "output": "24" }, { "input": "9\n1 2 7\n1 3 12\n4 1 2\n4 5 4\n4 6 47\n4 7 9\n5 8 2\n5 9 1", "output": "282" }, { "input": "2\n1 2 7", "output": "0" }, { "input": "2\n2 ...
466
2,867,200
-1
116,334
180
Cubes
[ "binary search", "dp", "two pointers" ]
null
null
Let's imagine that you're playing the following simple computer game. The screen displays *n* lined-up cubes. Each cube is painted one of *m* colors. You are allowed to delete not more than *k* cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score. Remember, you may delete no more than *k* any cubes. It is allowed not to delete cubes at all.
The first line contains three integers *n*, *m* and *k* (1<=≀<=*n*<=≀<=2Β·105,<=1<=≀<=*m*<=≀<=105,<=0<=≀<=*k*<=&lt;<=*n*). The second line contains *n* integers from 1 to *m* β€” the numbers of cube colors. The numbers of colors are separated by single spaces.
Print the maximum possible number of points you can score.
[ "10 3 2\n1 2 1 1 3 2 1 1 2 2\n", "10 2 2\n1 2 1 2 1 1 2 1 1 2\n", "3 1 2\n1 1 1\n" ]
[ "4\n", "5\n", "3\n" ]
In the first sample you should delete the fifth and the sixth cubes. In the second sample you should delete the fourth and the seventh cubes. In the third sample you shouldn't delete any cubes.
[ { "input": "10 3 2\n1 2 1 1 3 2 1 1 2 2", "output": "4" }, { "input": "10 2 2\n1 2 1 2 1 1 2 1 1 2", "output": "5" }, { "input": "3 1 2\n1 1 1", "output": "3" }, { "input": "10 2 2\n1 1 1 2 1 2 1 2 1 1", "output": "5" }, { "input": "1 1 0\n1", "output": "1" ...
92
0
0
116,366
690
Recover Polygon (easy)
[]
null
null
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good. Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle. As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides).
The first line of each test case contains one integer *N*, the size of the lattice grid (5<=≀<=*N*<=≀<=50). The next *N* lines each contain *N* characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4. Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of *y* coordinate, and in one row cells go in the order of increasing *x* coordinate. This means that the first row corresponds to cells with coordinates (1,<=*N*),<=...,<=(*N*,<=*N*) and the last row corresponds to cells with coordinates (1,<=1),<=...,<=(*N*,<=1).
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
[ "6\n000000\n000000\n012100\n024200\n012100\n000000\n" ]
[ "Yes\n" ]
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (*x*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">1</sub>), (*x*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">2</sub>), (*x*<sub class="lower-index">2</sub>, *y*<sub class="lower-index">1</sub>), (*x*<sub class="lower-index">2</sub>, *y*<sub class="lower-index">2</sub>)), has a non-zero area and be contained inside of the grid (that is, 0 ≀ *x*<sub class="lower-index">1</sub> &lt; *x*<sub class="lower-index">2</sub> ≀ *N*, 0 ≀ *y*<sub class="lower-index">1</sub> &lt; *y*<sub class="lower-index">2</sub> ≀ *N*), and result in the levels of Zombie Contamination as reported in the input.
[ { "input": "6\n000000\n000000\n012100\n024200\n012100\n000000", "output": "Yes" }, { "input": "6\n000000\n012210\n024420\n012210\n000000\n000000", "output": "Yes" }, { "input": "6\n000100\n001210\n002420\n001210\n000000\n000000", "output": "No" }, { "input": "10\n0000000000\n...
62
0
0
116,804
346
Doodle Jump
[ "math", "number theory" ]
null
null
In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. β€” Wikipedia. It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to the limits of its jumping ability. Consider the following problem. There are *n* platforms. The height of the *x*-th (1<=≀<=*x*<=≀<=*n*) platform is *a*Β·*x* mod *p*, where *a* and *p* are positive co-prime integers. The maximum possible height of a Doodler's jump is *h*. That is, it can jump from height *h*1 to height *h*2 (*h*1<=&lt;<=*h*2) if *h*2<=-<=*h*1<=≀<=*h*. Initially, the Doodler is on the ground, the height of which is 0. The question is whether it can reach the highest platform or not. For example, when *a*<==<=7, *n*<==<=4, *p*<==<=12, *h*<==<=2, the heights of the platforms are 7, 2, 9, 4 as in the picture below. With the first jump the Doodler can jump to the platform at height 2, with the second one the Doodler can jump to the platform at height 4, but then it can't jump to any of the higher platforms. So, it can't reach the highest platform. User xiaodao thought about the problem for a long time but didn't solve it, so she asks you for help. Also, she has a lot of instances of the problem. Your task is solve all of these instances.
The first line contains an integer *t* (1<=≀<=*t*<=≀<=104) β€” the number of problem instances. Each of the next *t* lines contains four integers *a*, *n*, *p* and *h* (1<=≀<=*a*<=≀<=109, 1<=≀<=*n*<=&lt;<=*p*<=≀<=109, 0<=≀<=*h*<=≀<=109). It's guaranteed that *a* and *p* are co-prime.
For each problem instance, if the Doodler can reach the highest platform, output "YES", otherwise output "NO".
[ "3\n7 4 12 2\n7 1 9 4\n7 4 12 3\n" ]
[ "NO\nNO\nYES\n" ]
none
[]
2,000
102,400
0
116,910
546
Soldier and Badges
[ "brute force", "greedy", "implementation", "sortings" ]
null
null
Colonel has *n* badges. He wants to give one badge to every of his *n* soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.
First line of input consists of one integer *n* (1<=≀<=*n*<=≀<=3000). Next line consists of *n* integers *a**i* (1<=≀<=*a**i*<=≀<=*n*), which stand for coolness factor of each badge.
Output single integer β€” minimum amount of coins the colonel has to pay.
[ "4\n1 3 1 4\n", "5\n1 2 3 2 5\n" ]
[ "1", "2" ]
In first sample test we can increase factor of first badge by 1. In second sample test we can increase factors of the second and the third badge by 1.
[ { "input": "4\n1 3 1 4", "output": "1" }, { "input": "5\n1 2 3 2 5", "output": "2" }, { "input": "5\n1 5 3 2 4", "output": "0" }, { "input": "10\n1 1 2 3 4 5 6 7 8 9", "output": "9" }, { "input": "11\n9 2 10 3 1 5 7 1 4 8 6", "output": "10" }, { "input...
30
0
0
116,973
294
Shaass and Painter Robot
[ "brute force", "implementation", "number theory" ]
null
null
Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of *n*Β·*m* square tiles forming a *n*<=Γ—<=*m* rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color. Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (*x**s*,<=*y**s*) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted. The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor. Let's consider an examples depicted below. If the robot starts at tile number 1 (the tile (1,<=1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
The first line of the input contains two integers *n* and *m*, (2<=≀<=*n*,<=*m*<=≀<=105). The second line contains two integers *x**s* and *y**s* (1<=≀<=*x**s*<=≀<=*n*,<=1<=≀<=*y**s*<=≀<=*m*) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right). Note, that record (*x**s*,<=*y**s*) denotes the tile that is located at the *x**s*-th row from the top and at the *y**s*-th column from the left of the kitchen. It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
[ "3 4\n1 1 DR\n", "3 4\n3 3 DR\n", "3 3\n1 1 DR\n", "3 3\n1 2 DL\n" ]
[ "7\n", "11\n", "-1\n", "4\n" ]
none
[ { "input": "3 4\n1 1 DR", "output": "7" }, { "input": "3 4\n3 3 DR", "output": "11" }, { "input": "3 3\n1 1 DR", "output": "-1" }, { "input": "3 3\n1 2 DL", "output": "4" }, { "input": "2 5\n2 3 DR", "output": "7" }, { "input": "2 3\n2 3 DL", "outp...
60
0
0
117,186
246
Blood Cousins Return
[ "binary search", "data structures", "dfs and similar", "dp", "sortings" ]
null
null
Polycarpus got hold of a family tree. The found tree describes the family relations of *n* people, numbered from 1 to *n*. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number *a* a 1-ancestor of the man with a number *b*, if the man with a number *a* is a direct ancestor of the man with a number *b*. We call the man with a number *a* a *k*-ancestor (*k*<=&gt;<=1) of the man with a number *b*, if the man with a number *b* has a 1-ancestor, and the man with a number *a* is a (*k*<=-<=1)-ancestor of the 1-ancestor of the man with a number *b*. In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an *x*-ancestor of himself, for some *x*, *x*<=&gt;<=0). We call a man with a number *a* the *k*-son of the man with a number *b*, if the man with a number *b* is a *k*-ancestor of the man with a number *a*. Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote *m* pairs of numbers *v**i*, *k**i*. Help him to learn for each pair *v**i*, *k**i* the number of distinct names among all names of the *k**i*-sons of the man with number *v**i*.
The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of people in the tree. Next *n* lines contain the description of people in the tree. The *i*-th line contains space-separated string *s**i* and integer *r**i* (0<=≀<=*r**i*<=≀<=*n*), where *s**i* is the name of the man with a number *i*, and *r**i* is either the number of the direct ancestor of the man with a number *i* or 0, if the man with a number *i* has no direct ancestor. The next line contains a single integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of Polycarpus's records. Next *m* lines contain space-separated pairs of integers. The *i*-th line contains integers *v**i*, *k**i* (1<=≀<=*v**i*,<=*k**i*<=≀<=*n*). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
Print *m* whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
[ "6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1\n", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1\n" ]
[ "2\n2\n0\n1\n0\n", "1\n0\n0\n0\n2\n0\n0\n" ]
none
[ { "input": "6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "output": "2\n2\n0\n1\n0" }, { "input": "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1", "output": "1\n0\n0\n0\n2\n0\n0" }, { "input":...
62
307,200
-1
117,922
33
Helper
[]
E. Helper
2
256
It's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a *list* of subjects that he can help with. Having spoken with *n* of his groupmates, Valera found out the following information about them: what subject each of them passes, time of the exam and sum of money that each person is ready to pay for Valera's help. Having this data, Valera's decided to draw up a timetable, according to which he will solve problems for his groupmates. For sure, Valera can't solve problems round the clock, that's why he's found for himself an optimum order of day and plans to stick to it during the whole exam period. Valera assigned time segments for sleep, breakfast, lunch and dinner. The rest of the time he can work. Obviously, Valera can help a student with some subject, only if this subject is on the *list*. It happened, that all the students, to whom Valera spoke, have different, but one-type problems, that's why Valera can solve any problem of subject *list**i* in *t**i* minutes. Moreover, if Valera starts working at some problem, he can break off only for sleep or meals, but he can't start a new problem, not having finished the current one. Having solved the problem, Valera can send it instantly to the corresponding student via the Internet. If this student's exam hasn't started yet, he can make a crib, use it to pass the exam successfully, and pay Valera the promised sum. Since Valera has little time, he asks you to write a program that finds the order of solving problems, which can bring Valera maximum profit.
The first line contains integers *m*,<=*n*,<=*k* (1<=≀<=*m*,<=*n*<=≀<=100, 1<=≀<=*k*<=≀<=30) β€” amount of subjects on the *list*, amount of Valera's potential employers and the duration of the exam period in days. The following *m* lines contain the names of subjects *list**i* (*list**i* is a non-empty string of at most 32 characters, consisting of lower case Latin letters). It's guaranteed that no two subjects are the same. The (*m*<=+<=2)-th line contains *m* integers *t**i* (1<=≀<=*t**i*<=≀<=1000) β€” time in minutes that Valera spends to solve problems of the *i*-th subject. Then follow four lines, containing time segments for sleep, breakfast, lunch and dinner correspondingly. Each line is in format H1:M1-H2:M2, where 00<=≀<= H1, H2 <=≀<=23, 00<=≀<= M1, M2 <=≀<=59. Time H1:M1 stands for the first minute of some Valera's action, and time H2:M2 stands for the last minute of this action. No two time segments cross. It's guaranteed that Valera goes to bed before midnight, gets up earlier than he has breakfast, finishes his breakfast before lunch, finishes his lunch before dinner, and finishes his dinner before midnight. All these actions last less than a day, but not less than one minute. Time of the beginning and time of the ending of each action are within one and the same day. But it's possible that Valera has no time for solving problems. Then follow *n* lines, each containing the description of students. For each student the following is known: his exam subject *s**i* (*s**i* is a non-empty string of at most 32 characters, consisting of lower case Latin letters), index of the exam day *d**i* (1<=≀<=*d**i*<=≀<=*k*), the exam time *time**i*, and sum of money *c**i* (0<=≀<=*c**i*<=≀<=106, *c**i* β€” integer) that he's ready to pay for Valera's help. Exam time *time**i* is in the format HH:MM, where 00<=≀<= HH <=≀<=23, 00<=≀<= MM <=≀<=59. Valera will get money, if he finishes to solve the problem strictly before the corresponding student's exam begins.
In the first line output the maximum profit that Valera can get. The second line should contain number *p* β€” amount of problems that Valera is to solve. In the following *p* lines output the order of solving problems in chronological order in the following format: index of a student, to whom Valera is to help; index of the time, when Valera should start the problem; time, when Valera should start the problem (the first minute of his work); index of the day, when Valera should finish the problem; time, when Valera should finish the problem (the last minute of his work). To understand the output format better, study the sample tests.
[ "3 3 4\ncalculus\nalgebra\nhistory\n58 23 15\n00:00-08:15\n08:20-08:35\n09:30-10:25\n19:00-19:45\ncalculus 1 09:36 100\nenglish 4 21:15 5000\nhistory 1 19:50 50\n", "2 2 1\nmatan\ncodeforces\n1 2\n00:00-08:00\n09:00-09:00\n12:00-12:00\n18:00-18:00\ncodeforces 1 08:04 2\nmatan 1 08:02 1\n", "2 2 1\nmatan\ncodefo...
[ "150\n2\n1 1 08:16 1 09:29\n3 1 10:26 1 10:40\n", "3\n2\n2 1 08:01 1 08:01\n1 1 08:02 1 08:03\n", "2\n1\n1 1 08:01 1 08:02\n" ]
none
[]
124
6,656,000
0
117,936
46
Comb
[ "data structures", "dp" ]
E. Comb
1
256
Having endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table *n*<=Γ—<=*m* panels in size with integers written on the panels. There also was a huge number of stones lying by the wall. On the pillar near the table Lara found a guidance note which said that to get hold of the treasures one has to choose some non-zero number of the first panels in each row of the table and put stones on all those panels to push them down. After that she will receive a number of golden coins equal to the sum of numbers written on the chosen panels. Lara quickly made up her mind on how to arrange the stones and was about to start when she noticed an addition to the note in small font below. According to the addition, for the room ceiling not to crush and smash the adventurer, the chosen panels should form a comb. It was explained that the chosen panels form a comb when the sequence *c*1,<=*c*2,<=...,<=*c**n* made from the quantities of panels chosen in each table line satisfies the following property: *c*1<=&gt;<=*c*2<=&lt;<=*c*3<=&gt;<=*c*4<=&lt;<=..., i.e. the inequation mark interchanges between the neighboring elements. Now Lara is bewildered and doesn't know what to do. Help her to determine the largest number of coins she can get and survive at the same time.
The first line contains a pair of integers *n*,<=*m* (2<=≀<=*n*,<=*m*<=≀<=1500). Next *n* lines contain *m* integers each β€” that is the table itself. The absolute value of the numbers in the table does not exceed 10000.
Print the single number β€” the maximum number of coins Lara can get.
[ "2 2\n-1 2\n1 3\n" ]
[ "2\n" ]
none
[]
46
0
0
117,967
309
Morning run
[ "binary search", "math", "two pointers" ]
null
null
People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly *l* meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning. The stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed β€” exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet. The company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by *t* time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for *t* time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once.
The first line of the input contains three integers *n*, *l*, *t* (1<=≀<=*n*<=≀<=106,<=1<=≀<=*l*<=≀<=109,<=1<=≀<=*t*<=≀<=109). The next line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*<=&lt;<=*l*), here *a**i* is the clockwise distance from the start line to the *i*-th runner's starting position.
Print a single real number β€” the answer to the problem with absolute or relative error of at most 10<=-<=6.
[ "2 5 1\n0 2\n", "3 7 3\n0 1 6\n" ]
[ "0.2500000000\n", "1.5000000000\n" ]
There are two runners in the first example. If the first runner run clockwise direction, then in 1 time unit he will be 1m away from the start line. If the second runner run counter-clockwise direction then in 1 time unit he will be also 1m away from the start line. And it is the only possible way to meet. We assume that each running direction is equiprobable, so the answer for the example is equal to 0.5Β·0.5 = 0.25.
[]
0
0
-1
118,499
509
Pretty Song
[ "math", "strings" ]
null
null
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title. Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word. Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word. More formally, let's define the function *vowel*(*c*) which is equal to 1, if *c* is a vowel, and to 0 otherwise. Let *s**i* be the *i*-th character of string *s*, and *s**i*..*j* be the substring of word *s*, staring at the *i*-th character and ending at the *j*-th character (*s**is**i*<=+<=1... *s**j*, *i*<=≀<=*j*). Then the simple prettiness of *s* is defined by the formula: The prettiness of *s* equals Find the prettiness of the given song title. We assume that the vowels are *I*,<=*E*,<=*A*,<=*O*,<=*U*,<=*Y*.
The input contains a single string *s* (1<=≀<=|*s*|<=≀<=5Β·105) β€” the title of the song.
Print the prettiness of the song with the absolute or relative error of at most 10<=-<=6.
[ "IEAIAIO\n", "BYOB\n", "YISVOWEL\n" ]
[ "28.0000000\n", "5.8333333\n", "17.0500000\n" ]
In the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.
[ { "input": "IEAIAIO", "output": "28.0000000" }, { "input": "BYOB", "output": "5.8333333" }, { "input": "YISVOWEL", "output": "17.0500000" }, { "input": "EZYYOIYUZXEVRTOUYXIQ", "output": "124.0168163" }, { "input": "MTOESEPRFEIWAIWLAFJMGBIQB", "output": "127.22...
171
34,406,400
3
118,557
615
Running Track
[ "dp", "greedy", "strings", "trees" ]
null
null
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art. First, he wants to construct the running track with coating *t*. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string. Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings *s*. Also, he has scissors and glue. Ayrat is going to buy some coatings *s*, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating *s* he needs to buy in order to get the coating *t* for his running track. Of course, he also want's to know some way to achieve the answer.
First line of the input contains the string *s*Β β€” the coating that is present in the shop. Second line contains the string *t*Β β€” the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.
The first line should contain the minimum needed number of coatings *n* or -1 if it's impossible to create the desired coating. If the answer is not -1, then the following *n* lines should contain two integers *x**i* and *y**i*Β β€” numbers of ending blocks in the corresponding piece. If *x**i*<=≀<=*y**i* then this piece is used in the regular order, and if *x**i*<=&gt;<=*y**i* piece is used in the reversed order. Print the pieces in the order they should be glued to get the string *t*.
[ "abc\ncbaabc\n", "aaabrytaaa\nayrat\n", "ami\nno\n" ]
[ "2\n3 1\n1 3\n", "3\n1 1\n6 5\n8 7\n", "-1\n" ]
In the first sample string "cbaabc" = "cba" + "abc". In the second sample: "ayrat" = "a" + "yr" + "at".
[ { "input": "abc\ncbaabc", "output": "2\n3 1\n1 3" }, { "input": "aaabrytaaa\nayrat", "output": "3\n1 1\n6 5\n8 7" }, { "input": "ami\nno", "output": "-1" }, { "input": "r\nr", "output": "1\n1 1" }, { "input": "r\nb", "output": "-1" }, { "input": "randb...
140
3,072,000
3
118,786
0
none
[ "none" ]
null
null
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z". The testtube is divided into *n* consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of *n* Latin characters. Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place. For example, consider a testtube with population "babb". There are six options for an attack that may happen next: - the first colony attacks the second colony (1<=β†’<=2), the resulting population is "bbbb";- 2<=β†’<=1, the result is "aabb";- 2<=β†’<=3, the result is "baab";- 3<=β†’<=2, the result is "bbbb" (note that the result is the same as the first option);- 3<=β†’<=4 or 4<=β†’<=3, the population does not change. The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109<=+<=7.
The first line contains an integer *n*Β β€” the number of regions in the testtube (1<=≀<=*n*<=≀<=5<=000). The second line contains *n* small Latin letters that describe the initial population of the testtube.
Print one numberΒ β€” the answer to the problem modulo 109<=+<=7.
[ "3\naaa\n", "2\nab\n", "4\nbabb\n", "7\nabacaba\n" ]
[ "1\n", "3\n", "11\n", "589\n" ]
In the first sample the population can never change since all bacteria are of the same type. In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony). To get the answer for the third sample, note that more than one attack can happen.
[]
30
0
0
119,086
305
Playing with String
[ "games" ]
null
null
Two people play the following string game. Initially the players have got some string *s*. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. A player's move is the sequence of actions: 1. The player chooses one of the available pieces of paper with some string written on it. Let's denote it is *t*. Note that initially, only one piece of paper is available. 1. The player chooses in the string *t*<==<=*t*1*t*2... *t*|*t*| character in position *i* (1<=≀<=*i*<=≀<=|*t*|) such that for some positive integer *l* (0<=&lt;<=*i*<=-<=*l*;Β *i*<=+<=*l*<=≀<=|*t*|) the following equations hold: *t**i*<=-<=1<==<=*t**i*<=+<=1, *t**i*<=-<=2<==<=*t**i*<=+<=2, ..., *t**i*<=-<=*l*<==<=*t**i*<=+<=*l*. 1. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string *t*1*t*2... *t**i*<=-<=1, the second one will contain a string consisting of a single character *t**i*, the third one contains string *t**i*<=+<=1*t**i*<=+<=2... *t*|*t*|. Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.
The first line contains string *s* (1<=≀<=|*s*|<=≀<=5000). It is guaranteed that string *s* only contains lowercase English letters.
If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move β€” integer *i* (1<=≀<=*i*<=≀<=|*s*|).
[ "abacaba\n", "abcde\n" ]
[ "First\n2\n", "Second\n" ]
In the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.
[ { "input": "abacaba", "output": "First\n2" }, { "input": "abcde", "output": "Second" }, { "input": "aaaaa", "output": "First\n3" }, { "input": "aaabbbbbbbbabaaabbaabbbbabbabaabaabbbaabbbbbbabbbabaabaaabaaaabbaaabbbbaabbbaaabababbbbabbabbabaaaaabababbbaabbbaabababaaabababbaaaa...
78
0
0
119,116
720
Array Covering
[ "data structures" ]
null
null
Misha has an array of integers of length *n*. He wants to choose *k* different continuous subarrays, so that each element of the array belongs to at least one of the chosen subarrays. Misha wants to choose the subarrays in such a way that if he calculated the sum of elements for each subarray, and then add up all these sums, the resulting value was maximum possible.
The first line of input contains two integers: *n*, *k* (1<=≀<=*n*<=≀<=100<=000, 1<=≀<=*k*<=≀<=*n*Β·(*n*<=+<=1)<=/<=2)Β β€” the number of elements in the array and the number of different subarrays that must be chosen. The second line contains *n* integers *a**i* (<=-<=50<=000<=≀<=*a**i*<=≀<=50<=000)Β β€” the elements of the array.
Output one integerΒ β€” the maximum possible value Misha can get by choosing *k* different subarrays.
[ "5 4\n6 -4 -10 -4 7\n" ]
[ "11\n" ]
none
[]
46
0
0
119,266
414
Mashmokh's Designed Problem
[ "data structures" ]
null
null
After a lot of trying, Mashmokh designed a problem and it's your job to solve it. You have a tree *T* with *n* vertices. Each vertex has a unique index from 1 to *n*. The root of *T* has index 1. For each vertex of this tree *v*, you are given a list of its children in a specific order. You must perform three types of query on this tree: 1. find distance (the number of edges in the shortest path) between *u* and *v*; 1. given *v* and *h*, disconnect *v* from its father and connect it to its *h*-th ancestor; more formally, let's denote the path from *v* to the root by *x*1,<=*x*2,<=...,<=*x**l*Β (*h*<=&lt;<=*l*), so that *x*1<==<=*v* and *x**l* is root; disconnect *v* from its father (*x*2) and connect it to *x**h*<=+<=1; vertex *v* must be added to the end of the child-list of vertex *x**h*<=+<=1; 1. in the vertex sequence produced by calling function dfs(root) find the latest vertex that has distance *k* from the root. The pseudo-code of function dfs(v):
The first line of input contains two space-separated integers *n*,<=*m*Β (2<=≀<=*n*<=≀<=105;Β 1<=≀<=*m*<=≀<=105), the number of vertices of *T* and number of queries to perform. The *i*-th of the following *n* lines contains an integer *l**i*Β (0<=≀<=*l**i*<=≀<=*n*), number of *i*-th vertex's children. Then *l**i* space-separated integers follow, the *j*-th of them is the index of *j*-th child of *i*-th vertex. Note that the order of these vertices is important. Each of the following *m* lines has one of the following format: "1 *v* *u*", "2 *v* *h*", or "3 *k*". The first number in the line is the type of query to perform according to the problem statement. The next numbers are description of the query. It's guaranteed that all the queries are correct. For example, in the second-type query *h* is at least 2 and at most distance of *v* from root. Also in the third-type query there is at least one vertex with distance *k* from the root at the time the query is given.
For each query of the first or third type output one line containing the result of the query.
[ "4 9\n1 2\n1 3\n1 4\n0\n1 1 4\n2 4 2\n1 3 4\n3 1\n3 2\n2 3 2\n1 1 2\n3 1\n3 2\n", "2 2\n1 2\n0\n1 2 1\n3 1\n" ]
[ "3\n2\n2\n4\n1\n3\n4\n", "1\n2\n" ]
none
[]
46
0
0
119,322
753
Interactive Bulls and Cows (Hard)
[ "brute force", "constructive algorithms", "interactive" ]
null
null
The only difference from the previous problem is the constraint on the number of requests. In this problem your program should guess the answer doing at most 7 requests. This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java β€” call System.out.flush(), and in Pascal β€” flush(output). Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind. On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed. Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers β€” the number of "bulls" and the number of "cows". A try can contain equal digits. More formally, let's the secret string is *s* and the second player are trying to guess it with a string *x*. The number of "bulls" is a number of such positions *i* (1<=≀<=*i*<=≀<=4) where *s*[*i*]<==<=*x*[*i*]. The number of "cows" is a number of such digits *c* that *s* contains *c* in the position *i* (i.e. *s*[*i*]<==<=*c*), *x* contains *c*, but *x*[*i*]<=β‰ <=*c*. For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow. In this problem you are to guess the string *s* that the system has chosen. You only know that the chosen string consists of 4 distinct digits. You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons β€” the program either guessed the number *x* or made an invalid action (for example, printed letters instead of digits). Your program is allowed to do at most 7 queries. You can hack solutions of other participants providing a 4-digit string containing distinct digits β€” the secret string.
To read answers to the queries, the program must use the standard input. The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string *s* and the string *x**i* printed by your program. If the system response equals "4 0", then your solution should terminate. The testing system will let your program read the *i*-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value *x**i* in a single line and executes operation flush.
The program must use the standard output to print queries. Your program must output requests β€” 4-digit strings *x*1,<=*x*2,<=..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input. Your program is allowed to do at most 7 queries.
[ "0 1\n2 0\n1 1\n0 4\n2 1\n4 0\n" ]
[ "8000\n0179\n3159\n3210\n0112\n0123" ]
The secret string *s* in the example is "0123".
[ { "input": "0123", "output": "1" }, { "input": "1234", "output": "4" }, { "input": "9876", "output": "5" }, { "input": "7158", "output": "3" }, { "input": "7590", "output": "7" }, { "input": "7325", "output": "5" }, { "input": "7524", "...
0
0
-1
120,039
442
Gena and Second Distance
[ "geometry" ]
null
null
Gena doesn't like geometry, so he asks you to solve this problem for him. A rectangle with sides parallel to coordinate axes contains *n* dots. Let's consider some point of the plane. Let's count the distances from this point to the given *n* points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum. Find the maximum beauty of a point inside the given rectangle.
The first line contains three integers *w*,<=*h*,<=*n* (1<=≀<=*w*,<=*h*<=≀<=106,<=2<=≀<=*n*<=≀<=1000) β€” the lengths of the rectangle sides and the number of points. Next *n* lines contain two integers *x**i*,<=*y**i* (0<=≀<=*x**i*<=≀<=*w*,<=0<=≀<=*y**i*<=≀<=*h*) each β€” the coordinates of a point. It is possible that it will be coincident points.
Print a single number β€” the maximum beauty of a point with the absolute or relative error of at most 10<=-<=9.
[ "5 5 4\n0 0\n5 0\n0 5\n5 5\n", "5 5 3\n4 0\n2 5\n4 1\n" ]
[ "4.99999999941792340\n", "5.65685424744772010\n" ]
The point which beauty we need to find must have coordinates (*x*, *y*), where 0 ≀ *x* ≀ *w*, 0 ≀ *y* ≀ *h*. Some of the *n* points can coincide.
[]
46
0
0
120,238
855
Helga Hufflepuff's Cup
[ "dp", "trees" ]
null
null
Harry, Ron and Hermione have figured out that Helga Hufflepuff's cup is a horcrux. Through her encounter with Bellatrix Lestrange, Hermione came to know that the cup is present in Bellatrix's family vault in Gringott's Wizarding Bank. The Wizarding bank is in the form of a tree with total *n* vaults where each vault has some type, denoted by a number between 1 to *m*. A tree is an undirected connected graph with no cycles. The vaults with the highest security are of type *k*, and all vaults of type *k* have the highest security. There can be at most *x* vaults of highest security. Also, if a vault is of the highest security, its adjacent vaults are guaranteed to not be of the highest security and their type is guaranteed to be less than *k*. Harry wants to consider every possibility so that he can easily find the best path to reach Bellatrix's vault. So, you have to tell him, given the tree structure of Gringotts, the number of possible ways of giving each vault a type such that the above conditions hold.
The first line of input contains two space separated integers, *n* and *m*Β β€” the number of vaults and the number of different vault types possible. (1<=≀<=*n*<=≀<=105,<=1<=≀<=*m*<=≀<=109). Each of the next *n*<=-<=1 lines contain two space separated integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*) representing the *i*-th edge, which shows there is a path between the two vaults *u**i* and *v**i*. It is guaranteed that the given graph is a tree. The last line of input contains two integers *k* and *x* (1<=≀<=*k*<=≀<=*m*,<=1<=≀<=*x*<=≀<=10), the type of the highest security vault and the maximum possible number of vaults of highest security.
Output a single integer, the number of ways of giving each vault a type following the conditions modulo 109<=+<=7.
[ "4 2\n1 2\n2 3\n1 4\n1 2\n", "3 3\n1 2\n1 3\n2 1\n", "3 1\n1 2\n1 3\n1 1\n" ]
[ "1\n", "13\n", "0\n" ]
In test case 1, we cannot have any vault of the highest security as its type is 1 implying that its adjacent vaults would have to have a vault type less than 1, which is not allowed. Thus, there is only one possible combination, in which all the vaults have type 2.
[ { "input": "4 2\n1 2\n2 3\n1 4\n1 2", "output": "1" }, { "input": "3 3\n1 2\n1 3\n2 1", "output": "13" }, { "input": "3 1\n1 2\n1 3\n1 1", "output": "0" }, { "input": "3 1000000000\n2 3\n3 1\n585430050 9", "output": "91592837" }, { "input": "4 50000\n2 1\n4 2\n2 3...
46
29,081,600
0
120,350
0
none
[ "none" ]
null
null
The German University in Cairo (GUC) dorm houses are numbered from 1 to *n*. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle). For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house. In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
The first line contains two space-separated integers *n* and *p* (1<=≀<=*n*<=≀<=1000,<=0<=≀<=*p*<=≀<=*n*) β€” the number of houses and the number of pipes correspondingly. Then *p* lines follow β€” the description of *p* pipes. The *i*-th line contains three integers *a**i* *b**i* *d**i*, indicating a pipe of diameter *d**i* going from house *a**i* to house *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*,<=1<=≀<=*d**i*<=≀<=106). It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it.
Print integer *t* in the first line β€” the number of tank-tap pairs of houses. For the next *t* lines, print 3 integers per line, separated by spaces: *tank**i*, *tap**i*, and *diameter**i*, where *tank**i*<=β‰ <=*tap**i* (1<=≀<=*i*<=≀<=*t*). Here *tank**i* and *tap**i* are indexes of tank and tap houses respectively, and *diameter**i* is the maximum amount of water that can be conveyed. All the *t* lines should be ordered (increasingly) by *tank**i*.
[ "3 2\n1 2 10\n2 3 20\n", "3 3\n1 2 20\n2 3 10\n3 1 5\n", "4 2\n1 2 60\n3 4 50\n" ]
[ "1\n1 3 10\n", "0\n", "2\n1 2 60\n3 4 50\n" ]
none
[ { "input": "3 2\n1 2 10\n2 3 20", "output": "1\n1 3 10" }, { "input": "3 3\n1 2 20\n2 3 10\n3 1 5", "output": "0" }, { "input": "4 2\n1 2 60\n3 4 50", "output": "2\n1 2 60\n3 4 50" }, { "input": "10 10\n10 3 70\n1 9 98\n9 10 67\n5 2 78\n8 6 71\n4 8 95\n7 1 10\n2 5 73\n6 7 94\...
46
0
0
120,793
650
Zip-line
[ "binary search", "data structures", "dp", "hashing" ]
null
null
Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them. It is known that the forest consists of *n* trees staying in a row numbered from left to right with integers from 1 to *n*. According to Vasya, the height of the *i*-th tree is equal to *h**i*. The zip-line of length *k* should hang over *k* (1<=≀<=*k*<=≀<=*n*) trees *i*1,<=*i*2,<=...,<=*i**k* (*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*) such that their heights form an increasing sequence, that is *h**i*1<=&lt;<=*h**i*2<=&lt;<=...<=&lt;<=*h**i**k*. Petya had been in this forest together with Vasya, and he now has *q* assumptions about the mistake in Vasya's sequence *h*. His *i*-th assumption consists of two integers *a**i* and *b**i* indicating that, according to Petya, the height of the tree numbered *a**i* is actually equal to *b**i*. Note that Petya's assumptions are independent from each other. Your task is to find the maximum length of a zip-line that can be built over the trees under each of the *q* assumptions. In this problem the length of a zip line is considered equal to the number of trees that form this zip-line.
The first line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=400<=000)Β β€” the number of the trees in the forest and the number of Petya's assumptions, respectively. The following line contains *n* integers *h**i* (1<=≀<=*h**i*<=≀<=109)Β β€” the heights of trees according to Vasya. Each of the following *m* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*<=≀<=*n*, 1<=≀<=*b**i*<=≀<=109).
For each of the Petya's assumptions output one integer, indicating the maximum length of a zip-line that can be built under this assumption.
[ "4 4\n1 2 3 4\n1 1\n1 4\n4 3\n4 5\n", "4 2\n1 3 2 6\n3 5\n2 4\n" ]
[ "4\n3\n3\n4\n", "4\n3\n" ]
Consider the first sample. The first assumption actually coincides with the height remembered by Vasya. In the second assumption the heights of the trees are (4, 2, 3, 4), in the third one they are (1, 2, 3, 3) and in the fourth one they are (1, 2, 3, 5).
[]
3,000
28,262,400
0
120,838
566
Logistical Questions
[ "dfs and similar", "divide and conquer", "trees" ]
null
null
Some country consists of *n* cities, connected by a railroad network. The transport communication of the country is so advanced that the network consists of a minimum required number of (*n*<=-<=1) bidirectional roads (in the other words, the graph of roads is a tree). The *i*-th road that directly connects cities *a**i* and *b**i*, has the length of *l**i* kilometers. The transport network is served by a state transporting company FRR (Fabulous Rail Roads). In order to simplify the price policy, it offers a single ride fare on the train. In order to follow the route of length *t* kilometers, you need to pay burles. Note that it is forbidden to split a long route into short segments and pay them separately (a special railroad police, or RRP, controls that the law doesn't get violated). A Large Software Company decided to organize a programming tournament. Having conducted several online rounds, the company employees determined a list of finalists and sent it to the logistical department to find a place where to conduct finals. The Large Software Company can easily organize the tournament finals in any of the *n* cities of the country, so the the main factor in choosing the city for the last stage of the tournament is the total cost of buying tickets for all the finalists. We know that the *i*-th city of the country has *w**i* cup finalists living there. Help the company employees find the city such that the total cost of travel of all the participants to it is minimum.
The first line of the input contains number *n* (1<=≀<=*n*<=≀<=200<=000) β€” the number of cities in the country. The next line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (0<=≀<=*w**i*<=≀<=108) β€” the number of finalists living in each city of the country. Next (*n*<=-<=1) lines contain the descriptions of the railroad, the *i*-th line contains three integers, *a**i*, *b**i*, *l**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a**i*<=β‰ <=*b**i*, 1<=≀<=*l**i*<=≀<=1000).
Print two numbers β€” an integer *f* that is the number of the optimal city to conduct the competition, and the real number *c*, equal to the minimum total cost of transporting all the finalists to the competition. Your answer will be considered correct if two conditions are fulfilled at the same time: 1. The absolute or relative error of the printed number *c* in comparison with the cost of setting up a final in city *f* doesn't exceed 10<=-<=6; 1. Absolute or relative error of the printed number *c* in comparison to the answer of the jury doesn't exceed 10<=-<=6. If there are multiple answers, you are allowed to print any of them.
[ "5\n3 1 2 6 5\n1 2 3\n2 3 1\n4 3 9\n5 3 1\n", "2\n5 5\n1 2 2\n" ]
[ "3 192.0", "1 14.142135623730951000\n" ]
In the sample test an optimal variant of choosing a city to conduct the finals of the competition is 3. At such choice the cost of conducting is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4219dfaeaed77b348dc7ca0c500739d1c0ff9e3f.png" style="max-width: 100.0%;max-height: 100.0%;"/> burles. In the second sample test, whatever city you would choose, you will need to pay for the transport for five participants, so you will need to pay <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bec9396b77dab4487d19f32c85b0edb26924da8c.png" style="max-width: 100.0%;max-height: 100.0%;"/> burles for each one of them.
[]
2,000
716,800
0
121,034
161
Polycarpus the Safecracker
[ "brute force", "dp" ]
null
null
Polycarpus has *t* safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them. Polycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote a prime number in each row of each matrix. To his surprise, he found that all the matrices turned out to be symmetrical (that is, they remain the same after transposition). Now, years later, Polycarp was irritated to find out that he remembers only the prime numbers *p**i*, written in the first lines of the password matrices. For each safe find the number of matrices which can be passwords to it. The number of digits in *p**i* determines the number of rows and columns of the *i*-th matrix. One prime number can occur in several rows of the password matrix or in several matrices. The prime numbers that are written not in the first row of the matrix may have leading zeros.
The first line of the input contains an integer *t* (1<=≀<=*t*<=≀<=30) β€” the number of safes. Next *t* lines contain integers *p**i* (10<=≀<=*p**i*<=≀<=99999), *p**i* is a prime number written in the first row of the password matrix for the *i*-th safe. All *p**i*'s are written without leading zeros.
Print *t* numbers, the *i*-th of them should be the number of matrices that can be a password to the *i*-th safe. Print the numbers on separate lines.
[ "4\n11\n239\n401\n9001\n" ]
[ "4\n28\n61\n2834\n" ]
Here is a possible password matrix for the second safe: Here is a possible password matrix for the fourth safe:
[]
92
0
0
121,048
54
Writing a Song
[ "brute force", "dp", "strings" ]
D. Writing a Song
2
256
One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names. The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song! The problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first *K* letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word). The resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name *P*, the length *N* of the required word, the given positions of the occurrences of the name *P* in the desired word and the alphabet's size *K*. Note that the occurrences of the name can overlap with each other.
The first line contains numbers *N* and *K* which are the length of the required string and the alphabet size accordingly. The limitations are: 1<=≀<=*N*<=≀<=100, 2<=≀<=*K*<=≀<=26. The second line contains the name *P* which is a non-empty string whose length does not exceed *N* characters. The string consists only of the first *K* lowercase symbols of an English alphabet. The third line contains the string of length *N*<=-<=*length*(*P*)<=+<=1, consisting only of numbers zero and one. A number one in the *i*-th position means that an occurrence of the name *P* should start from *i*-th position of the desired word, while a zero means that there is no occurrence starting here.
Print the desired word *S*. If there are several answers, print any of them. If there is no solution, then print "No solution".
[ "5 2\naba\n101\n", "5 2\na\n10001\n", "6 2\nabba\n101\n" ]
[ "ababa", "abbba", "No solution" ]
none
[ { "input": "5 2\naba\n101", "output": "ababa" }, { "input": "5 2\na\n10001", "output": "abbba" }, { "input": "6 2\nabba\n101", "output": "No solution" }, { "input": "12 5\nabacaba\n010001", "output": "aabacabacaba" }, { "input": "9 3\nac\n10100101", "output": ...
92
0
0
121,772
611
New Year and Three Musketeers
[ "data structures", "greedy", "sortings" ]
null
null
Do you know the story about the three musketeers? Anyway, you must help them now. Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength *a*, Borthos strength *b*, and Caramis has strength *c*. The year 2015 is almost over and there are still *n* criminals to be defeated. The *i*-th criminal has strength *t**i*. It's hard to defeat strong criminalsΒ β€” maybe musketeers will have to fight together to achieve it. Richelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting himΒ β€” a criminal would win then! In other words, there are three ways to defeat a criminal. - A musketeer of the strength *x* in one hour can defeat a criminal of the strength not greater than *x*. So, for example Athos in one hour can defeat criminal *i* only if *t**i*<=≀<=*a*. - Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal *i* only if *t**i*<=≀<=*a*<=+<=*c*. Note that the third remaining musketeer can either do nothing or fight some other criminal. - Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. *t**i*<=≀<=*a*<=+<=*b*<=+<=*c*. Richelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated. Find the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print "-1" (without the quotes) instead.
The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the number of criminals. The second line contains three integers *a*, *b* and *c* (1<=≀<=*a*,<=*b*,<=*c*<=≀<=108)Β β€” strengths of musketeers. The third line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≀<=*t**i*<=≀<=108)Β β€” strengths of criminals.
Print one line with the answer. If it's impossible to defeat all criminals, print "-1" (without the quotes). Otherwise, print the minimum number of hours the three musketeers will spend on defeating all criminals.
[ "5\n10 20 30\n1 1 1 1 50\n", "5\n10 20 30\n1 1 1 1 51\n", "7\n30 20 10\n34 19 50 33 88 15 20\n", "6\n10 5 10\n10 9 5 25 20 5\n" ]
[ "2\n", "3\n", "-1\n", "3\n" ]
In the first sample Athos has strength 10, Borthos 20, and Caramis 30. They can defeat all criminals in two hours: - Borthos and Caramis should together fight a criminal with strength 50. In the same hour Athos can fight one of four criminals with strength 1. - There are three criminals left, each with strength 1. Each musketeer can fight one criminal in the second hour. In the second sample all three musketeers must together fight a criminal with strength 51. It takes one hour. In the second hour they can fight separately, each with one criminal. In the third hour one criminal is left and any of musketeers can fight him.
[ { "input": "5\n10 20 30\n1 1 1 1 50", "output": "2" }, { "input": "5\n10 20 30\n1 1 1 1 51", "output": "3" }, { "input": "7\n30 20 10\n34 19 50 33 88 15 20", "output": "-1" }, { "input": "6\n10 5 10\n10 9 5 25 20 5", "output": "3" }, { "input": "9\n10 20 30\n5 5 5...
0
0
-1
122,412
372
Counting Rectangles is Fun
[ "brute force", "divide and conquer", "dp" ]
null
null
There is an *n*<=Γ—<=*m* rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the *i*-th row and the *j*-th column as (*i*,<=*j*). Let's define a "rectangle" as four integers *a*,<=*b*,<=*c*,<=*d* (1<=≀<=*a*<=≀<=*c*<=≀<=*n*;Β 1<=≀<=*b*<=≀<=*d*<=≀<=*m*). Rectangle denotes a set of cells of the grid {(*x*,<=*y*)Β :<=Β *a*<=≀<=*x*<=≀<=*c*,<=*b*<=≀<=*y*<=≀<=*d*}. Let's define a "good rectangle" as a rectangle that includes only the cells with zeros. You should answer the following *q* queries: calculate the number of good rectangles all of which cells are in the given rectangle.
There are three integers in the first line: *n*, *m* and *q* (1<=≀<=*n*,<=*m*<=≀<=40,<=1<=≀<=*q*<=≀<=3Β·105). Each of the next *n* lines contains *m* characters β€” the grid. Consider grid rows are numbered from top to bottom, and grid columns are numbered from left to right. Both columns and rows are numbered starting from 1. Each of the next *q* lines contains a query β€” four integers that describe the current rectangle, *a*, *b*, *c*, *d* (1<=≀<=*a*<=≀<=*c*<=≀<=*n*;Β 1<=≀<=*b*<=≀<=*d*<=≀<=*m*).
For each query output an answer β€” a single integer in a separate line.
[ "5 5 5\n00101\n00000\n00001\n01000\n00001\n1 2 2 4\n4 5 4 5\n1 2 5 2\n2 2 4 5\n4 2 5 3\n", "4 7 5\n0000100\n0000010\n0011000\n0000000\n1 7 2 7\n3 1 3 1\n2 3 4 5\n1 2 2 7\n2 2 4 7\n" ]
[ "10\n1\n7\n34\n5\n", "3\n1\n16\n27\n52\n" ]
For the first example, there is a 5 × 5 rectangular grid, and the first, the second, and the third queries are represented in the following image. - For the first query, there are 10 good rectangles, five 1 × 1, two 2 × 1, two 1 × 2, and one 1 × 3. - For the second query, there is only one 1 × 1 good rectangle. - For the third query, there are 7 good rectangles, four 1 × 1, two 2 × 1, and one 3 × 1.
[ { "input": "5 5 5\n00101\n00000\n00001\n01000\n00001\n1 2 2 4\n4 5 4 5\n1 2 5 2\n2 2 4 5\n4 2 5 3", "output": "10\n1\n7\n34\n5" }, { "input": "4 7 5\n0000100\n0000010\n0011000\n0000000\n1 7 2 7\n3 1 3 1\n2 3 4 5\n1 2 2 7\n2 2 4 7", "output": "3\n1\n16\n27\n52" }, { "input": "10 10 10\n00...
61
2,867,200
-1
122,416
175
Gnomes of Might and Magic
[ "data structures", "graphs", "implementation", "shortest paths" ]
null
null
Vasya plays a popular game the Gnomes of Might and Magic. In this game Vasya manages the kingdom of gnomes, consisting of several castles, connected by bidirectional roads. The kingdom road network has a special form. The kingdom has *m* main castles *a*1,<=*a*2,<=...,<=*a**m*, which form the Good Path. This path consists of roads between the castles *a**i*,<=*a**i*<=+<=1 (1<=≀<=*i*<=&lt;<=*m*) as well as the road between *a**m* and *a*1. There are no other roads between the castles of the Good Path. In addition, for each pair of neighboring Good Path castles *u* and *v* there is exactly one Evil Shortcut β€” a path that goes along the roads leading from the first castle (*u*) to the second one (*v*) and not having any common vertexes with the Good Path except for the vertexes *u* and *v*. It is known that there are no other roads and castles in the kingdom there, that is, every road and every castle lies either on the Good Path or the Evil Shortcut (castles can lie in both of them). In addition, no two Evil Shortcuts have any common castles, different than the castles of the Good Path. At the beginning of each week in the kingdom appears one very bad gnome who stands on one of the roads of the kingdom, and begins to rob the corovans going through this road. One road may accumulate multiple very bad gnomes. Vasya cares about his corovans, so sometimes he sends the Mission of Death from one castle to another. Let's suggest that the Mission of Death should get from castle *s* to castle *t*. Then it will move from castle *s* to castle *t*, destroying all very bad gnomes, which are on the roads of the Mission's path. Vasya is so tough that his Mission of Death can destroy any number of gnomes on its way. However, Vasya is very kind, so he always chooses such path between castles *s* and *t*, following which he will destroy the smallest number of gnomes. If there are multiple such paths, then Vasya chooses the path that contains the smallest number of roads among them. If there are multiple such paths still, Vasya chooses the lexicographically minimal one among them. Help Vasya to simulate the life of the kingdom in the Gnomes of Might and Magic game. A path is a sequence of castles, such that each pair of the neighboring castles on the path is connected by a road. Also, path *x*1,<=*x*2,<=... ,<=*x**p* is lexicographically less than path *y*1,<=*y*2,<=... ,<=*y**q*, if either *p*<=&lt;<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or exists such number *r* (*r*<=&lt;<=*p*,<=*r*<=&lt;<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=&lt;<=*y**r*<=+<=1.
The first line contains two integers *n* and *m* (3<=≀<=*m*<=≀<=*n*<=≀<=100000) β€” the number of castles in the kingdom, and the number of castles on the Good Path, respectively. The second line contains *m* integers, which are numbers of Good Path castles (the castles are numbered from 1 to *n*) in the order of occurrence on the Path, starting with some castle. All Good Path castles are different. Each of the following *m* lines describes an Evil Shortcut. First a line contains an integer *k**i* (3<=≀<=*k**i*<=≀<=100000) β€” the number of castles on the corresponding Evil Shortcut (with the two castles which are on the Good Path), followed by a *k**i* integers β€” number of castles in the order of occurrence in the given Shortcut. All castles in one Evil Shortcut are different. It is guaranteed that the first and the last castles from the Shortcut are on the Good Path and the first castles in the Evil Shortcuts form the Good Path and are presented in the same order in which the Path was represented on the second line. The next line contains an integer *q* (1<=≀<=*q*<=≀<=100000) β€” the number of events in the life of the kingdom. Each of the following *q* lines describes a single event. An event is described by the symbol *c**j* and two numbers or castles *s**j* and *t**j* (the character and numbers of castles are separated by a single space). If the character of *c**j* is equal to "+" (a plus), it means that a very bad gnome (probably not the first one) has appeared on the road between castles *s**j* and *t**j*. If *c**j* equals "?" (a question), then Vasya sent a Mission of Death from castle *s**j* to castle *t**j*. It is guaranteed that for each request "+", the road between castles *s**j* and *t**j* exists. The events are given in chronological order, starting with the earliest one. Initially there are no very bad gnomes on the roads. All numbers in all lines are separated by single spaces. It is guaranteed that all the given Evil Shortcuts and Good Path fit in the limitations given in the problem statement.
For each query "?" print a single number on a single line β€” the number of very bad gnomes destroyed by the corresponding Mission of Death. Print the answers to queries in the chronological order.
[ "6 3\n1 2 3\n3 1 4 2\n3 2 5 3\n3 3 6 1\n10\n+ 1 2\n+ 4 2\n+ 1 3\n+ 2 3\n? 1 2\n+ 2 5\n? 1 2\n? 1 2\n+ 1 2\n? 1 2\n" ]
[ "0\n1\n0\n1\n" ]
In the example after the first four requests there is only one path from castle 1 to castle 2, which does not contain roads with very bad gnomes: 1 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 6 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 5 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 2. After a gnome stood on the road (2, 5), the next Mission of Death moves along path 1 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 2, and destroys the gnome, who was on the road (1, 2). The next Mission of Death follows the same path which is already free of gnomes. After yet another gnome stood on the road (1, 2), the next Mission of Death goes on the path 1 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 2, and kills the gnome.
[]
60
0
0
122,889
273
Dima and Figure
[ "dp" ]
null
null
Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures. A piece of squared paper of size *n*<=Γ—<=*m* is represented by a table, consisting of *n* rows and *m* columns. All squares are white on blank squared paper. Dima defines a picture as an image on a blank piece of paper, obtained by painting some squares black. The picture portrays one of Dima's favorite figures, if the following conditions hold: - The picture contains at least one painted cell; - All painted cells form a connected set, that is, you can get from any painted cell to any other one (you can move from one cell to a side-adjacent one); - The minimum number of moves needed to go from the painted cell at coordinates (*x*1,<=*y*1) to the painted cell at coordinates (*x*2,<=*y*2), moving only through the colored cells, equals |*x*1<=-<=*x*2|<=+<=|*y*1<=-<=*y*2|. Now Dima is wondering: how many paintings are on an *n*<=Γ—<=*m* piece of paper, that depict one of his favorite figures? Count this number modulo 1000000007Β (109<=+<=7).
The first line contains two integers *n* and *m* β€” the sizes of the piece of paper (1<=≀<=*n*,<=*m*<=≀<=150).
In a single line print the remainder after dividing the answer to the problem by number 1000000007Β (109<=+<=7).
[ "2 2\n", "3 4\n" ]
[ "13\n", "571\n" ]
none
[ { "input": "2 2", "output": "13" }, { "input": "3 4", "output": "571" }, { "input": "2 8", "output": "948" }, { "input": "5 1", "output": "15" }, { "input": "10 5", "output": "10779285" }, { "input": "9 9", "output": "571345021" }, { "input...
60
0
0
122,898
136
Ternary Logic
[ "implementation", "math" ]
null
null
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the *xor* operation is performed on this computer (and whether there is anything like it). It turned out that the operation does exist (however, it is called *tor*) and it works like this. Suppose that we need to calculate the value of the expression *a* *tor* *b*. Both numbers *a* and *b* are written in the ternary notation one under the other one (*b* under *a*). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 1410 *tor* 5010<==<=01123 *tor* 12123<==<=10213<==<=3410. Petya wrote numbers *a* and *c* on a piece of paper. Help him find such number *b*, that *a* *tor* *b*<==<=*c*. If there are several such numbers, print the smallest one.
The first line contains two integers *a* and *c* (0<=≀<=*a*,<=*c*<=≀<=109). Both numbers are written in decimal notation.
Print the single integer *b*, such that *a* *tor* *b*<==<=*c*. If there are several possible numbers *b*, print the smallest one. You should print the number in decimal notation.
[ "14 34\n", "50 34\n", "387420489 225159023\n", "5 5\n" ]
[ "50\n", "14\n", "1000000001\n", "0\n" ]
none
[ { "input": "14 34", "output": "50" }, { "input": "50 34", "output": "14" }, { "input": "387420489 225159023", "output": "1000000001" }, { "input": "5 5", "output": "0" }, { "input": "23476 23875625", "output": "23860906" }, { "input": "11111 10101010",...
124
0
3
123,455
838
Future Failure
[ "dp", "games" ]
null
null
Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists *n* characters, each of which is one of the first *k* letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there is at least one character). In addition, their resulting word cannot have appeared before throughout the entire game. The player unable to make a valid move loses the game. Given *n*,<=*k*,<=*p*, find the number of words with exactly *n* characters consisting of the first *k* letters of the alphabet such that Alice will win if both Alice and Bob play optimally. Return this number modulo the prime number *p*.
The first line of input will contain three integers *n*,<=*k*,<=*p* (1<=≀<=*n*<=≀<=250<=000, 1<=≀<=*k*<=≀<=26, 108<=≀<=*p*<=≀<=109<=+<=100, *p* will be prime).
Print a single integer, the number of winning words for Alice, modulo *p*.
[ "4 2 100000007\n" ]
[ "14\n" ]
There are 14 strings that that Alice can win with. For example, some strings are "bbaa" and "baaa". Alice will lose on strings like "aaaa" or "bbbb".
[]
46
0
0
123,481
107
Darts
[ "geometry", "probabilities" ]
E. Darts
5
256
The night after the graduation ceremony graduate students of German University in Cairo (GUC) are playing darts. As there's no real dart board available, the photographs of members of the GUC upper management are being used. So, *n* rectangular photos are placed on the wall. They can overlap arbitrary and even coincide. The photos are not necessarily placed horizontally or vertically, they could also be rotated before being pinned to the wall. The score of one dart throw is simply the number of photos the dart went through. Fatma has made a throw but her score was not recorded. She only remembers that she did make it into at least one photo. Assuming that the probability distribution of the throw is equal across the whole wall, what would be the expectation of Fatma's score?
The first line of input contains integer *n* (1<=≀<=*n*<=≀<=500) β€” the number of photos on the wall. Then follow *n* lines describing the photos, each containing 8 single-space-separated integers (coordinates of 4 vertices): *x*1, *y*1, *x*2, *y*2, *x*3, *y*3, *x*4, *y*4. Each photo is a rectangle with a nonzero area. The coordinates are integers, not exceeding 104 by absolute value. The coordinates of the rectangle are given in either clockwise or counterclockwise order.
Print the expected score of the throw. The answer will be accepted if it has absolute or relative error not exceeding 10<=-<=6.
[ "1\n0 0 0 2 2 2 2 0\n", "1\n-1 0 0 1 1 0 0 -1\n", "4\n0 0 0 1 3 1 3 0\n0 0 0 3 1 3 1 0\n3 3 2 3 2 0 3 0\n3 3 3 2 0 2 0 3\n", "2\n-1 0 0 1 1 0 0 -1\n0 0 1 1 2 0 1 -1\n" ]
[ "1.0000000000\n", "1.0000000000\n", "1.5000000000\n", "1.1428571429\n" ]
none
[]
60
0
0
123,523
82
General Mobilization
[ "data structures", "dfs and similar", "sortings" ]
C. General Mobilization
2
256
The Berland Kingdom is a set of *n* cities connected with each other with *n*<=-<=1 railways. Each road connects exactly two different cities. The capital is located in city 1. For each city there is a way to get from there to the capital by rail. In the *i*-th city there is a soldier division number *i*, each division is characterized by a number of *a**i*. It represents the priority, the smaller the number, the higher the priority of this division. All values of *a**i* are different. One day the Berland King Berl Great declared a general mobilization, and for that, each division should arrive in the capital. Every day from every city except the capital a train departs. So there are exactly *n*<=-<=1 departing trains each day. Each train moves toward the capital and finishes movement on the opposite endpoint of the railway on the next day. It has some finite capacity of *c**j*, expressed in the maximum number of divisions, which this train can transport in one go. Each train moves in the direction of reducing the distance to the capital. So each train passes exactly one railway moving from a city to the neighboring (where it stops) toward the capital. In the first place among the divisions that are in the city, division with the smallest number of *a**i* get on the train, then with the next smallest and so on, until either the train is full or all the divisions are be loaded. So it is possible for a division to stay in a city for a several days. The duration of train's progress from one city to another is always equal to 1 day. All divisions start moving at the same time and end up in the capital, from where they don't go anywhere else any more. Each division moves along a simple path from its city to the capital, regardless of how much time this journey will take. Your goal is to find for each division, in how many days it will arrive to the capital of Berland. The countdown begins from day 0.
The first line contains the single integer *n* (1<=≀<=*n*<=≀<=5000). It is the number of cities in Berland. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* represents the priority of the division, located in the city number *i*. All numbers *a*1,<=*a*2,<=...,<=*a**n* are different (1<=≀<=*a**i*<=≀<=109). Then *n*<=-<=1 lines contain the descriptions of the railway roads. Each description consists of three integers *v**j*,<=*u**j*,<=*c**j*, where *v**j*, *u**j* are number of cities connected by the *j*-th rail, and *c**j* stands for the maximum capacity of a train riding on this road (1<=≀<=*v**j*,<=*u**j*<=≀<=*n*,<=*v**j*<=β‰ <=*u**j*, 1<=≀<=*c**j*<=≀<=*n*).
Print sequence *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* stands for the number of days it takes for the division of city *i* to arrive to the capital. Separate numbers with spaces.
[ "4\n40 10 30 20\n1 2 1\n2 3 1\n4 2 1\n", "5\n5 4 3 2 1\n1 2 1\n2 3 1\n2 4 1\n4 5 1\n" ]
[ "0 1 3 2 ", "0 1 4 2 3 " ]
none
[]
92
0
0
123,737
553
Nudist Beach
[ "binary search", "graphs", "greedy" ]
null
null
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers. There are *n* cities, labeled from 1 to *n*, and *m* bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are *k* cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses. After the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible. More formally, they would like to capture a non-empty set of cities *S* with no fortresses of Life Fibers. The strength of a city is defined as (number of neighbors of *x* in *S*) / (total number of neighbors of *x*). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in *S*. Given a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city.
The first line of input contains three integers *n*,<=*m*,<=*k* (2<=<=≀<=<=*n*<=<=≀<=100<=000, 1<=≀<=*m*<=≀<=100<=000, 1<=≀<=*k*<=≀<=*n*<=-<=1). The second line of input contains *k* integers, representing the cities with fortresses. These cities will all be distinct. The next *m* lines contain the roads. The *i*-th of these lines will have 2 integers *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a**i*<=β‰ <=*b**i*). Every city will have at least one road adjacent to it. There is no more than one road between each pair of the cities.
The first line should contain an integer *r*, denoting the size of an optimum set (1<=≀<=*r*<=≀<=*n*<=-<=*k*). The second line should contain *r* integers, denoting the cities in the set. Cities may follow in an arbitrary order. This line should not contain any of the cities with fortresses. If there are multiple possible answers, print any of them.
[ "9 8 4\n3 9 6 8\n1 2\n1 3\n1 4\n1 5\n2 6\n2 7\n2 8\n2 9\n", "10 8 2\n2 9\n1 3\n2 9\n4 5\n5 6\n6 7\n7 8\n8 10\n10 4\n" ]
[ "3\n1 4 5\n", "8\n1 5 4 8 10 6 3 7\n" ]
The first example case achieves a strength of 1/2. No other subset is strictly better. The second example case achieves a strength of 1. Note that the subset doesn't necessarily have to be connected.
[ { "input": "9 8 4\n3 9 6 8\n1 2\n1 3\n1 4\n1 5\n2 6\n2 7\n2 8\n2 9", "output": "3\n5 1 4" }, { "input": "10 8 2\n2 9\n1 3\n2 9\n4 5\n5 6\n6 7\n7 8\n8 10\n10 4", "output": "8\n3 10 6 1 5 8 7 4" }, { "input": "2 1 1\n1\n2 1", "output": "1\n2" } ]
30
0
0
123,972
666
Codeword
[ "combinatorics", "strings" ]
null
null
The famous sculptor Cicasso is a Reberlandian spy! These is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. To open it one should solve the problem which is hard for others but is simple for you. Every day the bunker generates a codeword *s*. Every time someone wants to enter the bunker, integer *n* appears on the screen. As the answer one should enter another integer β€” the residue modulo 109<=+<=7 of the number of strings of length *n* that consist only of lowercase English letters and contain the string *s* as the subsequence. The subsequence of string *a* is a string *b* that can be derived from the string *a* by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string "cfo" is the subsequence of the string "codeforces". You haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.
The first line contains integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of the events in the test case. The second line contains nonempty string *s* β€” the string generated by the bunker for the current day. The next *m* lines contain the description of the events. The description starts from integer *t* β€” the type of the event. If *t*<==<=1 consider a new day has come and now a new string *s* is used. In that case the same line contains a new value of the string *s*. If *t*<==<=2 integer *n* is given (1<=≀<=*n*<=≀<=105). This event means that it's needed to find the answer for the current string *s* and the value *n*. The sum of lengths of all generated strings doesn't exceed 105. All of the given strings consist only of lowercase English letters.
For each query of the type 2 print the answer modulo 109<=+<=7 on the separate line.
[ "3\na\n2 2\n1 bc\n2 5\n" ]
[ "51\n162626\n" ]
In the first event words of the form "a?" and "?a" are counted, where ? is an arbitrary symbol. There are 26 words of each of these types, but the word "aa" satisfies both patterns, so the answer is 51.
[]
46
0
0
124,025
1,000
We Need More Bosses
[ "dfs and similar", "graphs", "trees" ]
null
null
Your friend is developing a computer game. He has already decided how the game world should look like β€” it should consist of $n$ locations connected by $m$ two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location. Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses. The game will start in location $s$ and end in location $t$, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from $s$ to $t$ without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as $s$ or as $t$.
The first line contains two integers $n$ and $m$ ($2 \le n \le 3 \cdot 10^5$, $n - 1 \le m \le 3 \cdot 10^5$) β€” the number of locations and passages, respectively. Then $m$ lines follow, each containing two integers $x$ and $y$ ($1 \le x, y \le n$, $x \ne y$) describing the endpoints of one of the passages. It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Print one integer β€” the maximum number of bosses your friend can place, considering all possible choices for $s$ and $t$.
[ "5 5\n1 2\n2 3\n3 1\n4 1\n5 2\n", "4 3\n1 2\n4 3\n3 2\n" ]
[ "2\n", "3\n" ]
none
[ { "input": "5 5\n1 2\n2 3\n3 1\n4 1\n5 2", "output": "2" }, { "input": "4 3\n1 2\n4 3\n3 2", "output": "3" }, { "input": "50 72\n35 38\n19 46\n35 12\n27 30\n23 41\n50 16\n31 6\n20 33\n38 1\n10 35\n13 43\n29 25\n25 4\n1 13\n4 20\n36 29\n13 47\n48 5\n30 21\n30 38\n28 50\n41 45\n25 43\n40 3...
342
16,179,200
0
124,111
785
Anton and Permutation
[ "brute force", "data structures" ]
null
null
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of *n* elements is a sequence of numbers {*a*1,<=*a*2,<=...,<=*a**n*}, in which every number from 1 to *n* appears exactly once. One day Anton got a new permutation and started to play with it. He does the following operation *q* times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (*i*,<=*j*) such that 1<=≀<=*i*<=&lt;<=*j*<=≀<=*n* and *a**i*<=&gt;<=*a**j*. Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him. Initially Anton's permutation was {1,<=2,<=...,<=*n*}, that is *a**i*<==<=*i* for all *i* such that 1<=≀<=*i*<=≀<=*n*.
The first line of the input contains two integers *n* and *q* (1<=≀<=*n*<=≀<=200<=000,<=1<=≀<=*q*<=≀<=50<=000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following *q* lines of the input contains two integers *l**i* and *r**i* (1<=≀<=*l**i*,<=*r**i*<=≀<=*n*)Β β€” the indices of elements that Anton swaps during the *i*-th operation. Note that indices of elements that Anton swaps during the *i*-th operation can coincide. Elements in the permutation are numbered starting with one.
Output *q* lines. The *i*-th line of the output is the number of inversions in the Anton's permutation after the *i*-th operation.
[ "5 4\n4 5\n2 4\n2 5\n2 2\n", "2 1\n2 1\n", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1\n" ]
[ "1\n4\n3\n3\n", "1\n", "5\n6\n7\n7\n10\n11\n8\n" ]
Consider the first sample. After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5). After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4). After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4). After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
[ { "input": "5 4\n4 5\n2 4\n2 5\n2 2", "output": "1\n4\n3\n3" }, { "input": "2 1\n2 1", "output": "1" }, { "input": "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1", "output": "5\n6\n7\n7\n10\n11\n8" }, { "input": "42 42\n23 7\n9 6\n17 22\n19 23\n15 42\n14 10\n17 12\n2 25\n8 39\n13 9\...
46
0
0
124,220
0
none
[ "none" ]
null
null
Santa Claus has *n* tangerines, and the *i*-th of them consists of exactly *a**i* slices. Santa Claus came to a school which has *k* pupils. Santa decided to treat them with tangerines. However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice. Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa. Let *b**i* be the number of slices the *i*-th pupil has in the end. Let Santa's joy be the minimum among all *b**i*'s. Your task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts).
The first line contains two positive integers *n* and *k* (1<=≀<=*n*<=≀<=106, 1<=≀<=*k*<=≀<=2Β·109) denoting the number of tangerines and the number of pupils, respectively. The second line consists of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=107), where *a**i* stands for the number of slices the *i*-th tangerine consists of.
If there's no way to present a tangerine or a part of tangerine to everyone, print -1. Otherwise, print the maximum possible joy that Santa can have.
[ "3 2\n5 9 3\n", "2 4\n12 14\n", "2 3\n1 1\n" ]
[ "5\n", "6\n", "-1\n" ]
In the first example Santa should divide the second tangerine into two parts with 5 and 4 slices. After that he can present the part with 5 slices to the first pupil and the whole first tangerine (with 5 slices, too) to the second pupil. In the second example Santa should divide both tangerines, so that he'll be able to present two parts with 6 slices and two parts with 7 slices. In the third example Santa Claus can't present 2 slices to 3 pupils in such a way that everyone will have anything.
[ { "input": "3 2\n5 9 3", "output": "5" }, { "input": "2 4\n12 14", "output": "6" }, { "input": "2 3\n1 1", "output": "-1" }, { "input": "1 1\n10", "output": "10" }, { "input": "2 2\n6 10", "output": "6" }, { "input": "5 3\n199999 200000 199999 199999 2...
1,231
268,390,400
0
124,254
306
Optimizer
[ "data structures", "greedy", "sortings" ]
null
null
A process RAM is a sequence of bytes that are indexed from 1 to *n*. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains *m* instructions that look like "set13 a_i l_i". Instruction *i* fills a continuous memory segment of length *l**i*, starting from cell number *a**i*, (that it cells with numbers *a**i*,<=*a**i*<=+<=1,<=...,<=*a**i*<=+<=*l**i*<=-<=1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program.
The first line contains integers *n* and *m* (1<=≀<=*n*<=≀<=2Β·106,<=1<=≀<=*m*<=≀<=2Β·105) β€” the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then *m* lines follow, each line contains a pair of integers *a**i*, *l**i* (1<=≀<=*a**i*<=≀<=*n*,<=1<=≀<=*l**i*<=≀<=*n*<=-<=*a**i*<=+<=1).
Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to *m* in the order they appeared in the input. If there are multiple solutions, print any of them.
[ "10 4\n3 3\n3 1\n4 1\n9 2\n", "1 1\n1 1\n" ]
[ "2\n2 3 ", "0\n" ]
none
[]
122
0
0
124,293
643
Bearish Fanpages
[]
null
null
There is a social website with *n* fanpages, numbered 1 through *n*. There are also *n* companies, and the *i*-th company owns the *i*-th fanpage. Recently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow. The website doesn’t allow a situation where *i* follows *j* and at the same time *j* follows *i*. Also, a fanpage can't follow itself. Let’s say that fanpage *i* follows some other fanpage *j*0. Also, let’s say that *i* is followed by *k* other fanpages *j*1,<=*j*2,<=...,<=*j**k*. Then, when people visit fanpage *i* they see ads from *k*<=+<=2 distinct companies: *i*,<=*j*0,<=*j*1,<=...,<=*j**k*. Exactly *t**i* people subscribe (like) the *i*-th fanpage, and each of them will click exactly one add. For each of *k*<=+<=1 companies *j*0,<=*j*1,<=...,<=*j**k*, exactly people will click their ad. Remaining people will click an ad from company *i* (the owner of the fanpage). The total income of the company is equal to the number of people who click ads from this copmany. Limak and Radewoosh ask you for help. Initially, fanpage *i* follows fanpage *f**i*. Your task is to handle *q* queries of three types: - 1 i jΒ β€” fanpage *i* follows fanpage *j* from now. It's guaranteed that *i* didn't follow *j* just before the query. Note an extra constraint for the number of queries of this type (below, in the Input section). - 2 iΒ β€” print the total income of the *i*-th company. - 3Β β€” print two integers: the smallest income of one company and the biggest income of one company.
The first line of the input contains two integers *n* and *q* (3<=≀<=*n*<=≀<=100<=000, 1<=≀<=*q*<=≀<=100<=000)Β β€” the number of fanpages and the number of queries, respectively. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≀<=*t**i*<=≀<=1012) where *t**i* denotes the number of people subscribing the *i*-th fanpage. The third line contains *n* integers *f*1,<=*f*2,<=...,<=*f**n* (1<=≀<=*f**i*<=≀<=*n*). Initially, fanpage *i* follows fanpage *f**i*. Then, *q* lines follow. The *i*-th of them describes the *i*-th query. The first number in the line is an integer *type**i* (1<=≀<=*type**i*<=≀<=3)Β β€” the type of the query. There will be at most 50<=000 queries of the first type. There will be at least one query of the second or the third type (so, the output won't be empty). It's guaranteed that at each moment a fanpage doesn't follow itself, and that no two fanpages follow each other.
For each query of the second type print one integer in a separate line - the total income of the given company. For each query of the third type print two integers in a separate line - the minimum and the maximum total income, respectively.
[ "5 12\n10 20 30 40 50\n2 3 4 5 2\n2 1\n2 2\n2 3\n2 4\n2 5\n1 4 2\n2 1\n2 2\n2 3\n2 4\n2 5\n3\n" ]
[ "10\n36\n28\n40\n36\n9\n57\n27\n28\n29\n9 57\n" ]
In the sample test, there are 5 fanpages. The *i*-th of them has *i*Β·10 subscribers. On drawings, numbers of subscribers are written in circles. An arrow from *A* to *B* means that *A* follows *B*. The left drawing shows the initial situation. The first company gets income <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/aa287c04033fd5717b34060017a16ed1930b6a77.png" style="max-width: 100.0%;max-height: 100.0%;"/> from its own fanpage, and gets income <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/545b52a4f4acc0a81e4c81f01a57750f8d8a5045.png" style="max-width: 100.0%;max-height: 100.0%;"/> from the 2-nd fanpage. So, the total income is 5 + 5 = 10. After the first query ("2 1") you should print 10. The right drawing shows the situation after a query "1 4 2" (after which fanpage 4 follows fanpage 2). Then, the first company still gets income 5 from its own fanpage, but now it gets only <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/08e222f472ebd19466616b7774c41626722a1995.png" style="max-width: 100.0%;max-height: 100.0%;"/> from the 2-nd fanpage. So, the total income is 5 + 4 = 9 now.
[]
46
0
0
124,334
0
none
[ "none" ]
null
null
You are given an undirected graph that consists of *n* vertices and *m* edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red. Find the minimum possible number of moves required to make the colors of all edges equal.
The first line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100<=000)Β β€” the number of vertices and edges, respectively. The following *m* lines provide the description of the edges, as the *i*-th of them contains two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*, *u**i*<=β‰ <=*v**i*)Β β€” the indices of the vertices connected by the *i*-th edge, and a character *c**i* () providing the initial color of this edge. If *c**i* equals 'R', then this edge is initially colored red. Otherwise, *c**i* is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.
If there is no way to make the colors of all edges equal output <=-<=1 in the only line of the output. Otherwise first output *k*Β β€” the minimum number of moves required to achieve the goal, then output *k* integers *a*1,<=*a*2,<=...,<=*a**k*, where *a**i* is equal to the index of the vertex that should be used at the *i*-th move. If there are multiple optimal sequences of moves, output any of them.
[ "3 3\n1 2 B\n3 1 R\n3 2 B\n", "6 5\n1 3 R\n2 3 R\n3 4 B\n4 5 R\n4 6 R\n", "4 5\n1 2 R\n1 3 R\n2 3 B\n3 4 B\n1 4 B\n" ]
[ "1\n2 \n", "2\n3 4 \n", "-1\n" ]
none
[]
46
0
0
124,367
0
none
[ "none" ]
null
null
Π’Π΄ΠΎΠ»ΡŒ Π΄ΠΎΡ€ΠΎΠ³ΠΈ стоят *n* ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ². Π”ΠΎΡ€ΠΎΠ³Π° прСдставляСт собой ΠΏΡ€ΡΠΌΡƒΡŽ, Ρ€Π°Π·ΠΌΠ΅Ρ€Π°ΠΌΠΈ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ² ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡ€Π΅Π½Π΅Π±Ρ€Π΅Ρ‡ΡŒ, считая ΠΈΡ… Ρ‚ΠΎΡ‡ΠΊΠ°ΠΌΠΈ. Π’ΠΎΠ΄ΠΈΡ‚Π΅Π»ΡŒ автобуса Василий, благодаря ΠΌΠΎΠ±ΠΈΠ»ΡŒΠ½ΠΎΠΌΡƒ ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΡŽ, Π·Π½Π°Π΅Ρ‚ для ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠ° Ρ‚ΠΎΡ‡ΠΊΡƒ *x**i*, Π² ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΉ Ρ‚ΠΎΡ‚ стоит. ΠšΡ€ΠΎΠΌΠ΅ Ρ‚ΠΎΠ³ΠΎ, ΠΎΠ½ Π·Π½Π°Π΅Ρ‚ расстояниС *d**i*, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ *i*-ΠΉ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊ Ρ…ΠΎΡ‡Π΅Ρ‚ ΠΏΡ€ΠΎΠ΅Ρ…Π°Ρ‚ΡŒ Π½Π° автобусС. Π’Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ, *i*-ΠΉ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊ ΠΏΠ»Π°Π½ΠΈΡ€ΡƒΠ΅Ρ‚ Π²Ρ‹ΠΉΡ‚ΠΈ ΠΈΠ· автобуса Π² Ρ‚ΠΎΡ‡ΠΊΠ΅ *x**i*<=+<=*d**i*. Π’Π΅ΠΏΠ΅Ρ€ΡŒ Василий Ρ…ΠΎΡ‡Π΅Ρ‚ Ρ€Π΅ΡˆΠΈΡ‚ΡŒ, ΠΊΠΎΠ³ΠΎ ΠΈΠ· ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ² ΠΎΠ½ ΠΏΠΎΠ΄Π²Π΅Π·Ρ‘Ρ‚, Π° ΠΊΠΎΠ³ΠΎ оставит ΠΏΡ‹Π»ΠΈΡ‚ΡŒΡΡ Ρƒ Π΄ΠΎΡ€ΠΎΠ³ΠΈ. Василий Ρ€Π΅ΡˆΠΈΠ», Ρ‡Ρ‚ΠΎ сСгодня ΠΎΠ½ Π΄ΠΎΠ»ΠΆΠ΅Π½ Ρ…ΠΎΡ€ΠΎΡˆΠΎ Π·Π°Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ, поэтому Ρ€Π΅ΡˆΠΈΠ» ΠΏΠ΅Ρ€Π΅Π²Π΅Π·Ρ‚ΠΈ Π² точности *a* ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ². Π’ Π°Π²Ρ‚ΠΎΠΏΠ°Ρ€ΠΊΠ΅ Π΅ΡΡ‚ΡŒ автобусы Π»ΡŽΠ±Ρ‹Ρ… Π²ΠΈΠ΄ΠΎΠ². Π§Π΅ΠΌ большС мСст Π² автобусС, Ρ‚Π΅ΠΌ Π΄ΠΎΡ€ΠΎΠΆΠ΅ стоит Π΅Π³ΠΎ Π°Ρ€Π΅Π½Π΄Π°. ΠŸΠΎΠΌΠΎΠ³ΠΈΡ‚Π΅ Π’Π°ΡΠΈΠ»ΠΈΡŽ ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚ΡŒ минимальноС количСство пассаТирских мСст Π² автобусС, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… Π±ΡƒΠ΄Π΅Ρ‚ достаточно для ΠΏΠ΅Ρ€Π΅Π²ΠΎΠ·ΠΊΠΈ Ρ€ΠΎΠ²Π½ΠΎ *a* ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ². Ни Π² ΠΊΠ°ΠΊΠΎΠΉ ΠΌΠΎΠΌΠ΅Π½Ρ‚ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ Π² автобусС Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ‹Ρ‚ΡŒ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ² большС, Ρ‡Π΅ΠΌ количСство пассаТирских мСст Π² автобусС. Василий сам ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π΅ΡˆΠΈΡ‚ΡŒ ΠΊΠ°ΠΊΠΎΠ΅ ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½ΠΎ подмноТСство ΠΈΠ· *a* ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ² ΠΎΠ½ ΠΏΠ΅Ρ€Π΅Π²Π΅Π·Ρ‘Ρ‚ Π½Π° автобусС. Π‘Ρ‡ΠΈΡ‚Π°ΠΉΡ‚Π΅, Ρ‡Ρ‚ΠΎ автобус всСгда Π΅Π΄Π΅Ρ‚ слСва Π½Π°ΠΏΡ€Π°Π²ΠΎ (ΠΎΡ‚ ΠΌΠ΅Π½ΡŒΡˆΠΈΡ… ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚ ΠΊ большим) ΠΈ Π½Π°Ρ‡ΠΈΠ½Π°Π΅Ρ‚ свой ΠΏΡƒΡ‚ΡŒ Π»Π΅Π²Π΅Π΅ самого лСвостоящСго ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠ°. Если Π² ΠΎΠ΄Π½ΠΎΠΉ Ρ‚ΠΎΡ‡ΠΊΠ΅ ΠΊΠ°ΠΊΠΎΠΉ-Ρ‚ΠΎ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π²Ρ‹ΠΉΡ‚ΠΈ ΠΈΠ· автобуса, Π° Π΄Ρ€ΡƒΠ³ΠΎΠΉ Π²ΠΎΠΉΡ‚ΠΈ, считайтС, Ρ‡Ρ‚ΠΎ сначала ΠΏΡ€ΠΎΠΈΠ·ΠΎΠΉΠ΄Π΅Ρ‚ Π²Ρ‹Ρ…ΠΎΠ΄ ΠΎΠ΄Π½ΠΎΠ³ΠΎ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠ° ΠΈΠ· автобуса, Π° Π·Π°Ρ‚Π΅ΠΌ Π΄Ρ€ΡƒΠ³ΠΎΠΉ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊ смоТСт Π·Π°ΠΉΡ‚ΠΈ Π² автобус.
Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… слСдуСт Π΄Π²Π° Ρ†Π΅Π»Ρ‹Ρ… ΠΏΠΎΠ»ΠΎΠΆΠΈΡ‚Π΅Π»ΡŒΠ½Ρ‹Ρ… числа *n* ΠΈ *a* (1<=≀<=*a*<=≀<=*n*<=≀<=200<=000)Β β€” количСство ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ², стоящих вдоль Π΄ΠΎΡ€ΠΎΠ³ΠΈ, ΠΈ минимальноС количСство ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ², ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… Василий Ρ…ΠΎΡ‡Π΅Ρ‚ ΠΏΠΎΠ΄Π²Π΅Π·Ρ‚ΠΈ. Π’ ΠΊΠ°ΠΆΠ΄ΠΎΠΉ ΠΈΠ· ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΡ… *n* строк содСрТится ΠΏΠΎ Π΄Π²Π° Ρ†Π΅Π»Ρ‹Ρ… числа *x**i* ΠΈ *d**i* (1<=≀<=*x**i*,<=*d**i*<=≀<=109)Β β€” ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Π°, Π² ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΉ находится *i*-ΠΉ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊ, Π° Ρ‚Π°ΠΊΠΆΠ΅ расстояниС, Π½Π° ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ ΠΎΠ½ Ρ…ΠΎΡ‡Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅ΡΡ‚ΠΈΡ‚ΡŒΡΡ Π½Π° автобусС. ΠšΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ² Π·Π°Π΄Π°Π½Ρ‹ Π² ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ»ΡŒΠ½ΠΎΠΌ порядкС. Π’ ΠΎΠ΄Π½ΠΎΠΉ Ρ‚ΠΎΡ‡ΠΊΠ΅ ΠΌΠΎΠ³ΡƒΡ‚ Π½Π°Ρ…ΠΎΠ΄ΠΈΡ‚ΡŒΡΡ нСсколько ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ².
Π‘Π½Π°Ρ‡Π°Π»Π° Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ ΠΎΠ΄Π½ΠΎ Ρ†Π΅Π»ΠΎΠ΅ число — минимальноС количСство пассаТирских мСст Π² автобусС, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… Π±ΡƒΠ΄Π΅Ρ‚ достаточно для ΠΏΠ΅Ρ€Π΅Π²ΠΎΠ·ΠΊΠΈ хотя Π±Ρ‹ *a* ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ². Π—Π°Ρ‚Π΅ΠΌ Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ *a* Ρ†Π΅Π»Ρ‹Ρ… чисСл — Π½ΠΎΠΌΠ΅Ρ€Π° ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ², ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… ΠΏΠΎΠ΄Π²Π΅Π·Ρ‘Ρ‚ Василий. ΠŸΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΈ Π½ΡƒΠΌΠ΅Ρ€ΡƒΡŽΡ‚ΡΡ, начиная с Π΅Π΄ΠΈΠ½ΠΈΡ†Ρ‹, Π² Ρ‚ΠΎΠΌ порядкС, Π² ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΌ Π·Π°Π΄Π°Π½Ρ‹ Π²ΠΎ Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ…. НомСра ΠΌΠΎΠΆΠ½ΠΎ Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ΡŒ Π² ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ»ΡŒΠ½ΠΎΠΌ порядкС. Если ΠΎΡ‚Π²Π΅Ρ‚ΠΎΠ² нСсколько, Ρ€Π°Π·Ρ€Π΅ΡˆΠ°Π΅Ρ‚ΡΡ вывСсти любой ΠΈΠ· Π½ΠΈΡ….
[ "3 2\n8 9\n3 5\n1 3\n", "5 4\n20 40\n10 10\n15 5\n5 15\n20 30\n" ]
[ "1\n1 3 \n", "2\n4 2 5 1\n" ]
Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΌ тСстовом ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ достаточно одномСстного автобуса. К ΠΏΡ€ΠΈΠΌΠ΅Ρ€Ρƒ, Василий ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΠ΄Π²Π΅Π·Ρ‚ΠΈ Ρ‚Ρ€Π΅Ρ‚ΡŒΠ΅Π³ΠΎ ΠΈ ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ², Π»ΠΈΠ±ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠ³ΠΎ ΠΈ ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ ΠΏΡƒΡ‚Π΅ΡˆΠ΅ΡΡ‚Π²Π΅Π½Π½ΠΈΠΊΠΎΠ².
[]
0
0
-1
124,606
0
none
[ "none" ]
null
null
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground. Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed. Mole wants to find an optimal point to watch roses, that is such point with integer coordinates that the maximum Manhattan distance to the rose is minimum possible. As usual, he asks you to help. Manhattan distance between points (*x*1,<=Β *y*1,<=Β *z*1) and (*x*2,<=Β *y*2,<=Β *z*2) is defined as |*x*1<=-<=*x*2|<=+<=|*y*1<=-<=*y*2|<=+<=|*z*1<=-<=*z*2|.
The first line of the input contains an integer *t* *t* (1<=≀<=*t*<=≀<=100<=000)Β β€” the number of test cases. Then follow exactly *t* blocks, each containing the description of exactly one test. The first line of each block contains an integer *n**i* (1<=≀<=*n**i*<=≀<=100<=000)Β β€” the number of roses in the test. Then follow *n**i* lines, containing three integers eachΒ β€” the coordinates of the corresponding rose. Note that two or more roses may share the same position. It's guaranteed that the sum of all *n**i* doesn't exceed 100<=000 and all coordinates are not greater than 1018 by their absolute value.
For each of *t* test cases print three integersΒ β€” the coordinates of the optimal point to watch roses. If there are many optimal answers, print any of them. The coordinates of the optimal point may coincide with the coordinates of any rose.
[ "1\n5\n0 0 4\n0 0 -4\n0 4 0\n4 0 0\n1 1 1\n", "2\n1\n3 5 9\n2\n3 5 9\n3 5 9\n" ]
[ "0 0 0\n", "3 5 9\n3 5 9\n" ]
In the first sample, the maximum Manhattan distance from the point to the rose is equal to 4. In the second sample, the maximum possible distance is 0. Note that the positions of the roses may coincide with each other and with the position of the optimal point.
[]
30
0
0
124,889
513
Subarray Cuts
[ "dp" ]
null
null
You are given an array of length *n* and a number *k*. Let's pick *k* non-overlapping non-empty subarrays of the initial array. Let *s**i* be the sum of the *i*-th subarray in order from left to right. Compute the maximum value of the following expression: Here subarray is a contiguous part of an array.
The first line of input contains two integers *n* and *k*. The second line contains *n* integers β€” the elements of the array. The absolute values of elements do not exceed 104. The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. - In subproblem E1 (9 points), constraints 2<=≀<=*n*<=≀<=400, 2<=≀<=*k*<=≀<=*min*(*n*,<=50) will hold. - In subproblem E2 (12 points), constraints 2<=≀<=*n*<=≀<=30000, 2<=≀<=*k*<=≀<=*min*(*n*,<=200) will hold.
Output a single integer β€” the maximum possible value.
[ "5 3\n5 2 4 3 1\n", "4 2\n7 4 3 7\n" ]
[ "12\n", "8\n" ]
Consider the first sample test. The optimal solution is obtained if the first subarray contains the first element only, the second subarray spans the next three elements and the last subarray contains the last element only. The sums of these subarrays are 5, 9 and 1, correspondingly. Consider the second sample test. In the optimal solution, the first subarray consists of the first two elements and the second subarray consists of the third element only. Note that the last element does not belong to any subarray in this solution.
[ { "input": "5 3\n5 2 4 3 1", "output": "12" }, { "input": "4 2\n7 4 3 7", "output": "8" }, { "input": "9 6\n9 4 10 1 6 3 3 8 4", "output": "55" }, { "input": "8 6\n2 5 3 4 2 10 9 3", "output": "45" }, { "input": "9 2\n7 10 7 2 5 7 10 1 3", "output": "47" }, ...
93
307,200
-1
125,136
509
Sums of Digits
[ "dp", "greedy", "implementation" ]
null
null
Vasya had a strictly increasing sequence of positive integers *a*1, ..., *a**n*. Vasya used it to build a new sequence *b*1, ..., *b**n*, where *b**i* is the sum of digits of *a**i*'s decimal representation. Then sequence *a**i* got lost and all that remained is sequence *b**i*. Vasya wonders what the numbers *a**i* could be like. Of all the possible options he likes the one sequence with the minimum possible last number *a**n*. Help Vasya restore the initial sequence. It is guaranteed that such a sequence always exists.
The first line contains a single integer number *n* (1<=≀<=*n*<=≀<=300). Next *n* lines contain integer numbers *b*1, ..., *b**n* Β β€” the required sums of digits. All *b**i* belong to the range 1<=≀<=*b**i*<=≀<=300.
Print *n* integer numbers, one per lineΒ β€” the correct option for numbers *a**i*, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the *i*-th number should be equal to *b**i*. If there are multiple sequences with least possible number *a**n*, print any of them. Print the numbers without leading zeroes.
[ "3\n1\n2\n3\n", "3\n3\n2\n1\n" ]
[ "1\n2\n3\n", "3\n11\n100\n" ]
none
[ { "input": "3\n1\n2\n3", "output": "1\n2\n3" }, { "input": "3\n3\n2\n1", "output": "3\n11\n100" }, { "input": "10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n1", "output": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "input": "10\n8\n8\n5\n1\n2\n7\n3\n8\n9\n4", "output": "8\n17\n23\n100\n101\n10...
93
0
0
125,149
187
Weak Memory
[ "dfs and similar", "dsu" ]
null
null
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them. The park has *n* intersections numbered 1 through *n*. There are *m* bidirectional roads that connect some pairs of these intersections. At *k* intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct. When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most *q* intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most *q* that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most *q* intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it. PMP's initial location is intersection *s* and the buses are at intersection *t*. There will always be a volunteer at intersection *s*. Your job is to find out the minimum *q* which guarantees that PMP can find the buses.
The first line contains three space-separated integers *n*,<=*m*,<=*k* (2<=≀<=*n*<=≀<=105,<=0<=≀<=*m*<=≀<=2Β·105,<=1<=≀<=*k*<=≀<=*n*) β€” the number of intersections, roads and volunteers, respectively. Next line contains *k* distinct space-separated integers between 1 and *n* inclusive β€” the numbers of cities where volunteers are located. Next *m* lines describe the roads. The *i*-th of these lines contains two space-separated integers *u**i*,<=*v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*,<=*u**i*<=β‰ <=*v**i*) β€” two intersections that *i*-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers *s*,<=*t* (1<=≀<=*s*,<=*t*<=≀<=*n*,<=*s*<=β‰ <=*t*) β€” the initial location of PMP and the location of the buses. It might not always be possible to reach *t* from *s*. It is guaranteed that there is always a volunteer at intersection *s*.
Print on the only line the answer to the problem β€” the minimum value of *q* which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.
[ "6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6\n", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5\n" ]
[ "3\n", "3\n" ]
The first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with *q* = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
[]
62
0
0
125,964
254
Rats
[ "brute force", "dfs and similar", "graphs", "implementation", "shortest paths" ]
null
null
Rats have bred to hundreds and hundreds in the basement of the store, owned by Vasily Petrovich. Vasily Petrovich may have not noticed their presence, but they got into the habit of sneaking into the warehouse and stealing food from there. Vasily Petrovich cannot put up with it anymore, he has to destroy the rats in the basement. Since mousetraps are outdated and do not help, and rat poison can poison inattentive people as well as rats, he chose a radical way: to blow up two grenades in the basement (he does not have more). In this problem, we will present the shop basement as a rectangular table of *n*<=Γ—<=*m* cells. Some of the cells are occupied by walls, and the rest of them are empty. Vasily has been watching the rats and he found out that at a certain time they go to sleep, and all the time they sleep in the same places. He wants to blow up a grenade when this convenient time comes. On the plan of his basement, he marked cells with sleeping rats in them. Naturally, these cells are not occupied by walls. Grenades can only blow up in a cell that is not occupied by a wall. The blast wave from a grenade distributes as follows. We assume that the grenade blast occurs at time 0. During this initial time only the cell where the grenade blew up gets 'clear'. If at time *t* some cell is clear, then at time *t*<=+<=1 those side-neighbouring cells which are not occupied by the walls get clear too (some of them could have been cleared before). The blast wave distributes for exactly *d* seconds, then it dies immediately. Vasily Petrovich wonders, whether he can choose two cells to blast the grenades so as to clear all cells with sleeping rats. Write the program that finds it out.
The first line contains three integers *n*, *m* and *d*, separated by single spaces (4<=≀<=*n*,<=*m*<=≀<=1000,<=1<=≀<=*d*<=≀<=8). Next *n* lines contain the table that represents the basement plan. Each row of the table consists of *m* characters. Character "X" means that the corresponding cell is occupied by the wall, character "." represents a empty cell, character "R" represents a empty cell with sleeping rats. It is guaranteed that the first and the last row, as well as the first and the last column consist of characters "X". The plan has at least two empty cells. There is at least one cell with sleeping rats.
If it is impossible to blow up all cells with sleeping rats, print a single integer -1. Otherwise, print four space-separated integers *r*1,<=*c*1,<=*r*2,<=*c*2, that mean that one grenade should go off in cell (*r*1,<=*c*1), and the other one β€” in cell (*r*2,<=*c*2). Consider the table rows numbered from top to bottom from 1 to *n* and the table columns β€” from left to right from 1 to *m*. As *r*1 and *r*2 represent the row numbers, and *c*1 and *c*2 represent the column numbers in the table, they should fit the limits: 1<=≀<=*r*1,<=*r*2<=≀<=*n*,<=1<=≀<=*c*1,<=*c*2<=≀<=*m*. It is forbidden to blow a grenade twice in the same cell. The blast waves of the grenades can intersect. It is possible that one grenade blast destroys no rats, and the other one destroys all of them.
[ "4 4 1\nXXXX\nXR.X\nX.RX\nXXXX\n", "9 14 5\nXXXXXXXXXXXXXX\nX....R...R...X\nX..R.........X\nX....RXR..R..X\nX..R...X.....X\nXR.R...X.....X\nX....XXR.....X\nX....R..R.R..X\nXXXXXXXXXXXXXX\n", "7 7 1\nXXXXXXX\nX.R.R.X\nX.....X\nX..X..X\nX..R..X\nX....RX\nXXXXXXX\n" ]
[ "2 2 2 3\n", "2 3 6 9\n", "-1\n" ]
none
[ { "input": "4 4 1\nXXXX\nXR.X\nX.RX\nXXXX", "output": "2 2 2 3" }, { "input": "9 14 5\nXXXXXXXXXXXXXX\nX....R...R...X\nX..R.........X\nX....RXR..R..X\nX..R...X.....X\nXR.R...X.....X\nX....XXR.....X\nX....R..R.R..X\nXXXXXXXXXXXXXX", "output": "2 3 6 9" }, { "input": "7 7 1\nXXXXXXX\nX.R.R...
46
0
0
126,017
750
New Year and Binary Tree Paths
[ "bitmasks", "brute force", "combinatorics", "dp" ]
null
null
The New Year tree is an infinite perfect binary tree rooted in the node 1. Each node *v* has two children: nodes indexed (2Β·*v*) and (2Β·*v*<=+<=1). Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nodes. Though he was given an opportunity to pick the pair himself! Now he wants to know the number of unordered pairs of indices (*u*,<=*v*) (*u*<=≀<=*v*), such that the sum of indices of all nodes along the simple path between *u* and *v* (including endpoints) is equal to *s*. Can you help him and count this value?
The only line of the input contains a single integer *s* (1<=≀<=*s*<=≀<=1015).
Print one integer, denoting the number of unordered pairs of nodes indices defining simple paths with the sum of indices of vertices equal to *s*.
[ "10\n" ]
[ "4\n" ]
In sample test, there are 4 paths with the sum of indices equal to 10:
[]
46
0
0
126,222
802
Fake News (hard)
[ "string suffix structures" ]
null
null
Now that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined as where the sum is over all nonempty strings *p* and is the number of occurences of *p* in *s* as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.) Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway – do not bother, we have already tried.)
The input starts with a line indicating the number of test cases *T* (1<=≀<=*T*<=≀<=10). After that, *T* test cases follow, each of which consists of one line containing a string *s* (1<=≀<=|*s*|<=≀<=100<=000) composed of lowercase letters (a-z).
Output *T* lines, every line containing one number – the answer to the corresponding test case.
[ "4\naa\nabcd\nccc\nabcc\n" ]
[ "5\n10\n14\n12\n" ]
A string *s* contains another string *p* as a substring if *p* is a contiguous subsequence of *s*. For example, ab is a substring of cab but not of acb.
[]
30
0
0
126,508
216
Spider's Web
[ "binary search", "sortings", "two pointers" ]
null
null
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web. There are *n* main threads going from the center of the web. All main threads are located in one plane and divide it into *n* equal infinite sectors. The sectors are indexed from 1 to *n* in the clockwise direction. Sectors *i* and *i*<=+<=1 are adjacent for every *i*, 1<=≀<=*i*<=&lt;<=*n*. In addition, sectors 1 and *n* are also adjacent. Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them. A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells. Unstable cells are marked red in the figure. Stable cells are marked green. Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.
The first line contains integer *n* (3<=≀<=*n*<=≀<=1000) β€” the number of main threads. The *i*-th of following *n* lines describe the bridges located in the *i*-th sector: first it contains integer *k**i* (1<=≀<=*k**i*<=≀<=105) equal to the number of bridges in the given sector. Then follow *k**i* different integers *p**ij* (1<=≀<=*p**ij*<=≀<=105;Β 1<=≀<=*j*<=≀<=*k**i*). Number *p**ij* equals the distance from the attachment points of the *j*-th bridge of the *i*-th sector to the center of the web. It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.
Print a single integer β€” the number of unstable cells in Paw the Spider's web.
[ "7\n3 1 6 7\n4 3 5 2 9\n2 8 1\n4 3 7 6 4\n3 2 5 9\n3 6 3 8\n3 4 2 9\n" ]
[ "6" ]
none
[ { "input": "7\n3 1 6 7\n4 3 5 2 9\n2 8 1\n4 3 7 6 4\n3 2 5 9\n3 6 3 8\n3 4 2 9", "output": "6" }, { "input": "3\n1 1\n1 2\n1 3", "output": "0" }, { "input": "3\n2 1 2\n2 3 4\n2 5 6", "output": "0" }, { "input": "5\n3 2 4 10\n2 1 6\n2 8 7\n3 2 4 10\n2 1 6", "output": "2" ...
560
30,412,800
3
126,514
0
none
[ "none" ]
null
null
You are given an infinite periodic array *a*0,<=*a*1,<=...,<=*a**n*<=-<=1,<=... with the period of length *n*. Formally, . A periodic subarray (*l*,<=*s*) (0<=≀<=*l*<=&lt;<=*n*, 1<=≀<=*s*<=&lt;<=*n*) of array *a* is an infinite periodic array with a period of length *s* that is a subsegment of array *a*, starting with position *l*. A periodic subarray (*l*,<=*s*) is superior, if when attaching it to the array *a*, starting from index *l*, any element of the subarray is larger than or equal to the corresponding element of array *a*. An example of attaching is given on the figure (top β€” infinite array *a*, bottom β€” its periodic subarray (*l*,<=*s*)): Find the number of distinct pairs (*l*,<=*s*), corresponding to the superior periodic arrays.
The first line contains number *n* (1<=≀<=*n*<=≀<=2Β·105). The second line contains *n* numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (1<=≀<=*a**i*<=≀<=106), separated by a space.
Print a single integer β€” the sought number of pairs.
[ "4\n7 1 2 3\n", "2\n2 1\n", "3\n1 1 1\n" ]
[ "2\n", "1\n", "6\n" ]
In the first sample the superior subarrays are (0, 1) and (3, 2). Subarray (0, 1) is superior, as *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">0</sub>, *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">2</sub>, *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">3</sub>, *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">0</sub>, ... Subarray (3, 2) is superior *a*<sub class="lower-index">3</sub> β‰₯ *a*<sub class="lower-index">3</sub>, *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">0</sub>, *a*<sub class="lower-index">3</sub> β‰₯ *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">0</sub> β‰₯ *a*<sub class="lower-index">2</sub>, *a*<sub class="lower-index">3</sub> β‰₯ *a*<sub class="lower-index">3</sub>, ... In the third sample any pair of (*l*, *s*) corresponds to a superior subarray as all the elements of an array are distinct.
[]
124
3,481,600
0
126,570
869
The Untended Antiquity
[ "data structures", "hashing" ]
null
null
Adieu l'ami. Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence. The space is represented by a rectangular grid of *n*<=Γ—<=*m* cells, arranged into *n* rows and *m* columns. The *c*-th cell in the *r*-th row is denoted by (*r*,<=*c*). Oshino places and removes barriers around rectangular areas of cells. Specifically, an action denoted by "1 *r*1 *c*1 *r*2 *c*2" means Oshino's placing barriers around a rectangle with two corners being (*r*1,<=*c*1) and (*r*2,<=*c*2) and sides parallel to squares sides. Similarly, "2 *r*1 *c*1 *r*2 *c*2" means Oshino's removing barriers around the rectangle. Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the *n*<=Γ—<=*m* area. Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. "3 *r*1 *c*1 *r*2 *c*2" means that Koyomi tries to walk from (*r*1,<=*c*1) to (*r*2,<=*c*2) without crossing barriers. And you're here to tell Koyomi the feasibility of each of his attempts.
The first line of input contains three space-separated integers *n*, *m* and *q* (1<=≀<=*n*,<=*m*<=≀<=2<=500, 1<=≀<=*q*<=≀<=100<=000) β€” the number of rows and columns in the grid, and the total number of Oshino and Koyomi's actions, respectively. The following *q* lines each describes an action, containing five space-separated integers *t*, *r*1, *c*1, *r*2, *c*2 (1<=≀<=*t*<=≀<=3, 1<=≀<=*r*1,<=*r*2<=≀<=*n*, 1<=≀<=*c*1,<=*c*2<=≀<=*m*) β€” the type and two coordinates of an action. Additionally, the following holds depending on the value of *t*: - If *t*<==<=1: 2<=≀<=*r*1<=≀<=*r*2<=≀<=*n*<=-<=1, 2<=≀<=*c*1<=≀<=*c*2<=≀<=*m*<=-<=1; - If *t*<==<=2: 2<=≀<=*r*1<=≀<=*r*2<=≀<=*n*<=-<=1, 2<=≀<=*c*1<=≀<=*c*2<=≀<=*m*<=-<=1, the specified group of barriers exist on the ground before the removal. - If *t*<==<=3: no extra restrictions.
For each of Koyomi's attempts (actions with *t*<==<=3), output one line β€” containing "Yes" (without quotes) if it's feasible, and "No" (without quotes) otherwise.
[ "5 6 5\n1 2 2 4 5\n1 3 3 3 3\n3 4 4 1 1\n2 2 2 4 5\n3 1 1 4 4\n", "2500 2500 8\n1 549 1279 1263 2189\n1 303 795 1888 2432\n1 2227 622 2418 1161\n3 771 2492 1335 1433\n1 2017 2100 2408 2160\n3 48 60 798 729\n1 347 708 1868 792\n3 1940 2080 377 1546\n" ]
[ "No\nYes\n", "No\nYes\nNo\n" ]
For the first example, the situations of Koyomi's actions are illustrated below.
[ { "input": "5 6 5\n1 2 2 4 5\n1 3 3 3 3\n3 4 4 1 1\n2 2 2 4 5\n3 1 1 4 4", "output": "No\nYes" }, { "input": "2500 2500 8\n1 549 1279 1263 2189\n1 303 795 1888 2432\n1 2227 622 2418 1161\n3 771 2492 1335 1433\n1 2017 2100 2408 2160\n3 48 60 798 729\n1 347 708 1868 792\n3 1940 2080 377 1546", "ou...
1,122
248,012,800
-1
126,644
28
Don't fear, DravDe is kind
[ "binary search", "data structures", "dp", "hashing" ]
D. Don't fear, DravDe is kind
2
256
A motorcade of *n* trucks, driving from city Β«ZΒ» to city Β«Π—Β», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is described with four numbers: - *v* β€” value of the truck, of its passangers and cargo - *c* β€” amount of passanger on the truck, the driver included - *l* β€” total amount of people that should go into the tunnel before this truck, so that the driver can overcome his fear (Β«if the monster appears in front of the motorcade, he'll eat them firstΒ») - *r* β€” total amount of people that should follow this truck, so that the driver can overcome his fear (Β«if the monster appears behind the motorcade, he'll eat them firstΒ»). Since the road is narrow, it's impossible to escape DravDe, if he appears from one side. Moreover, the motorcade can't be rearranged. The order of the trucks can't be changed, but it's possible to take any truck out of the motorcade, and leave it near the tunnel for an indefinite period. You, as the head of the motorcade, should remove some of the trucks so, that the rest of the motorcade can move into the tunnel and the total amount of the left trucks' values is maximal.
The first input line contains integer number *n* (1<=≀<=*n*<=≀<=105) β€” amount of trucks in the motorcade. The following *n* lines contain four integers each. Numbers in the *i*-th line: *v**i*,<=*c**i*,<=*l**i*,<=*r**i* (1<=≀<=*v**i*<=≀<=104,<=1<=≀<=*c**i*<=≀<=105,<=0<=≀<=*l**i*,<=*r**i*<=≀<=105) β€” describe the *i*-th truck. The trucks are numbered from 1, counting from the front of the motorcade.
In the first line output number *k* β€” amount of trucks that will drive into the tunnel. In the second line output *k* numbers β€” indexes of these trucks in ascending order. Don't forget please that you are not allowed to change the order of trucks. If the answer is not unique, output any.
[ "5\n1 1 0 3\n1 1 1 2\n1 1 2 1\n1 1 3 0\n2 1 3 0\n", "5\n1 1 0 3\n10 1 2 1\n2 2 1 1\n10 1 1 2\n3 1 3 0\n" ]
[ "4\n1 2 3 5 \n", "3\n1 3 5 \n" ]
none
[ { "input": "5\n1 1 0 3\n1 1 1 2\n1 1 2 1\n1 1 3 0\n2 1 3 0", "output": "4\n1 2 3 5 " }, { "input": "5\n1 1 0 3\n10 1 2 1\n2 2 1 1\n10 1 1 2\n3 1 3 0", "output": "3\n1 3 5 " }, { "input": "10\n3007 1 0 12\n5126 1 1 11\n2245 2 2 9\n8547 1 4 8\n8531 1 5 7\n5017 1 6 6\n6222 1 7 5\n6748 1 8 4...
92
0
0
128,150
486
Palindrome Transformation
[ "brute force", "greedy", "implementation" ]
null
null
Nam is playing with a string on his computer. The string consists of *n* lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down. There is a cursor pointing at some symbol of the string. Suppose that cursor is at position *i* (1<=≀<=*i*<=≀<=*n*, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position *i*<=-<=1 if *i*<=&gt;<=1 or to the end of the string (i. e. position *n*) otherwise. The same holds when he presses the right arrow key (if *i*<==<=*n*, the cursor appears at the beginning of the string). When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key. Initially, the text cursor is at position *p*. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
The first line contains two space-separated integers *n* (1<=≀<=*n*<=≀<=105) and *p* (1<=≀<=*p*<=≀<=*n*), the length of Nam's string and the initial position of the text cursor. The next line contains *n* lowercase characters of Nam's string.
Print the minimum number of presses needed to change string into a palindrome.
[ "8 3\naeabcaez\n" ]
[ "6\n" ]
A string is a palindrome if it reads the same forward or reversed. In the sample test, initial Nam's string is: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7cd1b7b2498296406fff738215b48ddd9a12898d.png" style="max-width: 100.0%;max-height: 100.0%;"/> (cursor position is shown bold). In optimal solution, Nam may do 6 following steps: The result, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f998673d1ad2128f8e2de7ff01895c8ef9ee34ff.png" style="max-width: 100.0%;max-height: 100.0%;"/>, is now a palindrome.
[ { "input": "8 3\naeabcaez", "output": "6" }, { "input": "8 3\nabcddcbb", "output": "3" }, { "input": "4 4\nrkoa", "output": "14" }, { "input": "39 30\nyehuqwaffoiyxhkmdipxroolhahbhzprioobxfy", "output": "138" }, { "input": "40 23\nvwjzsgpdsopsrpsyccavfkyyahdgkmdxr...
46
0
0
128,287
723
st-Spanning Tree
[ "dsu", "graphs", "greedy", "implementation" ]
null
null
You are given an undirected connected graph consisting of *n* vertices and *m* edges. There are no loops and no multiple edges in the graph. You are also given two distinct vertices *s* and *t*, and two values *d**s* and *d**t*. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex *s* doesn't exceed *d**s*, and the degree of the vertex *t* doesn't exceed *d**t*, or determine, that there is no such spanning tree. The spanning tree of the graph *G* is a subgraph which is a tree and contains all vertices of the graph *G*. In other words, it is a connected graph which contains *n*<=-<=1 edges and can be obtained by removing some of the edges from *G*. The degree of a vertex is the number of edges incident to this vertex.
The first line of the input contains two integers *n* and *m* (2<=≀<=*n*<=≀<=200<=000, 1<=≀<=*m*<=≀<=*min*(400<=000,<=*n*Β·(*n*<=-<=1)<=/<=2))Β β€” the number of vertices and the number of edges in the graph. The next *m* lines contain the descriptions of the graph's edges. Each of the lines contains two integers *u* and *v* (1<=≀<=*u*,<=*v*<=≀<=*n*, *u*<=β‰ <=*v*)Β β€” the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers *s*, *t*, *d**s*, *d**t* (1<=≀<=*s*,<=*t*<=≀<=*n*, *s*<=β‰ <=*t*, 1<=≀<=*d**s*,<=*d**t*<=≀<=*n*<=-<=1).
If the answer doesn't exist print "No" (without quotes) in the only line of the output. Otherwise, in the first line print "Yes" (without quotes). In the each of the next (*n*<=-<=1) lines print two integers β€” the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them.
[ "3 3\n1 2\n2 3\n3 1\n1 2 1 1\n", "7 8\n7 4\n1 3\n5 4\n5 7\n3 2\n2 4\n6 1\n1 2\n6 4 1 4\n" ]
[ "Yes\n3 2\n1 3\n", "Yes\n1 3\n5 7\n3 2\n7 4\n2 4\n6 1\n" ]
none
[ { "input": "3 3\n1 2\n2 3\n3 1\n1 2 1 1", "output": "Yes\n3 2\n1 3" }, { "input": "7 8\n7 4\n1 3\n5 4\n5 7\n3 2\n2 4\n6 1\n1 2\n6 4 1 4", "output": "Yes\n1 3\n5 7\n3 2\n7 4\n2 4\n6 1" }, { "input": "10 15\n4 1\n5 10\n2 1\n5 7\n9 2\n4 6\n6 7\n9 1\n6 9\n8 4\n8 3\n9 8\n3 9\n2 3\n7 10\n10 1 ...
935
90,316,800
3
128,631
993
The Moral Dilemma
[]
null
null
Hibiki and Dita are in love with each other, but belong to communities that are in a long lasting conflict. Hibiki is deeply concerned with the state of affairs, and wants to figure out if his relationship with Dita is an act of love or an act of treason. Hibiki prepared several binary features his decision will depend on, and built a three layer logical circuit on top of them, each layer consisting of one or more [logic gates](https://en.wikipedia.org/wiki/Logic_gate). Each gate in the circuit is either "or", "and", "nor" (not or) or "nand" (not and). Each gate in the first layer is connected to exactly two features. Each gate in the second layer is connected to exactly two gates in the first layer. The third layer has only one "or" gate, which is connected to all the gates in the second layer (in other words, the entire circuit produces 1 if and only if at least one gate in the second layer produces 1). The problem is, Hibiki knows very well that when the person is in love, his ability to think logically degrades drastically. In particular, it is well known that when a person in love evaluates a logical circuit in his mind, every gate evaluates to a value that is the opposite of what it was supposed to evaluate to. For example, "or" gates return 1 if and only if both inputs are zero, "t{nand}" gates produce 1 if and only if both inputs are one etc. In particular, the "or" gate in the last layer also produces opposite results, and as such if Hibiki is in love, the entire circuit produces 1 if and only if all the gates on the second layer produced 0. Hibiki can’t allow love to affect his decision. He wants to know what is the smallest number of gates that needs to be removed from the second layer so that the output of the circuit for all possible inputs doesn't depend on whether Hibiki is in love or not.
The first line contains three integers $n$, $m$, $k$ ($2 \le n, m \le 50$; $1 \le k \le 50$) β€” the number of input features, the number of gates in the first layer, and the number of gates in the second layer correspondingly. The second line contains $m$ pairs of strings separated by spaces describing the first layer. The first string in each pair describes the gate ("and", "or", "nand" or "nor"), and the second string describes the two input features the gate is connected two as a string consisting of exactly $n$ characters, with exactly two characters (that correspond to the input features the gate is connected to) equal to 'x' and the remaining characters equal to ".'. The third line contains $k$ pairs of strings separated by spaces describing the second layer in the same format, where the strings that describe the input parameters have length $m$ and correspond to the gates of the first layer.
Print the number of gates that need to be removed from the second layer so that the output of the remaining circuit doesn't depend on whether Hibiki is in love or not. If no matter how many gates are removed the output of the circuit continues to depend on Hibiki's feelings, print $-1$.
[ "2 2 2\nand xx nand xx\nand xx or xx\n", "3 2 2\nand xx. nor .xx\nand xx nor xx\n", "4 4 5\nnor x..x and ..xx and xx.. nand xx..\nnand ..xx nor ..xx and xx.. nor ..xx or ..xx\n" ]
[ "1\n", "-1\n", "2\n" ]
In the first example the two gates in the first layer are connected to the same inputs, but first computes "and" while second computes "nand", and as such their output is always different no matter what the input is and whether Hibiki is in love or not. The second layer has "or" and "and" gates both connected to the two gates in the first layer. If Hibiki is not in love, the "and" gate will produce 0 and the "or" gate will produce 1 no matter what input features are equal to, with the final "or" gate in the third layer always producing the final answer of 1. If Hibiki is in love, "and" gate in the second layer will produce 1 and "or" gate will produce 0 no matter what the input is, with the final "or" gate in the third layer producing the final answer of 0. Thus, if both gates in the second layer are kept, the output of the circuit does depend on whether Hibiki is in love. If any of the two gates in the second layer is dropped, the output of the circuit will no longer depend on whether Hibiki is in love or not, and hence the answer is 1. In the second example no matter what gates are left in the second layer, the output of the circuit will depend on whether Hibiki is in love or not. In the third example if Hibiki keeps second, third and fourth gates in the second layer, the circuit will not depend on whether Hibiki is in love or not. Alternatively, he can keep the first and the last gates. The former requires removing two gates, the latter requires removing three gates, so the former is better, and the answer is 2.
[]
61
0
-1
128,652
540
Infinite Inversions
[ "binary search", "data structures", "implementation", "sortings", "trees" ]
null
null
There is an infinite sequence consisting of all positive integers in the increasing order: *p*<==<={1,<=2,<=3,<=...}. We performed *n* swap operations with this sequence. A *swap*(*a*,<=*b*) is an operation of swapping the elements of the sequence on positions *a* and *b*. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (*i*,<=*j*), that *i*<=&lt;<=*j* and *p**i*<=&gt;<=*p**j*.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=105)Β β€” the number of swap operations applied to the sequence. Each of the next *n* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=109, *a**i*<=β‰ <=*b**i*)Β β€” the arguments of the swap operation.
Print a single integer β€” the number of inversions in the resulting sequence.
[ "2\n4 2\n1 4\n", "3\n1 6\n3 4\n2 5\n" ]
[ "4\n", "15\n" ]
In the first sample the sequence is being modified as follows: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/014a32f190673020641bf266b205f41f0a704f2d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
[ { "input": "2\n4 2\n1 4", "output": "4" }, { "input": "3\n1 6\n3 4\n2 5", "output": "15" }, { "input": "1\n1000000000 1", "output": "1999999997" }, { "input": "5\n2 5\n6 3\n4 6\n5 4\n2 5", "output": "5" }, { "input": "4\n2 5\n4 3\n1 4\n6 2", "output": "8" },...
46
0
-1
128,978
98
Help Shrek and Donkey
[ "dp", "games", "math", "probabilities" ]
E. Help Shrek and Donkey
2
256
Shrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds *m* cards and the Donkey holds *n* cards (the players do not see each other's cards), and one more card lies on the table face down so that both players cannot see it as well. Thus, at the beginning of the game there are overall *m*<=+<=*n*<=+<=1 cards. Besides, the players know which cards the pack of cards consists of and their own cards (but they do not know which card lies on the table and which ones the other player has). The players move in turn and Shrek starts. During a move a player can: - Try to guess which card is lying on the table. If he guesses correctly, the game ends and he wins. If his guess is wrong, the game also ends but this time the other player wins.- Name any card from the pack. If the other player has such card, he must show it and put it aside (so that this card is no longer used in the game). If the other player doesn't have such card, he says about that. Help Shrek assuming the pills are good in quality and that both players using them start playing in the optimal manner.
The first line contains space-separated integers *m* and *n* (0<=≀<=*m*,<=*n*<=≀<=1000).
Print space-separated probabilities that Shrek wins and Donkey wins correspondingly; the absolute error should not exceed 10<=-<=9.
[ "0 3\n", "1 0\n", "1 1\n" ]
[ "0.25 0.75\n", "1 0\n", "0.5 0.5\n" ]
none
[ { "input": "0 3", "output": "0.2500000000000000 0.7500000000000000" }, { "input": "1 0", "output": "1.0000000000000000 0.0000000000000000" }, { "input": "1 1", "output": "0.5000000000000000 0.5000000000000000" }, { "input": "0 0", "output": "1.0000000000000000 0.000000000...
218
17,920,000
3.912121
129,468
380
Sereja and Cinema
[ "combinatorics", "math" ]
null
null
The cinema theater hall in Sereja's city is *n* seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for *n*<==<=4. Today it's the premiere of a movie called "Dry Hard". The tickets for all the seats have been sold. There is a very strict controller at the entrance to the theater, so all *n* people will come into the hall one by one. As soon as a person enters a cinema hall, he immediately (momentarily) takes his seat and occupies all empty slots to the left and to the right from him. If there are no empty slots, the man gets really upset and leaves. People are not very constant, so it's hard to predict the order in which the viewers will enter the hall. For some seats, Sereja knows the number of the viewer (his number in the entering queue of the viewers) that will come and take this seat. For others, it can be any order. Being a programmer and a mathematician, Sereja wonders: how many ways are there for the people to enter the hall, such that nobody gets upset? As the number can be quite large, print it modulo 1000000007 (109<=+<=7).
The first line contains integer *n* (1<=≀<=*n*<=≀<=105). The second line contains *n* integers, the *i*-th integer shows either the index of the person (index in the entering queue) with the ticket for the *i*-th seat or a 0, if his index is not known. It is guaranteed that all positive numbers in the second line are distinct. You can assume that the index of the person who enters the cinema hall is a unique integer from 1 to *n*. The person who has index 1 comes first to the hall, the person who has index 2 comes second and so on.
In a single line print the remainder after dividing the answer by number 1000000007 (109<=+<=7).
[ "11\n0 0 0 0 0 0 0 0 0 0 0\n", "6\n0 3 1 0 0 0\n" ]
[ "1024\n", "3\n" ]
none
[]
46
0
0
129,523
433
Tachibana Kanade's Tofu
[ "dp" ]
null
null
Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu. Each piece of tofu in the canteen is given a *m*-based number, all numbers are in the range [*l*,<=*r*] (*l* and *r* being *m*-based numbers), and for every *m*-based integer in the range [*l*,<=*r*], there exists a piece of tofu with that number. To judge what tofu is Mapo Tofu, Tachibana Kanade chose *n* *m*-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero. Tachibana Kanade considers tofu with values no more than *k* to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu?
The first line contains three integers *n*, *m* and *k*Β (1<=≀<=*n*<=≀<=200;Β 2<=≀<=*m*<=≀<=20;Β 1<=≀<=*k*<=≀<=500). Where *n* denotes the number of strings, *m* denotes the base used, and *k* denotes the limit of the value for Mapo Tofu. The second line represents the number *l*. The first integer in the line is *len* (1<=≀<=*len*<=≀<=200), describing the length (number of digits in base *m*) of *l*. Then follow *len* integers *a*1,<=*a*2,<=...,<=*a**len*Β (0<=≀<=*a**i*<=&lt;<=*m*;Β *a*1<=&gt;<=0) separated by spaces, representing the digits of *l*, with *a*1 being the highest digit and *a**len* being the lowest digit. The third line represents the number *r* in the same format as *l*. It is guaranteed that 1<=≀<=*l*<=≀<=*r*. Then follow *n* lines, each line describing a number string. The *i*-th line contains the *i*-th number string and *v**i* β€” the value of the *i*-th string (1<=≀<=*v**i*<=≀<=200). All number strings are described in almost the same format as *l*, the only difference is number strings may contain necessary leading zeros (see the first example). The sum of the lengths of all number strings does not exceed 200.
Output the number of pieces of Mapo Tofu modulo 1000000007 (109<=+<=7). The answer should be a decimal integer.
[ "2 10 1\n1 1\n3 1 0 0\n1 1 1\n1 0 1\n", "2 10 12\n2 5 9\n6 6 3 5 4 9 7\n2 0 6 1\n3 6 7 2 1\n", "4 2 6\n6 1 0 1 1 1 0\n6 1 1 0 1 0 0\n1 1 2\n3 0 1 0 5\n4 0 1 1 0 4\n3 1 0 1 2\n" ]
[ "97\n", "635439\n", "2\n" ]
In the first sample, 10, 11 and 100 are the only three decimal numbers in [1, 100] with a value greater than 1. Here the value of 1 is 1 but not 2, since numbers cannot contain leading zeros and thus cannot be written as "01". In the second sample, no numbers in the given interval have a value greater than 12. In the third sample, 110000 and 110001 are the only two binary numbers in the given interval with a value no greater than 6.
[]
46
0
0
129,790
63
Sweets Game
[ "bitmasks", "dfs and similar", "dp", "games", "implementation" ]
E. Sweets Game
3
256
Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward. The box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses. Karlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake.
The input data contains 5 lines, containing 19 words consisting of one symbol. The word "O" means that the cell contains a chocolate and a "." stands for an empty cell. It is guaranteed that the box contains at least one chocolate. See the examples for better understanding.
If Karlsson gets the cake, print "Karlsson" (without the quotes), otherwise print "Lillebror" (yet again without the quotes).
[ ". . .\n . . O .\n. . O O .\n . . . .\n . . .\n", ". . .\n . . . O\n. . . O .\n O . O .\n . O .\n" ]
[ "Lillebror", "Karlsson" ]
none
[ { "input": " . . .\n . . O .\n. . O O .\n . . . .\n . . .", "output": "Lillebror" }, { "input": " . . .\n . . . O\n. . . O .\n O . O .\n . O .", "output": "Karlsson" }, { "input": " . . .\n . . . .\n. . . . .\n . . O .\n . . .", "output": "Karlsson" }, { "input": " . ....
0
0
-1
129,867
374
Inna and Dima
[ "dfs and similar", "dp", "graphs", "implementation" ]
null
null
Inna and Dima bought a table of size *n*<=Γ—<=*m* in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A". Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: 1. initially, Inna chooses some cell of the table where letter "D" is written; 1. then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; 1. Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
The first line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=103). Then follow *n* lines that describe Inna and Dima's table. Each line contains *m* characters. Each character is one of the following four characters: "D", "I", "M", "A". Note that it is not guaranteed that the table contains at least one letter "D".
If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer β€” the maximum number of times Inna can go through name DIMA.
[ "1 2\nDI\n", "2 2\nMA\nID\n", "5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID\n" ]
[ "Poor Dima!\n", "Poor Inna!\n", "4\n" ]
Notes to the samples: In the first test sample, Inna cannot go through name DIMA a single time. In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner. In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
[ { "input": "1 2\nDI", "output": "Poor Dima!" }, { "input": "2 2\nMA\nID", "output": "Poor Inna!" }, { "input": "5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID", "output": "4" }, { "input": "1 1\nI", "output": "Poor Dima!" }, { "input": "5 5\nDIMAD\nADDDI\nMDDDM\nIDDDA\nDA...
1,000
66,764,800
0
129,924
704
Black Widow
[ "dp", "graphs", "implementation", "math" ]
null
null
Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form: Where represents logical OR and represents logical exclusive OR (XOR), and *v**i*,<=*j* are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and *v**i*,<=*j* are called literals. In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables *x*1,<=*x*2,<=...,<=*x**m* and their negations. An XNF formula is 2-XNF-2 if: 1. For each 1<=≀<=*i*<=≀<=*n*, *k**i*<=≀<=2, i.e. the size of each clause doesn't exceed two. 1. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of *m* variables, consisting of *n* clauses. Please, make sure to check the samples in order to properly understand how the formula looks like. Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set *x*1,<=...,<=*x**m* with *true* and *false* (out of total of 2*m* ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109<=+<=7. Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to *false* or *true* gives different ways to set variables).
The first line of input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100<=000)Β β€” the number of clauses and the number of variables respectively. The next *n* lines contain the formula. The *i*-th of them starts with an integer *k**i*Β β€” the number of literals in the *i*-th clause. It is followed by *k**i* non-zero integers *a**i*,<=1,<=...,<=*a**i*,<=*k**i*. If *a**i*,<=*j*<=&gt;<=0 then *v**i*,<=*j* is *x**a**i*,<=*j* otherwise it's negation of *x*<=-<=*a**i*,<=*j* (1<=≀<=*k**i*<=≀<=2, <=-<=*m*<=≀<=*a**i*,<=*j*<=≀<=*m*, *a**i*,<=*j*<=β‰ <=0).
Print the answer modulo 1<=000<=000<=007 (109<=+<=7) in one line.
[ "6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5\n", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8\n", "2 3\n2 1 1\n2 -3 3\n" ]
[ "48\n", "544\n", "4\n" ]
The equation in the first sample is: The equation in the second sample is: The equation in the third sample is:
[]
46
0
0
130,400
774
Perfectionist Arkadiy
[ "*special", "number theory" ]
null
null
Arkadiy has lots square photos with size *a*<=Γ—<=*a*. He wants to put some of them on a rectangular wall with size *h*<=Γ—<=*w*. The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and columns of photos to the nearest bound of the wall must be equal to *x*, where *x* is some non-negative real number. Look on the picture below for better understanding of the statement. Arkadiy haven't chosen yet how many photos he would put on the wall, however, he want to put at least one photo. Your task is to determine the minimum value of *x* which can be obtained after putting photos, or report that there is no way to put positive number of photos and satisfy all the constraints. Suppose that Arkadiy has enough photos to make any valid arrangement according to the constraints. Note that Arkadiy wants to put at least one photo on the wall. The photos should not overlap, should completely lie inside the wall bounds and should have sides parallel to the wall sides.
The first line contains three integers *a*, *h* and *w* (1<=≀<=*a*,<=*h*,<=*w*<=≀<=109) β€” the size of photos and the height and the width of the wall.
Print one non-negative real number β€” the minimum value of *x* which can be obtained after putting the photos on the wall. The absolute or the relative error of the answer must not exceed 10<=-<=6. Print -1 if there is no way to put positive number of photos and satisfy the constraints.
[ "2 18 13\n", "4 4 4\n", "3 4 3\n" ]
[ "0.5\n", "0\n", "-1\n" ]
In the first example Arkadiy can put 7 rows of photos with 5 photos in each row, so the minimum value of *x* equals to 0.5. In the second example Arkadiy can put only 1 photo which will take the whole wall, so the minimum value of *x* equals to 0. In the third example there is no way to put positive number of photos and satisfy the constraints described in the statement, so the answer is -1.
[ { "input": "2 18 13", "output": "0.50000000000000000000" }, { "input": "4 4 4", "output": "0.00000000000000000000" }, { "input": "3 4 3", "output": "-1" }, { "input": "9 81 23", "output": "-1" }, { "input": "11 21 21", "output": "5.00000000000000000000" }, ...
109
0
3
130,434
73
Morrowindows
[ "math", "number theory" ]
E. Morrowindows
2
256
Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than *x* and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in *n* different modes. Displaying in mode *i* is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly *a**i* items. In addition, each mode shows how many pages *b**i* is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it? Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size. Knowing the number of *a**i*, *x* and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers *a**i*, *x* and he is able to know number *b**i* after viewing items in mode *i*.
The first line contains two integers *n* and *x* (0<=≀<=*n*<=≀<=105,<=2<=≀<=*x*<=≀<=109). The second line contains integers *a**i* (1<=≀<=*a**i*<=≀<=109). Some numbers among all *a**i* may be equal.
Output the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output <=-<=1.
[ "2 4\n2 3\n", "1 4\n2\n" ]
[ "2\n", "-1\n" ]
In the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.
[]
92
0
0
130,548
718
Andrew and Chemistry
[ "dp", "hashing", "trees" ]
null
null
During the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he faced some difficulties and asks you to help. Formally, you are given a tree consisting of *n* vertices, such that the degree of each vertex doesn't exceed 4. You have to count the number of distinct non-isomorphic trees that can be obtained by adding to this tree one new vertex and one new edge, such that the graph is still the tree and the degree of each vertex doesn't exceed 4. Two trees are isomorphic if there exists a bijection *f*(*v*) such that vertices *u* and *v* are connected by an edge if and only if vertices *f*(*v*) and *f*(*u*) are connected by an edge.
The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of vertices in the tree. Then follow *n*<=-<=1 lines with edges descriptions. Each edge is given by two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*)Β β€” indices of vertices connected by an edge. It's guaranteed that the given graph is a tree and the degree of each vertex doesn't exceed 4.
Print one integerΒ β€” the answer to the question.
[ "4\n1 2\n2 3\n2 4\n", "5\n1 2\n1 3\n1 4\n1 5\n", "5\n2 5\n5 3\n4 3\n4 1\n" ]
[ "2\n", "1\n", "3\n" ]
In the first sample, one can add new vertex to any existing vertex, but the trees we obtain by adding a new vertex to vertices 1, 3 and 4 are isomorphic, thus the answer is 2. In the second sample, one can't add new vertex to the first vertex, as its degree is already equal to four. Trees, obtained by adding a new vertex to vertices 2, 3, 4 and 5 are isomorphic, thus the answer is 1.
[]
15
0
0
131,516
268
Playlist
[ "math", "probabilities", "sortings" ]
null
null
Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs. Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist: - If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song. - If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song. For example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following: 1. Manao listens to A, he likes it, he remembers it. 1. Manao listens to B, he does not like it, so he listens to A, again. 1. Manao listens to C, he likes the song and he remembers it, too. 1. Manao listens to D, but does not enjoy it and re-listens to songs A and C. That is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening. Manao has received *n* songs: the *i*-th of them is *l**i* seconds long and Manao may like it with a probability of *p**i* percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=50000). The *i*-th of the following *n* lines contains two integers, separated by a single space β€” *l**i* and *p**i* (15<=≀<=*l**i*<=≀<=1000, 0<=≀<=*p**i*<=≀<=100) β€” the length of the *i*-th song in seconds and the probability that Manao will like the song, in percents.
In a single line print a single real number β€” the maximum expected listening time over all permutations of songs. The answer will be considered valid if the absolute or relative error does not exceed 10<=-<=9.
[ "3\n150 20\n150 50\n100 50\n", "4\n300 0\n300 50\n240 50\n360 80\n" ]
[ "537.500000000\n", "2121.000000000\n" ]
Consider the first test case. If Manao listens to the songs in the order in which they were originally compiled, the mathematical expectation will be equal to 467.5 seconds. The maximum expected value is obtained by putting the first song at the end of the playlist. Consider the second test case. The song which is 360 seconds long should be listened to first. The song 300 seconds long which Manao will dislike for sure should be put in the end.
[]
92
0
0
131,704
0
none
[ "none" ]
null
null
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has *n* vertices. He wants to paint some vertices of the tree black such that from any vertex *u* there is at least one black vertex *v* at distance no more than *k*. Distance between two vertices of the tree is the minimum possible number of edges of the path between them. As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109<=+<=7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=100, 0<=≀<=*k*<=≀<=*min*(20,<=*n*<=-<=1))Β β€” the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for *k*. Each of the next *n*<=-<=1 lines contain two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*)Β β€” indices of vertices, connected by the *i*-th edge. It's guaranteed that given graph is a tree.
Print one integerΒ β€” the remainder of division of the number of ways to paint the tree by 1<=000<=000<=007 (109<=+<=7).
[ "2 0\n1 2\n", "2 1\n1 2\n", "4 1\n1 2\n2 3\n3 4\n", "7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7\n" ]
[ "1\n", "3\n", "9\n", "91\n" ]
In the first sample, Ostap has to paint both vertices black. In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both. In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.
[ { "input": "2 0\n1 2", "output": "1" }, { "input": "2 1\n1 2", "output": "3" }, { "input": "4 1\n1 2\n2 3\n3 4", "output": "9" }, { "input": "7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7", "output": "91" }, { "input": "1 0", "output": "1" }, { "input": "10 0\n5 6...
30
0
0
131,745
725
Family Photos
[ "games", "greedy" ]
null
null
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are *n* stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks. Each photo is described by two non-negative integers *a* and *b*, indicating that it is worth *a* units of happiness to Alice and *b* units of happiness to Bonnie. Values of *a* and *b* might differ for different photos. It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively. The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has *x* happiness and Bonnie has *y* happiness at the end, you should print *x*<=-<=*y*.
The first line of input contains a single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of two-photo stacks. Then follow *n* lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers *a*1, *b*1, *a*2 and *b*2, each not exceeding 109. *a*1 and *b*1 describe the top photo in the stack, while *a*2 and *b*2 describe the bottom photo in the stack.
Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.
[ "2\n12 3 4 7\n1 15 9 1\n", "2\n5 4 8 8\n4 12 14 0\n", "1\n0 10 0 10\n" ]
[ "1\n", "4\n", "-10\n" ]
none
[ { "input": "2\n12 3 4 7\n1 15 9 1", "output": "1" }, { "input": "2\n5 4 8 8\n4 12 14 0", "output": "4" }, { "input": "1\n0 10 0 10", "output": "-10" }, { "input": "10\n0 1000000000 0 1000000000\n0 1000000000 0 1000000000\n0 1000000000 0 1000000000\n0 1000000000 0 1000000000\n...
124
2,150,400
-1
131,860
370
Broken Monitor
[ "brute force", "constructive algorithms", "greedy", "implementation" ]
null
null
Innocentius has a problem β€” his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus. Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention". Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that: - the frame's width is 1 pixel, - the frame doesn't go beyond the borders of the screen, - all white pixels of the monitor are located on the frame, - of all frames that satisfy the previous three conditions, the required frame must have the smallest size. Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is *d*<==<=3, then it consists of 8 pixels, if its size is *d*<==<=2, then it contains 4 pixels and if *d*<==<=1, then the frame is reduced to a single pixel.
The first line contains the resolution of the monitor as a pair of integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=2000). The next *n* lines contain exactly *m* characters each β€” the state of the monitor pixels at the moment of the game. Character "." (period, ASCII code 46) corresponds to the black pixel, and character "w" (lowercase English letter w) corresponds to the white pixel. It is guaranteed that at least one pixel of the monitor is white.
Print the monitor screen. Represent the sought frame by characters "+" (the "plus" character). The pixels that has become white during the game mustn't be changed. Print them as "w". If there are multiple possible ways to position the frame of the minimum size, print any of them. If the required frame doesn't exist, then print a single line containing number -1.
[ "4 8\n..w..w..\n........\n........\n..w..w..\n", "5 6\n......\n.w....\n......\n..w...\n......\n", "2 4\n....\n.w..\n", "2 6\nw..w.w\n...w..\n" ]
[ "..w++w..\n..+..+..\n..+..+..\n..w++w..\n", "......\n+w+...\n+.+...\n++w...\n......\n", "....\n.w..\n", "-1\n" ]
In the first sample the required size of the optimal frame equals 4. In the second sample the size of the optimal frame equals 3. In the third sample, the size of the optimal frame is 1. In the fourth sample, the required frame doesn't exist.
[ { "input": "4 8\n..w..w..\n........\n........\n..w..w..", "output": "..w++w..\n..+..+..\n..+..+..\n..w++w.." }, { "input": "2 4\n....\n.w..", "output": "....\n.w.." }, { "input": "2 6\nw..w.w\n...w..", "output": "-1" }, { "input": "9 4\n....\n....\n....\n....\n....\n..w.\n......
1,465
35,123,200
3
132,299
615
Hexagons
[ "binary search", "implementation", "math" ]
null
null
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined: Ayrat is searching through the field. He started at point (0,<=0) and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after *n* moves.
The only line of the input contains integer *n* (0<=≀<=*n*<=≀<=1018)Β β€” the number of Ayrat's moves.
Print two integers *x* and *y*Β β€” current coordinates of Ayrat coordinates.
[ "3\n", "7\n" ]
[ "-2 0\n", "3 2\n" ]
none
[ { "input": "3", "output": "-2 0" }, { "input": "7", "output": "3 2" }, { "input": "39", "output": "5 6" }, { "input": "14", "output": "-2 -4" }, { "input": "94", "output": "8 8" }, { "input": "60", "output": "8 0" }, { "input": "60", "o...
15
0
0
133,023
156
Mrs. Hudson's Pancakes
[ "brute force", "dp" ]
null
null
Mrs. Hudson hasn't made her famous pancakes for quite a while and finally she decided to make them again. She has learned *m* new recipes recently and she can't wait to try them. Those recipes are based on *n* special spices. Mrs. Hudson has these spices in the kitchen lying in jars numbered with integers from 0 to *n*<=-<=1 (each spice lies in an individual jar). Each jar also has the price of the corresponding spice inscribed β€” some integer *a**i*. We know three values for the *i*-th pancake recipe: *d**i*, *s**i*, *c**i*. Here *d**i* and *c**i* are integers, and *s**i* is the pattern of some integer written in the numeral system with radix *d**i*. The pattern contains digits, Latin letters (to denote digits larger than nine) and question marks. Number *x* in the *d**i*-base numeral system matches the pattern *s**i*, if we can replace question marks in the pattern with digits and letters so that we obtain number *x* (leading zeroes aren't taken into consideration when performing the comparison). More formally: each question mark should be replaced by exactly one digit or exactly one letter. If after we replace all question marks we get a number with leading zeroes, we can delete these zeroes. For example, number 40A9875 in the 11-base numeral system matches the pattern "??4??987?", and number 4A9875 does not. To make the pancakes by the *i*-th recipe, Mrs. Hudson should take all jars with numbers whose representation in the *d**i*-base numeral system matches the pattern *s**i*. The control number of the recipe (*z**i*) is defined as the sum of number *c**i* and the product of prices of all taken jars. More formally: (where *j* is all such numbers whose representation in the *d**i*-base numeral system matches the pattern *s**i*). Mrs. Hudson isn't as interested in the control numbers as she is in their minimum prime divisors. Your task is: for each recipe *i* find the minimum prime divisor of number *z**i*. If this divisor exceeds 100, then you do not have to find it, print -1.
The first line contains the single integer *n* (1<=≀<=*n*<=≀<=104). The second line contains space-separated prices of the spices *a*0,<=*a*1,<=...,<=*a**n*<=-<=1, where *a**i* is an integer (1<=≀<=*a**i*<=≀<=1018). The third line contains the single integer *m* (1<=≀<=*m*<=≀<=3Β·104) β€” the number of recipes Mrs. Hudson has learned. Next *m* lines describe the recipes, one per line. First you are given an integer *d**i*, written in the decimal numeral system (2<=≀<=*d**i*<=≀<=16). Then after a space follows the *s**i* pattern β€” a string from 1 to 30 in length, inclusive, consisting of digits from "0" to "9", letters from "A" to "F" and signs "?". Letters from "A" to "F" should be considered as digits from 10 to 15 correspondingly. It is guaranteed that all digits of the pattern (including the digits that are represented by letters) are strictly less than *d**i*. Then after a space follows an integer *c**i*, written in the decimal numeral system (1<=≀<=*c**i*<=≀<=1018). Please do not use the %lld specificator to read or write 64-bit integers in Π‘++, in is preferred to use cin, cout, strings or the %I64d specificator instead.
For each recipe count by what minimum prime number the control number is divided and print this prime number on the single line. If this number turns out larger than 100, print -1.
[ "1\n1\n1\n2 ? 1\n", "4\n2 3 5 7\n4\n2 ?0 11\n2 ?1 13\n2 0? 17\n2 1? 19\n", "1\n1000000000000000000\n1\n16 ?????????????? 1\n" ]
[ "2\n", "3\n2\n23\n2\n", "-1\n" ]
In the first test any one-digit number in the binary system matches. The jar is only one and its price is equal to 1, the number *c* is also equal to 1, the control number equals 2. The minimal prime divisor of 2 is 2. In the second test there are 4 jars with numbers from 0 to 3, and the prices are equal 2, 3, 5 and 7 correspondingly β€” the first four prime numbers. In all recipes numbers should be two-digit. In the first recipe the second digit always is 0, in the second recipe the second digit always is 1, in the third recipe the first digit must be 0, in the fourth recipe the first digit always is 1. Consequently, the control numbers ​​are as follows: in the first recipe 2 × 5 + 11 = 21 (the minimum prime divisor is 3), in the second recipe 3 × 7 + 13 = 44 (the minimum prime divisor is 2), in the third recipe 2 × 3 + 17 = 23 (the minimum prime divisor is 23) and, finally, in the fourth recipe 5 × 7 + 19 = 54 (the minimum prime divisor is 2). In the third test, the number should consist of fourteen digits and be recorded in a sixteen-base numeral system. Number 0 (the number of the single bottles) matches, the control number will be equal to 10<sup class="upper-index">18</sup> + 1. The minimum prime divisor of this number is equal to 101 and you should print -1.
[]
60
0
0
133,342
86
Genetic engineering
[ "dp", "string suffix structures", "trees" ]
C. Genetic engineering
2
256
"Multidimensional spaces are completely out of style these days, unlike genetics problems" β€” thought physicist Woll and changed his subject of study to bioinformatics. Analysing results of sequencing he faced the following problem concerning DNA sequences. We will further think of a DNA sequence as an arbitrary string of uppercase letters "A", "C", "G" and "T" (of course, this is a simplified interpretation). Let *w* be a long DNA sequence and *s*1,<=*s*2,<=...,<=*s**m* β€” collection of short DNA sequences. Let us say that the collection filters *w* iff *w* can be covered with the sequences from the collection. Certainly, substrings corresponding to the different positions of the string may intersect or even cover each other. More formally: denote by |*w*| the length of *w*, let symbols of *w* be numbered from 1 to |*w*|. Then for each position *i* in *w* there exist pair of indices *l*,<=*r* (1<=≀<=*l*<=≀<=*i*<=≀<=*r*<=≀<=|*w*|) such that the substring *w*[*l*Β ...Β *r*] equals one of the elements *s*1,<=*s*2,<=...,<=*s**m* of the collection. Woll wants to calculate the number of DNA sequences of a given length filtered by a given collection, but he doesn't know how to deal with it. Help him! Your task is to find the number of different DNA sequences of length *n* filtered by the collection {*s**i*}. Answer may appear very large, so output it modulo 1000000009.
First line contains two integer numbers *n* and *m* (1<=≀<=*n*<=≀<=1000,<=1<=≀<=*m*<=≀<=10) β€” the length of the string and the number of sequences in the collection correspondently. Next *m* lines contain the collection sequences *s**i*, one per line. Each *s**i* is a nonempty string of length not greater than 10. All the strings consist of uppercase letters "A", "C", "G", "T". The collection may contain identical strings.
Output should contain a single integer β€” the number of strings filtered by the collection modulo 1000000009 (109<=+<=9).
[ "2 1\nA\n", "6 2\nCAT\nTACT\n" ]
[ "1\n", "2\n" ]
In the first sample, a string has to be filtered by "A". Clearly, there is only one such string: "AA". In the second sample, there exist exactly two different strings satisfying the condition (see the pictures below).
[]
60
0
0
133,567
938
Shortest Path Queries
[ "bitmasks", "data structures", "dsu", "graphs" ]
null
null
You are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). There are three types of queries you have to process: - 1 *x* *y* *d* β€” add an edge connecting vertex *x* to vertex *y* with weight *d*. It is guaranteed that there is no edge connecting *x* to *y* before this query; - 2 *x* *y* β€” remove an edge connecting vertex *x* to vertex *y*. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query; - 3 *x* *y* β€” calculate the length of the shortest path (possibly non-simple) from vertex *x* to vertex *y*. Print the answers for all queries of type 3.
The first line contains two numbers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=200000) β€” the number of vertices and the number of edges in the graph, respectively. Then *m* lines follow denoting the edges of the graph. Each line contains three integers *x*, *y* and *d* (1<=≀<=*x*<=&lt;<=*y*<=≀<=*n*, 0<=≀<=*d*<=≀<=230<=-<=1). Each pair (*x*,<=*y*) is listed at most once. The initial graph is connected. Then one line follows, containing an integer *q* (1<=≀<=*q*<=≀<=200000) β€” the number of queries you have to process. Then *q* lines follow, denoting queries in the following form: - 1 *x* *y* *d* (1<=≀<=*x*<=&lt;<=*y*<=≀<=*n*, 0<=≀<=*d*<=≀<=230<=-<=1) β€” add an edge connecting vertex *x* to vertex *y* with weight *d*. It is guaranteed that there is no edge connecting *x* to *y* before this query; - 2 *x* *y* (1<=≀<=*x*<=&lt;<=*y*<=≀<=*n*) β€” remove an edge connecting vertex *x* to vertex *y*. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query; - 3 *x* *y* (1<=≀<=*x*<=&lt;<=*y*<=≀<=*n*) β€” calculate the length of the shortest path (possibly non-simple) from vertex *x* to vertex *y*. It is guaranteed that at least one query has type 3.
Print the answers for all queries of type 3 in the order they appear in input.
[ "5 5\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n5\n3 1 5\n1 1 3 1\n3 1 5\n2 1 5\n3 1 5\n" ]
[ "1\n1\n2\n" ]
none
[ { "input": "5 5\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n5\n3 1 5\n1 1 3 1\n3 1 5\n2 1 5\n3 1 5", "output": "1\n1\n2" } ]
46
0
0
133,975
737
Tanya is 5!
[ "graph matchings", "graphs", "greedy", "schedules" ]
null
null
Tanya is now five so all her friends gathered together to celebrate her birthday. There are *n* children on the celebration, including Tanya. The celebration is close to its end, and the last planned attraction is gaming machines. There are *m* machines in the hall, they are numbered 1 through *m*. Each of the children has a list of machines he wants to play on. Moreover, for each of the machines he knows the exact time he wants to play on it. For every machine, no more than one child can play on this machine at the same time. It is evening already, so every adult wants to go home. To speed up the process, you can additionally rent second copies of each of the machines. To rent the second copy of the *j*-th machine, you have to pay *p**j* burles. After you rent a machine, you can use it for as long as you want. How long it will take to make every child play according to his plan, if you have a budget of *b* burles for renting additional machines? There is only one copy of each machine, so it's impossible to rent a third machine of the same type. The children can interrupt the game in any moment and continue it later. If the *i*-th child wants to play on the *j*-th machine, it is allowed after you rent the copy of the *j*-th machine that this child would play some part of the time on the *j*-th machine and some part of the time on its copy (each of these parts could be empty). The interruptions and changes take no time and can be performed in any integer moment of time. Of course, a child can't play on more than one machine at the same time. Remember, that it is not needed to save money (no one saves money at the expense of children happiness!), it is needed to minimize the latest moment of time some child ends his game.
The first line contains three integers *n*, *m* and *b* (1<=≀<=*n*<=≀<=40, 1<=≀<=*m*<=≀<=10, 0<=≀<=*b*<=≀<=106)Β β€” the number of children, the number of gaming machines and the budget for renting additional machines. The second line contains *m* integers *p*1,<=*p*2,<=...,<=*p**m* (1<=≀<=*p**j*<=≀<=106), where *p**j* is the rent price for the second copy of the *j*-th machine. *n* lines follow, *i*-th of them describes the wishes of the *i*-th child. The line starts with an integer *k**i* (0<=≀<=*k**i*<=≀<=*m*)Β β€” the number of machines, the *i*-th child wants to play on. Then there are *k**i* pairs in the line, the *y*-th of them is *x**iy*, *t**iy*. It means that, the *i*-th child wants to play *t**iy* (1<=≀<=*t**iy*<=≀<=2500) minutes on the *x**iy*-th (1<=≀<=*x**iy*<=≀<=*m*) machine. In each of these *n* lines the values *x**iy* are distinct.
In the first line print the minimum time in which all the children can finish their games. In the second line print a string of length *m* consisting of zeros and ones. The *j*-th character is '1', if the copy of *j*-th machine should be rated, and '0' otherwise. In the third line print integer *g* (0<=≀<=*g*<=≀<=106)Β β€” the total number of time segments of continuous playing for all of the children. Then in *g* lines print the segments as four integers *i*, *j*, *s*, *d*, meaning that the *i*-th child was playing on the *j*-th machine or its copy from the time moment *s* (*s*<=β‰₯<=0) for *d* minutes (*d*<=β‰₯<=1). You can print these lines in arbitrary order. If there are multiple answers, print any of them.
[ "2 2 100\n3 7\n2 1 3 2 1\n2 1 3 2 1\n", "3 2 15\n11 7\n2 2 10 1 5\n1 2 20\n2 1 4 2 3\n" ]
[ "4\n10\n8\n1 1 0 1\n2 2 0 1\n1 1 1 1\n2 1 1 1\n2 1 2 1\n1 1 2 1\n1 2 3 1\n2 1 3 1\n", "20\n01\n17\n2 2 0 4\n2 2 4 1\n1 1 5 2\n2 2 5 2\n1 2 7 5\n2 2 7 5\n2 2 12 1\n1 2 12 1\n3 1 13 4\n2 2 13 4\n1 2 13 4\n1 1 17 2\n3 2 17 2\n2 2 17 2\n1 1 19 1\n2 2 19 1\n3 2 19 1\n" ]
none
[]
30
0
0
134,087
838
Convex Countour
[ "dp" ]
null
null
You are given an strictly convex polygon with *n* vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once. More specifically your path can be represented as some sequence of distinct polygon vertices. Your path is the straight line segments between adjacent vertices in order. These segments are not allowed to touch or intersect each other except at the vertices in your sequence. Given the polygon, print the maximum length non-intersecting path that visits each point at most once.
The first line of input will contain a single integer *n* (2<=≀<=*n*<=≀<=2<=500), the number of points. The next *n* lines will contain two integers *x**i*,<=*y**i* (|*x**i*|,<=|*y**i*|<=≀<=109), denoting the coordinates of the *i*-th vertex. It is guaranteed that these points are listed in clockwise order.
Print a single floating point number, representing the longest non-intersecting path that visits the vertices at most once. Your answer will be accepted if it has absolute or relative error at most 10<=-<=9. More specifically, if your answer is *a* and the jury answer is *b*, your answer will be accepted if .
[ "4\n0 0\n0 1\n1 1\n1 0\n" ]
[ "3.4142135624\n" ]
One optimal path is to visit points 0,1,3,2 in order.
[]
0
0
-1
134,320
666
Forensic Examination
[ "data structures", "string suffix structures" ]
null
null
The country of Reberland is the archenemy of Berland. Recently the authorities of Berland arrested a Reberlandian spy who tried to bring the leaflets intended for agitational propaganda to Berland illegally . The most leaflets contain substrings of the Absolutely Inadmissible Swearword and maybe even the whole word. Berland legal system uses the difficult algorithm in order to determine the guilt of the spy. The main part of this algorithm is the following procedure. All the *m* leaflets that are brought by the spy are numbered from 1 to *m*. After that it's needed to get the answer to *q* queries of the following kind: "In which leaflet in the segment of numbers [*l*,<=*r*] the substring of the Absolutely Inadmissible Swearword [*p**l*,<=*p**r*] occurs more often?". The expert wants you to automate that procedure because this time texts of leaflets are too long. Help him!
The first line contains the string *s* (1<=≀<=|*s*|<=≀<=5Β·105) β€” the Absolutely Inadmissible Swearword. The string *s* consists of only lowercase English letters. The second line contains the only integer *m* (1<=≀<=*m*<=≀<=5Β·104) β€” the number of texts of leaflets for expertise. Each of the next *m* lines contains the only string *t**i* β€” the text of the *i*-th leaflet. The sum of lengths of all leaflet texts doesn't exceed 5Β·104. The text of the leaflets consists of only lowercase English letters. The next line contains integer *q* (1<=≀<=*q*<=≀<=5Β·105) β€” the number of queries for expertise. Finally, each of the last *q* lines contains four integers *l*, *r*, *p**l*, *p**r* (1<=≀<=*l*<=≀<=*r*<=≀<=*m*,<=1<=≀<=*p**l*<=≀<=*p**r*<=≀<=|*s*|), where |*s*| is the length of the Absolutely Inadmissible Swearword.
Print *q* lines. The *i*-th of them should contain two integers β€” the number of the text with the most occurences and the number of occurences of the substring [*p**l*,<=*p**r*] of the string *s*. If there are several text numbers print the smallest one.
[ "suffixtree\n3\nsuffixtreesareawesome\ncartesiantreeisworsethansegmenttree\nnyeeheeheee\n2\n1 2 1 10\n1 3 9 10\n" ]
[ "1 1\n3 4\n" ]
none
[]
0
0
-1
134,376
575
Party
[ "bitmasks", "brute force", "graph matchings" ]
null
null
Note the unusual memory limit for the problem. People working in MDCS (Microsoft Development Center Serbia) like partying. They usually go to night clubs on Friday and Saturday. There are *N* people working in MDCS and there are *N* clubs in the city. Unfortunately, if there is more than one Microsoft employee in night club, level of coolness goes infinitely high and party is over, so club owners will never let more than one Microsoft employee enter their club in the same week (just to be sure). You are organizing night life for Microsoft employees and you have statistics about how much every employee likes Friday and Saturday parties for all clubs. You need to match people with clubs maximizing overall sum of their happiness (they are happy as much as they like the club), while half of people should go clubbing on Friday and the other half on Saturday.
The first line contains integer *N* β€” number of employees in MDCS. Then an *N*<=Γ—<=*N* matrix follows, where element in *i*-th row and *j*-th column is an integer number that represents how much *i*-th person likes *j*-th club’s Friday party. Then another *N*<=Γ—<=*N* matrix follows, where element in *i*-th row and *j*-th column is an integer number that represents how much *i*-th person likes *j*-th club’s Saturday party. - 2<=≀<=*N*<=≀<=20 - *N* is even - 0<=≀<= level of likeness <=≀<=106 - All values are integers
Output should contain a single integer β€” maximum sum of happiness possible.
[ "4\n1 2 3 4\n2 3 4 1\n3 4 1 2\n4 1 2 3\n5 8 7 1\n6 9 81 3\n55 78 1 6\n1 1 1 1\n" ]
[ "167\n" ]
Here is how we matched people with clubs: Friday: 1st person with 4th club (4 happiness) and 4th person with 1st club (4 happiness). Saturday: 2nd person with 3rd club (81 happiness) and 3rd person with 2nd club (78 happiness). 4+4+81+78 = 167
[]
62
4,198,400
0
134,627
0
none
[ "none" ]
null
null
Instructors of Some Informatics School make students go to bed. The house contains *n* rooms, in each room exactly *b* students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to *n*. Initially, in *i*-th room there are *a**i* students. All students are currently somewhere in the house, therefore *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*. Also 2 instructors live in this house. The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room *n*, while the second instructor starts near room *n* and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if *n* is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends. When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to *b*, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students. While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most *d* rooms, that is she can move to a room with number that differs my at most *d*. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously. Formally, here is what's happening: - A curfew is announced, at this point in room *i* there are *a**i* students. - Each student can run to another room but not further than *d* rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. - Instructors enter room 1 and room *n*, they count students there and lock the room (after it no one can enter or leave this room). - Each student from rooms with numbers from 2 to *n*<=-<=1 can run to another room but not further than *d* rooms away from her current room, or stay in place. Each student can optionally hide under a bed. - Instructors move from room 1 to room 2 and from room *n* to room *n*<=-<=1. - This process continues until all rooms are processed. Let *x*1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from *b*, and *x*2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers *x**i*. Help them find this value if they use the optimal strategy.
The first line contains three integers *n*, *d* and *b* (2<=≀<=*n*<=≀<=100<=000, 1<=≀<=*d*<=≀<=*n*<=-<=1, 1<=≀<=*b*<=≀<=10<=000), number of rooms in the house, running distance of a student, official number of students in a room. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109), *i*-th of which stands for the number of students in the *i*-th room before curfew announcement. It is guaranteed that *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*.
Output one integer, the minimal possible value of the maximum of *x**i*.
[ "5 1 1\n1 0 0 0 4\n", "6 1 2\n3 8 0 1 0 0\n" ]
[ "1\n", "2\n" ]
In the first sample the first three rooms are processed by the first instructor, and the last two are processed by the second instructor. One of the optimal strategies is the following: firstly three students run from room 5 to room 4, on the next stage two of them run to room 3, and one of those two hides under a bed. This way, the first instructor writes down room 2, and the second writes down nothing. In the second sample one of the optimal strategies is the following: firstly all students in room 1 hide, all students from room 2 run to room 3. On the next stage one student runs from room 3 to room 4, and 5 students hide. This way, the first instructor writes down rooms 1 and 2, the second instructor writes down rooms 5 and 6.
[]
15
0
0
134,637
217
Alien DNA
[ "data structures", "dsu", "trees" ]
null
null
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations β€” each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as *s*1*s*2... *s*11, its mangled copy is *s*2*s*4*s*6*s*8*s*10*s*1*s*3*s*5*s*7*s*9*s*11. For example, if the original sequence was "ACTGG" and the mutation happened on the segment [2,<=4] (that is the activated subsequence is "CTG"), the mutated DNA is: "ACTGTCGG". The mangled copy of the activated subsequence is marked with bold font. Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first *k* elements of the DNA sequence after all the mutations.
The first line of input contains the original DNA sequence, consisting only of letters "A", "C", "T" and "G" and not exceeding 3Β·106 in length. The second line contains a single integer *k* (1<=≀<=*k*<=≀<=3Β·106). The third line contains a single integer *n* (0<=≀<=*n*<=≀<=5000) β€” the number of mutations. The next *n* lines describe the mutations in chronological order β€” each mutation is described by two numbers *l**i* and *r**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=109), meaning that the continuous subsequence [*l**i*,<=*r**i*] has become active and cloned itself, joining itself with the mangled copy. It is guaranteed that the input data is correct, that is, no mutation acts on non-existing elements of the DNA sequence, and the resulting DNA sequence has at least *k* elements. Assume that the DNA elements are indexed starting from 1 and that the notation [*l*,<=*r*] meaning the continuous subsequence of DNA sequence that consists of *r*<=-<=*l*<=+<=1 elements starting at the *l*-th DNA sequence element and ending at the *r*-th DNA sequence element.
Output a single line, containing the first *k* letters of the mutated DNA sequence.
[ "GAGA\n4\n0\n", "ACGTACGT\n16\n2\n1 2\n2 8\n" ]
[ "GAGA\n", "ACCAGTACCGACATCG\n" ]
In the second example, after the first mutation the sequence is "ACCAGTACGT". After the second mutation it's "ACCAGTACCGACATCGT".
[]
60
0
0
134,856
821
Okabe and City
[ "dfs and similar", "graphs", "shortest paths" ]
null
null
Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren. Okabe's city is represented by a 2D grid of cells. Rows are numbered from 1 to *n* from top to bottom, and columns are numbered 1 to *m* from left to right. Exactly *k* cells in the city are lit by a street lamp. It's guaranteed that the top-left cell is lit. Okabe starts his walk from the top-left cell, and wants to reach the bottom-right cell. Of course, Okabe will only walk on lit cells, and he can only move to adjacent cells in the up, down, left, and right directions. However, Okabe can also temporarily light all the cells in any single row or column at a time if he pays 1 coin, allowing him to walk through some cells not lit initially. Note that Okabe can only light a single row or column at a time, and has to pay a coin every time he lights a new row or column. To change the row or column that is temporarily lit, he must stand at a cell that is lit initially. Also, once he removes his temporary light from a row or column, all cells in that row/column not initially lit are now not lit. Help Okabe find the minimum number of coins he needs to pay to complete his walk!
The first line of input contains three space-separated integers *n*, *m*, and *k* (2<=≀<=*n*,<=*m*,<=*k*<=≀<=104). Each of the next *k* lines contains two space-separated integers *r**i* and *c**i* (1<=≀<=*r**i*<=≀<=*n*, 1<=≀<=*c**i*<=≀<=*m*)Β β€” the row and the column of the *i*-th lit cell. It is guaranteed that all *k* lit cells are distinct. It is guaranteed that the top-left cell is lit.
Print the minimum number of coins Okabe needs to pay to complete his walk, or -1 if it's not possible.
[ "4 4 5\n1 1\n2 1\n2 3\n3 3\n4 3\n", "5 5 4\n1 1\n2 1\n3 1\n3 2\n", "2 2 4\n1 1\n1 2\n2 1\n2 2\n", "5 5 4\n1 1\n2 2\n3 3\n4 4\n" ]
[ "2\n", "-1\n", "0\n", "3\n" ]
In the first sample test, Okabe can take the path <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fd8d0b719801e9cfe8f6be340d76a554f6ffb66b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, paying only when moving to (2, 3) and (4, 4). In the fourth sample, Okabe can take the path <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a91fe94734a09a4ba86d66070aa8cbeacdb2279f.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2ee6688fe94ce8e9a746b8e479e906fe25ff4d86.png" style="max-width: 100.0%;max-height: 100.0%;"/>, paying when moving to (1, 2), (3, 4), and (5, 4).
[ { "input": "4 4 5\n1 1\n2 1\n2 3\n3 3\n4 3", "output": "2" }, { "input": "5 5 4\n1 1\n2 1\n3 1\n3 2", "output": "-1" }, { "input": "2 2 4\n1 1\n1 2\n2 1\n2 2", "output": "0" }, { "input": "5 5 4\n1 1\n2 2\n3 3\n4 4", "output": "3" }, { "input": "7 10 53\n1 1\n7 5\...
78
23,142,400
-1
135,323
396
On Iteration of One Well-Known Function
[ "math" ]
null
null
Of course, many of you can calculate Ο†(*n*) β€” the number of positive integers that are less than or equal to *n*, that are coprime with *n*. But what if we need to calculate Ο†(Ο†(...Ο†(*n*))), where function Ο† is taken *k* times and *n* is given in the canonical decomposition into prime factors? You are given *n* and *k*, calculate the value of Ο†(Ο†(...Ο†(*n*))). Print the result in the canonical decomposition into prime factors.
The first line contains integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of distinct prime divisors in the canonical representaion of *n*. Each of the next *m* lines contains a pair of space-separated integers *p**i*,<=*a**i* (2<=≀<=*p**i*<=≀<=106;Β 1<=≀<=*a**i*<=≀<=1017) β€” another prime divisor of number *n* and its power in the canonical representation. The sum of all *a**i* doesn't exceed 1017. Prime divisors in the input follow in the strictly increasing order. The last line contains integer *k* (1<=≀<=*k*<=≀<=1018).
In the first line, print integer *w* β€” the number of distinct prime divisors of number Ο†(Ο†(...Ο†(*n*))), where function Ο† is taken *k* times. Each of the next *w* lines must contain two space-separated integers *q**i*,<=*b**i* (*b**i*<=β‰₯<=1) β€” another prime divisor and its power in the canonical representaion of the result. Numbers *q**i* must go in the strictly increasing order.
[ "1\n7 1\n1\n", "1\n7 1\n2\n", "1\n2 100000000000000000\n10000000000000000\n" ]
[ "2\n2 1\n3 1\n", "1\n2 1\n", "1\n2 90000000000000000\n" ]
You can read about canonical representation of a positive integer here: http://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic. You can read about function Ο†(*n*) here: http://en.wikipedia.org/wiki/Euler's_totient_function.
[]
30
0
0
135,431
121
Lucky Segments
[ "binary search", "implementation", "two pointers" ]
null
null
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has *n* number segments [*l*1;Β *r*1], [*l*2;Β *r*2], ..., [*l**n*;Β *r**n*]. During one move Petya can take any segment (let it be segment number *i*) and replace it with segment [*l**i*<=+<=1;Β *r**i*<=+<=1] or [*l**i*<=-<=1;Β *r**i*<=-<=1]. In other words, during one move Petya can shift any segment to the left or to the right by a unit distance. Petya calls a number full if it belongs to each segment. That is, number *x* is full if for any *i* (1<=≀<=*i*<=≀<=*n*) the condition *l**i*<=≀<=*x*<=≀<=*r**i* is fulfilled. Petya makes no more than *k* moves. After that he counts the quantity of full lucky numbers. Find the maximal quantity that he can get.
The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=105, 1<=≀<=*k*<=≀<=1018) β€” the number of segments and the maximum number of moves. Next *n* lines contain pairs of integers *l**i* and *r**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=1018). Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the %I64d specificator.
Print on the single line the single number β€” the answer to the problem.
[ "4 7\n1 4\n6 9\n4 7\n3 5\n", "2 7\n40 45\n47 74\n" ]
[ "1\n", "2\n" ]
In the first sample Petya shifts the second segment by two units to the left (it turns into [4;Β 7]), after that number 4 becomes full. In the second sample Petya shifts the first segment by two units to the right (it turns into [42;Β 47]), and shifts the second segment by three units to the left (it turns into [44;Β 71]), after that numbers 44 and 47 become full.
[]
93
2,150,400
-1
135,532
0
none
[ "none" ]
null
null
Polar bears like unique arrays β€” that is, arrays without repeated elements. You have got a unique array *s* with length *n* containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays *a* and *b* that are also of length *n*, with the following conditions for all *i* (1<=≀<=*i*<=≀<=*n*): - *a**i*,<=*b**i* are non-negative integers; - *s**i*<==<=*a**i*<=+<=*b**i* . Ideally, *a* and *b* should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length *n* to be almost unique, if and only if it can be turned into a unique array by removing no more than entries. For example, the array [1,<=2,<=1,<=3,<=2] is almost unique because after removing the first two entries, it becomes [1,<=3,<=2]. The array [1,<=2,<=1,<=3,<=1,<=2] is not almost unique because we need to remove at least 3 entries to turn it into a unique array. So, your task is to split the given unique array *s* into two almost unique arrays *a* and *b*.
The first line of the input contains integer *n* (1<=≀<=*n*<=≀<=105). The second line contains *n* distinct integers *s*1,<=*s*2,<=... *s**n* (0<=≀<=*s**i*<=≀<=109).
If it is possible to make Alice and Bob happy (if you can split the given array), print "YES" (without quotes) in the first line. In the second line, print the array *a*. In the third line, print the array *b*. There may be more than one solution. Any of them will be accepted. If it is impossible to split *s* into almost unique arrays *a* and *b*, print "NO" (without quotes) in the first line.
[ "6\n12 5 8 3 11 9\n" ]
[ "YES\n6 2 6 0 2 4\n6 3 2 3 9 5" ]
In the sample, we can remove the first two entries from *a* and the second entry from *b* to make them both unique.
[]
92
0
0
136,056
0
none
[ "none" ]
null
null
Stepan is a very experienced olympiad participant. He has *n* cups for Physics olympiads and *m* cups for Informatics olympiads. Each cup is characterized by two parameters β€” its significance *c**i* and width *w**i*. Stepan decided to expose some of his cups on a shelf with width *d* in such a way, that: - there is at least one Physics cup and at least one Informatics cup on the shelf, - the total width of the exposed cups does not exceed *d*, - from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance *x* is exposed, then all the cups for this subject with significance greater than *x* must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width *d*, considering all the rules described above. The total significance is the sum of significances of all the exposed cups.
The first line contains three integers *n*, *m* and *d* (1<=≀<=*n*,<=*m*<=≀<=100<=000, 1<=≀<=*d*<=≀<=109) β€” the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf. Each of the following *n* lines contains two integers *c**i* and *w**i* (1<=≀<=*c**i*,<=*w**i*<=≀<=109) β€” significance and width of the *i*-th cup for Physics olympiads. Each of the following *m* lines contains two integers *c**j* and *w**j* (1<=≀<=*c**j*,<=*w**j*<=≀<=109) β€” significance and width of the *j*-th cup for Informatics olympiads.
Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width *d*, considering all the rules described in the statement. If there is no way to expose cups on the shelf, then print 0.
[ "3 1 8\n4 2\n5 5\n4 2\n3 2\n", "4 3 12\n3 4\n2 4\n3 5\n3 4\n3 5\n5 2\n3 4\n", "2 2 2\n5 3\n6 3\n4 2\n8 1\n" ]
[ "8\n", "11\n", "0\n" ]
In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8.
[ { "input": "3 1 8\n4 2\n5 5\n4 2\n3 2", "output": "8" }, { "input": "4 3 12\n3 4\n2 4\n3 5\n3 4\n3 5\n5 2\n3 4", "output": "11" }, { "input": "2 2 2\n5 3\n6 3\n4 2\n8 1", "output": "0" }, { "input": "10 10 229\n15 17\n5 4\n4 15\n4 17\n15 11\n7 6\n5 19\n14 8\n4 1\n10 12\n20 13...
46
0
0
136,201
802
Marmots (easy)
[ "math" ]
null
null
Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of *V* (1<=≀<=*V*<=≀<=100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures. Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants *P* (10<=≀<=*P*<=≀<=1000) of the village, they respond with a random non-negative integer *k*, drawn from one of two types of probability distributions: - Poisson (d'avril) distribution: the probability of getting an answer *k* is for *k*<==<=0,<=1,<=2,<=3,<=..., - Uniform distribution: the probability of getting an answer *k* is for *k*<==<=0,<=1,<=2,<=...,<=2*P*. Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution. Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?
The first line of input will contain the number of villages *V* (1<=≀<=*V*<=≀<=100). The following *V* lines each describe one village. The description of each village consists of 250 space-separated integers *k*, drawn from one of the above distributions.
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answer came from a uniform distribution.
[ "2\n92 100 99 109 93 105 103 106 101 99 ... (input is truncated)\n28 180 147 53 84 80 180 85 8 16 ... (input is truncated)" ]
[ "poisson\nuniform\n" ]
The full example input is visually represented below, along with the probability distribution function it was drawn from (the *y*-axis is labeled by its values multiplied by 250). <img class="tex-graphics" src="https://espresso.codeforces.com/77563a6378b39d03eb21012c835c6e96df776b81.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[]
93
0
-1
136,282
494
Birthday
[ "data structures", "dfs and similar", "dp", "trees" ]
null
null
Ali is Hamed's little brother and tomorrow is his birthday. Hamed wants his brother to earn his gift so he gave him a hard programming problem and told him if he can successfully solve it, he'll get him a brand new laptop. Ali is not yet a very talented programmer like Hamed and although he usually doesn't cheat but this time is an exception. It's about a brand new laptop. So he decided to secretly seek help from you. Please solve this problem for Ali. An *n*-vertex weighted rooted tree is given. Vertex number 1 is a root of the tree. We define *d*(*u*,<=*v*) as the sum of edges weights on the shortest path between vertices *u* and *v*. Specifically we define *d*(*u*,<=*u*)<==<=0. Also let's define *S*(*v*) for each vertex *v* as a set containing all vertices *u* such that *d*(1,<=*u*)<==<=*d*(1,<=*v*)<=+<=*d*(*v*,<=*u*). Function *f*(*u*,<=*v*) is then defined using the following formula: The goal is to calculate *f*(*u*,<=*v*) for each of the *q* given pair of vertices. As the answer can be rather large it's enough to print it modulo 109<=+<=7.
In the first line of input an integer *n* (1<=≀<=*n*<=≀<=105), number of vertices of the tree is given. In each of the next *n*<=-<=1 lines three space-separated integers *a**i*,<=*b**i*,<=*c**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, 1<=≀<=*c**i*<=≀<=109) are given indicating an edge between *a**i* and *b**i* with weight equal to *c**i*. In the next line an integer *q* (1<=≀<=*q*<=≀<=105), number of vertex pairs, is given. In each of the next *q* lines two space-separated integers *u**i*,<=*v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*) are given meaning that you must calculate *f*(*u**i*,<=*v**i*). It is guaranteed that the given edges form a tree.
Output *q* lines. In the *i*-th line print the value of *f*(*u**i*,<=*v**i*) modulo 109<=+<=7.
[ "5\n1 2 1\n4 3 1\n3 5 1\n1 3 1\n5\n1 1\n1 5\n2 4\n2 1\n3 5\n", "8\n1 2 100\n1 3 20\n2 4 2\n2 5 1\n3 6 1\n3 7 2\n6 8 5\n6\n1 8\n2 3\n5 8\n2 6\n4 7\n6 1\n" ]
[ "10\n1000000005\n1000000002\n23\n1000000002\n", "999968753\n49796\n999961271\n999991235\n999958569\n45130\n" ]
none
[]
46
0
0
136,992
538
Summer Dichotomy
[ "2-sat", "data structures", "dfs and similar", "greedy" ]
null
null
*T* students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least *t* students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!) During a shift the students from the ZPP grade are tutored by *n* teachers. Due to the nature of the educational process, each of the teachers should be assigned to exactly one of two groups (it is possible that no teacher will be assigned to some of the groups!). The *i*-th teacher is willing to work in a group as long as the group will have at least *l**i* and at most *r**i* students (otherwise it would be either too boring or too hard). Besides, some pairs of the teachers don't like each other other and therefore can not work in the same group; in total there are *m* pairs of conflicting teachers. You, as the head teacher of Summer Irrelevant School, have got a difficult task: to determine how many students to enroll in each of the groups and in which group each teacher will teach.
The first line contains two space-separated integers, *t* and *T* (1<=≀<=*t*<=≀<=*T*<=≀<=109). The second line contains two space-separated integers *n* and *m* (1<=≀<=*n*<=≀<=105, 0<=≀<=*m*<=≀<=105). The *i*-th of the next *n* lines contain integers *l**i* and *r**i* (0<=≀<=*l**i*<=≀<=*r**i*<=≀<=109). The next *m* lines describe the pairs of conflicting teachers. Each of these lines contain two space-separated integers β€” the indices of teachers in the pair. The teachers are indexed starting from one. It is guaranteed that no teacher has a conflict with himself and no pair of conflicting teachers occurs in the list more than once.
If the distribution is possible, print in the first line a single word 'POSSIBLE' (without the quotes). In the second line print two space-separated integers *n*1 and *n*2Β β€” the number of students in the first and second group, correspondingly, the contstraint *t*<=≀<=*n*1<=+<=*n*2<=≀<=*T* should be met. In the third line print *n* characters, the *i*-th of which should be 1 or 2, if the *i*-th teacher should be assigned to the first or second group, correspondingly. If there are multiple possible distributions of students and teachers in groups, you can print any of them. If the sought distribution doesn't exist, print a single word 'IMPOSSIBLE' (without the quotes).
[ "10 20\n3 0\n3 6\n4 9\n16 25\n", "1 10\n3 3\n0 10\n0 10\n0 10\n1 2\n1 3\n2 3\n" ]
[ "POSSIBLE\n4 16\n112\n", "IMPOSSIBLE\n" ]
none
[]
30
0
0
137,809
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"...
982
82,329,600
0
137,869
724
Uniformly Branched Trees
[ "combinatorics", "dp", "trees" ]
null
null
A tree is a connected graph without cycles. Two trees, consisting of *n* vertices each, are called isomorphic if there exists a permutation *p*:<={1,<=...,<=*n*}<=β†’<={1,<=...,<=*n*} such that the edge (*u*,<=*v*) is present in the first tree if and only if the edge (*p**u*,<=*p**v*) is present in the second tree. Vertex of the tree is called internal if its degree is greater than or equal to two. Count the number of different non-isomorphic trees, consisting of *n* vertices, such that the degree of each internal vertex is exactly *d*. Print the answer over the given prime modulo *mod*.
The single line of the input contains three integers *n*, *d* andΒ *mod* (1<=≀<=*n*<=≀<=1000, 2<=≀<=*d*<=≀<=10, 108<=≀<=*mod*<=≀<=109) Β β€” the number of vertices in the tree, the degree of internal vertices and the prime modulo.
Print the number of trees over the modulo *mod*.
[ "5 2 433416647\n", "10 3 409693891\n", "65 4 177545087\n" ]
[ "1\n", "2\n", "910726\n" ]
none
[]
30
0
0
137,931
404
Marathon
[ "implementation", "math" ]
null
null
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0,<=0) and the length of the side equals *a* meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each *d* meters of the path. We know that Valera starts at the point with coordinates (0,<=0) and runs counter-clockwise. That is, when Valera covers *a* meters, he reaches the point with coordinates (*a*,<=0). We also know that the length of the marathon race equals *nd*<=+<=0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers *d*,<=2Β·*d*,<=...,<=*n*Β·*d* meters.
The first line contains two space-separated real numbers *a* and *d* (1<=≀<=*a*,<=*d*<=≀<=105), given with precision till 4 decimal digits after the decimal point. Number *a* denotes the length of the square's side that describes the stadium. Number *d* shows that after each *d* meters Valera gets an extra drink. The second line contains integer *n* (1<=≀<=*n*<=≀<=105) showing that Valera needs an extra drink *n* times.
Print *n* lines, each line should contain two real numbers *x**i* and *y**i*, separated by a space. Numbers *x**i* and *y**i* in the *i*-th line mean that Valera is at point with coordinates (*x**i*,<=*y**i*) after he covers *i*Β·*d* meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10<=-<=4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.
[ "2 5\n2\n", "4.147 2.8819\n6\n" ]
[ "1.0000000000 2.0000000000\n2.0000000000 0.0000000000\n", "2.8819000000 0.0000000000\n4.1470000000 1.6168000000\n3.7953000000 4.1470000000\n0.9134000000 4.1470000000\n0.0000000000 2.1785000000\n0.7034000000 0.0000000000\n" ]
none
[ { "input": "2 5\n2", "output": "1.0000000000 2.0000000000\n2.0000000000 0.0000000000" }, { "input": "4.147 2.8819\n6", "output": "2.8819000000 0.0000000000\n4.1470000000 1.6168000000\n3.7953000000 4.1470000000\n0.9134000000 4.1470000000\n0.0000000000 2.1785000000\n0.7034000000 0.0000000000" },...
202
13,312,000
0
138,035
256
Liars and Serge
[ "dp" ]
null
null
There are *n* people, sitting in a line at the table. For each person we know that he always tells either the truth or lies. Little Serge asked them: how many of you always tell the truth? Each of the people at the table knows everything (who is an honest person and who is a liar) about all the people at the table. The honest people are going to say the correct answer, the liars are going to say any integer from 1 to *n*, which is not the correct answer. Every liar chooses his answer, regardless of the other liars, so two distinct liars may give distinct answer. Serge does not know any information about the people besides their answers to his question. He took a piece of paper and wrote *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the answer of the *i*-th person in the row. Given this sequence, Serge determined that exactly *k* people sitting at the table apparently lie. Serge wonders, how many variants of people's answers (sequences of answers *a* of length *n*) there are where one can say that exactly *k* people sitting at the table apparently lie. As there can be rather many described variants of answers, count the remainder of dividing the number of the variants by 777777777.
The first line contains two integers *n*, *k*, (1<=≀<=*k*<=≀<=*n*<=≀<=28). It is guaranteed that *n* β€” is the power of number 2.
Print a single integer β€” the answer to the problem modulo 777777777.
[ "1 1\n", "2 1\n" ]
[ "0\n", "2\n" ]
none
[]
92
0
0
139,170
424
Colored Jenga
[ "dfs and similar", "dp", "probabilities" ]
null
null
Cold winter evenings in Tomsk are very boring β€” nobody wants be on the streets at such a time. Residents of Tomsk while away the time sitting in warm apartments, inventing a lot of different games. One of such games is 'Colored Jenga'. This game requires wooden blocks of three colors: red, green and blue. A tower of *n* levels is made from them. Each level consists of three wooden blocks. The blocks in each level can be of arbitrary colors, but they are always located close and parallel to each other. An example of such a tower is shown in the figure. The game is played by exactly one person. Every minute a player throws a special dice which has six sides. Two sides of the dice are green, two are blue, one is red and one is black. The dice shows each side equiprobably. If the dice shows red, green or blue, the player must take any block of this color out of the tower at this minute so that the tower doesn't fall. If this is not possible, the player waits until the end of the minute, without touching the tower. He also has to wait until the end of the minute without touching the tower if the dice shows the black side. It is not allowed to take blocks from the top level of the tower (whether it is completed or not). Once a player got a block out, he must put it on the top of the tower so as to form a new level or finish the upper level consisting of previously placed blocks. The newly constructed levels should have all the same properties as the initial levels. If the upper level is not completed, starting the new level is prohibited. For the tower not to fall, in each of the levels except for the top, there should be at least one block. Moreover, if at some of these levels there is exactly one block left and this block is not the middle block, the tower falls. The game ends at the moment when there is no block in the tower that you can take out so that the tower doesn't fall. Here is a wonderful game invented by the residents of the city of Tomsk. I wonder for how many minutes can the game last if the player acts optimally well? If a player acts optimally well, then at any moment he tries to choose the block he takes out so as to minimize the expected number of the game duration. Your task is to write a program that determines the expected number of the desired amount of minutes.
The first line of the input contains the only integer *n* (2<=≀<=*n*<=≀<=6) β€” the number of levels in the tower. Then *n* lines follow, describing the levels of the tower from the bottom to the top (the first line is the top of the tower). Each level is described by three characters, the first and the third of them set the border blocks of the level and the second one is the middle block. The character that describes the block has one of the following values 'R' (a red block), 'G' (a green block) and 'B' (a blue block).
In the only line of the output print the sought mathematical expectation value. The answer will be considered correct if its relative or absolute error doesn't exceed 10<=-<=6.
[ "6\nRGB\nGRG\nBBB\nGGR\nBRG\nBRB\n" ]
[ "17.119213696601992\n" ]
none
[]
31
0
0
139,343
594
Cutting the Line
[ "string suffix structures", "strings" ]
null
null
You are given a non-empty line *s* and an integer *k*. The following operation is performed with this line exactly once: - A line is split into at most *k* non-empty substrings, i.e. string *s* is represented as a concatenation of a set of strings *s*<==<=*t*1<=+<=*t*2<=+<=...<=+<=*t**m*, 1<=≀<=*m*<=≀<=*k*. - Some of strings *t**i* are replaced by strings *t**i**r*, that is, their record from right to left. - The lines are concatenated back in the same order, we get string *s*'<==<=*t*'1*t*'2... *t*'*m*, where *t*'*i* equals *t**i* or *t**i**r*. Your task is to determine the lexicographically smallest string that could be the result of applying the given operation to the string *s*.
The first line of the input contains string *s* (1<=≀<=|*s*|<=≀<=5<=000<=000), consisting of lowercase English letters. The second line contains integer *k* (1<=≀<=*k*<=≀<=|*s*|)Β β€” the maximum number of parts in the partition.
In the single line print the lexicographically minimum string *s*' which can be obtained as a result of performing the described operation.
[ "aba\n2\n", "aaaabacaba\n2\n", "bababa\n1\n", "abacabadabacaba\n4\n" ]
[ "aab\n", "aaaaabacab\n", "ababab\n", "aababacabacabad\n" ]
none
[]
46
0
0
139,576
802
April Fools' Problem (medium)
[ "binary search", "flows", "graphs" ]
null
null
The marmots need to prepare *k* problems for HC2 over *n* days. Each problem, once prepared, also has to be printed. The preparation of a problem on day *i* (at most one per day) costs *a**i* CHF, and the printing of a problem on day *i* (also at most one per day) costs *b**i* CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine). What is the minimum cost of preparation and printing?
The first line of input contains two space-separated integers *n* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=2200). The second line contains *n* space-separated integers *a*1,<=...,<=*a**n* () β€” the preparation costs. The third line contains *n* space-separated integers *b*1,<=...,<=*b**n* () β€” the printing costs.
Output the minimum cost of preparation and printing *k* problems β€” that is, the minimum possible sum *a**i*1<=+<=*a**i*2<=+<=...<=+<=*a**i**k*<=+<=*b**j*1<=+<=*b**j*2<=+<=...<=+<=*b**j**k*, where 1<=≀<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≀<=*n*, 1<=≀<=*j*1<=&lt;<=*j*2<=&lt;<=...<=&lt;<=*j**k*<=≀<=*n* and *i*1<=≀<=*j*1, *i*2<=≀<=*j*2, ..., *i**k*<=≀<=*j**k*.
[ "8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1\n" ]
[ "32" ]
In the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8.
[ { "input": "8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1", "output": "32" }, { "input": "10 6\n60 8 63 72 1 100 23 59 71 59\n81 27 66 53 46 64 86 27 41 82", "output": "472" }, { "input": "13 13\n93 19 58 34 96 7 35 46 60 5 36 40 41\n57 3 42 68 26 85 25 45 50 21 60 23 79", "output": "1154" ...
3,868
13,926,400
3
140,240
291
Parallel Programming
[ "*special", "greedy" ]
null
null
Polycarpus has a computer with *n* processors. Also, his computer has *n* memory cells. We'll consider the processors numbered by integers from 1 to *n* and that the memory cells are consecutively numbered by integers from 1 to *n*. Polycarpus needs to come up with a parallel program model. For each memory cell number *i* this program must record the value *n*<=-<=*i* to this cell. In other words, for each cell you've got to find the distance to cell *n*. Let's denote the value that is written in the *i*-th cell as *a**i*. Initially, *a**i*<==<=1 (1<=≀<=*i*<=&lt;<=*n*) and *a**n*<==<=0. We will consider that only processor *i* can write values in the memory cell number *i*. All processors can read an information from some cell (several processors can read an information from some cell simultaneously). The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: 1. Each processor independently of the other ones chooses some memory cell. Let's say that processor *i* has chosen a cell with number *c**i* (1<=≀<=*c**i*<=≀<=*n*). 1. All processors simultaneously execute operation *a**i*<==<=*a**i*<=+<=*a**c**i*. Help Polycarpus come up with the parallel program model that is executed in exactly *k* steps. Calculate the operations that need to be executed. Note that after *k* steps for all *i*'s value *a**i* must be equal *n*<=-<=*i*.
The first line contains two space-separated integers *n* and *k* (1<=≀<=*n*<=≀<=104,<=1<=≀<=*k*<=≀<=20). It is guaranteed that at the given *n* and *k* the required sequence of operations exists.
Print exactly *n*Β·*k* integers in *k* lines. In the first line print numbers *c*1,<=*c*2,<=...,<=*c**n* (1<=≀<=*c**i*<=≀<=*n*) for the first increment operation. In the second line print the numbers for the second increment operation. In the *k*-th line print the numbers for the *k*-th increment operation. As a result of the printed operations for any *i* value *a**i* must equal *n*<=-<=*i*.
[ "1 1\n", "3 2\n" ]
[ "1\n", "2 3 3\n3 3 3\n" ]
none
[ { "input": "1 1", "output": "1" }, { "input": "3 2", "output": "2 3 3\n3 3 3" }, { "input": "4 2", "output": "2 3 4 4\n3 4 4 4" }, { "input": "2 1", "output": "2 2" }, { "input": "2 20", "output": "2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 2\n2 ...
124
716,800
0
140,477
538
Demiurges Play Again
[ "dfs and similar", "dp", "math", "trees" ]
null
null
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game. There is a rooted tree on *n* nodes, *m* of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to *m* are placed in such a way that each number appears exactly in one leaf. Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well. Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.
The first line contains a single integer *n*Β β€” the number of nodes in the tree (1<=≀<=*n*<=≀<=2Β·105). Each of the next *n*<=-<=1 lines contains two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*)Β β€” the ends of the edge of the tree; the edge leads from node *u**i* to node *v**i*. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.
Print two space-separated integers β€” the maximum possible and the minimum possible result of the game.
[ "5\n1 2\n1 3\n2 4\n2 5\n", "6\n1 2\n1 3\n3 4\n1 5\n5 6\n" ]
[ "3 2\n", "3 3\n" ]
Consider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2. In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3.
[ { "input": "5\n1 2\n1 3\n2 4\n2 5", "output": "3 2" }, { "input": "6\n1 2\n1 3\n3 4\n1 5\n5 6", "output": "3 3" }, { "input": "1", "output": "1 1" }, { "input": "2\n1 2", "output": "1 1" }, { "input": "3\n1 2\n1 3", "output": "2 2" }, { "input": "10\n1...
108
20,172,800
0
140,582
731
Funny Game
[ "dp", "games" ]
null
null
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them. The game they came up with has the following rules. Initially, there are *n* stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first. One move happens as follows. Lets say there are *m*<=β‰₯<=2 stickers on the wall. The player, who makes the current move, picks some integer *k* from 2 to *m* and takes *k* leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent. Given the integer *n* and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
The first line of input contains a single integer *n* (2<=≀<=*n*<=≀<=200<=000)Β β€” the number of stickers, initially located on the wall. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (<=-<=10<=000<=≀<=*a**i*<=≀<=10<=000)Β β€” the numbers on stickers in order from left to right.
Print one integerΒ β€” the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
[ "3\n2 4 8\n", "4\n1 -7 -2 3\n" ]
[ "14\n", "-3\n" ]
In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0. In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value  - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) =  - 8, Gena's score is ( - 8) + 3 =  - 5, i.e. the score difference will be  - 3.
[ { "input": "3\n2 4 8", "output": "14" }, { "input": "4\n1 -7 -2 3", "output": "-3" }, { "input": "10\n35 11 35 28 48 25 2 43 23 10", "output": "260" }, { "input": "100\n437 89 481 95 29 326 10 304 97 414 52 46 106 181 385 173 337 148 437 133 52 136 86 250 289 61 480 314 166 6...
171
27,443,200
3
141,265
610
Vika and Segments
[ "constructive algorithms", "data structures", "geometry", "two pointers" ]
null
null
Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew *n* black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column. Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.
The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of segments drawn by Vika. Each of the next *n* lines contains four integers *x*1, *y*1, *x*2 and *y*2 (<=-<=109<=≀<=*x*1,<=*y*1,<=*x*2,<=*y*2<=≀<=109)Β β€” the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.
Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.
[ "3\n0 1 2 1\n1 4 1 2\n0 3 2 3\n", "4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2\n" ]
[ "8\n", "16\n" ]
In the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).
[ { "input": "3\n0 1 2 1\n1 4 1 2\n0 3 2 3", "output": "8" }, { "input": "4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2", "output": "16" }, { "input": "1\n1 1 1 1", "output": "1" }, { "input": "10\n-357884841 -999999905 -357884841 999999943\n-130177221 999999983 -130177221 -999...
1,044
268,390,400
0
141,321
0
none
[ "none" ]
null
null
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive. Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast. Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage. The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be *n* noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1<=/<=*n*). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
The first line contains a single integer *n* from the problem's statement (1<=≀<=*n*<=≀<=10000).
Print the sought expected number of tosses as an irreducible fraction in the following form: "*a*/*b*" (without the quotes) without leading zeroes.
[ "2\n", "3\n", "4\n" ]
[ "1/1\n", "8/3\n", "2/1\n" ]
none
[ { "input": "2", "output": "1/1" }, { "input": "3", "output": "8/3" }, { "input": "4", "output": "2/1" }, { "input": "8", "output": "3/1" }, { "input": "7", "output": "24/7" }, { "input": "6", "output": "11/3" }, { "input": "1", "output"...
60
0
0
142,496
659
Polycarp and Hay
[ "dfs and similar", "dsu", "graphs", "greedy", "sortings" ]
null
null
The farmer Polycarp has a warehouse with hay, which can be represented as an *n*<=Γ—<=*m* rectangular table, where *n* is the number of rows, and *m* is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the *i*-th row and the *j*-th column is equal to an integer *a**i*,<=*j* and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1<=Γ—<=1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack. Polycarp wants the following requirements to hold after the reorganization: - the total amount of hay remaining in the warehouse must be equal to *k*, - the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same, - the height of at least one stack must remain the same as it was, - for the stability of the remaining structure all the stacks should form one connected region. The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area. Help Polycarp complete this challenging task or inform that it is impossible.
The first line of the input contains three integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=1000) and *k* (1<=≀<=*k*<=≀<=1018)Β β€” the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization. Then *n* lines follow, each containing *m* positive integers *a**i*,<=*j* (1<=≀<=*a**i*,<=*j*<=≀<=109), where *a**i*,<=*j* is equal to the number of cubic meters of hay making the hay stack on the *i*-th row and *j*-th column of the table.
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next *n* lines print *m* numbersΒ β€” the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered. If there are multiple answers, print any of them.
[ "2 3 35\n10 4 9\n9 9 7\n", "4 4 50\n5 9 1 1\n5 1 1 5\n5 1 5 5\n5 5 7 1\n", "2 4 12\n1 1 3 1\n1 6 2 4\n" ]
[ "YES\n7 0 7 \n7 7 7 \n", "YES\n5 5 0 0 \n5 0 0 5 \n5 0 5 5 \n5 5 5 0 \n", "NO\n" ]
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value *k* = 7Β·5 = 35. At that the stack that is on the second line and third row remained unaltered.
[ { "input": "2 3 35\n10 4 9\n9 9 7", "output": "YES\n7 0 7 \n7 7 7 " }, { "input": "4 4 50\n5 9 1 1\n5 1 1 5\n5 1 5 5\n5 5 7 1", "output": "YES\n5 5 0 0 \n5 0 0 5 \n5 0 5 5 \n5 5 5 0 " }, { "input": "2 4 12\n1 1 3 1\n1 6 2 4", "output": "NO" }, { "input": "6 6 38\n1 100 1 100 ...
2,917
130,355,200
0
142,649