problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
D. Polycarp's phone booktime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.InputThe first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts.The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.OutputPrint exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.ExamplesInput3123456789100000000100123456Output900001Input4123456789193456789134567819934567891Output21938191
Input3123456789100000000100123456
Output900001
4 seconds
256 megabytes
['data structures', 'implementation', 'sortings', '*1600']
C. Did you mean...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example: the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.InputThe only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.OutputPrint the given word without any changes if there are no typos.If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.ExamplesInputhellnoOutputhell no InputabacabaOutputabacaba InputasdfasdfOutputasd fasd f
Inputhellno
Outputhell no
1 second
256 megabytes
['dp', 'greedy', 'implementation', '*1500']
B. Which floor?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.Given this information, is it possible to restore the exact floor for flat n? InputThe first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct.It is guaranteed that the given information is not self-contradictory.OutputPrint the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.ExamplesInput10 36 22 17 3Output4Input8 43 16 25 22 1Output-1NoteIn the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
Input10 36 22 17 3
Output4
1 second
256 megabytes
['brute force', 'implementation', '*1500']
A. k-roundingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.Write a program that will perform the k-rounding of n.InputThe only line contains two integers n and k (1 ≤ n ≤ 109, 0 ≤ k ≤ 8).OutputPrint the k-rounding of n.ExamplesInput375 4Output30000Input10000 1Output10000Input38101 0Output38101Input123456789 8Output12345678900000000
Input375 4
Output30000
1 second
256 megabytes
['brute force', 'math', 'number theory', '*1100']
F. To Play or not to Playtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya are playing an online game. As most online games, it has hero progress system that allows players to gain experience that make their heroes stronger. Of course, Vasya would like to get as many experience points as possible. After careful study of experience points allocation, he found out that if he plays the game alone, he gets one experience point each second. However, if two players are playing together, and their current experience values differ by at most C points, they can boost their progress, and each of them gets 2 experience points each second.Since Vasya and Petya are middle school students, their parents don't allow them to play all the day around. Each of the friends has his own schedule: Vasya can only play during intervals [a1;b1], [a2;b2], ..., [an;bn], and Petya can only play during intervals [c1;d1], [c2;d2], ..., [cm;dm]. All time periods are given in seconds from the current moment. Vasya is good in math, so he has noticed that sometimes it can be profitable not to play alone, because experience difference could become too big, and progress would not be boosted even when played together.Now they would like to create such schedule of playing that Vasya's final experience was greatest possible. The current players experience is the same. Petya is not so concerned about his experience, so he is ready to cooperate and play when needed to maximize Vasya's experience.InputThe first line of input data contains integers n, m and C — the number of intervals when Vasya can play, the number of intervals when Petya can play, and the maximal difference in experience level when playing together still gives a progress boost (1 ≤ n, m ≤ 2·105, 0 ≤ C ≤ 1018). The following n lines contain two integers each: ai, bi — intervals when Vasya can play (0 ≤ ai < bi ≤ 1018, bi < ai + 1).The following m lines contain two integers each: ci, di — intervals when Petya can play (0 ≤ ci < di ≤ 1018, di < ci + 1).OutputOutput one integer — the maximal experience that Vasya can have in the end, if both players try to maximize this value.ExamplesInput2 1 51 710 2010 20Output25Input1 2 50 10020 6085 90Output125
Input2 1 51 710 2010 20
Output25
2 seconds
256 megabytes
['greedy', '*3000']
E. Satellitestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReal Cosmic Communications is the largest telecommunication company on a far far away planet, located at the very edge of the universe. RCC launches communication satellites.The planet is at the very edge of the universe, so its form is half of a circle. Its radius is r, the ends of its diameter are points A and B. The line AB is the edge of the universe, so one of the half-planes contains nothing, neither the planet, nor RCC satellites, nor anything else. Let us introduce coordinates in the following way: the origin is at the center of AB segment, OX axis coincides with line AB, the planet is completely in y > 0 half-plane.The satellite can be in any point of the universe, except the planet points. Satellites are never located beyond the edge of the universe, nor on the edge itself — that is, they have coordinate y > 0. Satellite antennas are directed in such way that they cover the angle with the vertex in the satellite, and edges directed to points A and B. Let us call this area the satellite coverage area. The picture below shows coordinate system and coverage area of a satellite. When RCC was founded there were no satellites around the planet. Since then there have been several events of one of the following types: 1 x y — launch the new satellite and put it to the point (x, y). Satellites never move and stay at the point they were launched. Let us assign the number i to the i-th satellite in order of launching, starting from one. 2 i — remove satellite number i. 3 i j — make an attempt to create a communication channel between satellites i and j. To create a communication channel a repeater is required. It must not be located inside the planet, but can be located at its half-circle border, or above it. Repeater must be in coverage area of both satellites i and j. To avoid signal interference, it must not be located in coverage area of any other satellite. Of course, the repeater must be within the universe, it must have a coordinate y > 0. For each attempt to create a communication channel you must find out whether it is possible.Sample test has the following satellites locations: InputThe first line of input data contains integers r and n — radius of the planet and the number of events (1 ≤ r ≤ 109, 1 ≤ n ≤ 5·105).Each of the following n lines describe events in the specified format.Satellite coordinates are integer, the satisfy the following constraints |x| ≤ 109, 0 < y ≤ 109. No two satellites that simultaneously exist can occupy the same point. Distance from each satellite to the center of the planet is strictly greater than r.It is guaranteed that events of types 2 and 3 only refer to satellites that exist at the moment. For all events of type 3 the inequality i ≠ j is satisfied.OutputFor each event of type 3 print «YES» on a separate line, if it is possible to create a communication channel, or «NO» if it is impossible.ExampleInput5 81 -5 81 -4 81 -3 81 2 73 1 32 23 1 33 3 4OutputNOYESYES
Input5 81 -5 81 -4 81 -3 81 2 73 1 32 23 1 33 3 4
OutputNOYESYES
2 seconds
256 megabytes
['*3100']
D. Masha and Cactustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha is fond of cacti. When she was a little girl, she decided to plant a tree. Now Masha wants to make a nice cactus out of her tree.Recall that tree is a connected undirected graph that has no cycles. Cactus is a connected undirected graph such that each vertex belongs to at most one cycle.Masha has some additional edges that she can add to a tree. For each edge she knows which vertices it would connect and the beauty of this edge. Masha can add some of these edges to the graph if the resulting graph is a cactus. Beauty of the resulting cactus is sum of beauties of all added edges. Help Masha find out what maximum beauty of the resulting cactus she can achieve.InputThe first line of the input data contains two integers n and m — the number of vertices in a tree, and the number of additional edges available (3 ≤ n ≤ 2·105; 0 ≤ m ≤ 2·105).Let us describe Masha's tree. It has a root at vertex 1. The second line contains n - 1 integers: p2, p3, ..., pn, here pi — is the parent of a vertex i — the first vertex on a path from the vertex i to the root of the tree (1 ≤ pi < i).The following m lines contain three integers ui, vi and ci — pairs of vertices to be connected by the additional edges that Masha can add to the tree and beauty of edge (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ ci ≤ 104).It is guaranteed that no additional edge coincides with the edge of the tree.OutputOutput one integer — the maximum beauty of a cactus Masha can achieve.ExampleInput7 31 1 2 2 3 34 5 16 7 12 3 1Output2
Input7 31 1 2 2 3 34 5 16 7 12 3 1
Output2
2 seconds
256 megabytes
['dp', 'trees', '*2400']
C. Eleventh Birthdaytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number ai written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 × 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.InputInput data contains multiple test cases. The first line of the input data contains an integer t — the number of test cases (1 ≤ t ≤ 100). The descriptions of test cases follow.Each test is described by two lines.The first line contains an integer n (1 ≤ n ≤ 2000) — the number of cards in Borya's present.The second line contains n integers ai (1 ≤ ai ≤ 109) — numbers written on the cards.It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.OutputFor each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.ExampleInput421 131 31 12312345 67 8491 2 3 4 5 6 7 8 9Output22231680
Input421 131 31 12312345 67 8491 2 3 4 5 6 7 8 9
Output22231680
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*2400']
B. Similar Wordstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet us call a non-empty sequence of lowercase English letters a word. Prefix of a word x is a word y that can be obtained from x by removing zero or more last letters of x.Let us call two words similar, if one of them can be obtained from the other by removing its first letter.You are given a set S of words. Find the maximal possible size of set of non-empty words X such that they satisfy the following: each word of X is prefix of some word from S; X has no similar words. InputInput data contains multiple test cases. The first line of the input data contains an integer t — the number of test cases. The descriptions of test cases follow.The first line of each description contains an integer n — the number of words in the set S (1 ≤ n ≤ 106). Each of the following n lines contains one non-empty word — elements of S. All words in S are different.It is guaranteed that the total length of all words in one input data doesn't exceed 106.OutputFor each test case print one line that contains one integer m — the maximal number of words that X can contain.ExampleInput23abababaaaab2aaaOutput61
Input23abababaaaab2aaa
Output61
2 seconds
512 megabytes
['dp', 'hashing', 'strings', 'trees', '*2300']
A. Set Theorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha and Grisha like studying sets of positive integers.One day Grisha has written a set A containing n different integers ai on a blackboard. Now he asks Masha to create a set B containing n different integers bj such that all n2 integers that can be obtained by summing up ai and bj for all possible pairs of i and j are different.Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 106, and all numbers in B must also be in the same range.Help Masha to create the set B that satisfies Grisha's requirement.InputInput data contains multiple test cases. The first line contains an integer t — the number of test cases (1 ≤ t ≤ 100).Each test case is described in the following way: the first line of the description contains one integer n — the number of elements in A (1 ≤ n ≤ 100).The second line contains n integers ai — the elements of A (1 ≤ ai ≤ 106). OutputFor each test first print the answer: NO, if Masha's task is impossible to solve, there is no way to create the required set B. YES, if there is the way to create the required set. In this case the second line must contain n different positive integers bj — elements of B (1 ≤ bj ≤ 106). If there are several possible sets, output any of them. ExampleInput331 10 1001122 4OutputYES1 2 3 YES1 YES1 2
Input331 10 1001122 4
OutputYES1 2 3 YES1 YES1 2
1 second
256 megabytes
['brute force', 'constructive algorithms', '*1600']
G. Harry Vs Voldemorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter destroying all of Voldemort's Horcruxes, Harry and Voldemort are up for the final battle. They each cast spells from their wands and the spells collide.The battle scene is Hogwarts, which can be represented in the form of a tree. There are, in total, n places in Hogwarts joined using n - 1 undirected roads.Ron, who was viewing this battle between Harry and Voldemort, wondered how many triplets of places (u, v, w) are there such that if Harry is standing at place u and Voldemort is standing at place v, their spells collide at a place w. This is possible for a triplet only when u, v and w are distinct, and there exist paths from u to w and from v to w which do not pass through the same roads.Now, due to the battle havoc, new paths are being added all the time. You have to tell Ron the answer after each addition.Formally, you are given a tree with n vertices and n - 1 edges. q new edges are being added between the nodes of the tree. After each addition you need to tell the number of triplets (u, v, w) such that u, v and w are distinct and there exist two paths, one between u and w, another between v and w such that these paths do not have an edge in common.InputFirst line contains an integer n (1 ≤ n ≤ 105), the number of places in Hogwarts.Each of the next n - 1 lines contains two space separated integers u and v (1 ≤ u, v ≤ n) indicating a road between places u and v. It is guaranteed that the given roads form a connected tree.Next line contains a single integer q (1 ≤ q ≤ 105), the number of new edges being added.Each of the next q lines contains two space separated integers u and v (1 ≤ u, v ≤ n) representing the new road being added.Note that it is possible that a newly added road connects places that were connected by a road before. Also, a newly added road may connect a place to itself.OutputIn the first line print the value for the number of triplets before any changes occurred.After that print q lines, a single integer ansi in each line containing the value for the number of triplets after i-th edge addition.ExamplesInput31 22 312 3Output24Input41 22 32 421 43 4Output61824Input51 22 33 44 511 5Output2060NoteIn the first sample case, for the initial tree, we have (1, 3, 2) and (3, 1, 2) as the only possible triplets (u, v, w).After addition of edge from 2 to 3, we have (1, 3, 2), (3, 1, 2), (1, 2, 3) and (2, 1, 3) as the possible triplets.
Input31 22 312 3
Output24
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*3300']
F. Naginitime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNagini, being a horcrux You-know-who created with the murder of Bertha Jorkins, has accumulated its army of snakes and is launching an attack on Hogwarts school. Hogwarts' entrance can be imagined as a straight line (x-axis) from 1 to 105. Nagini is launching various snakes at the Hogwarts entrance. Each snake lands parallel to the entrance, covering a segment at a distance k from x = l to x = r. Formally, each snake can be imagined as being a line segment between points (l, k) and (r, k). Note that k can be both positive and negative, but not 0.Let, at some x-coordinate x = i, there be snakes at point (i, y1) and point (i, y2), such that y1 > 0 and y2 < 0. Then, if for any point (i, y3) containing a snake such that y3 > 0, y1 ≤ y3 holds and for any point (i, y4) containing a snake such that y4 < 0, |y2| ≤ |y4| holds, then the danger value at coordinate x = i is y1 + |y2|. If no such y1 and y2 exist, danger value is 0. Harry wants to calculate the danger value of various segments of the Hogwarts entrance. Danger value for a segment [l, r) of the entrance can be calculated by taking the sum of danger values for each integer x-coordinate present in the segment.Formally, you have to implement two types of queries: 1 l r k: a snake is added parallel to entrance from x = l to x = r at y-coordinate y = k (l inclusive, r exclusive). 2 l r: you have to calculate the danger value of segment l to r (l inclusive, r exclusive). InputFirst line of input contains a single integer q (1 ≤ q ≤ 5·104) denoting the number of queries.Next q lines each describe a query. Each query description first contains the query type typei (1 ≤ typei ≤ 2). This is followed by further description of the query. In case of the type being 1, it is followed by integers li, ri and ki (,  - 109 ≤ ki ≤ 109, k ≠ 0). Otherwise, it just contains two integers, li and ri (1 ≤ li < ri ≤ 105).OutputOutput the answer for each query of type 2 in a separate line.ExamplesInput31 1 10 101 2 4 -72 1 10Output34Input71 2 3 51 1 10 101 4 5 -52 4 81 1 10 -102 4 82 1 10Output1575170NoteIn the first sample case, the danger value for x-coordinates 1 is 0 as there is no y2 satisfying the above condition for x = 1.Danger values for x-coordinates 2 and 3 is 10 + | - 7| = 17.Danger values for x-coordinates 4 to 9 is again 0 as there is no y2 satisfying the above condition for these coordinates.Thus, total danger value is 17 + 17 = 34.
Input31 1 10 101 2 4 -72 1 10
Output34
4 seconds
256 megabytes
['binary search', 'data structures', '*3100']
E. Salazar Slytherin's Lockettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers.InputFirst line of input contains q (1 ≤ q ≤ 105) — number of queries.Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018).OutputYou have to output q lines, each containing a single integer, the answer to the corresponding query.ExamplesInput22 4 93 1 10Output12Input22 1 1005 1 100Output214NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1.
Input22 4 93 1 10
Output12
2 seconds
256 megabytes
['bitmasks', 'dp', '*2200']
D. Rowena Ravenclaw's Diademtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her. Harry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry is trying to get inside the Room of Requirement to destroy the diadem as he knows that it is a horcrux.But he has to answer a puzzle in order to enter the room. He is given n objects, numbered from 1 to n. Some of the objects have a parent object, that has a lesser number. Formally, object i may have a parent object parenti such that parenti < i.There is also a type associated with each parent relation, it can be either of type 1 or type 2. Type 1 relation means that the child object is like a special case of the parent object. Type 2 relation means that the second object is always a part of the first object and all its special cases.Note that if an object b is a special case of object a, and c is a special case of object b, then c is considered to be a special case of object a as well. The same holds for parts: if object b is a part of a, and object c is a part of b, then we say that object c is a part of a. Also note, that if object b is a part of a, and object c is a special case of a, then b is a part of c as well.An object is considered to be neither a part of itself nor a special case of itself.Now, Harry has to answer two type of queries: 1 u v: he needs to tell if object v is a special case of object u. 2 u v: he needs to tell if object v is a part of object u. InputFirst line of input contains the number n (1 ≤ n ≤ 105), the number of objects. Next n lines contain two integer parenti and typei ( - 1 ≤ parenti < i parenti ≠ 0,  - 1 ≤ typei ≤ 1), implying that the i-th object has the parent parenti. (If typei = 0, this implies that the object i is a special case of object parenti. If typei = 1, this implies that the object i is a part of object parenti). In case the i-th object has no parent, both parenti and typei are -1.Next line contains an integer q (1 ≤ q ≤ 105), the number of queries. Next q lines each represent a query having three space separated integers typei, ui, vi (1 ≤ typei ≤ 2, 1 ≤ u, v ≤ n).OutputOutput will contain q lines, each containing the answer for the corresponding query as "YES" (affirmative) or "NO" (without quotes).You can output each letter in any case (upper or lower).ExamplesInput3-1 -11 02 021 1 32 1 3OutputYESNOInput3-1 -11 01 122 2 32 3 2OutputYESNONoteIn test case 1, as object 2 is a special case of object 1 and object 3 is a special case of object 2, this makes object 3 a special case of object 1.In test case 2, as object 2 is a special case of object 1 and object 1 has object 3, this will mean that object 2 will also have object 3. This is because when a general case (object 1) has object 3, its special case (object 2) will definitely have object 3.
Input3-1 -11 02 021 1 32 1 3
OutputYESNO
2 seconds
256 megabytes
['trees', '*2500']
C. Helga Hufflepuff's Cuptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry, 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.InputThe 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 ui and vi (1 ≤ ui, vi ≤ n) representing the i-th edge, which shows there is a path between the two vaults ui and vi. 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.OutputOutput a single integer, the number of ways of giving each vault a type following the conditions modulo 109 + 7.ExamplesInput4 21 22 31 41 2Output1Input3 31 21 32 1Output13Input3 11 21 31 1Output0NoteIn 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.
Input4 21 22 31 41 2
Output1
2 seconds
256 megabytes
['dp', 'trees', '*2000']
B. Marvolo Gaunt's Ringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of p·ai + q·aj + r·ak for given p, q, r and array a1, a2, ... an such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.InputFirst line of input contains 4 integers n, p, q, r ( - 109 ≤ p, q, r ≤ 109, 1 ≤ n ≤ 105).Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≤ ai ≤ 109).OutputOutput a single integer the maximum value of p·ai + q·aj + r·ak that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.ExamplesInput5 1 2 31 2 3 4 5Output30Input5 1 2 -3-1 -2 -3 -4 -5Output12NoteIn the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Input5 1 2 31 2 3 4 5
Output30
2 seconds
256 megabytes
['brute force', 'data structures', 'dp', '*1500']
A. Tom Riddle's Diarytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes).InputFirst line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list.Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100.OutputOutput n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.You can print each letter in any case (upper or lower).ExamplesInput6tomluciusginnyharryginnyharryOutputNONONONOYESYESInput3aaaOutputNOYESYESNoteIn test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
Input6tomluciusginnyharryginnyharry
OutputNONONONOYESYES
2 seconds
256 megabytes
['brute force', 'implementation', 'strings', '*800']
B. Maxim Buys an Apartmenttime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputMaxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly k already inhabited apartments, but he doesn't know their indices yet.Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.InputThe only line of the input contains two integers: n and k (1 ≤ n ≤ 109, 0 ≤ k ≤ n).OutputPrint the minimum possible and the maximum possible number of apartments good for Maxim.ExampleInput6 3Output1 3NoteIn the sample test, the number of good apartments could be minimum possible if, for example, apartments with indices 1, 2 and 3 were inhabited. In this case only apartment 4 is good. The maximum possible number could be, for example, if apartments with indices 1, 3 and 5 were inhabited. In this case all other apartments: 2, 4 and 6 are good.
Input6 3
Output1 3
1 second
512 megabytes
['constructive algorithms', 'math', '*1200']
A. Fractiontime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputPetya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ( + ) instead of division button (÷) and got sum of numerator and denominator that was equal to n instead of the expected decimal notation. Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction such that sum of its numerator and denominator equals n. Help Petya deal with this problem. InputIn the only line of input there is an integer n (3 ≤ n ≤ 1000), the sum of numerator and denominator of the fraction.OutputOutput two space-separated positive integers a and b, numerator and denominator of the maximum possible proper irreducible fraction satisfying the given sum.ExamplesInput3Output1 2Input4Output1 3Input12Output5 7
Input3
Output1 2
1 second
512 megabytes
['brute force', 'constructive algorithms', 'math', '*800']
E. Lada Malinatime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter long-term research and lots of experiments leading Megapolian automobile manufacturer «AutoVoz» released a brand new car model named «Lada Malina». One of the most impressive features of «Lada Malina» is its highly efficient environment-friendly engines.Consider car as a point in Oxy plane. Car is equipped with k engines numbered from 1 to k. Each engine is defined by its velocity vector whose coordinates are (vxi, vyi) measured in distance units per day. An engine may be turned on at any level wi, that is a real number between  - 1 and  + 1 (inclusive) that result in a term of (wi·vxi, wi·vyi) in the final car velocity. Namely, the final car velocity is equal to (w1·vx1 + w2·vx2 + ... + wk·vxk,   w1·vy1 + w2·vy2 + ... + wk·vyk) Formally, if car moves with constant values of wi during the whole day then its x-coordinate will change by the first component of an expression above, and its y-coordinate will change by the second component of an expression above. For example, if all wi are equal to zero, the car won't move, and if all wi are equal to zero except w1 = 1, then car will move with the velocity of the first engine.There are n factories in Megapolia, i-th of them is located in (fxi, fyi). On the i-th factory there are ai cars «Lada Malina» that are ready for operation.As an attempt to increase sales of a new car, «AutoVoz» is going to hold an international exposition of cars. There are q options of exposition location and time, in the i-th of them exposition will happen in a point with coordinates (pxi, pyi) in ti days. Of course, at the «AutoVoz» is going to bring as much new cars from factories as possible to the place of exposition. Cars are going to be moved by enabling their engines on some certain levels, such that at the beginning of an exposition car gets exactly to the exposition location. However, for some of the options it may be impossible to bring cars from some of the factories to the exposition location by the moment of an exposition. Your task is to determine for each of the options of exposition location and time how many cars will be able to get there by the beginning of an exposition.InputThe first line of input contains three integers k, n, q (2 ≤ k ≤ 10, 1 ≤ n ≤ 105, 1 ≤ q ≤ 105), the number of engines of «Lada Malina», number of factories producing «Lada Malina» and number of options of an exposition time and location respectively.The following k lines contain the descriptions of «Lada Malina» engines. The i-th of them contains two integers vxi, vyi ( - 1000 ≤ vxi, vyi ≤ 1000) defining the velocity vector of the i-th engine. Velocity vector can't be zero, i.e. at least one of vxi and vyi is not equal to zero. It is guaranteed that no two velosity vectors are collinear (parallel).Next n lines contain the descriptions of factories. The i-th of them contains two integers fxi, fyi, ai ( - 109 ≤ fxi, fyi ≤ 109, 1 ≤ ai ≤ 109) defining the coordinates of the i-th factory location and the number of cars that are located there.The following q lines contain the descriptions of the car exposition. The i-th of them contains three integers pxi, pyi, ti ( - 109 ≤ pxi, pyi ≤ 109, 1 ≤ ti ≤ 105) defining the coordinates of the exposition location and the number of days till the exposition start in the i-th option.OutputFor each possible option of the exposition output the number of cars that will be able to get to the exposition location by the moment of its beginning.ExamplesInput2 4 11 1-1 12 3 12 -2 1-2 1 1-2 -2 10 0 2Output3Input3 4 32 0-1 1-1 -2-3 0 61 -2 1-3 -7 33 2 2-1 -4 10 4 26 0 1Output490NoteImages describing sample tests are given below. Exposition options are denoted with crosses, factories are denoted with points. Each factory is labeled with a number of cars that it has.First sample test explanation: Car from the first factory is not able to get to the exposition location in time. Car from the second factory can get to the exposition in time if we set w1 = 0, w2 = 1. Car from the third factory can get to the exposition in time if we set , . Car from the fourth factory can get to the exposition in time if we set w1 = 1, w2 = 0.
Input2 4 11 1-1 12 3 12 -2 1-2 1 1-2 -2 10 0 2
Output3
5 seconds
256 megabytes
['data structures', 'geometry', '*3400']
D. Michael and Charging Stationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMichael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.Michael's day starts from charging his electric car for getting to the work and back. He spends 1000 burles on charge if he goes to the first job, and 2000 burles if he goes to the second job.On a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of x burles, he is allowed to pay an amount of y (0 ≤ y ≤ x) burles that does not exceed the bonus card balance with bonus burles. In this case he pays x - y burles with cash, and the balance on the bonus card is decreased by y bonus burles. If customer pays whole price with cash (i.e., y = 0) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by bonus burles. Initially the bonus card balance is equal to 0 bonus burles.Michael has planned next n days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.InputThe first line of input contains a single integer n (1 ≤ n ≤ 300 000), the number of days Michael has planned.Next line contains n integers a1, a2, ..., an (ai = 1000 or ai = 2000) with ai denoting the charging cost at the day i.OutputOutput the minimum amount of burles Michael has to spend.ExamplesInput31000 2000 1000Output3700Input62000 2000 2000 2000 2000 1000Output10000NoteIn the first sample case the most optimal way for Michael is to pay for the first two days spending 3000 burles and get 300 bonus burles as return. After that he is able to pay only 700 burles for the third days, covering the rest of the price with bonus burles.In the second sample case the most optimal way for Michael is to pay the whole price for the first five days, getting 1000 bonus burles as return and being able to use them on the last day without paying anything in cash.
Input31000 2000 1000
Output3700
2 seconds
512 megabytes
['binary search', 'dp', 'greedy', '*2400']
C. Boredomtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIlya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly n·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.InputThe first line of input contains two integers n and q (2 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the size of the grid and the number of query rectangles.The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≤ pi ≤ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right.The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≤ l ≤ r ≤ n, 1 ≤ d ≤ u ≤ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.OutputFor each query rectangle output its beauty degree on a separate line.ExamplesInput2 31 21 1 1 11 1 1 21 1 2 2Output111Input4 21 3 2 44 1 4 41 1 2 3Output35NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Input2 31 21 1 1 11 1 1 21 1 2 2
Output111
2 seconds
512 megabytes
['data structures', '*2100']
B. Jury Meetingtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputCountry of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.InputThe first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106). The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.OutputOutput the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).ExamplesInput2 6 51 1 0 50003 2 0 55002 2 0 600015 0 2 90009 0 1 70008 0 2 6500Output24500Input2 4 51 2 0 50002 1 0 45002 1 0 30008 0 1 6000Output-1NoteThe optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Input2 6 51 1 0 50003 2 0 55002 2 0 600015 0 2 90009 0 1 70008 0 2 6500
Output24500
1 second
512 megabytes
['greedy', 'sortings', 'two pointers', '*1800']
A. Planningtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputHelen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.InputThe first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.OutputThe first line must contain the minimum possible total cost of delaying the flights.The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.ExampleInput5 24 2 1 10 2Output203 6 7 4 5 NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Input5 24 2 1 10 2
Output203 6 7 4 5
1 second
512 megabytes
['greedy', '*1500']
I. Datingtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThis story is happening in a town named BubbleLand. There are n houses in BubbleLand. In each of these n houses lives a boy or a girl. People there really love numbers and everyone has their favorite number f. That means that the boy or girl that lives in the i-th house has favorite number equal to fi.The houses are numerated with numbers 1 to n.The houses are connected with n - 1 bidirectional roads and you can travel from any house to any other house in the town. There is exactly one path between every pair of houses.A new dating had agency opened their offices in this mysterious town and the citizens were very excited. They immediately sent q questions to the agency and each question was of the following format: a b — asking how many ways are there to choose a couple (boy and girl) that have the same favorite number and live in one of the houses on the unique path from house a to house b. Help the dating agency to answer the questions and grow their business.InputThe first line contains an integer n (1 ≤ n ≤ 105), the number of houses in the town.The second line contains n integers, where the i-th number is 1 if a boy lives in the i-th house or 0 if a girl lives in i-th house.The third line contains n integers, where the i-th number represents the favorite number fi (1 ≤ fi ≤ 109) of the girl or boy that lives in the i-th house.The next n - 1 lines contain information about the roads and the i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ n) which means that there exists road between those two houses. It is guaranteed that it's possible to reach any house from any other.The following line contains an integer q (1 ≤ q ≤ 105), the number of queries.Each of the following q lines represents a question and consists of two integers a and b (1 ≤ a, b ≤ n).OutputFor each of the q questions output a single number, the answer to the citizens question.ExampleInput71 0 0 1 0 1 09 2 9 2 2 9 92 61 24 26 53 67 421 37 5Output23NoteIn the first question from house 1 to house 3, the potential couples are (1, 3) and (6, 3).In the second question from house 7 to house 5, the potential couples are (7, 6), (4, 2) and (4, 5).
Input71 0 0 1 0 1 09 2 9 2 2 9 92 61 24 26 53 67 421 37 5
Output23
2 seconds
64 megabytes
['brute force', 'dfs and similar', 'graphs', 'trees', '*2300']
H. Bob and stagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe citizens of BubbleLand are celebrating their 10th anniversary so they decided to organize a big music festival. Bob got a task to invite N famous singers who would sing on the fest. He was too busy placing stages for their performances that he totally forgot to write the invitation e-mails on time, and unfortunately he only found K available singers. Now there are more stages than singers, leaving some of the stages empty. Bob would not like if citizens of BubbleLand noticed empty stages and found out that he was irresponsible.Because of that he decided to choose exactly K stages that form a convex set, make large posters as edges of that convex set and hold festival inside. While those large posters will make it impossible for citizens to see empty stages outside Bob still needs to make sure they don't see any of the empty stages inside that area.Since lots of people are coming, he would like that the festival area is as large as possible. Help him calculate the maximum area that he could obtain respecting the conditions. If there is no such area, the festival cannot be organized and the answer is 0.00.InputThe first line of input contains two integers N (3 ≤ N ≤ 200) and K (3 ≤ K ≤ min(N, 50)), separated with one empty space, representing number of stages and number of singers, respectively.Each of the next N lines contains two integers Xi and Yi (0 ≤ Xi, Yi ≤ 106) representing the coordinates of the stages. There are no three or more collinear stages.OutputOutput contains only one line with one number, rounded to exactly two decimal places: the maximal festival area. Rounding is performed so that 0.5 and more rounds up and everything else rounds down.ExampleInput5 40 03 02 14 41 5Output10.00NoteExample explanation: From all possible convex polygon with 4 vertices and no other vertex inside, the largest is one with points (0, 0), (2, 1), (4, 4) and (1, 5).
Input5 40 03 02 14 41 5
Output10.00
2 seconds
256 megabytes
['dp', 'geometry', '*3000']
G. Bathroom terminaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:"Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle. You are given N strings which represent words. Each word is of the maximum length L and consists of characters 'a'-'e'. You are also given M strings which represent patterns. Pattern is a string of length  ≤  L and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin."Help Smith escape.InputThe first line of input contains two integers N and M (1 ≤ N ≤  100 000, 1 ≤ M ≤  5000), representing the number of words and patterns respectively.The next N lines represent each word, and after those N lines, following M lines represent each pattern. Each word and each pattern has a maximum length L (1 ≤ L ≤ 50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.OutputOutput contains M lines and each line consists of one integer, representing the number of words that match the corresponding pattern.ExampleInput3 1abcaecaca?cOutput3NoteIf we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively.
Input3 1abcaecaca?c
Output3
2 seconds
256 megabytes
['implementation', '*1700']
F. Product transformationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider an array A with N elements, all being the same integer a.Define the product transformation as a simultaneous update Ai = Ai·Ai + 1, that is multiplying each element to the element right to it for , with the last number AN remaining the same. For example, if we start with an array A with a = 2 and N = 4, then after one product transformation A = [4,  4,  4,  2], and after two product transformations A = [16,  16,  8,  2].Your simple task is to calculate the array A after M product transformations. Since the numbers can get quite big you should output them modulo Q.InputThe first and only line of input contains four integers N, M, a, Q (7 ≤ Q ≤ 109 + 123, 2 ≤ a ≤ 106 + 123, , is prime), where is the multiplicative order of the integer a modulo Q, see notes for definition.OutputYou should output the array A from left to right.ExampleInput2 2 2 7Output1 2 NoteThe multiplicative order of a number a modulo Q , is the smallest natural number x such that ax mod Q = 1. For example, .
Input2 2 2 7
Output1 2
3 seconds
256 megabytes
['combinatorics', 'math', 'number theory', '*2200']
E. Casinos and traveltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N.John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules.To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey.He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey.In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7.InputIn the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a,  b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road.OutputOutput one number, the answer to the problem modulo 109 + 7.ExamplesInput21 2Output4Input31 22 3Output10NoteExample 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4.Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
Input21 2
Output4
1 second
256 megabytes
['dp', '*2100']
D. Exploration plantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe competitors of Bubble Cup X gathered after the competition and discussed what is the best way to get to know the host country and its cities.After exploring the map of Serbia for a while, the competitors came up with the following facts: the country has V cities which are indexed with numbers from 1 to V, and there are E bi-directional roads that connect the cites. Each road has a weight (the time needed to cross that road). There are N teams at the Bubble Cup and the competitors came up with the following plan: each of the N teams will start their journey in one of the V cities, and some of the teams share the starting position.They want to find the shortest time T, such that every team can move in these T minutes, and the number of different cities they end up in is at least K (because they will only get to know the cities they end up in). A team doesn't have to be on the move all the time, if they like it in a particular city, they can stay there and wait for the time to pass.Please help the competitors to determine the shortest time T so it's possible for them to end up in at least K different cities or print -1 if that is impossible no matter how they move.Note that there can exist multiple roads between some cities.InputThe first line contains four integers: V, E, N and K (1 ≤  V  ≤  600,  1  ≤  E  ≤  20000,  1  ≤  N  ≤  min(V, 200),  1  ≤  K  ≤  N), number of cities, number of roads, number of teams and the smallest number of different cities they need to end up in, respectively.The second line contains N integers, the cities where the teams start their journey.Next E lines contain information about the roads in following format: Ai Bi Ti (1 ≤ Ai, Bi ≤ V,  1 ≤ Ti ≤ 10000), which means that there is a road connecting cities Ai and Bi, and you need Ti minutes to cross that road.OutputOutput a single integer that represents the minimal time the teams can move for, such that they end up in at least K different cities or output -1 if there is no solution.If the solution exists, result will be no greater than 1731311.ExampleInput6 7 5 45 5 2 2 51 3 31 5 21 6 52 5 42 6 73 4 113 5 3Output3NoteThree teams start from city 5, and two teams start from city 2. If they agree to move for 3 minutes, one possible situation would be the following: Two teams in city 2, one team in city 5, one team in city 3 , and one team in city 1. And we see that there are four different cities the teams end their journey at.
Input6 7 5 45 5 2 2 51 3 31 5 21 6 52 5 42 6 73 4 113 5 3
Output3
2 seconds
256 megabytes
['binary search', 'flows', 'graph matchings', 'shortest paths', '*2100']
C. Propertytime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n,  A2n =  A0, with sides of the exactly 1 meter in length. Court rules for removing part of his property are as follows: Split every edge Ak Ak + 1,  k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1 On every edge A2k A2k + 1,  k = 0... n - 1 court will choose one point B2k =  Pi for some i = 0, ...,  n - 1 such that On every edge A2k + 1A2k + 2,  k = 0...n - 1 Bill will choose one point B2k + 1 =  Pi for some i = 0, ...,  n - 1 such that Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1 Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.InputThe first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.The second line contains n distinct integer numbers B2k (0 ≤ B2k ≤ n - 1,  k = 0... n - 1) separated by a single space, representing points the court chose. If B2k = i, the court chose point Pi on side A2k A2k + 1.OutputOutput contains n distinct integers separated by a single space representing points B1, B3, ..., B2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.ExampleInput30 1 2Output0 2 1NoteTo maximize area Bill should choose points: B1 = P0, B3 = P2, B5 = P1
Input30 1 2
Output0 2 1
0.5 seconds
256 megabytes
['greedy', 'sortings', '*2100']
B. Neural Network countrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDue to the recent popularity of the Deep learning new countries are starting to look like Neural Networks. That is, the countries are being built deep with many layers, each layer possibly having many cities. They also have one entry, and one exit point.There are exactly L layers, each having N cities. Let us look at the two adjacent layers L1 and L2. Each city from the layer L1 is connected to each city from the layer L2 with the traveling cost cij for , and each pair of adjacent layers has the same cost in between their cities as any other pair (they just stacked the same layers, as usual). Also, the traveling costs to each city from the layer L2 are same for all cities in the L1, that is cij is the same for , and fixed j.Doctor G. needs to speed up his computations for this country so he asks you to find the number of paths he can take from entry to exit point such that his traveling cost is divisible by given number M.InputThe first line of input contains N (1 ≤ N ≤ 106), L (2 ≤ L ≤ 105) and M (2 ≤ M ≤ 100), the number of cities in each layer, the number of layers and the number that travelling cost should be divisible by, respectively.Second, third and fourth line contain N integers each denoting costs 0 ≤ cost ≤ M from entry point to the first layer, costs between adjacent layers as described above, and costs from the last layer to the exit point.OutputOutput a single integer, the number of paths Doctor G. can take which have total cost divisible by M, modulo 109 + 7.ExampleInput2 3 134 62 13 4Output2NoteThis is a country with 3 layers, each layer having 2 cities. Paths , and are the only paths having total cost divisible by 13. Notice that input edges for layer cities have the same cost, and that they are same for all layers.
Input2 3 134 62 13 4
Output2
2 seconds
256 megabytes
['dp', 'matrices', '*2000']
A. Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn gave Jack a very hard problem. He wrote a very big positive integer A0 on a piece of paper. The number is less than 10200000 . In each step, Jack is allowed to put ' + ' signs in between some of the digits (maybe none) of the current number and calculate the sum of the expression. He can perform the same procedure on that sum and so on. The resulting sums can be labeled respectively by A1, A2 etc. His task is to get to a single digit number.The problem is that there is not much blank space on the paper. There are only three lines of space, so he can't perform more than three steps. Since he wants to fill up the paper completely, he will perform exactly three steps.Jack must not add leading zeros to intermediate results, but he can put ' + ' signs in front of digit 0. For example, if the current number is 1000100, 10 + 001 + 00 is a valid step, resulting in number 11.InputFirst line contains a positive integer N (1 ≤ N ≤ 200000), representing the number of digits of A0.Second line contains a string of length N representing positive integer number A0. Each character is digit. There will be no leading zeros.OutputOutput exactly three lines, the steps Jack needs to perform to solve the problem. You can output any sequence of steps which results in a single digit number (and is logically consistent).Every step consists of digits and ' + ' signs. Steps should not contain several ' + ' signs in a row, whitespaces, or ' + ' signs as the first or last character. They also need to be arithmetically consistent.Solution might not be unique. Output any of them in that case.ExamplesInput11Output111Input45806Output5+8+0+61+91+0NoteIn the first sample, Jack can't put ' + ' signs anywhere, so he just writes 1 in each line and solves the problem. Here, solution is unique.In the second sample, Jack first puts ' + ' between every two consecutive digits, thus getting the result 5 + 8 + 0 + 6 = 19. He does the same on the second step, getting 1 + 9 = 10. Once more, he gets 1 + 0 = 1, so after three steps, the result is 1 and his solution is correct.
Input11
Output111
1 second
256 megabytes
['brute force', 'implementation', 'math', '*2500']
B. Arpa and an exam about geometrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArpa is taking a geometry exam. Here is the last problem of the exam.You are given three points a, b, c.Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.InputThe only line contains six integers ax, ay, bx, by, cx, cy (|ax|, |ay|, |bx|, |by|, |cx|, |cy| ≤ 109). It's guaranteed that the points are distinct.OutputPrint "Yes" if the problem has a solution, "No" otherwise.You can print each letter in any case (upper or lower).ExamplesInput0 1 1 1 1 0OutputYesInput1 1 0 0 1000 1000OutputNoNoteIn the first sample test, rotate the page around (0.5, 0.5) by .In the second sample test, you can't find any solution.
Input0 1 1 1 1 0
OutputYes
2 seconds
256 megabytes
['geometry', 'math', '*1400']
A. Arpa and a research in Mexican wavetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArpa is researching the Mexican wave.There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. At time 1, the first spectator stands. At time 2, the second spectator stands. ... At time k, the k-th spectator stands. At time k + 1, the (k + 1)-th spectator stands and the first spectator sits. At time k + 2, the (k + 2)-th spectator stands and the second spectator sits. ... At time n, the n-th spectator stands and the (n - k)-th spectator sits. At time n + 1, the (n + 1 - k)-th spectator sits. ... At time n + k, the n-th spectator sits. Arpa wants to know how many spectators are standing at time t.InputThe first line contains three integers n, k, t (1 ≤ n ≤ 109, 1 ≤ k ≤ n, 1 ≤ t < n + k).OutputPrint single integer: how many spectators are standing at time t.ExamplesInput10 5 3Output3Input10 5 7Output5Input10 5 12Output3NoteIn the following a sitting spectator is represented as -, a standing spectator is represented as ^. At t = 0  ---------- number of standing spectators = 0. At t = 1  ^--------- number of standing spectators = 1. At t = 2  ^^-------- number of standing spectators = 2. At t = 3  ^^^------- number of standing spectators = 3. At t = 4  ^^^^------ number of standing spectators = 4. At t = 5  ^^^^^----- number of standing spectators = 5. At t = 6  -^^^^^---- number of standing spectators = 5. At t = 7  --^^^^^--- number of standing spectators = 5. At t = 8  ---^^^^^-- number of standing spectators = 5. At t = 9  ----^^^^^- number of standing spectators = 5. At t = 10 -----^^^^^ number of standing spectators = 5. At t = 11 ------^^^^ number of standing spectators = 4. At t = 12 -------^^^ number of standing spectators = 3. At t = 13 --------^^ number of standing spectators = 2. At t = 14 ---------^ number of standing spectators = 1. At t = 15 ---------- number of standing spectators = 0.
Input10 5 3
Output3
1 second
256 megabytes
['implementation', 'math', '*800']
F. Rainbow Ballstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of balls of n different colors. You have ai balls of the i-th color.While there are at least two different colored balls in the bag, perform the following steps: Take out two random balls without replacement one by one. These balls might be the same color. Color the second ball to the color of the first ball. You are not allowed to switch the order of the balls in this step. Place both balls back in the bag. All these actions take exactly one second. Let M = 109 + 7. It can be proven that the expected amount of time needed before you stop can be represented as a rational number , where P and Q are coprime integers and where Q is not divisible by M. Return the value .InputThe first line of input will contain a single integer n (1 ≤ n ≤ 2 500) — the number of colors.The next line of input will contain n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the number of balls of each color.OutputPrint a single integer, the answer to the problem.ExamplesInput21 1Output1Input31 2 3Output750000026NoteIn the first sample, no matter what happens, the balls will become the same color after one step.For the second sample, we have 6 balls. Let’s label the balls from 1 to 6, and without loss of generality, let’s say balls 1,2,3 are initially color 1, balls 4,5 are color 2, and ball 6 are color 3.Here is an example of how these steps can go: We choose ball 5 and ball 6. Ball 6 then becomes color 2. We choose ball 4 and ball 5. Ball 5 remains the same color (color 2). We choose ball 1 and ball 5. Ball 5 becomes color 1. We choose ball 6 and ball 5. Ball 5 becomes color 2. We choose ball 3 and ball 4. Ball 4 becomes color 1. We choose ball 4 and ball 6. Ball 6 becomes color 1. We choose ball 2 and ball 5. Ball 5 becomes color 1. At this point, the game ends since all the balls are the same color. This particular sequence took 7 seconds.It can be shown that the answer to this case is .
Input21 1
Output1
2 seconds
256 megabytes
['math', '*2800']
E. Random Electionstime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe presidential election is coming in Bearland next year! Everybody is so excited about this!So far, there are three candidates, Alice, Bob, and Charlie. There are n citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, each of n citizens will choose one of six orders of preference between Alice, Bob and Charlie uniformly at random, independently from other voters.The government of Bearland has devised a function to help determine the outcome of the election given the voters preferences. More specifically, the function is (takes n boolean numbers and returns a boolean number). The function also obeys the following property: f(1 - x1, 1 - x2, ..., 1 - xn) = 1 - f(x1, x2, ..., xn).Three rounds will be run between each pair of candidates: Alice and Bob, Bob and Charlie, Charlie and Alice. In each round, xi will be equal to 1, if i-th citizen prefers the first candidate to second in this round, and 0 otherwise. After this, y = f(x1, x2, ..., xn) will be calculated. If y = 1, the first candidate will be declared as winner in this round. If y = 0, the second will be the winner, respectively.Define the probability that there is a candidate who won two rounds as p. p·6n is always an integer. Print the value of this integer modulo 109 + 7 = 1 000 000 007.InputThe first line contains one integer n (1 ≤ n ≤ 20).The next line contains a string of length 2n of zeros and ones, representing function f. Let bk(x) the k-th bit in binary representation of x, i-th (0-based) digit of this string shows the return value of f(b1(i), b2(i), ..., bn(i)).It is guaranteed that f(1 - x1, 1 - x2, ..., 1 - xn) = 1 - f(x1, x2, ..., xn) for any values of x1, x2, ldots, xn.OutputOutput one integer — answer to the problem.ExamplesInput301010101Output216Input301101001Output168NoteIn first sample, result is always fully determined by the first voter. In other words, f(x1, x2, x3) = x1. Thus, any no matter what happens, there will be a candidate who won two rounds (more specifically, the candidate who is at the top of voter 1's preference list), so p = 1, and we print 1·63 = 216.
Input301010101
Output216
2 seconds
1024 megabytes
['bitmasks', 'brute force', 'divide and conquer', 'fft', 'math', '*2800']
D. Tournament Constructiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIvan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex. Yesterday Ivan learned Landau's criterion: there is tournament with scores d1 ≤ d2 ≤ ... ≤ dn if and only if for all 1 ≤ k < n and .Now, Ivan wanna solve following problem: given a set of numbers S = {a1, a2, ..., am}, is there a tournament with given set of scores? I.e. is there tournament with sequence of scores d1, d2, ..., dn such that if we remove duplicates in scores, we obtain the required set {a1, a2, ..., am}? Find a tournament with minimum possible number of vertices. InputThe first line contains a single integer m (1 ≤ m ≤ 31).The next line contains m distinct integers a1, a2, ..., am (0 ≤ ai ≤ 30) — elements of the set S. It is guaranteed that all elements of the set are distinct.OutputIf there are no such tournaments, print string "=(" (without quotes).Otherwise, print an integer n — the number of vertices in the tournament.Then print n lines with n characters — matrix of the tournament. The j-th element in the i-th row should be 1 if the edge between the i-th and the j-th vertices is oriented towards the j-th vertex, and 0 otherwise. The main diagonal should contain only zeros.ExamplesInput21 2Output40011100101000010Input20 3Output6000111100011110001011001001101000000
Input21 2
Output40011100101000010
2 seconds
512 megabytes
['constructive algorithms', 'dp', 'graphs', 'greedy', 'math', '*2800']
C. Arpa and a game with Mojtabatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMojtaba and Arpa are playing a game. They have a list of n numbers in the game.In a player's turn, he chooses a number pk (where p is a prime number and k is a positive integer) such that pk divides at least one number in the list. For each number in the list divisible by pk, call it x, the player will delete x and add to the list. The player who can not make a valid choice of p and k loses.Mojtaba starts the game and the players alternatively make moves. Determine which one of players will be the winner if both players play optimally.InputThe first line contains a single integer n (1 ≤ n ≤ 100) — the number of elements in the list.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the list.OutputIf Mojtaba wins, print "Mojtaba", otherwise print "Arpa" (without quotes).You can print each letter in any case (upper or lower).ExamplesInput41 1 1 1OutputArpaInput41 1 17 17OutputMojtabaInput41 1 17 289OutputArpaInput51 2 3 4 5OutputArpaNoteIn the first sample test, Mojtaba can't move.In the second sample test, Mojtaba chooses p = 17 and k = 1, then the list changes to [1, 1, 1, 1].In the third sample test, if Mojtaba chooses p = 17 and k = 1, then Arpa chooses p = 17 and k = 1 and wins, if Mojtaba chooses p = 17 and k = 2, then Arpa chooses p = 17 and k = 1 and wins.
Input41 1 1 1
OutputArpa
1 second
256 megabytes
['bitmasks', 'dp', 'games', '*2200']
B. Arpa and a list of numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.InputFirst line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y.Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.OutputPrint a single integer: the minimum possible cost to make the list good.ExamplesInput4 23 171 17 17 16Output40Input10 6 2100 49 71 73 66 96 8 60 41 63Output10NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Input4 23 171 17 17 16
Output40
2 seconds
256 megabytes
['implementation', 'number theory', '*2100']
A. Five Dimensional Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors and is acute (i.e. strictly less than ). Otherwise, the point is called good.The angle between vectors and in 5-dimensional space is defined as , where is the scalar product and is length of .Given the list of points, print the indices of the good points in ascending order.InputThe first line of input contains a single integer n (1 ≤ n ≤ 103) — the number of points.The next n lines of input contain five integers ai, bi, ci, di, ei (|ai|, |bi|, |ci|, |di|, |ei| ≤ 103)  — the coordinates of the i-th point. All points are distinct.OutputFirst, print a single integer k — the number of good points.Then, print k integers, each on their own line — the indices of the good points in ascending order.ExamplesInput60 0 0 0 01 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1Output11Input30 0 1 2 00 0 9 2 00 0 5 9 0Output0NoteIn the first sample, the first point forms exactly a angle with all other pairs of points, so it is good.In the second sample, along the cd plane, we can see the points look as follows:We can see that all angles here are acute, so no points are good.
Input60 0 0 0 01 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1
Output11
2 seconds
256 megabytes
['brute force', 'geometry', 'math', '*1700']
B. Tell Your Worldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConnect the countless points with lines, till we reach the faraway yonder.There are n points on a coordinate plane, the i-th of which being (i, yi).Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.InputThe first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points.The second line contains n space-separated integers y1, y2, ..., yn ( - 109 ≤ yi ≤ 109) — the vertical coordinates of each point.OutputOutput "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise.You can print each letter in any case (upper or lower).ExamplesInput57 5 8 6 9OutputYesInput5-1 -2 0 0 -5OutputNoInput55 4 3 2 1OutputNoInput51000000000 0 0 0 0OutputYesNoteIn the first example, there are five points: (1, 7), (2, 5), (3, 8), (4, 6) and (5, 9). It's possible to draw a line that passes through points 1, 3, 5, and another one that passes through points 2, 4 and is parallel to the first one.In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.In the third example, it's impossible to satisfy both requirements at the same time.
Input57 5 8 6 9
OutputYes
1 second
256 megabytes
['brute force', 'geometry', '*1600']
A. Odds and Endstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhere do odds begin, and where do they end? Where does hope emerge, and will they ever break?Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.A subsegment is a contiguous slice of the whole sequence. For example, {3, 4, 5} and {1} are subsegments of sequence {1, 2, 3, 4, 5, 6}, while {1, 2, 4} and {7} are not.InputThe first line of input contains a non-negative integer n (1 ≤ n ≤ 100) — the length of the sequence.The second line contains n space-separated non-negative integers a1, a2, ..., an (0 ≤ ai ≤ 100) — the elements of the sequence.OutputOutput "Yes" if it's possible to fulfill the requirements, and "No" otherwise.You can output each letter in any case (upper or lower).ExamplesInput31 3 5OutputYesInput51 0 1 5 1OutputYesInput34 3 1OutputNoInput43 9 9 3OutputNoNoteIn the first example, divide the sequence into 1 subsegment: {1, 3, 5} and the requirements will be met.In the second example, divide the sequence into 3 subsegments: {1, 0, 1}, {5}, {1}.In the third example, one of the subsegments must start with 4 which is an even number, thus the requirements cannot be met.In the fourth example, the sequence can be divided into 2 subsegments: {3, 9, 9}, {3}, but this is not a valid solution because 2 is an even number.
Input31 3 5
OutputYes
1 second
256 megabytes
['implementation', '*1000']
E. Days of Floral Colourstime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days.On the rim of the Floral Clock are 2n flowers, numbered from 1 to 2n clockwise, each of which has a colour among all n possible ones. For each colour, there are exactly two flowers with it, the distance between which either is less than or equal to 2, or equals n. Additionally, if flowers u and v are of the same colour, then flowers opposite to u and opposite to v should be of the same colour as well — symmetry is beautiful!Formally, the distance between two flowers is 1 plus the number of flowers on the minor arc (or semicircle) between them. Below is a possible arrangement with n = 6 that cover all possibilities. The beauty of an arrangement is defined to be the product of the lengths of flower segments separated by all opposite flowers of the same colour. In other words, in order to compute the beauty, we remove from the circle all flowers that have the same colour as flowers opposite to them. Then, the beauty is the product of lengths of all remaining segments. Note that we include segments of length 0 in this product. If there are no flowers that have the same colour as flower opposite to them, the beauty equals 0. For instance, the beauty of the above arrangement equals 1 × 3 × 1 × 3 = 9 — the segments are {2}, {4, 5, 6}, {8} and {10, 11, 12}.While keeping the constraints satisfied, there may be lots of different arrangements. Find out the sum of beauty over all possible arrangements, modulo 998 244 353. Two arrangements are considered different, if a pair (u, v) (1 ≤ u, v ≤ 2n) exists such that flowers u and v are of the same colour in one of them, but not in the other.InputThe first and only line of input contains a lonely positive integer n (3 ≤ n ≤ 50 000) — the number of colours present on the Floral Clock.OutputOutput one integer — the sum of beauty over all possible arrangements of flowers, modulo 998 244 353.ExamplesInput3Output24Input4Output4Input7Output1316Input15Output3436404NoteWith n = 3, the following six arrangements each have a beauty of 2 × 2 = 4. While many others, such as the left one in the figure below, have a beauty of 0. The right one is invalid, since it's asymmetric.
Input3
Output24
7 seconds
256 megabytes
['combinatorics', 'divide and conquer', 'dp', 'fft', 'math', '*3400']
D. Shake It!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA never-ending, fast-changing and dream-like world unfolds, as the secret door opens.A world is an unordered graph G, in whose vertex set V(G) there are two special vertices s(G) and t(G). An initial world has vertex set {s(G), t(G)} and an edge between them.A total of n changes took place in an initial world. In each change, a new vertex w is added into V(G), an existing edge (u, v) is chosen, and two edges (u, w) and (v, w) are added into E(G). Note that it's possible that some edges are chosen in more than one change.It's known that the capacity of the minimum s-t cut of the resulting graph is m, that is, at least m edges need to be removed in order to make s(G) and t(G) disconnected.Count the number of non-similar worlds that can be built under the constraints, modulo 109 + 7. We define two worlds similar, if they are isomorphic and there is isomorphism in which the s and t vertices are not relabelled. Formally, two worlds G and H are considered similar, if there is a bijection between their vertex sets , such that: f(s(G)) = s(H); f(t(G)) = t(H); Two vertices u and v of G are adjacent in G if and only if f(u) and f(v) are adjacent in H. InputThe first and only line of input contains two space-separated integers n, m (1 ≤ n, m ≤ 50) — the number of operations performed and the minimum cut, respectively.OutputOutput one integer — the number of non-similar worlds that can be built, modulo 109 + 7.ExamplesInput3 2Output6Input4 4Output3Input7 3Output1196Input31 8Output64921457NoteIn the first example, the following 6 worlds are pairwise non-similar and satisfy the constraints, with s(G) marked in green, t(G) marked in blue, and one of their minimum cuts in light blue. In the second example, the following 3 worlds satisfy the constraints.
Input3 2
Output6
2 seconds
256 megabytes
['combinatorics', 'dp', 'flows', 'graphs', '*2900']
C. Goodbye Souvenirtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputI won't feel lonely, nor will I be sorrowful... not before everything is buried.A string of n beads is left as the message of leaving. The beads are numbered from 1 to n from left to right, each having a shape numbered by integers between 1 and n inclusive. Some beads may have the same shapes.The memory of a shape x in a certain subsegment of beads, is defined to be the difference between the last position and the first position that shape x appears in the segment. The memory of a subsegment is the sum of memories over all shapes that occur in it.From time to time, shapes of beads change as well as the memories. Sometimes, the past secreted in subsegments are being recalled, and you are to find the memory for each of them.InputThe first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 100 000) — the number of beads in the string, and the total number of changes and queries, respectively.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the initial shapes of beads 1, 2, ..., n, respectively.The following m lines each describes either a change in the beads or a query of subsegment. A line has one of the following formats: 1 p x (1 ≤ p ≤ n, 1 ≤ x ≤ n), meaning that the shape of the p-th bead is changed into x; 2 l r (1 ≤ l ≤ r ≤ n), denoting a query of memory of the subsegment from l to r, inclusive. OutputFor each query, print one line with an integer — the memory of the recalled subsegment.ExamplesInput7 61 2 3 1 3 2 12 3 72 1 31 7 21 3 22 1 62 5 7Output5071Input7 51 3 2 1 4 2 31 1 42 2 31 1 72 4 51 1 7Output00NoteThe initial string of beads has shapes (1, 2, 3, 1, 3, 2, 1).Consider the changes and queries in their order: 2 3 7: the memory of the subsegment [3, 7] is (7 - 4) + (6 - 6) + (5 - 3) = 5; 2 1 3: the memory of the subsegment [1, 3] is (1 - 1) + (2 - 2) + (3 - 3) = 0; 1 7 2: the shape of the 7-th bead changes into 2. Beads now have shapes (1, 2, 3, 1, 3, 2, 2) respectively; 1 3 2: the shape of the 3-rd bead changes into 2. Beads now have shapes (1, 2, 2, 1, 3, 2, 2) respectively; 2 1 6: the memory of the subsegment [1, 6] is (4 - 1) + (6 - 2) + (5 - 5) = 7; 2 5 7: the memory of the subsegment [5, 7] is (7 - 6) + (5 - 5) = 1.
Input7 61 2 3 1 3 2 12 3 72 1 31 7 21 3 22 1 62 5 7
Output5071
6 seconds
256 megabytes
['data structures', 'divide and conquer', '*2600']
B. Rooter's Songtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWherever the destination is, whoever we meet, let's render this song together.On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: Vertical: stands at (xi, 0), moves in positive y direction (upwards); Horizontal: stands at (0, yi), moves in positive x direction (rightwards). According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.InputThe first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively.The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.OutputOutput n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input.ExamplesInput8 10 81 1 101 4 131 7 11 8 22 2 02 5 142 6 02 6 1Output4 810 58 810 610 21 87 810 6Input3 2 31 1 22 1 11 1 5Output1 32 11 3NoteThe first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. In the second example, no dancers collide.
Input8 10 81 1 101 4 131 7 11 8 22 2 02 5 142 6 02 6 1
Output4 810 58 810 610 21 87 810 6
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'geometry', 'implementation', 'sortings', 'two pointers', '*1900']
A. From Y to Ytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFrom beginning till end, this message has been waiting to be conveyed.For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: Remove any two elements s and t from the set, and add their concatenation s + t to the set. The cost of such operation is defined to be , where f(s, c) denotes the number of times character c appears in string s.Given a non-negative integer k, construct any valid non-empty set of no more than 100 000 letters, such that the minimum accumulative cost of the whole process is exactly k. It can be shown that a solution always exists.InputThe first and only line of input contains a non-negative integer k (0 ≤ k ≤ 100 000) — the required minimum cost.OutputOutput a non-empty string of no more than 100 000 lowercase English letters — any multiset satisfying the requirements, concatenated to be a string.Note that the printed string doesn't need to be the final concatenated string. It only needs to represent an unordered multiset of letters.ExamplesInput12OutputababababInput3OutputcodeforcesNoteFor the multiset {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'}, one of the ways to complete the process is as follows: {"ab", "a", "b", "a", "b", "a", "b"}, with a cost of 0; {"aba", "b", "a", "b", "a", "b"}, with a cost of 1; {"abab", "a", "b", "a", "b"}, with a cost of 1; {"abab", "ab", "a", "b"}, with a cost of 0; {"abab", "aba", "b"}, with a cost of 1; {"abab", "abab"}, with a cost of 1; {"abababab"}, with a cost of 8. The total cost is 12, and it can be proved to be the minimum cost of the process.
Input12
Outputabababab
1 second
256 megabytes
['constructive algorithms', '*1600']
M. Weather Tomorrowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral.Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the first term equals to the average temperature on the first day, the second term equals to the average temperature on the second day and so on, then the average temperature of the next (n + 1)-th day will be equal to the next term of the arithmetic progression. Otherwise, according to Vasya's method, the temperature of the (n + 1)-th day will be equal to the temperature of the n-th day.Your task is to help Vasya predict the average temperature for tomorrow, i. e. for the (n + 1)-th day.InputThe first line contains a single integer n (2 ≤ n ≤ 100) — the number of days for which the average air temperature is known.The second line contains a sequence of integers t1, t2, ..., tn ( - 1000 ≤ ti ≤ 1000) — where ti is the average temperature in the i-th day.OutputPrint the average air temperature in the (n + 1)-th day, which Vasya predicts according to his method. Note that the absolute value of the predicted temperature can exceed 1000.ExamplesInput510 5 0 -5 -10Output-15Input41 1 1 1Output1Input35 1 -5Output-5Input2900 1000Output1100NoteIn the first example the sequence of the average temperatures is an arithmetic progression where the first term is 10 and each following terms decreases by 5. So the predicted average temperature for the sixth day is  - 10 - 5 =  - 15.In the second example the sequence of the average temperatures is an arithmetic progression where the first term is 1 and each following terms equals to the previous one. So the predicted average temperature in the fifth day is 1.In the third example the average temperatures do not form an arithmetic progression, so the average temperature of the fourth day equals to the temperature of the third day and equals to  - 5.In the fourth example the sequence of the average temperatures is an arithmetic progression where the first term is 900 and each the following terms increase by 100. So predicted average temperature in the third day is 1000 + 100 = 1100.
Input510 5 0 -5 -10
Output-15
1 second
256 megabytes
['implementation', 'math', '*1000']
L. Berland SU Computer Networktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through other routers) is possible. There are no cycles in the network, so there is only one path between each pair of routers over patch cords.Unfortunately, the exact topology of the network was lost by administrators. In order to restore it, the following auxiliary information was collected.For each patch cord p, directly connected to the router i, list of routers located behind the patch cord p relatively i is known. In other words, all routers path from which to the router i goes through p are known. So for each router i there are ki lists, where ki is the number of patch cords connected to i.For example, let the network consists of three routers connected in chain 1 - 2 - 3. Then: the router 1: for the single patch cord connected to the first router there is a single list containing two routers: 2 and 3; the router 2: for each of the patch cords connected to the second router there is a list: one list contains the router 1 and the other — the router 3; the router 3: for the single patch cord connected to the third router there is a single list containing two routers: 1 and 2. Your task is to help administrators to restore the network topology, i. e. to identify all pairs of routers directly connected by a patch cord.InputThe first line contains a single integer n (2 ≤ n ≤ 1000) — the number of routers in the network.The i-th of the following n lines contains a description of the lists for the router i.The description of each list begins with the number of routers in it. Then the symbol ':' follows, and after that the numbers of routers from the list are given. This numbers are separated by comma. Lists are separated by symbol '-'.It is guaranteed, that for each router i the total number of routers in its lists equals to n - 1 and all the numbers in lists of each router are distinct. For each router i lists do not contain the number i.OutputPrint -1 if no solution exists.In the other case print to the first line n - 1 — the total number of patch cords in the network. In each of the following n - 1 lines print two integers — the routers which are directly connected by a patch cord. Information about each patch cord must be printed exactly once.Patch cords and routers can be printed in arbitrary order.ExamplesInput32:3,21:1-1:32:1,2Output22 12 3Input54:2,5,3,41:4-1:1-2:5,34:4,5,2,14:2,1,3,51:3-3:4,2,1Output42 12 45 23 5Input31:2-1:31:1-1:31:1-1:2Output-1NoteThe first example is analyzed in the statement.The answer to the second example is shown on the picture. The first router has one list, which contains all other routers. The second router has three lists: the first — the single router 4, the second — the single router 1, the third — two routers 3 and 5. The third router has one list, which contains all other routers. The fourth router also has one list, which contains all other routers. The fifth router has two lists: the first — the single router 3, the second — three routers 1, 2 and 4.
Input32:3,21:1-1:32:1,2
Output22 12 3
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'hashing', 'trees', '*2400']
K. Travel Cardstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the evening Polycarp decided to analyze his today's travel expenses on public transport.The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.For example, if Polycarp made three consecutive trips: "BerBank" "University", "University" "BerMall", "University" "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards?InputThe first line contains five integers n, a, b, k, f (1 ≤ n ≤ 300, 1 ≤ b < a ≤ 100, 0 ≤ k ≤ 300, 1 ≤ f ≤ 1000) where: n — the number of Polycarp trips, a — the cost of a regualar single trip, b — the cost of a trip after a transshipment, k — the maximum number of travel cards Polycarp can buy, f — the cost of a single travel card. The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space — the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different.OutputPrint the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards.ExamplesInput3 5 3 1 8BerBank UniversityUniversity BerMallUniversity BerBankOutput11Input4 2 1 300 1000a AA aaaa AAAA aOutput5NoteIn the first example Polycarp can buy travel card for the route "BerBank University" and spend 8 burles. Note that his second trip "University" "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles.In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.
Input3 5 3 1 8BerBank UniversityUniversity BerMallUniversity BerBank
Output11
4 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*1800']
J. Students Initiationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSoon the first year students will be initiated into students at the University of Berland. The organizers of the initiation come up with a program for this holiday. In their opinion, it would be good if the first-year students presented small souvenirs to each other. When they voiced this idea to the first-year students, they found out the following: some pairs of the new students already know each other; each new student agrees to give souvenirs only to those with whom they are already familiar; each new student does not want to present too many souvenirs. The organizers have written down all the pairs of first-year friends who are familiar with each other and now want to determine for each new student, whom they should give souvenirs to. In their opinion, in each pair of familiar students exactly one student must present a souvenir to another student.First year students already decided to call the unluckiest the one who will have to present the greatest number of souvenirs. The organizers in return promised that the unluckiest will be unlucky to the minimum possible degree: of course, they will have to present the greatest number of souvenirs compared to the other students, but this number will be as small as possible.Organizers are very busy, and they asked you to determine for each pair of first-year friends who and to whom should present a souvenir.InputThe first line contains two integers n and m (1 ≤ n ≤ 5000, 0 ≤ m ≤ min(5000, n·(n - 1) / 2)) — the number of the first year students and the number of pairs of the students that know each other. The students are numbered from 1 to n.Each of the following m lines contains two integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi) — the students in each pair.It is guaranteed that each pair is present in the list exactly once. It is also guaranteed that if there is a pair (xi, yi) in the list, then there is no pair (yi, xi).OutputPrint a single integer into the first line — the smallest number of souvenirs that the unluckiest student will have to present.Following should be m lines, each containing two integers — the students which are familiar with each other. The first number in the pair must be the student that will present the souvenir to the second student in the pair.Pairs can be printed in any order. If there are many solutions, print any of them.ExamplesInput5 42 11 32 32 5Output11 22 33 15 2Input4 31 21 31 4Output11 42 13 1Input4 61 24 14 23 24 31 3Output21 32 12 43 24 14 3
Input5 42 11 32 32 5
Output11 22 33 15 2
2 seconds
256 megabytes
['binary search', 'flows', 'graphs', '*2400']
I. Noise Leveltime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland's capital has the form of a rectangle with sizes n × m quarters. All quarters are divided into three types: regular (labeled with the character '.') — such quarters do not produce the noise but are not obstacles to the propagation of the noise; sources of noise (labeled with an uppercase Latin letter from 'A' to 'Z') — such quarters are noise sources and are not obstacles to the propagation of the noise; heavily built-up (labeled with the character '*') — such quarters are soundproofed, the noise does not penetrate into them and they themselves are obstacles to the propagation of noise. A quarter labeled with letter 'A' produces q units of noise. A quarter labeled with letter 'B' produces 2·q units of noise. And so on, up to a quarter labeled with letter 'Z', which produces 26·q units of noise. There can be any number of quarters labeled with each letter in the city.When propagating from the source of the noise, the noise level is halved when moving from one quarter to a quarter that shares a side with it (when an odd number is to be halved, it's rounded down). The noise spreads along the chain. For example, if some quarter is located at a distance 2 from the noise source, then the value of noise which will reach the quarter is divided by 4. So the noise level that comes from the source to the quarter is determined solely by the length of the shortest path between them. Heavily built-up quarters are obstacles, the noise does not penetrate into them. The values in the cells of the table on the right show the total noise level in the respective quarters for q = 100, the first term in each sum is the noise from the quarter 'A', the second — the noise from the quarter 'B'. The noise level in quarter is defined as the sum of the noise from all sources. To assess the quality of life of the population of the capital of Berland, it is required to find the number of quarters whose noise level exceeds the allowed level p.InputThe first line contains four integers n, m, q and p (1 ≤ n, m ≤ 250, 1 ≤ q, p ≤ 106) — the sizes of Berland's capital, the number of noise units that a quarter 'A' produces, and the allowable noise level.Each of the following n lines contains m characters — the description of the capital quarters, in the format that was described in the statement above. It is possible that in the Berland's capital there are no quarters of any type.OutputPrint the number of quarters, in which the noise level exceeds the allowed level p.ExamplesInput3 3 100 140...A*..B.Output3Input3 3 2 8B*.BB*BBBOutput4Input3 4 5 4..*B..**D...Output7NoteThe illustration to the first example is in the main part of the statement.
Input3 3 100 140...A*..B.
Output3
5 seconds
256 megabytes
['dfs and similar', 'implementation', 'math', '*1900']
H. Load Testingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send ai requests.Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n.InputThe first line contains a single integer n (1 ≤ n ≤ 100 000) — the duration of the load testing.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of requests from friends in the i-th minute of the load testing.OutputPrint the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.ExamplesInput51 4 3 2 5Output6Input51 2 2 2 1Output1Input710 20 40 50 70 90 30Output0NoteIn the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests.In the second example it is enough to make one additional request in the third minute, so the answer is 1.In the third example the load already satisfies all conditions described in the statement, so the answer is 0.
Input51 4 3 2 5
Output6
1 second
256 megabytes
['greedy', '*1600']
G. University Classestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.InputThe first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups. Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.OutputPrint minimum number of rooms needed to hold all groups classes on Monday.ExamplesInput201010101010101Output1Input3010101100110010110111Output3NoteIn the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.In the second example three rooms is enough, because in the seventh time slot all three groups have classes.
Input201010101010101
Output1
1 second
256 megabytes
['implementation', '*900']
F. Berland Electionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe elections to Berland parliament are happening today. Voting is in full swing!Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 ≤ k ≤ n) top candidates will take seats in the parliament.After the end of the voting the number of votes for each candidate is calculated. In the resulting table the candidates are ordered by the number of votes. In case of tie (equal number of votes) they are ordered by the time of the last vote given. The candidate with ealier last vote stands higher in the resulting table.So in the resulting table candidates are sorted by the number of votes (more votes stand for the higher place) and if two candidates have equal number of votes they are sorted by the time of last vote (earlier last vote stands for the higher place).There is no way for a candidate with zero votes to take a seat in the parliament. So it is possible that less than k candidates will take a seat in the parliament.In Berland there are m citizens who can vote. Each of them will vote for some candidate. Each citizen will give a vote to exactly one of n candidates. There is no option "against everyone" on the elections. It is not accepted to spoil bulletins or not to go to elections. So each of m citizens will vote for exactly one of n candidates.At the moment a citizens have voted already (1 ≤ a ≤ m). This is an open election, so for each citizen it is known the candidate for which the citizen has voted. Formally, the j-th citizen voted for the candidate gj. The citizens who already voted are numbered in chronological order; i.e. the (j + 1)-th citizen voted after the j-th.The remaining m - a citizens will vote before the end of elections, each of them will vote for one of n candidates.Your task is to determine for each of n candidates one of the three possible outcomes: a candidate will be elected to the parliament regardless of votes of the remaining m - a citizens; a candidate has chance to be elected to the parliament after all n citizens have voted; a candidate has no chances to be elected to the parliament regardless of votes of the remaining m - a citizens. InputThe first line contains four integers n, k, m and a (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100, 1 ≤ a ≤ m) — the number of candidates, the number of seats in the parliament, the number of Berland citizens and the number of citizens who already have voted.The second line contains a sequence of a integers g1, g2, ..., ga (1 ≤ gj ≤ n), where gj is the candidate for which the j-th citizen has voted. Citizens who already voted are numbered in increasing order of voting times.OutputPrint the sequence consisting of n integers r1, r2, ..., rn where: ri = 1 means that the i-th candidate is guaranteed to take seat in the parliament regardless of votes of the remaining m - a citizens; ri = 2 means that the i-th candidate has a chance to take a seat in the parliament, i.e. the remaining m - a citizens can vote in such a way that the candidate will take a seat in the parliament; ri = 3 means that the i-th candidate will not take a seat in the parliament regardless of votes of the remaining m - a citizens. ExamplesInput3 1 5 41 2 1 3Output1 3 3 Input3 1 5 31 3 1Output2 3 2 Input3 2 5 31 3 1Output1 2 2
Input3 1 5 41 2 1 3
Output1 3 3
1 second
256 megabytes
['greedy', 'sortings', '*2100']
E. Packmentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA game field is a strip of 1 × n square cells. In some cells there are Packmen, in some cells — asterisks, other cells are empty.Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.In the initial moment of time all Packmen begin to move. Each Packman can change direction of its move unlimited number of times, but it is not allowed to go beyond the boundaries of the game field. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.Your task is to determine minimum possible time after which Packmen can eat all the asterisks.InputThe first line contains a single integer n (2 ≤ n ≤ 105) — the length of the game field.The second line contains the description of the game field consisting of n symbols. If there is symbol '.' in position i — the cell i is empty. If there is symbol '*' in position i — in the cell i contains an asterisk. If there is symbol 'P' in position i — Packman is in the cell i.It is guaranteed that on the game field there is at least one Packman and at least one asterisk.OutputPrint minimum possible time after which Packmen can eat all asterisks.ExamplesInput7*..P*P*Output3Input10.**PP.*P.*Output2NoteIn the first example Packman in position 4 will move to the left and will eat asterisk in position 1. He will spend 3 time units on it. During the same 3 time units Packman in position 6 will eat both of neighboring with it asterisks. For example, it can move to the left and eat asterisk in position 5 (in 1 time unit) and then move from the position 5 to the right and eat asterisk in the position 7 (in 2 time units). So in 3 time units Packmen will eat all asterisks on the game field.In the second example Packman in the position 4 will move to the left and after 2 time units will eat asterisks in positions 3 and 2. Packmen in positions 5 and 8 will move to the right and in 2 time units will eat asterisks in positions 7 and 10, respectively. So 2 time units is enough for Packmen to eat all asterisks on the game field.
Input7*..P*P*
Output3
1 second
256 megabytes
['binary search', 'dp', '*1800']
D. Dog Showtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!On the show a dog needs to eat as many bowls of dog food as possible (bottomless stomach helps here). Dogs compete separately of each other and the rules are as follows:At the start of the show the dog and the bowls are located on a line. The dog starts at position x = 0 and n bowls are located at positions x = 1, x = 2, ..., x = n. The bowls are numbered from 1 to n from left to right. After the show starts the dog immediately begins to run to the right to the first bowl.The food inside bowls is not ready for eating at the start because it is too hot (dog's self-preservation instinct prevents eating). More formally, the dog can eat from the i-th bowl after ti seconds from the start of the show or later.It takes dog 1 second to move from the position x to the position x + 1. The dog is not allowed to move to the left, the dog runs only to the right with the constant speed 1 distance unit per second. When the dog reaches a bowl (say, the bowl i), the following cases are possible: the food had cooled down (i.e. it passed at least ti seconds from the show start): the dog immediately eats the food and runs to the right without any stop, the food is hot (i.e. it passed less than ti seconds from the show start): the dog has two options: to wait for the i-th bowl, eat the food and continue to run at the moment ti or to skip the i-th bowl and continue to run to the right without any stop. After T seconds from the start the show ends. If the dog reaches a bowl of food at moment T the dog can not eat it. The show stops before T seconds if the dog had run to the right of the last bowl.You need to help your dog create a strategy with which the maximum possible number of bowls of food will be eaten in T seconds.InputTwo integer numbers are given in the first line - n and T (1 ≤ n ≤ 200 000, 1 ≤ T ≤ 2·109) — the number of bowls of food and the time when the dog is stopped.On the next line numbers t1, t2, ..., tn (1 ≤ ti ≤ 109) are given, where ti is the moment of time when the i-th bowl of food is ready for eating.OutputOutput a single integer — the maximum number of bowls of food the dog will be able to eat in T seconds.ExamplesInput3 51 5 3Output2Input1 21Output1Input1 11Output0NoteIn the first example the dog should skip the second bowl to eat from the two bowls (the first and the third).
Input3 51 5 3
Output2
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*2200']
C. Sum of Nestingstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the following sequences are regular: "()()()", "(())" and "()". The following sequences are not regular bracket sequences: ")(", "(()" and "())(()".In this problem you are given two integers n and k. Your task is to construct a regular bracket sequence consisting of round brackets with length 2·n with total sum of nesting of all opening brackets equals to exactly k. The nesting of a single opening bracket equals to the number of pairs of brackets in which current opening bracket is embedded.For example, in the sequence "()(())" the nesting of first opening bracket equals to 0, the nesting of the second opening bracket equals to 0 and the nesting of the third opening bracket equal to 1. So the total sum of nestings equals to 1.InputThe first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ 1018) — the number of opening brackets and needed total nesting.OutputPrint the required regular bracket sequence consisting of round brackets.If there is no solution print "Impossible" (without quotes).ExamplesInput3 1Output()(())Input4 6Output(((())))Input2 5OutputImpossibleNoteThe first example is examined in the statement.In the second example the answer is "(((())))". The nesting of the first opening bracket is 0, the nesting of the second is 1, the nesting of the third is 2, the nesting of fourth is 3. So the total sum of nestings equals to 0 + 1 + 2 + 3 = 6.In the third it is impossible to construct a regular bracket sequence, because the maximum possible total sum of nestings for two opening brackets equals to 1. This total sum of nestings is obtained for the sequence "(())".
Input3 1
Output()(())
2 seconds
256 megabytes
['constructive algorithms', '*1800']
B. Preparing for Merge Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.Ivan represent his array with increasing sequences with help of the following algorithm.While there is at least one unused number in array Ivan repeats the following procedure: iterate through array from the left to the right; Ivan only looks at unused numbers on current iteration; if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down. For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.InputThe first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of elements in Ivan's array.The second line contains a sequence consisting of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — Ivan's array.OutputPrint representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.ExamplesInput51 3 2 5 4Output1 3 5 2 4 Input44 3 2 1Output4 3 2 1 Input410 30 50 101Output10 30 50 101
Input51 3 2 5 4
Output1 3 5 2 4
2 seconds
256 megabytes
['binary search', 'data structures', '*1600']
A. Union of Doubly Linked Liststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.For each cell i you are given two values: li — cell containing previous element for the element in the cell i; ri — cell containing next element for the element in the cell i. If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0. Three lists are shown on the picture. For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.Any other action, other than joining the beginning of one list to the end of another, can not be performed.InputThe first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.OutputPrint n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.ExampleInput74 75 00 06 10 20 41 0Output4 75 60 56 13 22 41 0
Input74 75 00 06 10 20 41 0
Output4 75 60 56 13 22 41 0
2 seconds
256 megabytes
['implementation', '*1500']
F. Random Querytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).InputThe first line contains one integer number n (1 ≤ n ≤ 106). The second line contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 106) — elements of the array.OutputPrint one number — the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 — formally, the answer is correct if , where x is jury's answer, and y is your answer.ExamplesInput21 2Output1.500000Input22 2Output1.000000
Input21 2
Output1.500000
2 seconds
256 megabytes
['data structures', 'math', 'probabilities', 'two pointers', '*1800']
E. Chemistry in Berlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 ≤ i ≤ n) there exist two numbers xi and ki that denote a possible transformation: ki kilograms of material xi can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material xi. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.For each i (1 ≤ i ≤ n) Igor knows that the experiment requires ai kilograms of material i, and the laboratory contains bi kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?InputThe first line contains one integer number n (1 ≤ n ≤ 105) — the number of materials discovered by Berland chemists.The second line contains n integer numbers b1, b2... bn (1 ≤ bi ≤ 1012) — supplies of BerSU laboratory.The third line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 1012) — the amounts required for the experiment.Then n - 1 lines follow. j-th of them contains two numbers xj + 1 and kj + 1 that denote transformation of (j + 1)-th material (1 ≤ xj + 1 ≤ j, 1 ≤ kj + 1 ≤ 109).OutputPrint YES if it is possible to conduct an experiment. Otherwise print NO.ExamplesInput31 2 33 2 11 11 1OutputYESInput33 2 11 2 31 11 2OutputNO
Input31 2 33 2 11 11 1
OutputYES
2 seconds
256 megabytes
['dfs and similar', 'greedy', 'trees', '*2300']
D. Monitortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).InputThe first line contains four integer numbers n, m, k, q (1 ≤ n, m ≤ 500, 1 ≤ k ≤ min(n, m), 0 ≤ q ≤ n·m) — the length and width of the monitor, the size of a rectangle such that the monitor is broken if there is a broken rectangle with this size, and the number of broken pixels.Each of next q lines contain three integer numbers xi, yi, ti (1 ≤ xi ≤ n, 1 ≤ yi ≤ m, 0 ≤ t ≤ 109) — coordinates of i-th broken pixel (its row and column in matrix) and the moment it stopped working. Each pixel is listed at most once.We consider that pixel is already broken at moment ti.OutputPrint one number — the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.ExamplesInput2 3 2 52 1 82 2 81 2 11 3 42 3 2Output8Input3 3 2 51 2 22 2 12 3 53 2 102 1 100Output-1
Input2 3 2 52 1 82 2 81 2 11 3 42 3 2
Output8
2 seconds
256 megabytes
['binary search', 'data structures', '*1900']
C. Four Segmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integer numbers. Let sum(l, r) be the sum of all numbers on positions from l to r non-inclusive (l-th element is counted, r-th element is not counted). For indices l and r holds 0 ≤ l ≤ r ≤ n. Indices in array are numbered from 0. For example, if a = [ - 5, 3, 9, 4], then sum(0, 1) =  - 5, sum(0, 2) =  - 2, sum(1, 4) = 16 and sum(i, i) = 0 for each i from 0 to 4.Choose the indices of three delimiters delim0, delim1, delim2 (0 ≤ delim0 ≤ delim1 ≤ delim2 ≤ n) and divide the array in such a way that the value of res = sum(0, delim0) - sum(delim0, delim1) + sum(delim1, delim2) - sum(delim2, n) is maximal. Note that some of the expressions sum(l, r) can correspond to empty segments (if l = r for some segment).InputThe first line contains one integer number n (1 ≤ n ≤ 5000).The second line contains n numbers a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109).OutputChoose three indices so that the value of res is maximal. If there are multiple answers, print any of them.ExamplesInput3-1 2 3Output0 1 3Input40 0 -1 0Output0 0 0Input110000Output1 1 1
Input3-1 2 3
Output0 1 3
1 second
256 megabytes
['brute force', 'data structures', 'dp', '*1800']
B. Math Showtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him tj minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all k of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is k + 1.Polycarp has M minutes of time. What is the maximum number of points he can earn?InputThe first line contains three integer numbers n, k and M (1 ≤ n ≤ 45, 1 ≤ k ≤ 45, 0 ≤ M ≤ 2·109).The second line contains k integer numbers, values tj (1 ≤ tj ≤ 1000000), where tj is the time in minutes required to solve j-th subtask of any task.OutputPrint the maximum amount of points Polycarp can earn in M minutes.ExamplesInput3 4 111 2 3 4Output6Input5 5 101 2 4 8 16Output7NoteIn the first example Polycarp can complete the first task and spend 1 + 2 + 3 + 4 = 10 minutes. He also has the time to solve one subtask of the second task in one minute.In the second example Polycarp can solve the first subtask of all five tasks and spend 5·1 = 5 minutes. Also he can solve the second subtasks of two tasks and spend 2·2 = 4 minutes. Thus, he earns 5 + 2 = 7 points in total.
Input3 4 111 2 3 4
Output6
1 second
256 megabytes
['brute force', 'greedy', '*1800']
A. Curriculum Vitaetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.More formally, you are given an array s1, s2, ..., sn of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.InputThe first line contains one integer number n (1 ≤ n ≤ 100).The second line contains n space-separated integer numbers s1, s2, ..., sn (0 ≤ si ≤ 1). 0 corresponds to an unsuccessful game, 1 — to a successful one.OutputPrint one integer — the maximum number of games Hideo can leave in his CV so that no unsuccessful game comes after a successful one.ExamplesInput41 1 0 1Output3Input60 1 0 0 1 0Output4Input10Output1
Input41 1 0 1
Output3
1 second
256 megabytes
['brute force', 'implementation', '*1500']
G. Shortest Path Problem?time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected 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). You have to find the minimum length of path between vertex 1 and vertex n.Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.InputThe first line contains two numbers n and m (1 ≤ n ≤ 100000, n - 1 ≤ m ≤ 100000) — the number of vertices and the number of edges, respectively.Then m lines follow, each line containing three integer numbers x, y and w (1 ≤ x, y ≤ n, 0 ≤ w ≤ 108). These numbers denote an edge that connects vertices x and y and has weight w.OutputPrint one number — the minimum length of path between vertices 1 and n.ExamplesInput3 31 2 31 3 23 2 0Output2Input2 21 1 31 2 3Output0
Input3 31 2 31 3 23 2 0
Output2
3 seconds
512 megabytes
['dfs and similar', 'graphs', 'math', '*2300']
F. Guards In The Storehousetime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop.The storehouse can be represented as a matrix with n rows and m columns. Each element of the matrix is either . (an empty space) or x (a wall).Polycarp wants to hire some guards (possibly zero) to watch for the storehouse. Each guard will be in some cell of matrix and will protect every cell to the right of his own cell and every cell to the bottom of his own cell, until the nearest wall. More formally, if the guard is standing in the cell (x0, y0), then he protects cell (x1, y1) if all these conditions are met: (x1, y1) is an empty cell; either x0 = x1 and y0 ≤ y1, or x0 ≤ x1 and y0 = y1; there are no walls between cells (x0, y0) and (x1, y1). There can be a guard between these cells, guards can look through each other. Guards can be placed only in empty cells (and can protect only empty cells). The plan of placing the guards is some set of cells where guards will be placed (of course, two plans are different if there exists at least one cell that is included in the first plan, but not included in the second plan, or vice versa). Polycarp calls a plan suitable if there is not more than one empty cell that is not protected.Polycarp wants to know the number of suitable plans. Since it can be very large, you have to output it modulo 109 + 7.InputThe first line contains two numbers n and m — the length and the width of the storehouse (1 ≤ n, m ≤ 250, 1 ≤ nm ≤ 250).Then n lines follow, ith line contains a string consisting of m characters — ith row of the matrix representing the storehouse. Each character is either . or x.OutputOutput the number of suitable plans modulo 109 + 7.ExamplesInput1 3.x.Output3Input2 2xxxxOutput1Input2 2....Output10Input3 1x.xOutput2NoteIn the first example you have to put at least one guard, so there are three possible arrangements: one guard in the cell (1, 1), one guard in the cell (1, 3), and two guards in both these cells.
Input1 3.x.
Output3
1.5 seconds
512 megabytes
['bitmasks', 'dp', '*2500']
E. Fire in the Citytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe capital of Berland looks like a rectangle of size n × m of the square blocks of same size.Fire!It is known that k + 1 blocks got caught on fire (k + 1 ≤ n·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct.The fire goes the following way: during the zero minute of fire only these k + 1 centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner.Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of k blocks (centers of ignition) are known and (k + 1)-th can be positioned in any other block.Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.InputThe first line contains three integers n, m and k (1 ≤ n, m ≤ 109, 1 ≤ k ≤ 500).Each of the next k lines contain two integers xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ m) — coordinates of the i-th center of ignition. It is guaranteed that the locations of all centers of ignition are distinct.OutputPrint the minimal time it takes the fire to lighten up the whole city (in minutes).ExamplesInput7 7 31 22 15 5Output3Input10 5 13 3Output2NoteIn the first example the last block can have coordinates (4, 4).In the second example the last block can have coordinates (8, 3).
Input7 7 31 22 15 5
Output3
2 seconds
256 megabytes
['binary search', 'data structures', '*2400']
D. Driving Testtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); overtake is allowed: this sign means that after some car meets it, it can overtake any other car; no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.In the beginning of the ride overtake is allowed and there is no speed limit.You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: Polycarp changes the speed of his car to specified (this event comes with a positive integer number); Polycarp's car overtakes the other car; Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); Polycarp's car goes past the "overtake is allowed" sign; Polycarp's car goes past the "no speed limit"; Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?InputThe first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events.Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event.An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit).It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).OutputPrint the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.ExamplesInput111 1003 70423 12053 12061 15043 300Output2Input51 1003 200245Output0Input71 20264662Output2NoteIn the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120.In the second example Polycarp didn't make any rule violation.In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
Input111 1003 70423 12053 12061 15043 300
Output2
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*1800']
C. Two TVstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a great fan of television.He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.Polycarp wants to check out all n shows. Are two TVs enough to do so?InputThe first line contains one integer n (1 ≤ n ≤ 2·105) — the number of shows.Each of the next n lines contains two integers li and ri (0 ≤ li < ri ≤ 109) — starting and ending time of i-th show.OutputIf Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).ExamplesInput31 22 34 5OutputYESInput41 22 32 31 2OutputNO
Input31 22 34 5
OutputYES
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*1500']
B. Luba And The Tickettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.InputYou are given a string consisting of 6 characters (all characters are digits from 0 to 9) — this string denotes Luba's ticket. The ticket can start with the digit 0.OutputPrint one number — the minimum possible number of digits Luba needs to replace to make the ticket lucky.ExamplesInput000000Output0Input123456Output2Input111000Output1NoteIn the first example the ticket is already lucky, so the answer is 0.In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required.In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required.
Input000000
Output0
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', '*1600']
A. Chess Tourneytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland annual chess tournament is coming!Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.Thus, organizers should divide all 2·n players into two teams with n people each in such a way that the first team always wins.Every chess player has its rating ri. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.After teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.Is it possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?InputThe first line contains one integer n (1 ≤ n ≤ 100).The second line contains 2·n integers a1, a2, ... a2n (1 ≤ ai ≤ 1000).OutputIf it's possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing, then print "YES". Otherwise print "NO".ExamplesInput21 3 2 4OutputYESInput13 3OutputNO
Input21 3 2 4
OutputYES
1 second
256 megabytes
['implementation', 'sortings', '*1100']
B. Rectanglestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: All cells in a set have the same color. Every two cells in a set share row or column. InputThe first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns correspondingly.The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black.OutputOutput single integer  — the number of non-empty sets from the problem description.ExamplesInput1 10Output1Input2 31 0 10 1 0Output8NoteIn the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets.
Input1 10
Output1
1 second
256 megabytes
['combinatorics', 'math', '*1300']
A. Diversitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCalculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.InputFirst line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s).Second line of input contains integer k (1 ≤ k ≤ 26).OutputPrint single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.ExamplesInputyandex6Output0Inputyahoo5Output1Inputgoogle7OutputimpossibleNoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.
Inputyandex6
Output0
1 second
256 megabytes
['greedy', 'implementation', 'strings', '*1000']
E. Maximum Flowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph, consisting of n vertices and m edges. The vertices s and t are marked as source and sink correspondingly. Additionally, there are no edges ending at s and there are no edges beginning in t.The graph was constructed in a following way: initially each edge had capacity ci > 0. A maximum flow with source at s and sink at t was constructed in this flow network. Let's denote fi as the value of flow passing through edge with index i. Next, all capacities ci and flow value fi were erased. Instead, indicators gi were written on edges — if flow value passing through edge i was positive, i.e. 1 if fi > 0 and 0 otherwise.Using the graph and values gi, find out what is the minimum possible number of edges in the initial flow network that could be saturated (the passing flow is equal to capacity, i.e. fi = ci). Also construct the corresponding flow network with maximum flow in it.A flow in directed graph is described by flow values fi on each of the edges so that the following conditions are satisfied: for each vertex, except source and sink, total incoming flow and total outcoming flow are equal, for each edge 0 ≤ fi ≤ ci A flow is maximum if the difference between the sum of flow values on edges from the source, and the sum of flow values on edges to the source (there are no such in this problem), is maximum possible.InputThe first line of input data contains four positive integers n, m, s, t (2 ≤ n ≤ 100, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of vertices, the number of edges, index of source vertex and index of sink vertex correspondingly.Each of next m lines of input data contain non-negative integers ui, vi, gi (1 ≤ ui, vi ≤ n, ) — the beginning of edge i, the end of edge i and indicator, which equals to 1 if flow value passing through edge i was positive and 0 if not.It's guaranteed that no edge connects vertex with itself. Also it's guaranteed that there are no more than one edge between each ordered pair of vertices and that there exists at least one network flow that satisfies all the constrains from input data.OutputIn the first line print single non-negative integer k — minimum number of edges, which should be saturated in maximum flow.In each of next m lines print two integers fi, ci (1 ≤ ci ≤ 109, 0 ≤ fi ≤ ci) — the flow value passing through edge i and capacity of edge i. This data should form a correct maximum flow in flow network. Also there must be exactly k edges with statement fi = ci satisfied. Also statement fi > 0 must be true if and only if gi = 1.If there are several possible answers, print any of them.ExampleInput5 6 1 51 2 12 3 13 5 11 4 14 3 04 5 1Output23 33 83 44 40 54 9NoteThe illustration for second sample case. The saturated edges are marked dark, while edges with gi = 0 are marked with dotted line. The integer on edge is the index of this edge in input list.
Input5 6 1 51 2 12 3 13 5 11 4 14 3 04 5 1
Output23 33 83 44 40 54 9
1 second
256 megabytes
['flows', 'graphs', '*3000']
D. Dynamic Shortest Pathtime limit per test10 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a weighted directed graph, consisting of n vertices and m edges. You should answer q queries of two types: 1 v — find the length of shortest path from vertex 1 to vertex v. 2 c l1 l2 ... lc — add 1 to weights of edges with indices l1, l2, ..., lc. InputThe first line of input data contains integers n, m, q (1 ≤ n, m ≤ 105, 1 ≤ q ≤ 2000) — the number of vertices and edges in the graph, and the number of requests correspondingly.Next m lines of input data contain the descriptions of edges: i-th of them contains description of edge with index i — three integers ai, bi, ci (1 ≤ ai, bi ≤ n, 0 ≤ ci ≤ 109) — the beginning and the end of edge, and its initial weight correspondingly.Next q lines of input data contain the description of edges in the format described above (1 ≤ v ≤ n, 1 ≤ lj ≤ m). It's guaranteed that inside single query all lj are distinct. Also, it's guaranteed that a total number of edges in all requests of the second type does not exceed 106.OutputFor each query of first type print the length of the shortest path from 1 to v in a separate line. Print -1, if such path does not exists.ExamplesInput3 2 91 2 02 3 02 1 21 31 22 1 11 31 22 2 1 21 31 2Output102142Input5 4 92 3 12 4 13 4 11 2 01 51 42 1 22 1 21 42 2 1 31 42 1 41 4Output-11234NoteThe description of changes of the graph in the first sample case:The description of changes of the graph in the second sample case:
Input3 2 91 2 02 3 02 1 21 31 22 1 11 31 22 2 1 21 31 2
Output102142
10 seconds
512 megabytes
['graphs', 'shortest paths', '*3400']
C. Upgrading Treetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices and you are allowed to perform no more than 2n transformations on it. Transformation is defined by three vertices x, y, y' and consists of deleting edge (x, y) and adding edge (x, y'). Transformation x, y, y' could be performed if all the following conditions are satisfied: There is an edge (x, y) in the current tree. After the transformation the graph remains a tree. After the deletion of edge (x, y) the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex x by Vx, and the set of nodes in the component containing vertex y by Vy. Then condition |Vx| > |Vy| should be satisfied, i.e. the size of the component with x should be strictly larger than the size of the component with y. You should minimize the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than 2n transformations and output any sequence of transformations leading initial tree to such state.Note that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.InputThe first line of input contains integer n (1 ≤ n ≤ 2·105) — number of vertices in tree.The next n - 1 lines of input contains integers a and b (1 ≤ a, b ≤ n, a ≠ b) — the descriptions of edges. It is guaranteed that the given edges form a tree.OutputIn the first line output integer k (0 ≤ k ≤ 2n) — the number of transformations from your example, minimizing sum of squared distances between all pairs of vertices.In each of the next k lines output three integers x, y, y' — indices of vertices from the corresponding transformation.Transformations with y = y' are allowed (even though they don't change tree) if transformation conditions are satisfied.If there are several possible answers, print any of them.ExamplesInput33 21 3Output0Input71 22 33 44 55 66 7Output24 3 24 5 6NoteThis is a picture for the second sample. Added edges are dark, deleted edges are dotted.
Input33 21 3
Output0
4 seconds
512 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'math', 'trees', '*2600']
B. Interactive LowerBoundtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the integer value in this element, and nexti that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if nexti ≠  - 1, then valuenexti > valuei.You are given the number of elements in the list n, the index of the first element start, and the integer x.You can make up to 2000 queries of the following two types: ? i (1 ≤ i ≤ n) — ask the values valuei and nexti, ! ans — give the answer for the problem: the minimum integer, greater than or equal to x, or ! -1, if there are no such integers. Your program should terminate after this query. Write a program that solves this problem.InputThe first line contains three integers n, start, x (1 ≤ n ≤ 50000, 1 ≤ start ≤ n, 0 ≤ x ≤ 109) — the number of elements in the list, the index of the first element and the integer x.OutputTo print the answer for the problem, print ! ans, where ans is the minimum integer in the list greater than or equal to x, or -1, if there is no such integer.InteractionTo make a query of the first type, print ? i (1 ≤ i ≤ n), where i is the index of element you want to know information about.After each query of type ? read two integers valuei and nexti (0 ≤ valuei ≤ 109,  - 1 ≤ nexti ≤ n, nexti ≠ 0).It is guaranteed that if nexti ≠  - 1, then valuenexti > valuei, and that the array values give a valid singly linked list with start being the first element.Note that you can't ask more than 1999 queries of the type ?.If nexti =  - 1 and valuei =  - 1, then it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive "Wrong Answer", it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.Your solution will get "Idleness Limit Exceeded", if you don't print anything or forget to flush the output, including the final answer.To flush you can use (just after printing a query and line end): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; For other languages see documentation. Hacks formatFor hacks, use the following format:In the first line print three integers n, start, x (1 ≤ n ≤ 50000, 1 ≤ start ≤ n, 0 ≤ x ≤ 109).In the next n lines print the description of the elements of the list: in the i-th line print two integers valuei and nexti (0 ≤ valuei ≤ 109,  - 1 ≤ nexti ≤ n, nexti ≠ 0).The printed structure should be a valid singly linked list. In particular, it should be possible to reach all elements from start by following links nexti, and the last element end should have -1 in the nextend.ExampleInput5 3 8097 -158 516 281 179 4Output? 1? 2? 3? 4? 5! 81NoteYou can read more about singly linked list by the following link: https://en.wikipedia.org/wiki/Linked_list#Singly_linked_list The illustration for the first sample case. Start and finish elements are marked dark.
Input5 3 8097 -158 516 281 179 4
Output? 1? 2? 3? 4? 5! 81
1 second
256 megabytes
['brute force', 'interactive', 'probabilities', '*2000']
A. Sorting by Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.InputThe first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence.The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.OutputIn the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements.In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once.If there are several possible answers, print any of them.ExamplesInput63 2 1 6 5 4Output42 1 31 22 4 61 5Input683 -75 -49 11 37 62Output16 1 2 3 4 5 6NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
Input63 2 1 6 5 4
Output42 1 31 22 4 61 5
1 second
256 megabytes
['dfs and similar', 'dsu', 'implementation', 'math', 'sortings', '*1400']
E. Nikita and gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikita plays a new computer game. There are m levels in this game. In the beginning of each level a new class appears in the game; this class is a child-class of the class yi (and yi is called parent-class for this new class). Thus, the classes form a tree. Initially there is only one class with index 1.Changing the class to its neighbour (child-class or parent-class) in the tree costs 1 coin. You can not change the class back. The cost of changing the class a to the class b is equal to the total cost of class changes on the path from a to b in the class tree.Suppose that at i -th level the maximum cost of changing one class to another is x. For each level output the number of classes such that for each of these classes there exists some other class y, and the distance from this class to y is exactly x.InputFirst line contains one integer number m — number of queries (1 ≤ m ≤ 3·105).Next m lines contain description of queries. i -th line (1 ≤ i ≤ m) describes the i -th level and contains an integer yi — the index of the parent-class of class with index i + 1 (1 ≤ yi ≤ i). OutputSuppose that at i -th level the maximum cost of changing one class to another is x. For each level output the number of classes such that for each of these classes there exists some other class y, and the distance from this class to y is exactly x.ExamplesInput41121Output2223Input41123Output2222
Input41121
Output2223
2 seconds
256 megabytes
['binary search', 'dfs and similar', 'divide and conquer', 'graphs', 'trees', '*2800']
D. Vitya and Strange Lessontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.Vitya quickly understood all tasks of the teacher, but can you do the same?You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps: Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x. Find mex of the resulting array. Note that after each query the array changes.InputFirst line contains two integer numbers n and m (1 ≤ n, m ≤ 3·105) — number of elements in array and number of queries.Next line contains n integer numbers ai (0 ≤ ai ≤ 3·105) — elements of then array.Each of next m lines contains query — one integer number x (0 ≤ x ≤ 3·105).OutputFor each query print the answer on a separate line.ExamplesInput2 21 313Output10Input4 30 1 5 6124Output200Input5 40 1 5 6 71145Output2202
Input2 21 313
Output10
2 seconds
256 megabytes
['binary search', 'data structures', '*2000']
C. Ilya And The Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai.Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.For each vertex the answer must be considered independently.The beauty of the root equals to number written on it.InputFirst line contains one integer number n — the number of vertices in tree (1 ≤ n ≤ 2·105).Next line contains n integer numbers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 2·105).Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n, x ≠ y), which means that there is an edge (x, y) in the tree.OutputOutput n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i.ExamplesInput26 21 2Output6 6 Input36 2 31 21 3Output6 6 6 Input110Output10
Input26 21 2
Output6 6
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'math', 'number theory', 'trees', '*2000']
B. Gleb And Pizzatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.InputFirst string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust.Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105).Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.OutputOutput the number of pieces of sausage that lay on the crust.ExamplesInput8 477 8 1-7 3 20 2 10 -2 2-3 -3 10 6 25 3 1Output2Input10 840 0 90 0 101 0 11 0 2Output0NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.
Input8 477 8 1-7 3 20 2 10 -2 2-3 -3 10 6 25 3 1
Output2
2 seconds
256 megabytes
['geometry', '*1100']
A. Kirill And The Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.For each two integer numbers a and b such that l ≤ a ≤ r and x ≤ b ≤ y there is a potion with experience a and cost b in the store (that is, there are (r - l + 1)·(y - x + 1) potions).Kirill wants to buy a potion which has efficiency k. Will he be able to do this?InputFirst string contains five integer numbers l, r, x, y, k (1 ≤ l ≤ r ≤ 107, 1 ≤ x ≤ y ≤ 107, 1 ≤ k ≤ 107).OutputPrint "YES" without quotes if a potion with efficiency exactly k can be bought in the store and "NO" without quotes otherwise.You can output each of the letters in any register.ExamplesInput1 10 1 10 1OutputYESInput1 5 6 10 1OutputNO
Input1 10 1 10 1
OutputYES
2 seconds
256 megabytes
['brute force', 'two pointers', '*1200']
B. Godsendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?InputFirst line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array.Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).OutputOutput answer in single line. "First", if first player wins, and "Second" otherwise (without quotes).ExamplesInput41 3 2 3OutputFirstInput22 2OutputSecondNoteIn first sample first player remove whole array in one move and win.In second sample first player can't make a move and lose.
Input41 3 2 3
OutputFirst
2 seconds
256 megabytes
['games', 'math', '*1100']
A. Generous Kefatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.InputThe first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.Next line contains string s — colors of baloons.OutputAnswer to the task — «YES» or «NO» in a single line.You can choose the case (lower or upper) for each letter arbitrary.ExamplesInput4 2aabbOutputYESInput6 3aacaabOutputNONoteIn the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Input4 2aabb
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', '*900']
E. In a Traptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLech got into a tree consisting of n vertices with a root in vertex number 1. At each vertex i written integer ai. He will not get out until he answers q queries of the form u v. Answer for the query is maximal value among all vertices i on path from u to v including u and v, where dist(i, v) is number of edges on path from i to v. Also guaranteed that vertex u is ancestor of vertex v. Leha's tastes are very singular: he believes that vertex is ancestor of itself.Help Leha to get out.The expression means the bitwise exclusive OR to the numbers x and y.Note that vertex u is ancestor of vertex v if vertex u lies on the path from root to the vertex v.InputFirst line of input data contains two integers n and q (1 ≤ n ≤ 5·104, 1 ≤ q ≤ 150 000) — number of vertices in the tree and number of queries respectively.Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — numbers on vertices.Each of next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n) — description of the edges in tree.Guaranteed that given graph is a tree.Each of next q lines contains two integers u and v (1 ≤ u, v ≤ n) — description of queries. Guaranteed that vertex u is ancestor of vertex v.OutputOutput q lines — answers for a queries.ExamplesInput5 30 3 2 1 41 22 33 43 51 41 52 4Output343Input5 41 2 3 4 51 22 33 44 51 52 51 43 3Output5543
Input5 30 3 2 1 41 22 33 43 51 41 52 4
Output343
3 seconds
256 megabytes
['trees', '*3200']
D. Destinytime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOnce, Leha found in the left pocket an array consisting of n integers, and in the right pocket q queries of the form l r k. If there are queries, then they must be answered. Answer for the query is minimal x such that x occurs in the interval l r strictly more than times or  - 1 if there is no such number. Help Leha with such a difficult task.InputFirst line of input data contains two integers n and q (1 ≤ n, q ≤ 3·105) — number of elements in the array and number of queries respectively.Next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — Leha's array.Each of next q lines contains three integers l, r and k (1 ≤ l ≤ r ≤ n, 2 ≤ k ≤ 5) — description of the queries.OutputOutput answer for each query in new line.ExamplesInput4 21 1 2 21 3 21 4 2Output1-1Input5 31 2 1 3 22 5 31 2 35 5 2Output212
Input4 21 1 2 21 3 21 4 2
Output1-1
2.5 seconds
512 megabytes
['data structures', 'probabilities', '*2500']
C. On the Benchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.InputFirst line of input data contains single integer n (1 ≤ n ≤ 300) — length of the array.Next line contains n integers a1, a2, ... , an (1 ≤ ai ≤ 109) — found array.OutputOutput single integer — number of right permutations modulo 109 + 7.ExamplesInput31 2 4Output2Input75 2 4 2 4 1 1Output144NoteFor first example:[1, 2, 4] — right permutation, because 2 and 8 are not perfect squares.[1, 4, 2] — wrong permutation, because 4 is square of 2.[2, 1, 4] — wrong permutation, because 4 is square of 2.[2, 4, 1] — wrong permutation, because 4 is square of 2.[4, 1, 2] — wrong permutation, because 4 is square of 2.[4, 2, 1] — right permutation, because 8 and 2 are not perfect squares.
Input31 2 4
Output2
2 seconds
256 megabytes
['combinatorics', 'dp', '*2500']
B. Leha and another game about graphtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or  - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di =  - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.InputThe first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges.The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices.Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected.OutputPrint  - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.ExamplesInput1 01Output-1Input4 50 0 0 -11 22 33 41 42 4Output0Input2 11 11 2Output11Input3 30 -1 11 22 31 3Output12NoteIn the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
Input1 01
Output-1
3 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'dp', 'graphs', '*2100']
A. Leha and Functiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum is maximally possible, where A' is already rearranged array.InputFirst line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B.Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A.Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.OutputOutput m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.ExamplesInput57 3 5 3 42 1 3 2 3Output4 7 3 5 3Input74 6 5 8 8 2 62 1 2 2 1 1 2Output2 6 4 5 8 8 6
Input57 3 5 3 42 1 3 2 3
Output4 7 3 5 3
2 seconds
256 megabytes
['combinatorics', 'greedy', 'math', 'number theory', 'sortings', '*1300']
E. Mother of Dragonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself. Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has k liters of a strange liquid. He wants to distribute that liquid among the castles, so each castle may contain some liquid (possibly zero or non-integer number of liters). After that the stability of a wall is defined as follows: if the wall connects two castles a and b, and they contain x and y liters of that liquid, respectively, then the strength of that wall is x·y.Your task is to print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.InputThe first line of the input contains two integers n and k (1 ≤ n ≤ 40, 1 ≤ k ≤ 1000).Then n lines follows. The i-th of these lines contains n integers ai, 1, ai, 2, ..., ai, n (). If castles i and j are connected by a wall, then ai, j = 1. Otherwise it is equal to 0.It is guaranteed that ai, j = aj, i and ai, i = 0 for all 1 ≤ i, j ≤ n.OutputPrint the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3 10 1 01 0 00 0 0Output0.250000000000Input4 40 1 0 11 0 1 00 1 0 11 0 1 0Output4.000000000000NoteIn the first sample, we can assign 0.5, 0.5, 0 liters of liquid to castles 1, 2, 3, respectively, to get the maximum sum (0.25).In the second sample, we can assign 1.0, 1.0, 1.0, 1.0 liters of liquid to castles 1, 2, 3, 4, respectively, to get the maximum sum (4.0)
Input3 10 1 01 0 00 0 0
Output0.250000000000
2 seconds
256 megabytes
['brute force', 'graphs', 'math', 'meet-in-the-middle', '*2700']
D. Winter is heretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWinter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan if i1 < i2 < i3 < ... < ik and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan k·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans.Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7).Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.InputThe first line contains integer n (1 ≤ n ≤ 200000) — the size of the army.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his soldiers.OutputPrint one integer — the strength of John Snow's army modulo 1000000007 (109 + 7).ExamplesInput33 3 1Output12Input42 3 4 6Output39NoteIn the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12
Input33 3 1
Output12
3 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*2200']
C. Journeytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.InputThe first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road.It is guaranteed that one can reach any city from any other by the roads.OutputPrint a number — the expected length of their journey. The journey starts in the city 1.Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput41 21 32 4Output1.500000000000000Input51 21 33 42 5Output2.000000000000000NoteIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
Input41 21 32 4
Output1.500000000000000
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'probabilities', 'trees', '*1500']
B. Game of the Rowstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDaenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1, 2}, {3, 4}, {4, 5}, {5, 6} or {7, 8}. A row in the airplane Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.InputThe first line contains two integers n and k (1 ≤ n ≤ 10000, 1 ≤ k ≤ 100) — the number of rows and the number of groups of soldiers, respectively.The second line contains k integers a1, a2, a3, ..., ak (1 ≤ ai ≤ 10000), where ai denotes the number of soldiers in the i-th group.It is guaranteed that a1 + a2 + ... + ak ≤ 8·n.OutputIf we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes).You can choose the case (lower or upper) for each letter arbitrary.ExamplesInput2 25 8OutputYESInput1 27 1OutputNOInput1 24 4OutputYESInput1 42 2 1 2OutputYESNoteIn the first sample, Daenerys can place the soldiers like in the figure below: In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group.In the third example Daenerys can place the first group on seats (1, 2, 7, 8), and the second group an all the remaining seats.In the fourth example she can place the first two groups on seats (1, 2) and (7, 8), the third group on seats (3), and the fourth group on seats (5, 6).
Input2 25 8
OutputYES
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*1900']
A. Arya and Brantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).Print -1 if she can't give him k candies during n given days.InputThe first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).OutputIf it is impossible for Arya to give Bran k candies within n days, print -1.Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.ExamplesInput2 31 2Output2Input3 1710 10 10Output3Input1 910Output-1NoteIn the first sample, Arya can give Bran 3 candies in 2 days.In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Input2 31 2
Output2
1 second
256 megabytes
['implementation', '*900']
F. Expected Earningstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a game with a bag of red and black balls. Initially, you are told that the bag has n balls total. In addition, you are also told that the bag has probability pi / 106 of containing exactly i red balls.You now would like to buy balls from this bag. You really like the color red, so red balls are worth a unit of 1, while black balls are worth nothing. To buy a ball, if there are still balls in the bag, you pay a cost c with 0 ≤ c ≤ 1, and draw a ball randomly from the bag. You can choose to stop buying at any point (and you can even choose to not buy anything at all).Given that you buy optimally to maximize the expected profit (i.e. # red balls - cost needed to obtain them), print the maximum expected profit.InputThe first line of input will contain two integers n, X (1 ≤ n ≤ 10 000, 0 ≤ X ≤ 106).The next line of input will contain n + 1 integers p0, p1, ... pn (0 ≤ pi ≤ 106, )The value of c can be computed as .OutputPrint a single floating point number representing the optimal expected value.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 .ExampleInput3 200000250000 250000 250000 250000Output0.9000000000NoteHere, there is equal probability for the bag to contain 0,1,2,3 red balls. Also, it costs 0.2 to draw a ball from the bag.
Input3 200000250000 250000 250000 250000
Output0.9000000000
2 seconds
256 megabytes
['*2800']
E. Convex Countourtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou 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.InputThe 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 xi, yi (|xi|, |yi| ≤ 109), denoting the coordinates of the i-th vertex.It is guaranteed that these points are listed in clockwise order.OutputPrint 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 .ExampleInput40 00 11 11 0Output3.4142135624NoteOne optimal path is to visit points 0,1,3,2 in order.
Input40 00 11 11 0
Output3.4142135624
2 seconds
256 megabytes
['dp', '*2300']