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
E. Analysis of Pathes in Functional Graphtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.Graph is given as the array f0, f1, ..., fn - 1, where fi β€” the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi β€” the arc weight from i to fi. The graph from the first sample test. Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where: si β€” the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i; mi β€” the minimal weight from all arcs on the path with length k which starts from the vertex i. The length of the path is the number of arcs on this path.InputThe first line contains two integers n, k (1 ≀ n ≀ 105, 1 ≀ k ≀ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≀ fi < n) and the third β€” the sequence w0, w1, ..., wn - 1 (0 ≀ wi ≀ 108).OutputPrint n lines, the pair of integers si, mi in each line.ExamplesInput7 31 2 3 4 3 2 66 3 1 4 2 2 3Output10 18 17 110 28 27 19 3Input4 40 1 2 30 1 2 3Output0 04 18 212 3Input5 31 2 3 4 04 1 2 14 3Output7 117 119 221 38 1
Input7 31 2 3 4 3 2 66 3 1 4 2 2 3
Output10 18 17 110 28 27 19 3
2 seconds
512 megabytes
['data structures', 'graphs', '*2100']
D. Road to Post Officetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers.Vasiliy's car is not new β€” it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station.To drive one kilometer on car Vasiliy spends a seconds, to walk one kilometer on foot he needs b seconds (a < b).Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.InputThe first line contains 5 positive integers d, k, a, b, t (1 ≀ d ≀ 1012; 1 ≀ k, a, b, t ≀ 106; a < b), where: d β€” the distance from home to the post office; k β€” the distance, which car is able to drive before breaking; a β€” the time, which Vasiliy spends to drive 1 kilometer on his car; b β€” the time, which Vasiliy spends to walk 1 kilometer on foot; t β€” the time, which Vasiliy spends to repair his car. OutputPrint the minimal time after which Vasiliy will be able to reach the post office.ExamplesInput5 2 1 4 10Output14Input5 2 1 4 5Output13NoteIn the first example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds) and then to walk on foot 3 kilometers (in 12 seconds). So the answer equals to 14 seconds.In the second example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds), then repair his car (in 5 seconds) and drive 2 kilometers more on the car (in 2 seconds). After that he needs to walk on foot 1 kilometer (in 4 seconds). So the answer equals to 13 seconds.
Input5 2 1 4 10
Output14
1 second
256 megabytes
['math', '*1900']
C. Cellular Networktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on the straight line β€” the positions (x-coordinates) of the cities and m points on the same line β€” the positions (x-coordinates) of the cellular towers. All towers work in the same way β€” they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.InputThe first line contains two positive integers n and m (1 ≀ n, m ≀ 105) β€” the number of cities and the number of cellular towers.The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≀ bj ≀ 109) β€” the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.OutputPrint minimal r so that each city will be covered by cellular network.ExamplesInput3 2-2 2 4-3 0Output4Input5 31 5 10 14 174 11 15Output3
Input3 2-2 2 4-3 0
Output4
3 seconds
256 megabytes
['binary search', 'implementation', 'two pointers', '*1500']
B. Powers of Twotime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).InputThe first line contains the single positive integer n (1 ≀ n ≀ 105) β€” the number of integers.The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.ExamplesInput47 3 2 1Output2Input31 1 1Output3NoteIn the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).In the second example all pairs of indexes (i, j) (where i < j) include in answer.
Input47 3 2 1
Output2
3 seconds
256 megabytes
['brute force', 'data structures', 'implementation', 'math', '*1500']
A. Maximum Increasetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.InputThe first line contains single positive integer n (1 ≀ n ≀ 105) β€” the number of integers.The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint the maximum length of an increasing subarray of the given array.ExamplesInput51 7 2 11 15Output3Input6100 100 100 100 100 100Output1Input31 2 3Output3
Input51 7 2 11 15
Output3
1 second
256 megabytes
['dp', 'greedy', 'implementation', '*800']
C. They Are Everywheretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit. InputThe first line contains the integer n (1 ≀ n ≀ 100 000) β€” the number of flats in the house.The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i. OutputPrint the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house. ExamplesInput3AaAOutput2Input7bcAAcbcOutput3Input6aaBCCeOutput5NoteIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.
Input3AaA
Output2
2 seconds
256 megabytes
['binary search', 'strings', 'two pointers', '*1500']
B. Cells Not Under Attacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.InputThe first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.OutputPrint m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.ExamplesInput3 31 13 12 2Output4 2 0 Input5 21 55 1Output16 9 Input100000 1300 400Output9999800001 NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Input3 31 13 12 2
Output4 2 0
2 seconds
256 megabytes
['data structures', 'math', '*1200']
A. Cardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.InputThe first line of the input contains integer n (2 ≀ n ≀ 100)Β β€” the number of cards in the deck. It is guaranteed that n is even.The second line contains the sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is equal to the number written on the i-th card.OutputPrint n / 2 pairs of integers, the i-th pair denote the cards that should be given to the i-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them.ExamplesInput61 5 7 4 4 3Output1 36 24 5Input410 10 10 10Output1 23 4NoteIn the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8. In the second sample, all values ai are equal. Thus, any distribution is acceptable.
Input61 5 7 4 4 3
Output1 36 24 5
1 second
256 megabytes
['greedy', 'implementation', '*800']
E. Cool Sloganstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBomboslav set up a branding agency and now helps companies to create new logos and advertising slogans. In term of this problems, slogan of the company should be a non-empty substring of its name. For example, if the company name is "hornsandhoofs", then substrings "sand" and "hor" could be its slogans, while strings "e" and "hornss" can not.Sometimes the company performs rebranding and changes its slogan. Slogan A is considered to be cooler than slogan B if B appears in A as a substring at least twice (this occurrences are allowed to overlap). For example, slogan A =  "abacaba" is cooler than slogan B =  "ba", slogan A =  "abcbcbe" is cooler than slogan B =  "bcb", but slogan A =  "aaaaaa" is not cooler than slogan B =  "aba".You are given the company name w and your task is to help Bomboslav determine the length of the longest sequence of slogans s1, s2, ..., sk, such that any slogan in the sequence is cooler than the previous one.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the length of the company name that asks Bomboslav to help. The second line contains the string w of length n, that consists of lowercase English letters.OutputPrint a single integerΒ β€” the maximum possible length of the sequence of slogans of the company named w, such that any slogan in the sequence (except the first one) is cooler than the previousExamplesInput3abcOutput1Input5dddddOutput5Input11abracadabraOutput3
Input3abc
Output1
4 seconds
512 megabytes
['string suffix structures', 'strings', '*3300']
D. Huffman Coding on Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice wants to send an important message to Bob. Message a = (a1, ..., an) is a sequence of positive integers (characters).To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function f, that maps each letter that appears in the string to some binary string (that is, string consisting of characters '0' and '1' only) such that for each pair of different characters ai and aj string f(ai) is not a prefix of f(aj) (and vice versa). The result of the encoding of the message a1, a2, ..., an is the concatenation of the encoding of each character, that is the string f(a1)f(a2)... f(an). Huffman codes are very useful, as the compressed message can be easily and uniquely decompressed, if the function f is given. Code is usually chosen in order to minimize the total length of the compressed message, i.e. the length of the string f(a1)f(a2)... f(an).Because of security issues Alice doesn't want to send the whole message. Instead, she picks some substrings of the message and wants to send them separately. For each of the given substrings ali... ari she wants to know the minimum possible length of the Huffman coding. Help her solve this problem.InputThe first line of the input contains the single integer n (1 ≀ n ≀ 100 000)Β β€” the length of the initial message. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 100 000)Β β€” characters of the message.Next line contains the single integer q (1 ≀ q ≀ 100 000)Β β€” the number of queries.Then follow q lines with queries descriptions. The i-th of these lines contains two integers li and ri (1 ≀ li ≀ ri ≀ n)Β β€” the position of the left and right ends of the i-th substring respectively. Positions are numbered from 1. Substrings may overlap in any way. The same substring may appear in the input more than once.OutputPrint q lines. Each line should contain a single integerΒ β€” the minimum possible length of the Huffman encoding of the substring ali... ari.ExampleInput71 2 1 3 1 2 151 71 33 52 44 4Output103350NoteIn the first query, one of the optimal ways to encode the substring is to map 1 to "0", 2 to "10" and 3 to "11".Note that it is correct to map the letter to the empty substring (as in the fifth query from the sample).
Input71 2 1 3 1 2 151 71 33 52 44 4
Output103350
4 seconds
256 megabytes
['data structures', 'greedy', '*3100']
C. Break Uptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAgain, there are hard times in Berland! Many towns have such tensions that even civil war is possible. There are n towns in Reberland, some pairs of which connected by two-way roads. It is not guaranteed that it is possible to reach one town from any other town using these roads. Towns s and t announce the final break of any relationship and intend to rule out the possibility of moving between them by the roads. Now possibly it is needed to close several roads so that moving from s to t using roads becomes impossible. Each town agrees to spend money on closing no more than one road, therefore, the total number of closed roads will be no more than two.Help them find set of no more than two roads such that there will be no way between s and t after closing these roads. For each road the budget required for its closure was estimated. Among all sets find such that the total budget for the closure of a set of roads is minimum.InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 1000, 0 ≀ m ≀ 30 000)Β β€” the number of towns in Berland and the number of roads.The second line contains integers s and t (1 ≀ s, t ≀ n, s ≠ t)Β β€” indices of towns which break up the relationships.Then follow m lines, each of them contains three integers xi, yi and wi (1 ≀ xi, yi ≀ n, 1 ≀ wi ≀ 109)Β β€” indices of towns connected by the i-th road, and the budget on its closure.All roads are bidirectional. It is allowed that the pair of towns is connected by more than one road. Roads that connect the city to itself are allowed. OutputIn the first line print the minimum budget required to break up the relations between s and t, if it is allowed to close no more than two roads.In the second line print the value c (0 ≀ c ≀ 2)Β β€” the number of roads to be closed in the found solution.In the third line print in any order c diverse integers from 1 to mΒ β€” indices of closed roads. Consider that the roads are numbered from 1 to m in the order they appear in the input. If it is impossible to make towns s and t disconnected by removing no more than 2 roads, the output should contain a single line -1. If there are several possible answers, you may print any of them.ExamplesInput6 71 62 1 62 3 53 4 94 6 44 6 54 5 13 1 3Output822 7Input6 71 62 3 11 2 21 3 34 5 43 6 54 6 61 5 7Output924 5Input5 41 52 1 33 2 13 4 44 5 2Output112Input2 31 21 2 7344588401 2 8173800271 2 304764803Output-1
Input6 71 62 1 62 3 53 4 94 6 44 6 54 5 13 1 3
Output822 7
3 seconds
256 megabytes
['dfs and similar', 'graphs', '*2600']
B. Connecting Universitiestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1. InputThe first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ n / 2)Β β€” the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n. The second line contains 2k distinct integers u1, u2, ..., u2k (1 ≀ ui ≀ n)Β β€” indices of towns in which universities are located. The next n - 1 line contains the description of roads. Each line contains the pair of integers xj and yj (1 ≀ xj, yj ≀ n), which means that the j-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads. OutputPrint the maximum possible sum of distances in the division of universities into k pairs.ExamplesInput7 21 5 6 21 33 24 53 74 34 6Output6Input9 33 2 1 6 5 98 93 22 73 47 64 52 12 8Output9NoteThe figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example.
Input7 21 5 6 21 33 24 53 74 34 6
Output6
3 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*1800']
A. As Fast As Possibletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. InputThe first line of the input contains five positive integers n, l, v1, v2 and k (1 ≀ n ≀ 10 000, 1 ≀ l ≀ 109, 1 ≀ v1 < v2 ≀ 109, 1 ≀ k ≀ n)Β β€” the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. OutputPrint the real numberΒ β€” the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.ExamplesInput5 10 1 2 5Output5.0000000000Input3 6 1 2 1Output4.7142857143NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Input5 10 1 2 5
Output5.0000000000
1 second
256 megabytes
['binary search', 'math', '*1900']
B. One Bombtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a description of a depot. It is a rectangular checkered field of n × m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y.You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall.InputThe first line contains two positive integers n and m (1 ≀ n, m ≀ 1000)Β β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" eachΒ β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall.OutputIf it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes).Otherwise print "YES" (without quotes) in the first line and two integers in the second lineΒ β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them.ExamplesInput3 4.*.......*..OutputYES1 2Input3 3..*.*.*..OutputNOInput6 5..*....*..*****..*....*....*..OutputYES3 3
Input3 4.*.......*..
OutputYES1 2
1 second
256 megabytes
['implementation', '*1400']
A. Launch of Collidertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movementΒ β€” it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.InputThe first line contains the positive integer n (1 ≀ n ≀ 200 000)Β β€” the number of particles. The second line contains n symbols "L" and "R". If the i-th symbol equals "L", then the i-th particle will move to the left, otherwise the i-th symbol equals "R" and the i-th particle will move to the right.The third line contains the sequence of pairwise distinct even integers x1, x2, ..., xn (0 ≀ xi ≀ 109)Β β€” the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order. OutputIn the first line print the only integerΒ β€” the first moment (in microseconds) when two particles are at the same point and there will be an explosion. Print the only integer -1, if the collision of particles doesn't happen. ExamplesInput4RLRL2 4 6 10Output1Input3LLR40 50 60Output-1NoteIn the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point.
Input4RLRL2 4 6 10
Output1
2 seconds
256 megabytes
['implementation', '*1000']
F. Coprime Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo positive integers are coprime if and only if they don't have a common divisor greater than 1.Some bear doesn't want to tell Radewoosh how to solve some algorithmic problem. So, Radewoosh is going to break into that bear's safe with solutions. To pass through the door, he must enter a permutation of numbers 1 through n. The door opens if and only if an entered permutation p1, p2, ..., pn satisfies:In other words, two different elements are coprime if and only if their indices are coprime. Some elements of a permutation may be already fixed. In how many ways can Radewoosh fill the remaining gaps so that the door will open? Print the answer modulo 109 + 7.InputThe first line of the input contains one integer n (2 ≀ n ≀ 1 000 000).The second line contains n integers p1, p2, ..., pn (0 ≀ pi ≀ n) where pi = 0 means a gap to fill, and pi β‰₯ 1 means a fixed number.It's guaranteed that if i ≠ j and pi, pj β‰₯ 1 then pi ≠ pj.OutputPrint the number of ways to fill the gaps modulo 109 + 7 (i.e. modulo 1000000007).ExamplesInput40 0 0 0Output4Input50 0 1 2 0Output2Input60 0 1 2 0 0Output0Input55 3 4 2 1Output0NoteIn the first sample test, none of four element is fixed. There are four permutations satisfying the given conditions: (1,2,3,4), (1,4,3,2), (3,2,1,4), (3,4,1,2).In the second sample test, there must be p3 = 1 and p4 = 2. The two permutations satisfying the conditions are: (3,4,1,2,5), (5,4,1,2,3).
Input40 0 0 0
Output4
2 seconds
256 megabytes
['combinatorics', 'number theory', '*3000']
E. Crontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSometime the classic solution are not powerful enough and we have to design our own. For the purpose of this problem you have to implement the part of the system of task scheduling.Each task should be executed at some particular moments of time. In our system you may set the exact value for the second, minute, hour, day of the week, day and month, when the task should be executed. Moreover, one can set a special value -1 that means any value of this parameter is valid.For example, if the parameter string is -1 59 23 -1 -1 -1, the problem will be executed every day at 23:59:00, 23:59:01, 23:59:02, ..., 23:59:59 (60 times in total).Seconds, minutes and hours are numbered starting from zero, while day, months and days of the week are numbered starting from one. The first day of the week is Monday.There is one special case that is treated separately. If both day of the week and day are given (i.e. differ from -1) to execute the task only one of these two (at least one, if both match this is fine too) parameters should match the current time (of course, all other parameters should match too). For example, the string of parameters 0 0 12 6 3 7 means that the task will be executed both on Saturday, July 2nd, 2016 and on Sunday, July 3rd, 2016 at noon.One should not forget about the existence of the leap years. The year is leap if it's number is divisible by 400, or is not divisible by 100, but is divisible by 4. Each leap year has 366 days instead of usual 365, by extending February to 29 days rather than the common 28.The current time is represented as the number of seconds passed after 00:00:00 January 1st, 1970 (Thursday).You are given the string of six parameters, describing the moments of time the task should be executed. You are also given a number of moments of time. For each of them you have to find the first moment of time strictly greater than the current when the task will be executed.InputThe first line of the input contains six integers s, m, h, day, date and month (0 ≀ s, m ≀ 59, 0 ≀ h ≀ 23, 1 ≀ day ≀ 7, 1 ≀ date ≀ 31, 1 ≀ month ≀ 12). Each of the number can also be equal to  - 1. It's guaranteed, that there are infinitely many moments of time when this task should be executed.Next line contains the only integer n (1 ≀ n ≀ 1000)Β β€” the number of moments of time you have to solve the problem for. Each of the next n lines contains a single integer ti (0 ≀ ti ≀ 1012).OutputPrint n lines, the i-th of them should contain the first moment of time strictly greater than ti, when the task should be executed.ExamplesInput-1 59 23 -1 -1 -16146737265814674175401467417541146741759814674175991467417600Output146741754014674175411467417542146741759914675039401467503940Input0 0 12 6 3 73146737265814674608101467547200Output146746080014675472001468065600NoteThe moment of time 1467372658 after the midnight of January 1st, 1970 is 11:30:58 July 1st, 2016.
Input-1 59 23 -1 -1 -16146737265814674175401467417541146741759814674175991467417600
Output146741754014674175411467417542146741759914675039401467503940
3 seconds
256 megabytes
['*2800']
D. Limak and Shooting Pointstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBearland is a dangerous place. Limak can’t travel on foot. Instead, he has k magic teleportation stones. Each stone can be used at most once. The i-th stone allows to teleport to a point (axi, ayi). Limak can use stones in any order.There are n monsters in Bearland. The i-th of them stands at (mxi, myi).The given k + n points are pairwise distinct.After each teleportation, Limak can shoot an arrow in some direction. An arrow will hit the first monster in the chosen direction. Then, both an arrow and a monster disappear. It’s dangerous to stay in one place for long, so Limak can shoot only one arrow from one place.A monster should be afraid if it’s possible that Limak will hit it. How many monsters should be afraid of Limak?InputThe first line of the input contains two integers k and n (1 ≀ k ≀ 7, 1 ≀ n ≀ 1000)Β β€” the number of stones and the number of monsters.The i-th of following k lines contains two integers axi and ayi ( - 109 ≀ axi, ayi ≀ 109)Β β€” coordinates to which Limak can teleport using the i-th stone.The i-th of last n lines contains two integers mxi and myi ( - 109 ≀ mxi, myi ≀ 109)Β β€” coordinates of the i-th monster.The given k + n points are pairwise distinct.OutputPrint the number of monsters which should be afraid of Limak.ExamplesInput2 4-2 -14 54 22 14 -11 -1Output3Input3 810 200 020 40300 60030 60170 34050 10028 5690 180-4 -8-1 -2Output5NoteIn the first sample, there are two stones and four monsters. Stones allow to teleport to points ( - 2,  - 1) and (4, 5), marked blue in the drawing below. Monsters are at (4, 2), (2, 1), (4,  - 1) and (1,  - 1), marked red. A monster at (4,  - 1) shouldn't be afraid because it's impossible that Limak will hit it with an arrow. Other three monsters can be hit and thus the answer is 3. In the second sample, five monsters should be afraid. Safe monsters are those at (300, 600), (170, 340) and (90, 180).
Input2 4-2 -14 54 22 14 -11 -1
Output3
3 seconds
256 megabytes
['brute force', 'geometry', 'math', '*2600']
C. LRUtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile creating high loaded systems one should pay a special attention to caching. This problem will be about one of the most popular caching algorithms called LRU (Least Recently Used).Suppose the cache may store no more than k objects. At the beginning of the workflow the cache is empty. When some object is queried we check if it is present in the cache and move it here if it's not. If there are more than k objects in the cache after this, the least recently used one should be removed. In other words, we remove the object that has the smallest time of the last query.Consider there are n videos being stored on the server, all of the same size. Cache can store no more than k videos and caching algorithm described above is applied. We know that any time a user enters the server he pick the video i with probability pi. The choice of the video is independent to any events before.The goal of this problem is to count for each of the videos the probability it will be present in the cache after 10100 queries.InputThe first line of the input contains two integers n and k (1 ≀ k ≀ n ≀ 20)Β β€” the number of videos and the size of the cache respectively. Next line contains n real numbers pi (0 ≀ pi ≀ 1), each of them is given with no more than two digits after decimal point.It's guaranteed that the sum of all pi is equal to 1.OutputPrint n real numbers, the i-th of them should be equal to the probability that the i-th video will be present in the cache after 10100 queries. You 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.3 0.2 0.5Output0.3 0.2 0.5 Input2 10.0 1.0Output0.0 1.0 Input3 20.3 0.2 0.5Output0.675 0.4857142857142857 0.8392857142857143 Input3 30.2 0.3 0.5Output1.0 1.0 1.0
Input3 10.3 0.2 0.5
Output0.3 0.2 0.5
2 seconds
256 megabytes
['bitmasks', 'dp', 'math', 'probabilities', '*2400']
B. Fix a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent). For this rooted tree the array p is [2, 3, 3, 2]. Given a sequence p1, p2, ..., pn, one is able to restore a tree: There must be exactly one index r that pr = r. A vertex r is a root of the tree. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi. A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.InputThe first line of the input contains an integer n (2 ≀ n ≀ 200 000)Β β€” the number of vertices in the tree.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n).OutputIn the first line print the minimum number of elements to change, in order to get a valid sequence.In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.ExamplesInput42 3 3 4Output12 3 4 4 Input53 2 2 5 3Output03 2 2 5 3 Input82 3 5 4 1 6 6 7Output22 3 7 8 1 6 6 7NoteIn the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. In the second sample, the given sequence is already valid.
Input42 3 3 4
Output12 3 4 4
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'trees', '*1700']
A. Vacationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: on this day the gym is closed and the contest is not carried out; on this day the gym is closed and the contest is carried out; on this day the gym is open and the contest is not carried out; on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.InputThe first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations.The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.OutputPrint the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: to do sport on any two consecutive days, to write the contest on any two consecutive days. ExamplesInput41 3 2 0Output2Input71 3 3 2 1 2 3Output0Input22 2Output1NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Input41 3 2 0
Output2
1 second
256 megabytes
['dp', '*1400']
B. Barnicletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and x = A × 10B is true. In our case A is between 0 and 9 and B is non-negative.Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.InputThe first and only line of input contains a single string of form a.deb where a, d and b are integers and e is usual character 'e' (0 ≀ a ≀ 9, 0 ≀ d < 10100, 0 ≀ b ≀ 100)Β β€” the scientific notation of the desired distance value.a and b contain no leading zeros and d contains no trailing zeros (but may be equal to 0). Also, b can not be non-zero if a is zero.OutputPrint the only real number x (the desired distance value) in the only line in its decimal notation. Thus if x is an integer, print it's integer value without decimal part and decimal point and without leading zeroes. Otherwise print x in a form of p.q such that p is an integer that have no leading zeroes (but may be equal to zero), and q is an integer that have no trailing zeroes (and may not be equal to zero).ExamplesInput8.549e2Output854.9Input8.549e3Output8549Input0.33e0Output0.33
Input8.549e2
Output854.9
1 second
256 megabytes
['brute force', 'implementation', 'math', 'strings', '*1400']
A. Pineapple Incidenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTed has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc. Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.InputThe first and only line of input contains three integers t, s and x (0 ≀ t, x ≀ 109, 2 ≀ s ≀ 109)Β β€” the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.OutputPrint a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.ExamplesInput3 10 4OutputNOInput3 10 3OutputYESInput3 8 51OutputYESInput3 8 52OutputYESNoteIn the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Input3 10 4
OutputNO
1 second
256 megabytes
['implementation', 'math', '*900']
F. ...Dary!time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarney has finally found the one, a beautiful young lady named Lyanna. The problem is, Lyanna and Barney are trapped in Lord Loss' castle. This castle has shape of a convex polygon of n points. Like most of castles in Demonata worlds, this castle has no ceiling. Barney and Lyanna have an escape plan, but it requires some geometry knowledge, so they asked for your help.Barney knows that demons are organized and move in lines. He and Lyanna want to wait for the appropriate time so they need to watch for the demons. Each of them wants to stay in a point inside the castle (possibly on edges or corners), also they may stay in the same position. They both want to pick a real number r and watch all points in the circles with radius r around each of them (these two circles may overlap). We say that Barney and Lyanna are watching carefully if and only if for every edge of the polygon, at least one of them can see at least one point on the line this edge lies on, thus such point may not be on the edge but it should be on edge's line. Formally, each edge line should have at least one common point with at least one of two circles.The greater r is, the more energy and focus they need. So they asked you to tell them the minimum value of r such that they can watch carefully.InputThe first line of input contains a single integer n (3 ≀ n ≀ 300)Β β€” the number of castle polygon vertices.The next n lines describe the polygon vertices in counter-clockwise order. i-th of them contains two integers xi and yi (|xi|, |yi| ≀ 104)Β β€” the coordinates of i-th point of the castle. It is guaranteed that given points form a convex polygon, in particular, any three of them do not line on the same line.OutputIn the first line print the single number rΒ β€” minimum radius of guys' watching circles.In the second line print the pair of coordinates of point where Barney should stay.In the third line print the pair of coordinates of point where Lyanna should stay.Points should lie inside the polygon.Coordinates may not be integers. If there are multiple answers print any of them.Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.ExamplesInput4-41 67-16 2025 25-36 85Output0-16 20-36 85Input7-7 54-5 31-2 1720 1932 2334 2726 57Output2.934224832.019503 23.0390067-6.929116 54.006444NoteIn the first example guys can stay in opposite corners of the castle.
Input4-41 67-16 2025 25-36 85
Output0-16 20-36 85
3 seconds
256 megabytes
['binary search', 'geometry', 'two pointers', '*3300']
E. ...Wait for it...time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarney is searching for his dream girl. He lives in NYC. NYC has n junctions numbered from 1 to n and n - 1 roads connecting them. We will consider the NYC as a rooted tree with root being junction 1. m girls live in NYC, i-th of them lives along junction ci and her weight initially equals i pounds. Barney consider a girl x to be better than a girl y if and only if: girl x has weight strictly less than girl y or girl x and girl y have equal weights and index of girl x living junction index is strictly less than girl y living junction index, i.e. cx < cy. Thus for any two girls one of them is always better than another one.For the next q days, one event happens each day. There are two types of events: Barney goes from junction v to junction u. As a result he picks at most k best girls he still have not invited from junctions on his way and invites them to his house to test if one of them is his dream girl. If there are less than k not invited girls on his path, he invites all of them. Girls living along junctions in subtree of junction v (including v itself) put on some weight. As result, their weights increase by k pounds. Your task is for each event of first type tell Barney the indices of girls he will invite to his home in this event.InputThe first line of input contains three integers n, m and q (1 ≀ n, m, q ≀ 105)Β β€” the number of junctions in NYC, the number of girls living in NYC and the number of events respectively.The next n - 1 lines describes the roads. Each line contains two integers v and u (1 ≀ v, u ≀ n, v ≠ u) meaning that there is a road connecting junctions v and u .The next line contains m integers c1, c2, ..., cm (1 ≀ ci ≀ n)Β β€” the girl's living junctions.The next q lines describe the events in chronological order. Each line starts with an integer t (1 ≀ t ≀ 2)Β β€” type of the event .If t = 1 then the line describes event of first type three integers v, u and k (1 ≀ v, u, k ≀ n) followΒ β€” the endpoints of Barney's path and the number of girls that he will invite at most.Otherwise the line describes event of second type and two integers v and k (1 ≀ v ≀ n, 1 ≀ k ≀ 109) followΒ β€” the root of the subtree and value by which all the girls' weights in the subtree should increase.OutputFor each event of the first type, print number t and then t integers g1, g2, ..., gt in one line, meaning that in this event Barney will invite t girls whose indices are g1, ..., gt in the order from the best to the worst according to Barney's considerations.ExampleInput5 7 113 52 34 31 44 1 4 5 4 1 42 4 31 2 1 21 4 2 12 2 102 1 101 2 4 11 2 3 42 5 22 4 91 3 5 21 1 2 3Output2 2 1 1 3 1 5 0 1 4 2 6 7 NoteFor the first sample case: Description of events: Weights of girls in subtree of junction 4 increase by 3. These girls have IDs: 1, 3, 5, 4, 7. Barney goes from junction 2 to 1. Girls on his way have IDs 1, 2, 3, 5, 6, 7 with weights 4, 2, 6, 8, 6, 10 respectively. So, he invites girls 2 and 1. Barney goes from junction 4 to junction 2. Girls on his way has IDs 3, 5, 7 with weights 6, 8, 10 respectively. So he invites girl 3. Weight of girls in subtree of junction 2 increase by 10. There are no not invited girls, so nothing happens. Weight of girls in subtree of junction 1 increase by 10. These girls (all girls left) have IDs: 4, 5, 6, 7. Barney goes from junction 2 to junction 4. Girls on his way has IDs 5, 7 with weights 18, 20 respectively. So he invites girl 5. Barney goes from junction 2 to junction 3. There is no girl on his way. Weight of girls in subtree of junction 5 increase by 2. The only girl there is girl with ID 4. Weight of girls in subtree of junction 4 increase by 9. These girls have IDs: 4, 6, 7. Barney goes from junction 3 to junction 5. Only girl on his way is girl with ID 4. Barney goes from junction 1 to junction 2. Girls on his way has IDs 6, 7 with weights 16, 29 respectively.
Input5 7 113 52 34 31 44 1 4 5 4 1 42 4 31 2 1 21 4 2 12 2 102 1 101 2 4 11 2 3 42 5 22 4 91 3 5 21 1 2 3
Output2 2 1 1 3 1 5 0 1 4 2 6 7
3 seconds
256 megabytes
['data structures', 'dsu', 'trees', '*3000']
D. Legen...time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.Due to texting app limits, Barney's text may have up to l characters.Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...InputThe first line of input contains two integers n and l (1 ≀ n ≀ 200, 1 ≀ l ≀ 1014)Β β€” the number of pickup lines and the maximum length of Barney's text.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line.The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200.All strings are not empty.OutputPrint the only integerΒ β€” the maximum possible value of Nora's happiness level after reading Barney's text.ExamplesInput3 63 2 1heartearthartOutput6Input3 63 2 8heartearthartOutput16NoteAn optimal answer for the first sample case is hearth containing each pickup line exactly once.An optimal answer for the second sample case is artart.
Input3 63 2 1heartearthart
Output6
6 seconds
256 megabytes
['data structures', 'dp', 'matrices', 'strings', '*2500']
C. PLEASEtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that in other words, n is multiplication of all elements of the given array.Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that , where is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7.Please note that we want of p and q to be 1, not of their remainders after dividing by 109 + 7.InputThe first line of input contains a single integer k (1 ≀ k ≀ 105)Β β€” the number of elements in array Barney gave you.The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018)Β β€” the elements of the array.OutputIn the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7.ExamplesInput12Output1/2Input31 1 1Output0/1
Input12
Output1/2
1 second
256 megabytes
['combinatorics', 'dp', 'implementation', 'math', 'matrices', '*2000']
B. Puzzlestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:let starting_time be an array of length ncurrent_time = 0dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u)As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.InputThe first line of input contains a single integer n (1 ≀ n ≀ 105)Β β€” the number of cities in USC.The second line contains n - 1 integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.OutputIn the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.ExamplesInput71 2 1 1 4 4Output1.0 4.0 5.0 3.5 4.5 5.0 5.0 Input121 1 2 2 4 4 3 3 1 10 8Output1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Input71 2 1 1 4 4
Output1.0 4.0 5.0 3.5 4.5 5.0 5.0
1 second
256 megabytes
['dfs and similar', 'math', 'probabilities', 'trees', '*1700']
A. Lorenzo Von Matterhorntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBarney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).InputThe first line of input contains a single integer q (1 ≀ q ≀ 1 000).The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u.1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.OutputFor each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.ExampleInput71 3 4 301 4 1 21 3 6 82 4 31 6 1 402 3 72 2 4Output94032NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Input71 3 4 301 4 1 21 3 6 82 4 31 6 1 402 3 72 2 4
Output94032
1 second
256 megabytes
['brute force', 'data structures', 'implementation', 'trees', '*1500']
F. Couple Covertime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCouple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with n balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) β€” the number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball β€” the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold p square meters, the players win. Otherwise, they lose.The organizers of the game are trying to select an appropriate value for p so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of p. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different.InputThe input begins with a single positive integer n in its own line (1 ≀ n ≀ 106).The second line contains n positive integers β€” the i-th number in this line is equal to ai (1 ≀ ai ≀ 3Β·106), the number written on the i-th ball.The next line contains an integer m (1 ≀ m ≀ 106), the number of questions you are being asked.Then, the following line contains m positive integers β€” the j-th number in this line is equal to the value of p (1 ≀ p ≀ 3Β·106) in the j-th question you are being asked.OutputFor each question, print the number of winning pairs of balls that exist for the given value of p in the separate line.ExamplesInput54 2 6 1 341 3 5 8Output20181410Input25 6230 31Output20
Input54 2 6 1 341 3 5 8
Output20181410
3 seconds
512 megabytes
['brute force', 'dp', 'number theory', '*2200']
E. Xor-sequencestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a1,  a2,  ...,  an.A sequence of integers x1,  x2,  ...,  xk is called a "xor-sequence" if for every 1  ≀  i  ≀  k - 1 the number of ones in the binary representation of the number xi xi  +  1's is a multiple of 3 and for all 1 ≀ i ≀ k. The symbol is used for the binary exclusive or operation.How many "xor-sequences" of length k exist? Output the answer modulo 109 + 7.Note if a = [1, 1] and k = 1 then the answer is 2, because you should consider the ones from a as different.InputThe first line contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1018) β€” the number of given integers and the length of the "xor-sequences".The second line contains n integers ai (0 ≀ ai ≀ 1018).OutputPrint the only integer c β€” the number of "xor-sequences" of length k modulo 109 + 7.ExamplesInput5 215 1 2 4 8Output13Input5 115 1 2 4 8Output5
Input5 215 1 2 4 8
Output13
3 seconds
256 megabytes
['matrices', '*1900']
D. Swaps in Permutationtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≀ i ≀ n exists, so pk = qk for 1 ≀ k < i and pi < qi.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 106) β€” the length of the permutation p and the number of pairs of positions.The second line contains n distinct integers pi (1 ≀ pi ≀ n) β€” the elements of the permutation p.Each of the last m lines contains two integers (aj, bj) (1 ≀ aj, bj ≀ n) β€” the pairs of positions to swap. Note that you are given a positions, not the values to swap.OutputPrint the only line with n distinct integers p'i (1 ≀ p'i ≀ n) β€” the lexicographically maximal permutation one can get.ExampleInput9 61 2 3 4 5 6 7 8 91 44 72 55 83 66 9Output7 8 9 4 5 6 1 2 3
Input9 61 2 3 4 5 6 7 8 91 44 72 55 83 66 9
Output7 8 9 4 5 6 1 2 3
5 seconds
256 megabytes
['dfs and similar', 'dsu', 'math', '*1700']
C. Exponential notationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive decimal number x.Your task is to convert it to the "simple exponential notation".Let x = aΒ·10b, where 1 ≀ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.InputThe only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.OutputPrint the only line β€” the "simple exponential notation" of the given number x.ExamplesInput16Output1.6E1Input01.23400Output1.234Input.100Output1E-1Input100.Output1E2
Input16
Output1.6E1
2 seconds
256 megabytes
['implementation', 'strings', '*1800']
B. s-palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half. English alphabet You are given a string s. Check if the string is "s-palindrome".InputThe only line contains the string s (1 ≀ |s| ≀ 1000) which consists of only English letters.OutputPrint "TAK" if the string s is "s-palindrome" and "NIE" otherwise.ExamplesInputoXoxoXoOutputTAKInputbodOutputTAKInputEROutputNIE
InputoXoxoXo
OutputTAK
1 second
256 megabytes
['implementation', 'strings', '*1600']
A. Fashion in Berlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.InputThe first line contains integer n (1 ≀ n ≀ 1000) β€” the number of buttons on the jacket.The second line contains n integers ai (0 ≀ ai ≀ 1). The number ai = 0 if the i-th button is not fastened. Otherwise ai = 1.OutputIn the only line print the word "YES" if the jacket is fastened in a right way. Otherwise print the word "NO".ExamplesInput31 0 1OutputYESInput31 0 0OutputNO
Input31 0 1
OutputYES
1 second
256 megabytes
['implementation', '*1000']
F3. Tree of Life (hard)time limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo add insult to injury, the zombies have taken all but two drawings from Heidi! Please help her recover the Tree of Life from only these two drawings.InputThe input format is the same as in the medium version, except that now the bound on n is 2 ≀ n ≀ 1000 and that k = 2.OutputThe same as in the medium version.ExampleInput19 264 35 46 18 68 27 158 68 78 17 35 1OutputYES2 13 15 46 57 68 59 81 4
Input19 264 35 46 18 68 27 158 68 78 17 35 1
OutputYES2 13 15 46 57 68 59 81 4
8 seconds
256 megabytes
['trees', '*3200']
F2. Tree of Life (medium)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi got tired of deciphering the prophecy hidden in the Tree of Life and decided to go back to her headquarters, rest a little and try there. Of course, she cannot uproot the Tree and take it with her, so she made a drawing of the Tree on a piece of paper. On second thought, she made more identical drawings so as to have n in total (where n is the number of vertices of the Tree of Life) – who knows what might happen?Indeed, on her way back Heidi was ambushed by a group of zombies. While she managed to fend them off, they have damaged her drawings in a peculiar way: from the i-th copy, the vertex numbered i was removed, along with all adjacent edges. In each picture, the zombies have also erased all the vertex numbers and relabeled the remaining n - 1 vertices arbitrarily using numbers 1 to n (fortunately, each vertex still has a distinct number). What's more, the drawings have been arbitrarily shuffled/reordered.Now Heidi wants to recover the Tree of Life from her descriptions of all the drawings (as lists of edges).InputThe first line of the input contains Z ≀ 20 – the number of test cases. Z descriptions of single test cases follow.In each test case, the first line of input contains numbers n (2 ≀ n ≀ 100) and k (where k is the number of drawings; we have k = n). In the following lines, the descriptions of the k drawings are given. The description of the i-th drawing is a line containing mi – the number of edges in this drawing, followed by mi lines describing edges, each of which contains two space-separated integers –- the numbers of the two vertices connected by the edge.OutputIf Heidi's drawings cannot possibly come from a single tree, you should output the word NO. Otherwise, output one line containing the word YES and n - 1 lines describing any tree that Heidi's drawings could have come from. For every edge you should output the numbers of the vertices that it connects, separated with a single space. If there are many solutions, print any of them.ExampleInput15 524 12 113 134 14 32 133 13 24 132 13 24 2OutputYES2 54 23 25 1
Input15 524 12 113 134 14 32 133 13 24 132 13 24 2
OutputYES2 54 23 25 1
5 seconds
256 megabytes
['constructive algorithms', 'hashing', 'trees', '*2700']
F1. Tree of Life (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her!InputThe first line of the input contains a single integer n – the number of vertices in the tree (1 ≀ n ≀ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≀ a < b ≀ n). It is guaranteed that the input represents a tree.OutputPrint one integer – the number of lifelines in the tree.ExamplesInput41 21 31 4Output3Input51 22 33 43 5Output4NoteIn the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5.
Input41 21 31 4
Output3
2 seconds
256 megabytes
['*1300']
D3. The Wall (hard)time limit per test15 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo many wall designs to choose from! Even modulo 106 + 3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow them down.Heidi is quick to come up with criteria for a useful wall: In a useful wall, at least one segment is wider than W bricks. This should give the zombies something to hit their heads against. Or, in a useful wall, at least one column is higher than H bricks. This provides a lookout from which zombies can be spotted at a distance. This should rule out a fair amount of possibilities, right? Help Heidi compute the number of useless walls that do not confirm to either of these criteria. In other words, a wall is useless if every segment has width at most W and height at most H.Parameter C, the total width of the wall, has the same meaning as in the easy version. However, note that the number of bricks is now unlimited.Output the number of useless walls modulo 106 + 3.InputThe first and the only line of the input contains three space-separated integers C, W and H (1 ≀ C ≀ 108, 1 ≀ W, H ≀ 100).OutputOutput the number of different walls, modulo 106 + 3, which are useless according to Heidi's criteria.ExamplesInput1 1 1Output2Input1 2 2Output3Input1 2 3Output4Input3 2 2Output19Input5 4 9Output40951Input40 37 65Output933869NoteIf there is no brick in any of the columns, the structure is considered as a useless wall.
Input1 1 1
Output2
15 seconds
256 megabytes
['dp', '*2100']
D2. The Wall (medium)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter:How to build a wall: Take a set of bricks. Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader. Place bricks on top of each other, according to the chosen design. This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to n bricks.A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most n bricks? Two walls are different if there exist a column c and a row r such that one wall has a brick in this spot, and the other does not.Along with n, you will be given C, the width of the wall (as defined in the easy version). Return the number of different walls modulo 106 + 3.InputThe first line contains two space-separated integers n and C, 1 ≀ n ≀ 500000, 1 ≀ C ≀ 200000.OutputPrint the number of different walls that Heidi could build, modulo 106 + 3.ExamplesInput5 1Output5Input2 2Output5Input3 2Output9Input11 5Output4367Input37 63Output230574NoteThe number 106 + 3 is prime.In the second sample case, the five walls are: B BB., .B, BB, B., and .BIn the third sample case, the nine walls are the five as in the second sample case and in addition the following four: B BB B B BB., .B, BB, and BB
Input5 1
Output5
2 seconds
256 megabytes
['combinatorics', '*1800']
D1. The Wall (easy)time limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.InputThe first line of the input consists of two space-separated integers R and C, 1 ≀ R, C ≀ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. The input will contain at least one character B and it will be valid.OutputThe number of wall segments in the input configuration.ExamplesInput3 7...............BB.B..Output2Input4 5..B....B..B.B.BBBB.BOutput2Input4 6..B...B.B.BBBBB.BBBBBBBBOutput1Input1 1BOutput1Input10 7...........................................................B...B.BB.B.Output3Input8 8.................................B.......B.....B.B.....B.BB...BBOutput2NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Input3 7...............BB.B..
Output2
0.5 seconds
256 megabytes
['*1200']
C3. Brain Network (hard)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBreaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.InputThe first line of the input contains one number n – the number of brains in the final nervous system (2 ≀ n ≀ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain .OutputOutput n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.ExampleInput612215Output1 2 2 3 4
Input612215
Output1 2 2 3 4
2 seconds
256 megabytes
['trees', '*2200']
C2. Brain Network (medium)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurther research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≀ u, v ≀ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.InputThe first line of the input contains two space-separated integers n and m (1 ≀ n, m ≀ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≀ a, b ≀ n and a ≠ b).OutputPrint one number – the brain latency.ExamplesInput4 31 21 31 4Output2Input5 41 22 33 43 5Output3
Input4 31 21 31 4
Output2
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*1500']
C1. Brain Network (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly: It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.InputThe first line of the input contains two space-separated integers n and m (1 ≀ n, m ≀ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≀ a, b ≀ n, a ≠ b).OutputThe output consists of one line, containing either yes or no depending on whether the nervous system is valid.ExamplesInput4 41 22 33 14 1OutputnoInput6 51 22 33 44 53 6Outputyes
Input4 41 22 33 14 1
Outputno
2 seconds
256 megabytes
['*1300']
B3. Recover Polygon (hard)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZombies have found out about the Zombie Contamination level checker and managed to damage it! Now detecting the shape of their main compound will be a real challenge for Heidi. As before, a lair can be represented as a strictly convex polygon on a lattice. Each vertex of the polygon occupies a point on the lattice. However, the damaged Zombie Contamination level checker can only tell, for each cell, whether the level of Zombie Contamination for that cell is in the set {1, 2, 3}. In other words, Heidi knows all the cells of the lattice for which the Contamination level is not 0 and not 4.Given this information, Heidi still wants to know the exact shape of the lair to rain destruction on the zombies. Help her!InputThe input contains multiple test cases.The first line of each test case contains two space-separated integers N and M, where N is the size of the lattice grid (5 ≀ N ≀ 100000) and M is the number of lattice points for which the Zombie Contamination level is 1, 2, or 3 (8 ≀ M ≀ 200000).The second line of each test case contains M pairs of integers x1, y1, ..., xM, yM – coordinates of the cells with Zombie Contamination level not equal to 0 nor 4. It is guaranteed that 1 ≀ xi, yi ≀ N. All pairs xi, yi are different.Cells are enumerated based on the coordinates of their upper right corner. This means that the bottommost leftmost cell that touches the origin has coordinates (1, 1), and the uppermost leftmost cell is identified as (1, N).The last line of the file contains two zeroes. This line should not be treated as a test case. The sum of the M values for all tests in one file will not exceed 200000.OutputFor each test case, the following output is expected:The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.ExampleInput8 192 3 2 4 2 5 3 3 3 5 4 3 4 5 4 6 5 2 5 3 5 6 6 2 6 3 6 4 6 5 6 6 6 7 7 6 7 75 82 2 2 3 2 4 3 2 3 4 4 2 4 3 4 40 0Output42 32 46 65 242 22 33 33 2NoteIt is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 1 and N - 1. A vertex (x1, y1) is lexicographically smaller than vertex (x2, y2) if x1 < x2 or .
Input8 192 3 2 4 2 5 3 3 3 5 4 3 4 5 4 6 5 2 5 3 5 6 6 2 6 3 6 4 6 5 6 6 6 7 7 6 7 75 82 2 2 3 2 4 3 2 3 4 4 2 4 3 4 40 0
Output42 32 46 65 242 22 33 33 2
5 seconds
256 megabytes
['data structures', '*2600']
B2. Recover Polygon (medium)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!InputThe input contains multiple test cases.The first line of each test case contains one integer N, the size of the lattice grid (5 ≀ N ≀ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4. Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.OutputFor each test case, give the following output:The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.ExamplesInput8000000000000011000012210012342000244420001223200000011000000000050000001210024200121000000700000000122100013420000132000002200000110000000000Output42 32 46 65 242 22 33 33 232 54 54 2NoteIt is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 2 and N - 2. A vertex (x1, y1) is lexicographically smaller than vertex (x2, y2) if x1 < x2 or .
Input8000000000000011000012210012342000244420001223200000011000000000050000001210024200121000000700000000122100013420000132000002200000110000000000
Output42 32 46 65 242 22 33 33 232 54 54 2
4 seconds
256 megabytes
['geometry', '*2600']
B1. Recover Polygon (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides). InputThe first line of each test case contains one integer N, the size of the lattice grid (5 ≀ N ≀ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).OutputThe first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.ExampleInput6000000000000012100024200012100000000OutputYesNoteThe lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x1, y1), (x1, y2), (x2, y1), (x2, y2)), has a non-zero area and be contained inside of the grid (that is, 0 ≀ x1 < x2 ≀ N, 0 ≀ y1 < y2 ≀ N), and result in the levels of Zombie Contamination as reported in the input.
Input6000000000000012100024200012100000000
OutputYes
2 seconds
256 megabytes
['*1700']
A3. Collective Mindsets (hard)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the N attendees love to play a very risky game...Every zombie gets a number ni (1 ≀ ni ≀ N) written on his forehead. Although no zombie can see his own number, he can see the numbers written on the foreheads of all N - 1 fellows. Note that not all numbers have to be unique (they can even all be the same). From this point on, no more communication between zombies is allowed. Observation is the only key to success. When the cuckoo clock strikes midnight, all attendees have to simultaneously guess the number on their own forehead. If at least one of them guesses his number correctly, all zombies survive and go home happily. On the other hand, if not a single attendee manages to guess his number correctly, all of them are doomed to die!Zombies aren't very bright creatures though, and Heidi has to act fast if she does not want to jeopardize her life. She has one single option: by performing some quick surgery on the brain she managed to get from the chest, she has the ability to remotely reprogram the decision-making strategy of all attendees for their upcoming midnight game! Can you suggest a sound strategy to Heidi which, given the rules of the game, ensures that at least one attendee will guess his own number correctly, for any possible sequence of numbers on the foreheads?Given a zombie's rank R and the N - 1 numbers ni on the other attendees' foreheads, your program will have to return the number that the zombie of rank R shall guess. Those answers define your strategy, and we will check if it is flawless or not.InputThe first line of input contains a single integer T (1 ≀ T ≀ 50000): the number of scenarios for which you have to make a guess.The T scenarios follow, described on two lines each: The first line holds two integers, N (2 ≀ N ≀ 6), the number of attendees, and R (1 ≀ R ≀ N), the rank of the zombie who has to make the guess. The second line lists N - 1 integers: the numbers on the foreheads of all other attendees, listed in increasing order of the attendees' rank. (Every zombie knows the rank of every other zombie.) OutputFor every scenario, output a single integer: the number that the zombie of rank R shall guess, based on the numbers ni on his N - 1 fellows' foreheads.ExamplesInput42 112 212 122 22Output1221Input25 22 2 2 26 43 2 6 1 2Output52NoteFor instance, if there were N = 2 two attendees, a successful strategy could be: The zombie of rank 1 always guesses the number he sees on the forehead of the zombie of rank 2. The zombie of rank 2 always guesses the opposite of the number he sees on the forehead of the zombie of rank 1.
Input42 112 212 122 22
Output1221
4 seconds
256 megabytes
['*2400']
A2. Collective Mindsets (medium)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWay to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)?The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the N - 1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.InputThe only line of input contains one integer: N, the number of attendees (1 ≀ N ≀ 109).OutputOutput one integer: the smallest number of brains in the chest which allows Heidi to merely survive.ExamplesInput1Output0Input3Output1Input99Output49
Input1
Output0
1 second
256 megabytes
['*2300']
A1. Collective Mindsets (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.They will be N guests tonight: N - 1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to N - 1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, N. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure:The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes – in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.)You should know that zombies are very greedy and sly, and they know this too – basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order: survive the event (they experienced death already once and know it is no fun), get as many brains as possible. Heidi goes first and must make an offer which at least half of the attendees will accept, and which allocates at least one brain for Heidi herself.What is the smallest number of brains that have to be in the chest for this to be possible?InputThe only line of input contains one integer: N, the number of attendees (1 ≀ N ≀ 109).OutputOutput one integer: the smallest number of brains in the chest which allows Heidi to take one brain home.ExamplesInput1Output1Input4Output2Note
Input1
Output1
1 second
256 megabytes
['*1100']
E. Mike and Geometry Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≀ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you? InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 200 000)Β β€” the number of segments and the number of segments in intersection groups respectively.Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≀ li ≀ ri ≀ 109), describing i-th segment bounds.OutputPrint one integer numberΒ β€” the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.ExamplesInput3 21 21 32 3Output5Input3 31 31 31 3Output3Input3 11 22 33 4Output6NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
Input3 21 21 32 3
Output5
3 seconds
256 megabytes
['combinatorics', 'data structures', 'dp', 'geometry', 'implementation', '*2000']
D. Friends and Subsequencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you)Β β€” who knows? Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r), Mike can instantly tell the value of while !Mike can instantly tell the value of .Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l, r) (1 ≀ l ≀ r ≀ n) (so he will make exactly n(n + 1) / 2 queries) and counts how many times their answers coincide, thus for how many pairs is satisfied.How many occasions will the robot count?InputThe first line contains only integer n (1 ≀ n ≀ 200 000).The second line contains n integer numbers a1, a2, ..., an ( - 109 ≀ ai ≀ 109)Β β€” the sequence a.The third line contains n integer numbers b1, b2, ..., bn ( - 109 ≀ bi ≀ 109)Β β€” the sequence b.OutputPrint the only integer numberΒ β€” the number of occasions the robot will count, thus for how many pairs is satisfied.ExamplesInput61 2 3 2 1 46 7 1 2 3 2Output2Input33 3 31 1 1Output0NoteThe occasions in the first sample case are:1.l = 4,r = 4 since max{2} = min{2}.2.l = 4,r = 5 since max{2, 1} = min{2, 3}.There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1.
Input61 2 3 2 1 46 7 1 2 3 2
Output2
2 seconds
512 megabytes
['binary search', 'data structures', '*2100']
C. Mike and Chocolate Thievestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible! Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly k times more than the previous one. The value of k (k > 1) is a secret integer known only to them. It is also known that each thief's bag can carry at most n chocolates (if they intend to take more, the deal is cancelled) and that there were exactly four thieves involved. Sadly, only the thieves know the value of n, but rumours say that the numbers of ways they could have taken the chocolates (for a fixed n, but not fixed k) is m. Two ways are considered different if one of the thieves (they should be numbered in the order they take chocolates) took different number of chocolates in them.Mike want to track the thieves down, so he wants to know what their bags are and value of n will help him in that. Please find the smallest possible value of n or tell him that the rumors are false and there is no such n.InputThe single line of input contains the integer m (1 ≀ m ≀ 1015)Β β€” the number of ways the thieves might steal the chocolates, as rumours say.OutputPrint the only integer nΒ β€” the maximum amount of chocolates that thieves' bags can carry. If there are more than one n satisfying the rumors, print the smallest one.If there is no such n for a false-rumoured m, print  - 1.ExamplesInput1Output8Input8Output54Input10Output-1NoteIn the first sample case the smallest n that leads to exactly one way of stealing chocolates is n = 8, whereas the amounts of stealed chocolates are (1, 2, 4, 8) (the number of chocolates stolen by each of the thieves).In the second sample case the smallest n that leads to exactly 8 ways is n = 54 with the possibilities: (1, 2, 4, 8),  (1, 3, 9, 27),  (2, 4, 8, 16),  (2, 6, 18, 54),  (3, 6, 12, 24),  (4, 8, 16, 32),  (5, 10, 20, 40),  (6, 12, 24, 48).There is no n leading to exactly 10 ways of stealing chocolates in the third sample case.
Input1
Output8
2 seconds
256 megabytes
['binary search', 'combinatorics', 'math', '*1700']
B. Mike and Shortcutstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to units of energy.Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≀ ai ≀ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≀ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≀ i ≀ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.InputThe first line contains an integer n (1 ≀ n ≀ 200 000)Β β€” the number of Mike's city intersection.The second line contains n integers a1, a2, ..., an (i ≀ ai ≀ n , , describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).OutputIn the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.ExamplesInput32 2 3Output0 1 2 Input51 2 3 4 5Output0 1 2 3 4 Input74 4 4 4 7 7 7Output0 1 2 1 2 3 3 NoteIn the first sample case desired sequences are:1: 1; m1 = 0;2: 1, 2; m2 = 1;3: 1, 3; m3 = |3 - 1| = 2.In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.In the third sample caseΒ β€” consider the following intersection sequences:1: 1; m1 = 0;2: 1, 2; m2 = |2 - 1| = 1;3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;4: 1, 4; m4 = 1;5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.
Input32 2 3
Output0 1 2
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'shortest paths', '*1600']
A. Mike and Cellphonetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253": Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?InputThe first line of the input contains the only integer n (1 ≀ n ≀ 9)Β β€” the number of digits in the phone number that Mike put in.The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.OutputIf there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.Otherwise print "NO" (without quotes) in the first line.ExamplesInput3586OutputNOInput209OutputNOInput9123456789OutputYESInput3911OutputYESNoteYou can find the picture clarifying the first sample case in the statement above.
Input3586
OutputNO
1 second
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*1400']
B. Lovely Palindromestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?InputThe only line of the input contains a single integer n (1 ≀ n ≀ 10100 000).OutputPrint the n-th even-length palindrome number.ExamplesInput1Output11Input10Output1001NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.
Input1
Output11
1 second
256 megabytes
['constructive algorithms', 'math', '*1000']
A. Opponentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.For each opponent Arya knows his scheduleΒ β€” whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.InputThe first line of the input contains two integers n and d (1 ≀ n, d ≀ 100)Β β€” the number of opponents and the number of days, respectively.The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.OutputPrint the only integerΒ β€” the maximum number of consecutive days that Arya will beat all present opponents.ExamplesInput2 21000Output2Input4 10100Output1Input4 511011111011010111111Output2NoteIn the first and the second samples, Arya will beat all present opponents each of the d days.In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4.
Input2 21000
Output2
1 second
256 megabytes
['implementation', '*800']
E. TOFtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Pari gave Arya a cool graph problem. Arya wrote a non-optimal solution for it, because he believes in his ability to optimize non-optimal solutions. In addition to being non-optimal, his code was buggy and he tried a lot to optimize it, so the code also became dirty! He keeps getting Time Limit Exceeds and he is disappointed. Suddenly a bright idea came to his mind!Here is how his dirty code looks like:dfs(v){ set count[v] = count[v] + 1 if(count[v] < 1000) { foreach u in neighbors[v] { if(visited[u] is equal to false) { dfs(u) } break } } set visited[v] = true}main(){ input the digraph() TOF() foreach 1<=i<=n { set count[i] = 0 , visited[i] = false } foreach 1 <= v <= n { if(visited[v] is equal to false) { dfs(v) } } ... // And do something cool and magical but we can't tell you what!}He asks you to write the TOF function in order to optimize the running time of the code with minimizing the number of calls of the dfs function. The input is a directed graph and in the TOF function you have to rearrange the edges of the graph in the list neighbors for each vertex. The number of calls of dfs function depends on the arrangement of neighbors of each vertex.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 5000)Β β€” the number of vertices and then number of directed edges in the input graph.Each of the next m lines contains a pair of integers ui and vi (1  ≀  ui,  vi  ≀  n), meaning there is a directed edge in the input graph. You may assume that the graph won't contain any self-loops and there is at most one edge between any unordered pair of vertices.OutputPrint a single integerΒ β€” the minimum possible number of dfs calls that can be achieved with permuting the edges.ExamplesInput3 31 22 33 1Output2998Input6 71 22 33 13 44 55 66 4Output3001
Input3 31 22 33 1
Output2998
1 second
256 megabytes
['dfs and similar', 'graphs', '*2900']
D. Dividing Kingdom IItime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLong time ago, there was a great kingdom and it was being ruled by The Great Arya and Pari The Great. These two had some problems about the numbers they like, so they decided to divide the great kingdom between themselves.The great kingdom consisted of n cities numbered from 1 to n and m bidirectional roads between these cities, numbered from 1 to m. The i-th road had length equal to wi. The Great Arya and Pari The Great were discussing about destructing some prefix (all road with numbers less than some x) and suffix (all roads with numbers greater than some x) of the roads so there will remain only the roads with numbers l, l + 1, ..., r - 1 and r.After that they will divide the great kingdom into two pieces (with each city belonging to exactly one piece) such that the hardness of the division is minimized. The hardness of a division is the maximum length of a road such that its both endpoints are in the same piece of the kingdom. In case there is no such road, the hardness of the division is considered to be equal to  - 1.Historians found the map of the great kingdom, and they have q guesses about the l and r chosen by those great rulers. Given these data, for each guess li and ri print the minimum possible hardness of the division of the kingdom.InputThe first line of the input contains three integers n, m and q (1 ≀ n, q ≀ 1000, )Β β€” the number of cities and roads in the great kingdom, and the number of guesses, respectively.The i-th line of the following m lines contains three integers ui, vi and wi (1  ≀  ui,  vi  ≀  n, 0 ≀ wi ≀ 109), denoting the road number i connects cities ui and vi and its length is equal wi. It's guaranteed that no road connects the city to itself and no pair of cities is connected by more than one road.Each of the next q lines contains a pair of integers li and ri (1  ≀ li ≀ ri ≀ m)Β β€” a guess from the historians about the remaining roads in the kingdom.OutputFor each guess print the minimum possible hardness of the division in described scenario.ExampleInput5 6 55 4 865 1 01 3 382 1 332 4 282 3 403 52 61 32 31 6Output-133-1-133
Input5 6 55 4 865 1 01 3 382 1 332 4 282 3 403 52 61 32 31 6
Output-133-1-133
6 seconds
256 megabytes
['brute force', 'data structures', 'dsu', 'graphs', 'sortings', '*2500']
C. The Values You Can Maketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.InputThe first line contains two integers n and k (1  ≀  n, k  ≀  500)Β β€” the number of coins and the price of the chocolate, respectively.Next line will contain n integers c1, c2, ..., cn (1 ≀ ci ≀ 500)Β β€” the values of Pari's coins.It's guaranteed that one can make value k using these coins.OutputFirst line of the output must contain a single integer qβ€” the number of suitable values x. Then print q integers in ascending orderΒ β€” the values that Arya can make for some subset of coins of Pari that pays for the chocolate.ExamplesInput6 185 6 1 10 12 2Output160 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18 Input3 5025 25 50Output30 25 50
Input6 185 6 1 10 12 2
Output160 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18
2 seconds
256 megabytes
['dp', '*1900']
B. Remainders Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value for any positive integer x?Note, that means the remainder of x after dividing it by y.InputThe first line of the input contains two integers n and k (1 ≀ n,  k ≀ 1 000 000)Β β€” the number of ancient integers and value k that is chosen by Pari.The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 1 000 000).OutputPrint "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.ExamplesInput4 52 3 5 12OutputYesInput2 72 3OutputNoNoteIn the first sample, Arya can understand because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7.
Input4 52 3 5 12
OutputYes
1 second
256 megabytes
['chinese remainder theorem', 'math', 'number theory', '*1800']
A. NP-Hard Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. or (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000)Β β€” the number of vertices and the number of edges in the prize graph, respectively.Each of the next m lines contains a pair of integers ui and vi (1  ≀  ui,  vi  ≀  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.OutputIf it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes).If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integersΒ β€” the indices of vertices. Note that because of m β‰₯ 1, vertex cover cannot be empty.ExamplesInput4 21 22 3Output12 21 3 Input3 31 22 31 3Output-1NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.
Input4 21 22 3
Output12 21 3
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1500']
B. Little Robber Girl's Zootime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.InputThe first line contains a single integer n (1 ≀ n ≀ 100)Β β€” number of animals in the robber girl's zoo.The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the height of the animal occupying the i-th place.OutputPrint the sequence of operations that will rearrange the animals by non-decreasing height.The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≀ li < ri ≀ n)Β β€” descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.The number of operations should not exceed 20 000.If the animals are arranged correctly from the start, you are allowed to output nothing.ExamplesInput42 1 4 3Output1 4Input736 28 57 39 66 69 68Output1 46 7Input51 2 1 2 1Output2 53 41 41 4NoteNote that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Input42 1 4 3
Output1 4
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'sortings', '*1100']
A. Free Ice Creamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.InputThe first line contains two space-separated integers n and x (1 ≀ n ≀ 1000, 0 ≀ x ≀ 109).Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1 ≀ di ≀ 109). Record "+ di" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record "- di" means that a child who wants to take di packs stands in i-th place.OutputPrint two space-separated integersΒ β€” number of ice cream packs left after all operations, and number of kids that left the house in distress.ExamplesInput5 7+ 5- 10- 20+ 40- 20Output22 1Input5 17- 16- 2- 98+ 100- 98Output3 2NoteConsider the first sample. Initially Kay and Gerda have 7 packs of ice cream. Carrier brings 5 more, so now they have 12 packs. A kid asks for 10 packs and receives them. There are only 2 packs remaining. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. Carrier bring 40 packs, now Kay and Gerda have 42 packs. Kid asks for 20 packs and receives them. There are 22 packs remaining.
Input5 7+ 5- 10- 20+ 40- 20
Output22 1
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*800']
E. Travelling Through the Snow Queen's Kingdomtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerda is travelling to the palace of the Snow Queen.The road network consists of n intersections and m bidirectional roads. Roads are numbered from 1 to m. Snow Queen put a powerful spell on the roads to change the weather conditions there. Now, if Gerda steps on the road i at the moment of time less or equal to i, she will leave the road exactly at the moment i. In case she steps on the road i at the moment of time greater than i, she stays there forever.Gerda starts at the moment of time l at the intersection number s and goes to the palace of the Snow Queen, located at the intersection number t. Moreover, she has to be there at the moment r (or earlier), before the arrival of the Queen.Given the description of the road network, determine for q queries li, ri, si and ti if it's possible for Gerda to get to the palace on time.InputThe first line of the input contains integers n, m and q (2 ≀ n ≀ 1000, 1 ≀ m, q ≀ 200 000)Β β€” the number of intersections in the road network of Snow Queen's Kingdom, the number of roads and the number of queries you have to answer.The i-th of the following m lines contains the description of the road number i. The description consists of two integers vi and ui (1 ≀ vi, ui ≀ n, vi ≠ ui)Β β€” the indices of the intersections connected by the i-th road. It's possible to get both from vi to ui and from ui to vi using only this road. Each pair of intersection may appear several times, meaning there are several roads connecting this pair.Last q lines contain the queries descriptions. Each of them consists of four integers li, ri, si and ti (1 ≀ li ≀ ri ≀ m, 1 ≀ si, ti ≀ n, si ≠ ti)Β β€” the moment of time Gerda starts her journey, the last moment of time she is allowed to arrive to the palace, the index of the starting intersection and the index of the intersection where palace is located.OutputFor each query print "Yes" (without quotes) if Gerda can be at the Snow Queen palace on time (not later than ri) or "No" (without quotes) otherwise.ExampleInput5 4 61 22 33 43 51 3 1 41 3 2 41 4 4 51 4 4 12 3 1 42 2 2 3OutputYesYesYesNoNoYes
Input5 4 61 22 33 43 51 3 1 41 3 2 41 4 4 51 4 4 12 3 1 42 2 2 3
OutputYesYesYesNoNoYes
1.5 seconds
256 megabytes
['bitmasks', 'brute force', 'divide and conquer', 'graphs', '*2800']
D. Kay and Eternitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSnow Queen told Kay to form a word "eternity" using pieces of ice. Kay is eager to deal with the task, because he will then become free, and Snow Queen will give him all the world and a pair of skates.Behind the palace of the Snow Queen there is an infinite field consisting of cells. There are n pieces of ice spread over the field, each piece occupying exactly one cell and no two pieces occupying the same cell. To estimate the difficulty of the task Kay looks at some squares of size k × k cells, with corners located at the corners of the cells and sides parallel to coordinate axis and counts the number of pieces of the ice inside them.This method gives an estimation of the difficulty of some part of the field. However, Kay also wants to estimate the total difficulty, so he came up with the following criteria: for each x (1 ≀ x ≀ n) he wants to count the number of squares of size k × k, such that there are exactly x pieces of the ice inside.Please, help Kay estimate the difficulty of the task given by the Snow Queen.InputThe first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 300)Β β€” the number of pieces of the ice and the value k, respectively. Each of the next n lines contains two integers xi and yi ( - 109 ≀ xi, yi ≀ 109)Β β€” coordinates of the cell containing i-th piece of the ice. It's guaranteed, that no two pieces of the ice occupy the same cell.OutputPrint n integers: the number of squares of size k × k containing exactly 1, 2, ..., n pieces of the ice.ExampleInput5 34 54 65 55 67 7Output10 8 1 4 0
Input5 34 54 65 55 67 7
Output10 8 1 4 0
2 seconds
256 megabytes
['brute force', 'implementation', 'sortings', '*2600']
C. Optimal Pointtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.Mole wants to find an optimal point to watch roses, that is such point with integer coordinates that the maximum Manhattan distance to the rose is minimum possible.As usual, he asks you to help.Manhattan distance between points (x1,  y1,  z1) and (x2,  y2,  z2) is defined as |x1 - x2| + |y1 - y2| + |z1 - z2|.InputThe first line of the input contains an integer t t (1 ≀ t ≀ 100 000)Β β€” the number of test cases. Then follow exactly t blocks, each containing the description of exactly one test.The first line of each block contains an integer ni (1 ≀ ni ≀ 100 000)Β β€” the number of roses in the test. Then follow ni lines, containing three integers eachΒ β€” the coordinates of the corresponding rose. Note that two or more roses may share the same position.It's guaranteed that the sum of all ni doesn't exceed 100 000 and all coordinates are not greater than 1018 by their absolute value.OutputFor each of t test cases print three integersΒ β€” the coordinates of the optimal point to watch roses. If there are many optimal answers, print any of them.The coordinates of the optimal point may coincide with the coordinates of any rose.ExamplesInput150 0 40 0 -40 4 04 0 01 1 1Output0 0 0Input213 5 923 5 93 5 9Output3 5 93 5 9NoteIn the first sample, the maximum Manhattan distance from the point to the rose is equal to 4.In the second sample, the maximum possible distance is 0. Note that the positions of the roses may coincide with each other and with the position of the optimal point.
Input150 0 40 0 -40 4 04 0 01 1 1
Output0 0 0
3 seconds
256 megabytes
['binary search', 'math', '*2900']
B. Kay and Snowflaketime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).InputThe first line of the input contains two integers n and q (2 ≀ n ≀ 300 000, 1 ≀ q ≀ 300 000)Β β€” the size of the initial tree and the number of queries respectively.The second line contains n - 1 integer p2, p3, ..., pn (1 ≀ pi ≀ n)Β β€” the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree.Each of the following q lines contain a single integer vi (1 ≀ vi ≀ n)Β β€” the index of the node, that define the subtree, for which we want to find a centroid.OutputFor each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.ExampleInput7 41 1 3 3 5 31235Output3236Note The first query asks for a centroid of the whole treeΒ β€” this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6Β β€” both answers are considered correct.
Input7 41 1 3 3 5 31235
Output3236
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'trees', '*1900']
A. Robbers' watchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRobbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches.First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hours, and each hour in m minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from 0 to n - 1, while the second has the smallest possible number of places that is necessary to display any integer from 0 to m - 1. Finally, if some value of hours or minutes can be displayed using less number of places in base 7 than this watches have, the required number of zeroes is added at the beginning of notation.Note that to display number 0 section of the watches is required to have at least one place.Little robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are distinct. Help her calculate this number.InputThe first line of the input contains two integers, given in the decimal notation, n and m (1 ≀ n, m ≀ 109)Β β€” the number of hours in one day and the number of minutes in one hour, respectively.OutputPrint one integer in decimal notationΒ β€” the number of different pairs of hour and minute, such that all digits displayed on the watches are distinct.ExamplesInput2 3Output4Input8 2Output5NoteIn the first sample, possible pairs are: (0: 1), (0: 2), (1: 0), (1: 2).In the second sample, possible pairs are: (02: 1), (03: 1), (04: 1), (05: 1), (06: 1).
Input2 3
Output4
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'math', '*1700']
J. The Hero with Bombstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a new computer game you need to help the hero to get out of the maze, which is a rectangular field of size n × m. The hero is located in one of the cells of this field. He knows where the exit of the maze is, and he wants to reach it.In one move, the hero can either move to the next cell (i.e. the cell which has a common side with the current cell) if it is free, or plant a bomb on the cell where he is, or skip the move and do nothing. A planted bomb explodes after three moves, that is, after the hero makes 3 more actions but does not have time to make the fourth (all three types of moves described above are considered as actions).The explosion destroys the obstacles in all the cells which have at least one common point with this cell (i.e. in all the cells sharing with the bomb cell a corner or a side). The explosion must not hurt the cell with the exit or the cell with the hero. The hero can not go beyond the boundaries of the maze.Your task is to determine the sequence of hero's actions to reach the exit. Note that you haven't to minimize the length of the sequence. The only restriction β€” the length of the resulting sequence should not exceed 100,000 symbols.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 100, nΒ·m > 1) β€” sizes of the maze.Each of the following n lines contains m characters β€” description of the maze. The character "." means a free cell, "E" β€” the hero, "T" β€” the exit, "X" β€” the obstacle.It is guaranteed that there is exactly one hero and exactly one exit in the maze.OutputPrint the hero's actions which will help him get out of the maze ("M" β€” to plant a bomb, "T" β€” to skip the move, "S" β€” to go down, "W" β€” to go left, "N" β€” to go up, "E" β€” to go right). If the hero can not reach the exit, print "No solution" (without quotes).The length of the resulting sequence should not exceed 100,000 symbols. If there are several solutions it is allowed to print any of them.ExampleInput3 5XEX.XX.XXTX.X.XOutputSSMNNTSSNEMWWTEEEE
Input3 5XEX.XX.XXTX.X.X
OutputSSMNNTSSNEMWWTEEEE
2 seconds
256 megabytes
['*special problem', '*3000']
I. Loadertime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA loader works in a warehouse, which is a rectangular field with size n × m. Some cells of this field are free, others are occupied by pillars on which the roof of the warehouse rests. There is a load in one of the free cells, and the loader in another. At any moment, the loader and the load can not be in the cells with columns, outside the warehouse or in the same cell.The loader can move to the adjacent cell (two cells are considered adjacent if they have a common side), or move the load. To move the load, the loader should reach the cell adjacent to the load and push the load. In this case the load advances to the next cell in the direction in which the loader pushes it and the loader ends up in the cell in which the load was.Your task is to determine a sequence of pushes and loader's movements after which the load will reach the given cell (it is guaranteed that this cell is free). The load is rather heavy, so you need to minimize first the number of pushes and second the number of loader's movements.InputThe first line contains two positive integers n and m (1 ≀ n, m ≀ 40, nΒ·m β‰₯ 3) β€” the number of rows and columns in the rectangular field.Each of the next n lines contains m characters β€” the description of the warehouse. If there is a character in the next cell of the warehouse: "X", it means, that the current cell contains the column; ".", it means, that the current cell is free; "Y", it means, that the loader is in the current cell; "B", it means, that the load is in the current cell; "T", it means, that the load should be moved to this cell. It is guaranteed that there is exactly one load, one loader and one cell to which the load should be moved.OutputIf the loader is not able to move the load to the given cell, print "NO" (without the quotes) in the first line of the output.Otherwise, print "YES" (without the quotes) in the first line of the output, and in the second line β€” the sequence of characters that determines movements and pushes of the loader. Characters w, e, n, s shall denote loader's moves to the west, east, north and south, respectively. Characters W, E, N, S must denote loader's pushes in the corresponding directions. First of all you need to minimize the number of pushes of the load and second, the number of movements of the loader. If there are several answers, you are allowed to print any of them.ExamplesInput3 3..Y.BX..TOutputYESwSwsEInput3 3.BY...TXXOutputNO
Input3 3..Y.BX..T
OutputYESwSwsE
4 seconds
256 megabytes
['*special problem', 'graphs', '*2500']
H. Exchange of Bookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn pupils, who love to read books, study at school. It is known that each student has exactly one best friend, and each pupil is the best friend of exactly one other pupil. Each of the pupils has exactly one interesting book.The pupils decided to share books with each other. Every day, all pupils give their own books to their best friends. Thus, every day each of the pupils has exactly one book.Your task is to use the list of the best friends and determine the exchange of books among pupils after k days. For simplicity, all students are numbered from 1 to n in all tests.InputThe first line contains two integers n and k (2 ≀ n ≀ 100000, 1 ≀ k ≀ 1016) β€” the number of pupils and days during which they will exchange books.The second line contains n different integers ai (1 ≀ ai ≀ n), where ai is equal to the number of the pupil who has the best friend with the number i.It is guaranteed that no pupil is the best friend of himself.OutputIn a single line print n different integers, where i-th integer should be equal to the number of the pupil who will have the book, which the pupil with the number i had in the beginning, after k days.ExamplesInput4 12 4 1 3Output3 1 4 2 Input5 53 4 5 2 1Output3 4 5 2 1 Input6 182 3 5 1 6 4Output1 2 3 4 5 6 NoteThe explanation to the first test.There are 4 pupils and 1 day. The list of the best friends equals to {2, 4, 1, 3}. It means that: the pupil with the number 3 β€” is the best friend of pupil with the number 1, the pupil with the number 1 β€” is the best friend of pupil with the number 2, the pupil with the number 4 β€” is the best friend of pupil with the number 3, the pupil with the number 2 β€” is the best friend of pupil with the number 4. After the first day the exchange of books will be {3, 1, 4, 2}. the pupil with the number 3 will have the book, which the pupil with the number 1 had in the beginning, the pupil with the number 1 will have the book, which the pupil with the number 2 had in the beginning, the pupil with the number 4 will have the book, which the pupil with the number 3 had in the beginning the pupil with the number 2 will have the book, which the pupil with the number 4 had in the beginning. Thus, the answer is 3 1 4 2.
Input4 12 4 1 3
Output3 1 4 2
1 second
256 megabytes
['*special problem', '*1900']
G. The Fractiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeriodic decimal fraction is usually written as: [entire_part.non-periodic_part (period)]. Any simple fraction can be represented as a periodic decimal fraction and vice versa. For example, the decimal fraction 0.2(45) corresponds to a fraction 27 / 110. Your task is to convert the periodic fraction to a simple periodic fraction.InputThe first line contains the periodic decimal fraction x (0 < x < 1) in the format described in the statement. The total number of digits in the period and non-periodic part of the fraction does not exceed 8. Non-periodic part may be absent, the periodic part can't be absent (but it can be equal to any non-negative number).OutputPrint the representation of the fraction x as a simple fraction p / q, where p and q are mutually prime integers.ExamplesInput0.2(45)Output27/110Input0.75(0)Output3/4
Input0.2(45)
Output27/110
1 second
256 megabytes
['*special problem', '*1900']
F. Reformat the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you are given a string s consisting of uppercase and lowercase Latin letters, spaces, dots and commas. Your task is to correct the formatting of this string by removing and inserting spaces, as well as changing the case of the letters.After formatting, the resulting string must meet the following requirements: the string must not start with a space; there should be exactly one space between any two consecutive words; there should be a Latin letter immediately before a dot or a comma, and there should be a space immediately after a dot or a comma in the case that there is a word after that dot or comma, otherwise that dot or comma must be the last character in the string; all letters must be lowercase, except all first letters in the first words of the sentences, they must be capitalized. The first word of a sentence is a word that is either the first word of the string or a word after a dot. It is guaranteed that there is at least one letter in the given string between any two punctuation marks (commas and dots are punctuation marks). There is at least one letter before the leftmost punctuation mark.InputThe first line contains a non-empty string s, consisting of uppercase and lowercase Latin letters, spaces, dots and commas. The length of the given string does not exceed 255. The string is guaranteed to have at least one character other than the space.OutputOutput the corrected string which meets all the requirements described in the statement.ExamplesInput hello ,i AM veRy GooD.BorisOutputHello, i am very good. BorisInput a. b, C . OutputA. B, c.
Input hello ,i AM veRy GooD.Boris
OutputHello, i am very good. Boris
1 second
256 megabytes
['*special problem', '*1800']
E. Hammer throwingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn athletes take part in the hammer throw. Each of them has his own unique identifier β€” the integer from 1 to n (all athletes have distinct identifiers). After the draw, the order in which the athletes will throw the hammer has been determined (they will do it one by one).Unfortunately, a not very attentive judge lost the list with the order of athletes, but each of the athletes has remembered how many competitors with identifiers larger than his own will throw the hammer before him.Your task is to help the organizers as quickly as possible to restore the order of the athletes.InputThe first line contains the positive integer n (1 ≀ n ≀ 1000) β€” the number of athletes.The next line contains the sequence of integers a1, a2, ..., an (0 ≀ ai < n), where ai is equal to the number of the athletes with identifiers larger than i, who should throw the hammer before the athlete with identifier i.OutputPrint n distinct numbers β€” the sequence of athletes' identifiers in the order in which they will throw the hammer. If there are several answers it is allowed to print any of them. ExamplesInput42 0 1 0Output2 4 1 3 Input62 2 0 1 1 0Output3 6 1 2 4 5
Input42 0 1 0
Output2 4 1 3
1 second
256 megabytes
['*special problem', '*1800']
D. Chocolate Bartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA chocolate bar has a rectangular shape and consists of n × m slices. In other words, a bar consists of n rows with m slices of chocolate in each row.Each slice of chocolate is known to weigh 1 gram. Your task is to determine for each of the q chocolate bars whether it is possible to obtain a piece weighing p grams by breaking the bar several (possibly zero) times. The final piece of the chocolate bar should be whole, and breaks are made along the line of slices' section for the whole length of the current piece.InputThe first line contains the positive integer q (1 ≀ q ≀ 100) β€” the number of chocolate bars. Each of the following q lines contains three positive integers n, m and p (1 ≀ n, m, p ≀ 1000) β€” the size of the chocolate bar, and the weight of the piece which should be obtained.OutputThe output should contain q lines and the i-th line must contain "Yes" (without the quotes), if it is possible to perform the task for i-th chocolate bar, or "No" otherwise.ExampleInput23 3 44 4 7OutputYesNo
Input23 3 44 4 7
OutputYesNo
1 second
256 megabytes
['*special problem', 'math', '*1400']
C. Symmetric Differencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two sets of numbers. Your task is to print all numbers from the sets, that both sets don't contain simultaneously.InputThe first line contains the description of the first set, the second line contains the description of the second set. Each description begins with the number of elements in this set. All elements of the set follow in the arbitrary order. In each set all elements are distinct and both sets are not empty. The number of elements in each set doesn't exceed 1000. All elements of the sets are integers from -1000 to 1000.OutputPrint the number of the required numbers and then the numbers themselves separated by a space.ExamplesInput3 1 2 33 2 3 4Output2 1 4Input5 1 4 8 9 104 1 2 8 10Output3 2 4 9
Input3 1 2 33 2 3 4
Output2 1 4
1 second
256 megabytes
['*special problem', '*1600']
B. The Teacher of Physical Educationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn pupils came to Physical Education lesson. We know the name and the height of each pupil. Your task is to help the teacher of Physical Education to line up all pupils in non-decreasing order of their heights.InputThe first line contains the positive integer n (1 ≀ n ≀ 5000) β€” the number of pupils.The next n lines contain the pupils' description. In the i-th line there is pupil's name namei (a non-empty string which consists of uppercase and lowercase Latin letters, the length does not exceed five) and pupil's height xi (130 ≀ xi ≀ 215). Some pupils can have the same name. Uppercase and lowercase letters of the alphabet should be considered different. OutputPrint n lines β€” pupils' names in the non-decreasing order of their heights. Each line must contain exactly one name. If there are several answers, print any of them. Uppercase and lowercase letters of the alphabet should be considered different. ExamplesInput4Ivan 150Igor 215Dasha 158Katya 150OutputIvanKatyaDashaIgorInput2SASHA 180SASHA 170OutputSASHASASHA
Input4Ivan 150Igor 215Dasha 158Katya 150
OutputIvanKatyaDashaIgor
1 second
256 megabytes
['*special problem', '*1600']
A. The Check of the Pointtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the coordinate plane there is a square with sides parallel to the coordinate axes. The length of the square side is equal to a. The lower left corner of the square coincides with the point (0, 0) (the point of the origin). The upper right corner of the square has positive coordinates.You are given a point with coordinates (x, y). Your task is to determine whether this point is located strictly inside the square, on its side, or strictly outside the square.InputThe first line contains three integers a, x and y (1 ≀ a ≀ 1000,  - 1000 ≀ x, y ≀ 1000) β€” the length of the square side and the coordinates of the point which should be checked.OutputPrint one integer: 0, if the point is located strictly inside the square; 1, if the point is located on the side of the square; 2, if the point is located strictly outside the square. ExamplesInput2 1 1Output0Input4 4 4Output1Input10 5 -4Output2
Input2 1 1
Output0
1 second
256 megabytes
['*special problem', 'geometry', '*1200']
E. Alyona and Trianglestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.InputIn the first line of the input two integers n and S (3 ≀ n ≀ 5000, 1 ≀ S ≀ 1018) are givenΒ β€” the number of points given and the upper bound value of any triangle's area, formed by any three of given n points.The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≀ xi, yi ≀ 108)Β β€” coordinates of ith point.It is guaranteed that there is at least one triple of points not lying on the same line.OutputPrint the coordinates of three pointsΒ β€” vertices of a triangle which contains all n points and which area doesn't exceed 4S.Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value.It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.ExampleInput4 10 01 00 11 1Output-1 02 00 2Note
Input4 10 01 00 11 1
Output-1 02 00 2
3 seconds
256 megabytes
['geometry', 'two pointers', '*2600']
D. Alyona and Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants.Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.A substring of a string is a subsequence of consecutive characters of the string.InputIn the first line of the input three integers n, m, k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 10) are givenΒ β€” the length of the string s, the length of the string t and Alyona's favourite number respectively.The second line of the input contains string s, consisting of lowercase English letters.The third line of the input contains string t, consisting of lowercase English letters.OutputIn the only line print the only non-negative integerΒ β€” the sum of the lengths of the strings in a desired sequence.It is guaranteed, that at least one desired sequence exists.ExamplesInput3 2 2abcabOutput2Input9 12 4bbaaababbabbbabbaaabaOutput7NoteThe following image describes the answer for the second sample case:
Input3 2 2abcab
Output2
2 seconds
256 megabytes
['dp', 'strings', '*1900']
C. Alyona and the Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β€” root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?InputIn the first line of the input integer n (1 ≀ n ≀ 105) is givenΒ β€” the number of vertices in the tree.In the second line the sequence of n integers a1, a2, ..., an (1 ≀ ai ≀ 109) is given, where ai is the number written on vertex i.The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≀ pi ≀ n,  - 109 ≀ ci ≀ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.OutputPrint the only integerΒ β€” the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.ExampleInput988 22 83 14 95 91 98 53 113 247 -81 671 649 655 126 -803 8Output5NoteThe following image represents possible process of removing leaves from the tree:
Input988 22 83 14 95 91 98 53 113 247 -81 671 649 655 126 -803 8
Output5
1 second
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*1600']
B. Alyona and Mextime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSomeone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1, b2, ..., bn such that 1 ≀ bi ≀ ai for every 1 ≀ i ≀ n. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of elements in the Alyona's array.The second line of the input contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the elements of the array.OutputPrint one positive integerΒ β€” the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.ExamplesInput51 3 3 3 6Output5Input22 1Output3NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements.
Input51 3 3 3 6
Output5
1 second
256 megabytes
['sortings', '*1200']
A. Alyona and Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integersΒ β€” the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5.Formally, Alyona wants to count the number of pairs of integers (x, y) such that 1 ≀ x ≀ n, 1 ≀ y ≀ m and equals 0.As usual, Alyona has some troubles and asks you to help.InputThe only line of the input contains two integers n and m (1 ≀ n, m ≀ 1 000 000).OutputPrint the only integerΒ β€” the number of pairs of integers (x, y) such that 1 ≀ x ≀ n, 1 ≀ y ≀ m and (x + y) is divisible by 5.ExamplesInput6 12Output14Input11 14Output31Input1 5Output1Input3 8Output5Input5 7Output7Input21 21Output88NoteFollowing pairs are suitable in the first sample case: for x = 1 fits y equal to 4 or 9; for x = 2 fits y equal to 3 or 8; for x = 3 fits y equal to 2, 7 or 12; for x = 4 fits y equal to 1, 6 or 11; for x = 5 fits y equal to 5 or 10; for x = 6 fits y equal to 4 or 9. Only the pair (1, 4) is suitable in the third sample case.
Input6 12
Output14
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1100']
E. Runaway to a Shadowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima is living in a dormitory, as well as some cockroaches.At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly T seconds for aiming, and after that he will precisely strike the cockroach and finish it.To survive the cockroach has to run into a shadow, cast by round plates standing on the table, in T seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed v. If at some moment t ≀ T it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.Determine the probability of that the cockroach will stay alive.InputIn the first line of the input the four integers x0, y0, v, T (|x0|, |y0| ≀ 109, 0 ≀ v, T ≀ 109) are givenΒ β€” the cockroach initial position on the table in the Cartesian system at the moment 0, the cockroach's constant speed and the time in seconds Dima needs for aiming respectively.In the next line the only number n (1 ≀ n ≀ 100 000) is givenΒ β€” the number of shadow circles casted by plates.In the next n lines shadow circle description is given: the ith of them consists of three integers xi, yi, ri (|xi|, |yi| ≀ 109, 0 ≀ r ≀ 109)Β β€” the ith shadow circle on-table position in the Cartesian system and its radius respectively.Consider that the table is big enough for the cockroach not to run to the table edges and avoid Dima's precise strike.OutputPrint the only real number pΒ β€” the probability of that the cockroach will stay alive.Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.ExamplesInput0 0 1 131 1 1-1 -1 1-2 2 1Output0.50000000000Input0 0 1 011 0 1Output1.00000000000NoteThe picture for the first sample is given below. Red color stands for points which being chosen as the cockroach's running direction will cause him being killed, green color for those standing for survival directions. Please note that despite containing a circle centered in ( - 2, 2) a part of zone is colored red because the cockroach is not able to reach it in one second.
Input0 0 1 131 1 1-1 -1 1-2 2 1
Output0.50000000000
1 second
256 megabytes
['geometry', 'sortings', '*2500']
D. Gifts by the Listtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.Each man has at most one father but may have arbitrary number of sons.Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied: A = B; the man number A is the father of the man number B; there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B. Of course, if the man number A is an ancestor of the man number B and A ≠ B, then the man number B is not an ancestor of the man number A.The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens. A list of candidates is prepared, containing some (possibly all) of the n men in some order. Each of the n men decides to give a gift. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone. This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?InputIn the first line of the input two integers n and m (0 ≀ m < n ≀ 100 000) are givenΒ β€” the number of the men in the Sasha's family and the number of family relations in it respectively.The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 ≀ pi, qi ≀ n, pi ≠ qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 ≀ i ≀ n the man numbered ai is an ancestor of the man numbered i.OutputPrint an integer k (1 ≀ k ≀ n)Β β€” the number of the men in the list of candidates, in the first line.Print then k pairwise different positive integers not exceeding n β€” the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.If there are more than one appropriate lists, print any of them. If there is no appropriate list print  - 1 in the only line.ExamplesInput3 21 22 31 2 1Output-1Input4 21 23 41 2 3 3Output3213NoteThe first sample explanation: if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1); if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2); if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2). if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1).
Input3 21 22 31 2 1
Output-1
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'trees', '*2000']
C. Heap Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has recently learned data structure named "Binary heap".The heap he is now operating with allows the following operations: put the given number into the heap; get the value of the minimum element in the heap; extract the minimum element from the heap; Thus, at any moment of time the heap contains several integers (possibly none), some of them might be equal.In order to better learn this data structure Petya took an empty heap and applied some operations above to it. Also, he carefully wrote down all the operations and their results to his event log, following the format: insert xΒ β€” put the element with value x in the heap; getMin xΒ β€” the value of the minimum element contained in the heap was equal to x; removeMinΒ β€” the minimum element was extracted from the heap (only one instance, if there were many). All the operations were correct, i.e. there was at least one element in the heap each time getMin or removeMin operations were applied.While Petya was away for a lunch, his little brother Vova came to the room, took away some of the pages from Petya's log and used them to make paper boats.Now Vova is worried, if he made Petya's sequence of operations inconsistent. For example, if one apply operations one-by-one in the order they are written in the event log, results of getMin operations might differ from the results recorded by Petya, and some of getMin or removeMin operations may be incorrect, as the heap is empty at the moment they are applied.Now Vova wants to add some new operation records to the event log in order to make the resulting sequence of operations correct. That is, the result of each getMin operation is equal to the result in the record, and the heap is non-empty when getMin ad removeMin are applied. Vova wants to complete this as fast as possible, as the Petya may get back at any moment. He asks you to add the least possible number of operation records to the current log. Note that arbitrary number of operations may be added at the beginning, between any two other operations, or at the end of the log.InputThe first line of the input contains the only integer n (1 ≀ n ≀ 100 000)Β β€” the number of the records left in Petya's journal.Each of the following n lines describe the records in the current log in the order they are applied. Format described in the statement is used. All numbers in the input are integers not exceeding 109 by their absolute value.OutputThe first line of the output should contain a single integer mΒ β€” the minimum possible number of records in the modified sequence of operations.Next m lines should contain the corrected sequence of records following the format of the input (described in the statement), one per line and in the order they are applied. All the numbers in the output should be integers not exceeding 109 by their absolute value.Note that the input sequence of operations must be the subsequence of the output sequence.It's guaranteed that there exists the correct answer consisting of no more than 1 000 000 operations.ExamplesInput2insert 3getMin 4Output4insert 3removeMininsert 4getMin 4Input4insert 1insert 1removeMingetMin 2Output6insert 1insert 1removeMinremoveMininsert 2getMin 2NoteIn the first sample, after number 3 is inserted into the heap, the minimum number is 3. To make the result of the first getMin equal to 4 one should firstly remove number 3 from the heap and then add number 4 into the heap.In the second sample case number 1 is inserted two times, so should be similarly removed twice.
Input2insert 3getMin 4
Output4insert 3removeMininsert 4getMin 4
1 second
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1600']
B. Economy Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to 0.Kolya remembers that at the beginning of the game his game-coin score was equal to n and that he have bought only some houses (for 1 234 567 game-coins each), cars (for 123 456 game-coins each) and computers (for 1 234 game-coins each).Kolya is now interested, whether he could have spent all of his initial n game-coins buying only houses, cars and computers or there is a bug in the game. Formally, is there a triple of non-negative integers a, b and c such that a × 1 234 567 + b × 123 456 + c × 1 234 = n?Please help Kolya answer this question.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 109)Β β€” Kolya's initial game-coin score.OutputPrint "YES" (without quotes) if it's possible that Kolya spent all of his initial n coins buying only houses, cars and computers. Otherwise print "NO" (without quotes).ExamplesInput1359257OutputYESInput17851817OutputNONoteIn the first sample, one of the possible solutions is to buy one house, one car and one computer, spending 1 234 567 + 123 456 + 1234 = 1 359 257 game-coins in total.
Input1359257
OutputYES
1 second
256 megabytes
['brute force', '*1300']
A. A Good Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCodeforces user' handle color depends on his ratingΒ β€” it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100)Β β€” the number of participants Anton has outscored in this contest .The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri ( - 4000 ≀ beforei, afteri ≀ 4000)Β β€” participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters Β«_Β» and Β«-Β» characters.It is guaranteed that all handles are distinct.OutputPrint Β«YESΒ» (quotes for clarity), if Anton has performed good in the contest and Β«NOΒ» (quotes for clarity) otherwise.ExamplesInput3Burunduk1 2526 2537BudAlNik 2084 2214subscriber 2833 2749OutputYESInput3Applejack 2400 2400Fluttershy 2390 2431Pinkie_Pie -2500 -2450OutputNONoteIn the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest.
Input3Burunduk1 2526 2537BudAlNik 2084 2214subscriber 2833 2749
OutputYES
1 second
256 megabytes
['implementation', '*800']
B. Bear and Finding Criminalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Bearland, numbered 1 through n. Cities are arranged in one long row. The distance between cities i and j is equal to |i - j|.Limak is a police officer. He lives in a city a. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he knows that there is at most one criminal in each city.Limak is going to use a BCD (Bear Criminal Detector). The BCD will tell Limak how many criminals there are for every distance from a city a. After that, Limak can catch a criminal in each city for which he is sure that there must be a criminal.You know in which cities criminals are. Count the number of criminals Limak will catch, after he uses the BCD.InputThe first line of the input contains two integers n and a (1 ≀ a ≀ n ≀ 100)Β β€” the number of cities and the index of city where Limak lives.The second line contains n integers t1, t2, ..., tn (0 ≀ ti ≀ 1). There are ti criminals in the i-th city.OutputPrint the number of criminals Limak will catch.ExamplesInput6 31 1 1 0 1 0Output3Input5 20 0 0 1 0Output1NoteIn the first sample, there are six cities and Limak lives in the third one (blue arrow below). Criminals are in cities marked red. Using the BCD gives Limak the following information: There is one criminal at distance 0 from the third cityΒ β€” Limak is sure that this criminal is exactly in the third city. There is one criminal at distance 1 from the third cityΒ β€” Limak doesn't know if a criminal is in the second or fourth city. There are two criminals at distance 2 from the third cityΒ β€” Limak is sure that there is one criminal in the first city and one in the fifth city. There are zero criminals for every greater distance. So, Limak will catch criminals in cities 1, 3 and 5, that is 3 criminals in total.In the second sample (drawing below), the BCD gives Limak the information that there is one criminal at distance 2 from Limak's city. There is only one city at distance 2 so Limak is sure where a criminal is.
Input6 31 1 1 0 1 0
Output3
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1000']
A. Bear and Five Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.He is allowed to at most once discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number.Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?InputThe only line of the input contains five integers t1, t2, t3, t4 and t5 (1 ≀ ti ≀ 100)Β β€” numbers written on cards.OutputPrint the minimum possible sum of numbers written on remaining cards.ExamplesInput7 3 7 3 20Output26Input7 9 3 1 8Output28Input10 10 10 10 10Output20NoteIn the first sample, Limak has cards with numbers 7, 3, 7, 3 and 20. Limak can do one of the following. Do nothing and the sum would be 7 + 3 + 7 + 3 + 20 = 40. Remove two cards with a number 7. The remaining sum would be 3 + 3 + 20 = 26. Remove two cards with a number 3. The remaining sum would be 7 + 7 + 20 = 34. You are asked to minimize the sum so the answer is 26.In the second sample, it's impossible to find two or three cards with the same number. Hence, Limak does nothing and the sum is 7 + 9 + 1 + 3 + 8 = 28.In the third sample, all cards have the same number. It's optimal to discard any three cards. The sum of two remaining numbers is 10 + 10 = 20.
Input7 3 7 3 20
Output26
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*800']
E. Bear and Bad Powers of 42time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak, a bear, isn't good at handling queries. So, he asks you to do it.We say that powers of 42 (numbers 1, 42, 1764, ...) are bad. Other numbers are good.You are given a sequence of n good integers t1, t2, ..., tn. Your task is to handle q queries of three types: 1 iΒ β€” print ti in a separate line. 2 a b xΒ β€” for set ti to x. It's guaranteed that x is a good number. 3 a b xΒ β€” for increase ti by x. After this repeat the process while at least one ti is bad. You can note that after each query all ti are good.InputThe first line of the input contains two integers n and q (1 ≀ n, q ≀ 100 000)Β β€” the size of Limak's sequence and the number of queries, respectively.The second line of the input contains n integers t1, t2, ..., tn (2 ≀ ti ≀ 109)Β β€” initial elements of Limak's sequence. All ti are good.Then, q lines follow. The i-th of them describes the i-th query. The first number in the line is an integer typei (1 ≀ typei ≀ 3)Β β€” the type of the query. There is at least one query of the first type, so the output won't be empty.In queries of the second and the third type there is 1 ≀ a ≀ b ≀ n.In queries of the second type an integer x (2 ≀ x ≀ 109) is guaranteed to be good.In queries of the third type an integer x (1 ≀ x ≀ 109) may be bad.OutputFor each query of the first type, print the answer in a separate line.ExampleInput6 1240 1700 7 1672 4 17223 2 4 421 21 33 2 6 501 21 41 62 3 4 413 1 5 11 11 31 5Output1742491842181418224344107NoteAfter a query 3 2 4 42 the sequence is 40, 1742, 49, 1714, 4, 1722.After a query 3 2 6 50 the sequence is 40, 1842, 149, 1814, 104, 1822.After a query 2 3 4 41 the sequence is 40, 1842, 41, 41, 104, 1822.After a query 3 1 5 1 the sequence is 43, 1845, 44, 44, 107, 1822.
Input6 1240 1700 7 1672 4 17223 2 4 421 21 33 2 6 501 21 41 62 3 4 413 1 5 11 11 31 5
Output1742491842181418224344107
5 seconds
256 megabytes
['data structures', '*3100']
D. Bear and Chasetime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBearland has n cities, numbered 1 through n. There are m bidirectional roads. The i-th road connects two distinct cities ai and bi. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).The distance between cities a and b is defined as the minimum number of roads used to travel between a and b.Limak is a grizzly bear. He is a criminal and your task is to catch him, or at least to try to catch him. You have only two days (today and tomorrow) and after that Limak is going to hide forever.Your main weapon is BCD (Bear Criminal Detector). Where you are in some city, you can use BCD and it tells you the distance between you and a city where Limak currently is. Unfortunately, BCD can be used only once a day.You don't know much about Limak's current location. You assume that he is in one of n cities, chosen uniformly at random (each city with probability ). You decided for the following plan: Choose one city and use BCD there. After using BCD you can try to catch Limak (but maybe it isn't a good idea). In this case you choose one city and check it. You win if Limak is there. Otherwise, Limak becomes more careful and you will never catch him (you loose). Wait 24 hours to use BCD again. You know that Limak will change his location during that time. In detail, he will choose uniformly at random one of roads from his initial city, and he will use the chosen road, going to some other city. Tomorrow, you will again choose one city and use BCD there. Finally, you will try to catch Limak. You will choose one city and check it. You will win if Limak is there, and loose otherwise. Each time when you choose one of cities, you can choose any of n cities. Let's say it isn't a problem for you to quickly get somewhere.What is the probability of finding Limak, if you behave optimally?InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 400, )Β β€” the number of cities and the number of roads, respectively.Then, m lines follow. The i-th of them contains two integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi)Β β€” cities connected by the i-th road.No two roads connect the same pair of cities. It's possible to get from any city to any other city.OutputPrint one real numberΒ β€” the probability of finding Limak, if you behave optimally. Your answer will be considered correct if its absolute 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 |a - b| ≀ 10 - 6.ExamplesInput3 31 21 32 3Output0.833333333333Input5 41 23 15 11 4Output1.000000000000Input4 41 21 32 31 4Output0.916666666667Input5 51 22 33 44 51 5Output0.900000000000NoteIn the first sample test, there are three cities and there is a road between every pair of cities. Let's analyze one of optimal scenarios. Use BCD in city 1. With probability Limak is in this city and BCD tells you that the distance is 0. You should try to catch him now and you win for sure. With probability the distance is 1 because Limak is in city 2 or city 3. In this case you should wait for the second day. You wait and Limak moves to some other city. There is probability that Limak was in city 2 and then went to city 3. that he went from 2 to 1. that he went from 3 to 2. that he went from 3 to 1. Use BCD again in city 1 (though it's allowed to use it in some other city). If the distance is 0 then you're sure Limak is in this city (you win). If the distance is 1 then Limak is in city 2 or city 3. Then you should guess that he is in city 2 (guessing city 3 would be fine too). You loose only if Limak was in city 2 first and then he moved to city 3. The probability of loosing is . The answer is .
Input3 31 21 32 3
Output0.833333333333
7 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'implementation', 'math', 'probabilities', '*2900']
C. Bear and Square Gridtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a grid with n rows and n columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X').Two empty cells are directly connected if they share a side. Two cells (r1, c1) (located in the row r1 and column c1) and (r2, c2) are connected if there exists a sequence of empty cells that starts with (r1, c1), finishes with (r2, c2), and any two consecutive cells in this sequence are directly connected. A connected component is a set of empty cells such that any two cells in the component are connected, and there is no cell in this set that is connected to some cell not in this set.Your friend Limak is a big grizzly bear. He is able to destroy any obstacles in some range. More precisely, you can choose a square of size k × k in the grid and Limak will transform all blocked cells there to empty ones. However, you can ask Limak to help only once.The chosen square must be completely inside the grid. It's possible that Limak won't change anything because all cells are empty anyway.You like big connected components. After Limak helps you, what is the maximum possible size of the biggest connected component in the grid?InputThe first line of the input contains two integers n and k (1 ≀ k ≀ n ≀ 500)Β β€” the size of the grid and Limak's range, respectively.Each of the next n lines contains a string with n characters, denoting the i-th row of the grid. Each character is '.' or 'X', denoting an empty cell or a blocked one, respectively.OutputPrint the maximum possible size (the number of cells) of the biggest connected component, after using Limak's help.ExamplesInput5 2..XXXXX.XXX.XXXX...XXXXX.Output10Input5 3......XXX..XXX..XXX......Output25NoteIn the first sample, you can choose a square of size 2 × 2. It's optimal to choose a square in the red frame on the left drawing below. Then, you will get a connected component with 10 cells, marked blue in the right drawing.
Input5 2..XXXXX.XXX.XXXX...XXXXX.
Output10
3 seconds
256 megabytes
['dfs and similar', 'dsu', 'implementation', '*2400']
B. Bear and Tower of Cubestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.Limak is going to build a tower. First, he asks you to tell him a positive integer XΒ β€” the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≀ m that results this number of blocks.InputThe only line of the input contains one integer m (1 ≀ m ≀ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.OutputPrint two integersΒ β€” the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.ExamplesInput48Output9 42Input6Output6 6NoteIn the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.In more detail, after choosing X = 42 the process of building a tower is: Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15. The second added block has side 2, so the remaining volume is 15 - 8 = 7. Finally, Limak adds 7 blocks with side 1, one by one. So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7Β·13 = 27 + 8 + 7 = 42.
Input48
Output9 42
2 seconds
256 megabytes
['binary search', 'dp', 'greedy', '*2200']
A. Bear and Prime 100time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden numberΒ β€” an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).InputAfter each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.OutputUp to 20 times you can ask a queryΒ β€” print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input.In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program.To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. Hacking. To hack someone, as the input you should print the hidden numberΒ β€” one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.ExamplesInputyesnoyesOutput2805compositeInputnoyesnononoOutput585978782primeNoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).
Inputyesnoyes
Output2805composite
1 second
256 megabytes
['constructive algorithms', 'interactive', 'math', '*1400']
F. Lena and Queriestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLena is a programmer. She got a task to solve at work.There is an empty set of pairs of integers and n queries to process. Each query is one of three types: Add a pair (a, b) to the set. Remove a pair added in the query number i. All queries are numbered with integers from 1 to n. For a given integer q find the maximal value xΒ·q + y over all pairs (x, y) from the set. Help Lena to process the queries.InputThe first line of input contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of queries.Each of the next n lines starts with integer t (1 ≀ t ≀ 3) β€” the type of the query.A pair of integers a and b ( - 109 ≀ a, b ≀ 109) follows in the query of the first type.An integer i (1 ≀ i ≀ n) follows in the query of the second type. It is guaranteed that i is less than the number of the query, the query number i has the first type and the pair from the i-th query is not already removed.An integer q ( - 109 ≀ q ≀ 109) follows in the query of the third type.OutputFor the queries of the third type print on a separate line the desired maximal value of xΒ·q + y.If there are no pairs in the set print "EMPTY SET".ExampleInput73 11 2 33 11 -1 1003 12 43 1OutputEMPTY SET5995
Input73 11 2 33 11 -1 1003 12 43 1
OutputEMPTY SET5995
4 seconds
256 megabytes
['data structures', 'divide and conquer', 'geometry', '*2500']
E. Another Sith Tournamenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.InputThe first line contains a single integer n (1 ≀ n ≀ 18)Β β€” the number of participants of the Sith Tournament.Each of the next n lines contains n real numbers, which form a matrix pij (0 ≀ pij ≀ 1). Each its element pij is the probability that the i-th participant defeats the j-th in a duel.The elements on the main diagonal pii are equal to zero. For all different i, j the equality pij + pji = 1 holds. All probabilities are given with no more than six decimal places.Jedi Ivan is the number 1 in the list of the participants.OutputOutput a real numberΒ β€” the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10 - 6.ExamplesInput30.0 0.5 0.80.5 0.0 0.40.2 0.6 0.0Output0.680000000000000
Input30.0 0.5 0.80.5 0.0 0.40.2 0.6 0.0
Output0.680000000000000
2.5 seconds
256 megabytes
['bitmasks', 'dp', 'math', 'probabilities', '*2200']
D. Iterated Linear Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a linear function f(x) = Ax + B. Let's define g(0)(x) = x and g(n)(x) = f(g(n - 1)(x)) for n > 0. For the given integer values A, B, n and x find the value of g(n)(x) modulo 109 + 7.InputThe only line contains four integers A, B, n and x (1 ≀ A, B, x ≀ 109, 1 ≀ n ≀ 1018) β€” the parameters from the problem statement.Note that the given value n can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.OutputPrint the only integer s β€” the value g(n)(x) modulo 109 + 7.ExamplesInput3 4 1 1Output7Input3 4 2 1Output25Input3 4 3 1Output79
Input3 4 1 1
Output7
1 second
256 megabytes
['math', 'number theory', '*1700']
C. Joty and Chocolatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a and b can be either painted Red or Blue.After her painting is done, she will get p chocolates for each tile that is painted Red and q chocolates for each tile that is painted Blue.Note that she can paint tiles in any order she wants.Given the required information, find the maximumΒ number of chocolates Joty can get.InputThe only line contains five integers n, a, b, p and q (1 ≀ n, a, b, p, q ≀ 109).OutputPrint the only integer s β€” the maximum number of chocolates Joty can get.Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.ExamplesInput5 2 3 12 15Output39Input20 2 3 3 5Output51
Input5 2 3 12 15
Output39
1 second
256 megabytes
['implementation', 'math', 'number theory', '*1600']