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
A. Even Substringstime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s=s_1s_2\dots s_n of length n, which only contains digits 1, 2, ..., 9.A substring s[l \dots r] of s is a string s_l s_{l + 1} s_{l + 2} \ldots s_r. A substring s[l \dots r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some substrings are equal as strings, but have different l and r, they are counted as different substrings.InputThe first line contains an integer n (1 \le n \le 65000) — the length of the string s.The second line contains a string s of length n. The string s consists only of digits 1, 2, ..., 9.OutputPrint the number of even substrings of s.ExamplesInput 4 1234 Output 6Input 4 2244 Output 10NoteIn the first example, the [l, r] pairs corresponding to even substrings are: s[1 \dots 2] s[2 \dots 2] s[1 \dots 4] s[2 \dots 4] s[3 \dots 4] s[4 \dots 4] In the second example, all 10 substrings of s are even substrings. Note, that while substrings s[1 \dots 1] and s[2 \dots 2] both define the substring "2", they are still counted as different substrings.
4 1234
6
0.5 seconds
256 megabytes
['implementation', 'strings', '*800']
B. Circustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0).Split the artists into two performances in such a way that: each artist plays in exactly one performance, the number of artists in the two performances is equal (i.e. equal to \frac{n}{2}), the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. InputThe first line contains a single integer n (2 \le n \le 5\,000, n is even) — the number of artists in the troupe.The second line contains n digits c_1 c_2 \ldots c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise.The third line contains n digits a_1 a_2 \ldots a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise.OutputPrint \frac{n}{2} distinct integers — the indices of the artists that should play in the first performance.If there are multiple answers, print any.If there is no solution, print a single integer -1.ExamplesInput 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 NoteIn the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well.In the second example, the division is not possible.In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
4 0011 0101
1 4
1 second
256 megabytes
['brute force', 'greedy', 'math', 'strings', '*1800']
A. Sushi for Twotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from the left sushi as t_i, where t_i = 1 means it is with tuna, and t_i = 2 means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment [2, 2, 2, 1, 1, 1] is valid, but subsegment [1, 2, 1, 2, 1, 2] is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.InputThe first line contains a single integer n (2 \le n \le 100\,000) — the number of pieces of sushi.The second line contains n integers t_1, t_2, ..., t_n (t_i = 1, denoting a sushi with tuna or t_i = 2, denoting a sushi with eel), representing the types of sushi from left to right.It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.OutputPrint a single integer — the maximum length of a valid continuous segment.ExamplesInput 7 2 2 2 1 1 2 2 Output 4 Input 6 1 2 1 2 1 2 Output 2 Input 9 2 2 1 1 1 2 2 2 2 Output 6 NoteIn the first example Arkady can choose the subsegment [2, 2, 1, 1] or the subsegment [1, 1, 2, 2] with length 4.In the second example there is no way but to choose one of the subsegments [2, 1] or [1, 2] with length 2.In the third example Arkady's best choice is the subsegment [1, 1, 1, 2, 2, 2].
7 2 2 2 1 1 2 2
4
1 second
256 megabytes
['binary search', 'greedy', 'implementation', '*900']
F. Matches Are Not a Child's Play time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLena is playing with matches. The natural question arising in the head of any child playing with matches is whether it's possible to set a tree on fire with a matches, or not.Let's say, that the tree is a connected graph without cycles and the vertices are labeled with integers 1, 2, \ldots, n. Also every vertex v has some integer priority p_v associated with it. All priorities are distinct.It turns out, that if you set a tree on fire, it will burn to nothing. However, this process doesn't happen instantly. At the beginning, burns out the leaf (a vertex is called to be a leaf if it has only one adjacent vertex) of the tree of the minimum priority. Then burns out the leaf of the minimal priority of the remaining tree, and so on. This way, the vertices turn into the leaves and burn out until only one vertex remains. Then this vertex burns out as well.Lena has prepared a tree of n vertices and every vertex in it has a priority p_v = v. Lena is very curious about burning out this tree. However, she understands, that if she will burn the tree now, then it will disappear completely. Lena is a kind girl and she will feel bad for the burned tree, so she wants to study the process of burning the tree only in her mind. Lena wants to process q queries, each of them is one of three following types: "up v", assign the vertex v priority 1 + \max\{p_1, p_2, \ldots, p_n\}; "when v", find the step at which the vertex v will burn out, if the tree would be set on fire now; "compare v u", find out which of the vertices v and u will burn out first, if the tree would be set on fire now. Notice, that if all priorities would be distinct, then after the "up" query they will stay distinct as well. Initially all priorities are distinct, hence during any (purely hypothetical of course) burning of the tree, all leafs would have distinct priorities.InputThe first line contains two integers n and q (2 \le n \le 200\,000, 1 \le q \le 200\,000) — the number of vertices in the tree and the number of queries.The i-th of the following n - 1 lines contains two integers v_i, u_i (1 \le v_i, u_i \le n), denoting the endpoints of the i-th edge.Each of the remaining q lines contains a query of one of the following three types: "up v" (1 \le v \le n) — change the priority of vertex v; "when v" (1 \le v \le n) — determine the step at which the vertex v will burn out; "compare v u" (1 \le v, u \le n, v \ne u) — determine which of vertices v and u will burn out earlier in the current tree. It's guaranteed, that there is at least one query of type "when" or "compare".OutputFor every query of type "when" print one integer in range from 1 to n — the step at which the vertex v will burn out.For every query of type "compare" print either v or u, depending on which one will burn out earlier.ExamplesInput 5 7 1 5 1 2 1 3 4 3 when 1 when 2 when 3 when 4 when 5 compare 2 3 compare 3 4 Output 4 1 3 2 5 2 4 Input 5 5 1 5 1 2 1 3 4 3 up 1 compare 2 4 compare 4 3 compare 3 1 compare 1 5 Output 2 4 3 5 NoteIn the first example, the process of burning of the tree is illustrated on the following picture: In particular, the vertices of the tree will burn out in the following order: [2, 4, 3, 1, 5].In the second example, after applying the "up" operation, the order of vertices will change to: [2, 4, 3, 5, 1].
5 7 1 5 1 2 1 3 4 3 when 1 when 2 when 3 when 4 when 5 compare 2 3 compare 3 4
4 1 3 2 5 2 4
4 seconds
512 megabytes
['data structures', 'trees', '*3400']
E. Train Car Selectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya likes to travel by train, but doesn't like when the car he travels in is located in the tail of the train.Vasya gets on the train at the station. The train consists of n cars indexed from 1 to n counting from the locomotive (head of the train). Three types of events occur while the train is moving: Some number of cars are added to the head of the train; Some number of cars are added to the tail of the train; Vasya recalculates the values of the convenience of the cars (read more about it below). At each moment of time we will index the cars from the head of the train, starting from 1. Note that when adding new cars to the head of the train, the indexing of the old ones may shift.To choose which car to go in, Vasya will use the value A_i for each car (where i is a car index), which is calculated as follows: At the beginning of the trip A_i=0, as well as for the new cars at the time of their addition. During the next recalculation Vasya chooses some positive integers b and s and adds to all A_i value b + (i - 1) \cdot s. Vasya hasn't decided yet where he will get on the train and where will get off the train, so after each event of one of the three types he wants to know the least index of the car, such that its value A_i is minimal. Since there is a lot of cars, Vasya asked you to write a program that answers his question.InputThe first line contains two integers n and m (1 \leq n \leq 10^9, 1 \leq m \leq 300\,000), the number of cars in the train at the time of departure from the station and the number of stations, respectively.Next m lines contain the descriptions of events. Each event is one of the following three types: "1 k" (1 \le k \le 10^9), add k cars to the head of the train "2 k" (1 \le k \le 10^9), add k cars to the tail of the train "3 b s" (1 \le b, s \le 10^9), recalculate the convenience of all train cars. It is guaranteed that at any time the train length does not exceed 10^9. Also it's guaranteed that the integers A_i will not grow too high. Formally, it's guaranteed that if we sum the largest addition over all events of the 3-rd type (that is, b + (n - 1) \cdot s, where n is the number of cars at that moment) then the acquired sum would be at most 10^{18}.OutputAfter each of the m queries print two integers: j and A_j — the number of the car closest to the head of the train, such that its value A_j is minimal, and the value A_j itself.ExampleInput 1 8 1 1 3 1 1 3 1 1 2 1 2 1 3 1 1 2 1 3 1 5 Output 1 0 1 1 1 2 3 0 3 0 1 3 5 0 1 4 Note Initially the train consists of one car with A_1 = 0, let's denote train as [0] for simplicity. After adding one car to the head, train is [0, 0]. After recalculation of values with parameters b=1, s=1, train is [1, 2]. After another recalculation of values with the parameters b=1, s=1, train is [2, 4]. After adding one car to the end, train is [2, 4, 0]. After another adding one car to the end, train is [2, 4, 0, 0]. After recalculation of values with parameters b=1, s=1, train is [3, 6, 3, 4]. After adding one car to the end, train is [3, 6, 3, 4, 0]. After recalculation of values with parameters b=1, s=5, train is [4, 12, 14, 20, 21].
1 8 1 1 3 1 1 3 1 1 2 1 2 1 3 1 1 2 1 3 1 5
1 0 1 1 1 2 3 0 3 0 1 3 5 0 1 4
2 seconds
512 megabytes
['data structures', 'greedy', '*2700']
D. Cooperative Gametime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c. Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.At the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game. Misha has drawn such a field that 1 \le t, c, (t+c) \leq 1000 and q = 3 \cdot (t+c).InputThere is no input — go to the interaction part straight away.OutputAfter all friends gather at the finish vertex, print "done" and terminate your program.InteractionTo give a command to move the friends, print "next" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print "next 0 2 5 9". At each turn, you must move at least one of your friends.As an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.For example, the answer "2 05 12346789" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer "4 01 567 234 89" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Answer "stop" instead of a valid one means that you made an invalid query. Exit immediately after receiving "stop" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.HacksIn order to hack, print two integers t and c in a single line (1 \le t, c, (t+c) \leq 1000).ExampleInput 2 05 12346789 3 246789 135 0 3 246789 0 135 3 246789 0 135 2 135 0246789 1 0123456789 Output next 0 5 next 0 1 3 next 2 3 0 1 4 5 6 7 8 9 next 9 8 7 6 5 4 3 2 1 0 next 0 1 3 5 next 1 3 5 doneNoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.In the example, the friends move as follows:
2 05 12346789 3 246789 135 0 3 246789 0 135 3 246789 0 135 2 135 0246789 1 0123456789
next 0 5 next 0 1 3 next 2 3 0 1 4 5 6 7 8 9 next 9 8 7 6 5 4 3 2 1 0 next 0 1 3 5 next 1 3 5 done
1 second
512 megabytes
['constructive algorithms', 'interactive', 'number theory', '*2400']
C. Museums Tourtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the country N, there are n cities connected by m one-way roads. Although this country seems unremarkable, there are two interesting facts about it. At first, a week lasts d days here. At second, there is exactly one museum in each city of the country N.Travel agency "Open museums" is developing a new program for tourists interested in museums. Agency's employees know which days each of the museums is open. The tour should start in the capital — the city number 1, and the first day of the tour must be on the first day of a week. Each day a tourist will be in some city, watching the exposition in its museum (in case museum is open today), and by the end of the day, the tour either ends or the tourist goes into another city connected by a road with the current one. The road system of N is designed in such a way that traveling by a road always takes one night and also all the roads are one-way. It's allowed to visit a city multiple times during the trip.You should develop such route for the trip that the number of distinct museums, possible to visit during it, is maximum.InputThe first line contains three integers n, m and d (1 \leq n \leq 100\,000, 0 \leq m \leq 100\,000, 1 \leq d \leq 50), the number of cities, the number of roads and the number of days in a week.Each of next m lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i), denoting a one-way road from the city u_i to the city v_i.The next n lines contain the museums' schedule. The schedule of the museum located in the i-th city is described in the i-th of these lines. Each line consists of exactly d characters "0" or "1", the j-th character of the string equals to "1" if the museum is open at the j-th day of a week, and "0", otherwise.It's guaranteed that for each pair of cities (u, v) there exists no more than one road leading from u to v.OutputPrint a single integer — the maximum number of distinct museums, that it's possible to visit, starting a trip in the first city on the first day of the week.ExamplesInput 4 5 3 3 1 1 2 2 4 4 1 2 3 011 110 111 001 Output 3 Input 3 3 7 1 2 1 3 2 3 1111111 0000000 0111111 Output 2 Note Explanation of the first example The maximum number of distinct museums to visit is 3. It's possible to visit 3 museums, for example, in the way described below. Day 1. Now it's the 1st day of a week, and the tourist is in the city 1. The museum there is closed. At night the tourist goes to the city number 2. Day 2. Now it's the 2nd day of a week, and the tourist is in the city 2. The museum there is open, and the tourist visits it. At night the tourist goes to the city number 4. Day 3. Now it's the 3rd day of a week, and the tourist is in the city 4. The museum there is open, and the tourist visits it. At night the tourist goes to the city number 1. Day 4. Now it's the 1st day of a week, and the tourist is in the city 1. The museum there is closed. At night the tourist goes to the city number 2. Day 5. Now it's the 2nd of a week number 2, and the tourist is in the city 2. The museum there is open, but the tourist has already visited it. At night the tourist goes to the city number 3. Day 6. Now it's the 3rd day of a week, and the tourist is in the city 3. The museum there is open, and the tourist visits it. After this, the tour is over. Explanation of the second example The maximum number of distinct museums to visit is 2. It's possible to visit 2 museums, for example, in the way described below. Day 1. Now it's the 1st day of a week, and the tourist is in the city 1. The museum there is open, and the tourist visits it. At night the tourist goes to the city number 2. Day 2. Now it's the 2nd day of a week, and the tourist is in the city 2. The museum there is closed. At night the tourist goes to the city number 3. Day 3. Now it's the 3rd day of a week, and the tourist is in the city 3. The museum there is open, and the tourist visits it. After this, the tour is over.
4 5 3 3 1 1 2 2 4 4 1 2 3 011 110 111 001
3
4 seconds
512 megabytes
['dp', 'graphs', 'implementation', '*2500']
B. Camp Scheduletime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symbol is '1' if students will write the contest in the i-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule t (which can be described in the same format as schedule s). Since the number of days in the current may be different from number of days in schedule t, Gleb required that the camp's schedule must be altered so that the number of occurrences of t in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?InputThe first line contains string s (1 \leqslant |s| \leqslant 500\,000), denoting the current project of the camp's schedule.The second line contains string t (1 \leqslant |t| \leqslant 500\,000), denoting the optimal schedule according to Gleb.Strings s and t contain characters '0' and '1' only.OutputIn the only line print the schedule having the largest number of substrings equal to t. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in s and the number of ones should be equal to the number of ones in s.In case there multiple optimal schedules, print any of them.ExamplesInput 101101 110 Output 110110Input 10010110 100011 Output 01100011 Input 10 11100 Output 01NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of t wouldn't change.In the third example it's impossible to make even a single occurrence.
101101 110
110110
1 second
512 megabytes
['greedy', 'hashing', 'strings', '*1600']
A. Skyscraperstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the i-th Eastern and j-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of nm intersections Dora solves an independent problem. She sees n + m - 1 skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer x and assign every skyscraper a height from 1 to x. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible x.For example, if the intersection and the two streets corresponding to it look as follows: Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) The largest used number is 5, hence the answer for this intersection would be 5.Help Dora to compute the answers for each intersection.InputThe first line contains two integers n and m (1 \le n, m \le 1000) — the number of streets going in the Eastern direction and the number of the streets going in Southern direction.Each of the following n lines contains m integers a_{i,1}, a_{i,2}, ..., a_{i,m} (1 \le a_{i,j} \le 10^9). The integer a_{i,j}, located on j-th position in the i-th line denotes the height of the skyscraper at the intersection of the i-th Eastern street and j-th Southern direction.OutputPrint n lines containing m integers each. The integer x_{i,j}, located on j-th position inside the i-th line is an answer for the problem at the intersection of i-th Eastern street and j-th Southern street.ExamplesInput 2 3 1 2 1 2 1 2 Output 2 2 2 2 2 2 Input 2 2 1 2 3 4 Output 2 3 3 2 NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows: For the intersection of the first line and the first column For the intersection of the first line and the second column For the intersection of the second line and the first column For the intersection of the second line and the second column
2 3 1 2 1 2 1 2
2 2 2 2 2 2
2 seconds
512 megabytes
['implementation', 'sortings', '*1600']
E. Nastya Hasn't Written a Legendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this task, Nastya asked us to write a formal statement.An array a of length n and an array k of length n-1 are given. Two types of queries should be processed: increase a_i by x. Then if a_{i+1} < a_i + k_i, a_{i+1} becomes exactly a_i + k_i; again, if a_{i+2} < a_{i+1} + k_{i+1}, a_{i+2} becomes exactly a_{i+1} + k_{i+1}, and so far for a_{i+3}, ..., a_n; print the sum of the contiguous subarray from the l-th element to the r-th element of the array a. It's guaranteed that initially a_i + k_i \leq a_{i+1} for all 1 \leq i \leq n-1.InputThe first line contains a single integer n (2 \leq n \leq 10^{5}) — the number of elements in the array a.The second line contains n integers a_1, a_2, \ldots, a_n (-10^{9} \leq a_i \leq 10^{9}) — the elements of the array a.The third line contains n-1 integers k_1, k_2, \ldots, k_{n-1} (-10^{6} \leq k_i \leq 10^{6}) — the elements of the array k.The fourth line contains a single integer q (1 \leq q \leq 10^{5}) — the number of queries.Each of the following q lines contains a query of one of two types: if the query has the first type, the corresponding line contains the character '+' (without quotes), and then there are two integers i and x (1 \leq i \leq n, 0 \leq x \leq 10^{6}), it means that integer x is added to the i-th element of the array a as described in the statement. if the query has the second type, the corresponding line contains the character 's' (without quotes) and then there are two integers l and r (1 \leq l \leq r \leq n). OutputFor each query of the second type print a single integer in a new line — the sum of the corresponding subarray.ExamplesInput 3 1 2 3 1 -1 5 s 2 3 + 1 2 s 1 2 + 3 1 s 2 3 Output 5 7 8 Input 3 3 6 7 3 1 3 + 1 3 + 2 4 s 1 3 Output 33 NoteIn the first example: after the first change a = [3, 4, 3]; after the second change a = [3, 4, 4]. In the second example: after the first change a = [6, 9, 10]; after the second change a = [6, 13, 14].
3 1 2 3 1 -1 5 s 2 3 + 1 2 s 1 2 + 3 1 s 2 3
5 7 8
2 seconds
256 megabytes
['binary search', 'data structures', '*2200']
D. Nastya Is Buying Lunchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward. InputThe first line contains two integers n and m (1 \leq n \leq 3 \cdot 10^{5}, 0 \leq m \leq 5 \cdot 10^{5}) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.The second line contains n integers p_1, p_2, ..., p_n — the initial arrangement of pupils in the queue, from the queue start to its end (1 \leq p_i \leq n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.The i-th of the following m lines contains two integers u_i, v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i \neq j, than v_i \neq v_j or u_i \neq u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.Nastya is the last person in the queue, i.e. the pupil with number p_n.OutputPrint a single integer — the number of places in queue she can move forward.ExamplesInput2 11 21 2Output1Input3 33 1 21 23 13 2Output2Input5 23 1 5 4 25 25 4Output1NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers 1 and 3. change places for pupils with numbers 3 and 2. change places for pupils with numbers 1 and 2. The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Input2 11 21 2
Output1
2 seconds
256 megabytes
['greedy', '*1800']
C. Nastya Is Transposing Matricestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices A and B are given, each of them has size n \times m. Nastya can perform the following operation to matrix A unlimited number of times: take any square square submatrix of A and transpose it (i.e. the element of the submatrix which was in the i-th row and j-th column of the submatrix will be in the j-th row and i-th column after transposing, and the transposed submatrix itself will keep its place in the matrix A). Nastya's task is to check whether it is possible to transform the matrix A to the matrix B. Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix M is a matrix which consist of all elements which comes from one of the rows with indeces x, x+1, \dots, x+k-1 of matrix M and comes from one of the columns with indeces y, y+1, \dots, y+k-1 of matrix M. k is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).InputThe first line contains two integers n and m separated by space (1 \leq n, m \leq 500) — the numbers of rows and columns in A and B respectively.Each of the next n lines contains m integers, the j-th number in the i-th of these lines denotes the j-th element of the i-th row of the matrix A (1 \leq A_{ij} \leq 10^{9}).Each of the next n lines contains m integers, the j-th number in the i-th of these lines denotes the j-th element of the i-th row of the matrix B (1 \leq B_{ij} \leq 10^{9}).OutputPrint "YES" (without quotes) if it is possible to transform A to B and "NO" (without quotes) otherwise.You can print each letter in any case (upper or lower).ExamplesInput 2 2 1 1 6 1 1 6 1 1 Output YESInput 2 2 4 4 4 5 5 4 4 4 Output NOInput 3 3 1 2 3 4 5 6 7 8 9 1 4 7 2 5 6 3 8 9 Output YESNoteConsider the third example. The matrix A initially looks as follows. \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} Then we choose the whole matrix as transposed submatrix and it becomes \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} Then we transpose the submatrix with corners in cells (2, 2) and (3, 3). \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} So matrix becomes \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} and it is B.
2 2 1 1 6 1 1 6 1 1
YES
1 second
256 megabytes
['constructive algorithms', 'sortings', '*1500']
B. Nastya Is Playing Computer Gamestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFinished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are closed, and there is one stone on every manhole. There is exactly one coin under every manhole, and to win the game Nastya should pick all the coins. Initially Nastya stands near the k-th manhole from the left. She is thinking what to do.In one turn, Nastya can do one of the following: if there is at least one stone on the manhole Nastya stands near, throw exactly one stone from it onto any other manhole (yes, Nastya is strong). go to a neighboring manhole; if there are no stones on the manhole Nastya stays near, she can open it and pick the coin from it. After it she must close the manhole immediately (it doesn't require additional moves). The figure shows the intermediate state of the game. At the current position Nastya can throw the stone to any other manhole or move left or right to the neighboring manholes. If she were near the leftmost manhole, she could open it (since there are no stones on it). Nastya can leave the room when she picks all the coins. Monsters are everywhere, so you need to compute the minimum number of moves Nastya has to make to pick all the coins.Note one time more that Nastya can open a manhole only when there are no stones onto it.InputThe first and only line contains two integers n and k, separated by space (2 \leq n \leq 5000, 1 \leq k \leq n) — the number of manholes and the index of manhole from the left, near which Nastya stays initially. Initially there is exactly one stone near each of the n manholes. OutputPrint a single integer — minimum number of moves which lead Nastya to pick all the coins.ExamplesInput 2 2 Output 6 Input 4 2 Output 13 Input 5 1 Output 15 NoteLet's consider the example where n = 2, k = 2. Nastya should play as follows: At first she throws the stone from the second manhole to the first. Now there are two stones on the first manhole. Then she opens the second manhole and pick the coin from it. Then she goes to the first manhole, throws two stones by two moves to the second manhole and then opens the manhole and picks the coin from it. So, 6 moves are required to win.
2 2
6
1 second
256 megabytes
['constructive algorithms', 'math', '*1000']
A. Nastya Is Reading a Booktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the first page which was not read (i.e. she read all pages from the 1-st to the (k-1)-th).The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).InputThe first line contains a single integer n (1 \leq n \leq 100) — the number of chapters in the book.There are n lines then. The i-th of these lines contains two integers l_i, r_i separated by space (l_1 = 1, l_i \leq r_i) — numbers of the first and the last pages of the i-th chapter. It's guaranteed that l_{i+1} = r_i + 1 for all 1 \leq i \leq n-1, and also that every chapter contains at most 100 pages.The (n+2)-th line contains a single integer k (1 \leq k \leq r_n) — the index of the marked page. OutputPrint a single integer — the number of chapters which has not been completely read so far.ExamplesInput 3 1 3 4 7 8 11 2 Output 3 Input 3 1 4 5 9 10 12 9 Output 2 Input 1 1 7 4 Output 1 NoteIn the first example the book contains 11 pages and 3 chapters — [1;3], [4;7] and [8;11]. Nastya marked the 2-nd page, so she finished in the middle of the 1-st chapter. So, all chapters has not been read so far, so the answer is 3.The book in the second example contains 12 pages and 3 chapters too, but Nastya finished reading in the middle of the 2-nd chapter, so that the answer is 2.
3 1 3 4 7 8 11 2
3
1 second
256 megabytes
['implementation', '*800']
F2. Spanning Tree with One Fixed Degreetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label 1 on it) is equal to D (or say that there are no such spanning trees). Recall that the degree of a vertex is the number of edges incident to it.InputThe first line contains three integers n, m and D (2 \le n \le 2 \cdot 10^5, n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2}), 1 \le D < n) — the number of vertices, the number of edges and required degree of the first vertex, respectively.The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 \le v_i, u_i \le n, u_i \ne v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i \ne u_i is satisfied.OutputIf there is no spanning tree satisfying the condition from the problem statement, print "NO" in the first line.Otherwise print "YES" in the first line and then print n-1 lines describing the edges of a spanning tree such that the degree of the first vertex (vertex with label 1 on it) is equal to D. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)).If there are multiple possible answers, print any of them.ExamplesInput 4 5 1 1 2 1 3 1 4 2 3 3 4 Output YES 2 1 2 3 3 4 Input 4 5 3 1 2 1 3 1 4 2 3 3 4 Output YES 1 2 1 3 4 1 Input 4 4 3 1 2 1 4 2 3 3 4 Output NO NoteThe picture corresponding to the first and second examples: The picture corresponding to the third example:
4 5 1 1 2 1 3 1 4 2 3 3 4
YES 2 1 2 3 3 4
3 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', '*1900']
F1. Spanning Tree with Maximum Degreetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5, n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})) — the number of vertices and edges, respectively.The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 \le v_i, u_i \le n, u_i \ne v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i \ne u_i is satisfied.OutputPrint n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)).If there are multiple possible answers, print any of them.ExamplesInput 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 NotePicture corresponding to the first example: In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.Picture corresponding to the second example: In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.Picture corresponding to the third example: In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
5 5 1 2 2 3 3 5 4 3 1 5
3 5 2 1 3 2 3 4
3 seconds
256 megabytes
['graphs', '*1600']
E. K Balanced Teamstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).It is possible that some students not be included in any team at all.Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 5000) — the number of students and the maximum number of teams, correspondingly.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is a programming skill of the i-th student.OutputPrint one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.ExamplesInput 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4
5 2 1 2 15 15 15
5
3 seconds
256 megabytes
['dp', 'sortings', 'two pointers', '*1800']
D. Zero Quantity Maximizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, each contains n integers.You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i \in [1, n] let c_i := d \cdot a_i + b_i.Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if you choose d optimally?InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in both arrays.The second line contains n integers a_1, a_2, ..., a_n (-10^9 \le a_i \le 10^9).The third line contains n integers b_1, b_2, ..., b_n (-10^9 \le b_i \le 10^9).OutputPrint one integer — the maximum number of zeroes in array c, if you choose d optimally.ExamplesInput 5 1 2 3 4 5 2 4 7 11 3 Output 2 Input 3 13 37 39 1 2 3 Output 2 Input 4 0 0 0 0 1 2 3 4 Output 0 Input 3 1 2 -1 -6 -12 6 Output 3 NoteIn the first example, we may choose d = -2.In the second example, we may choose d = -\frac{1}{13}.In the third example, we cannot obtain any zero in array c, no matter which d we choose.In the fourth example, we may choose d = 6.
5 1 2 3 4 5 2 4 7 11 3
2
2 seconds
256 megabytes
['hashing', 'math', 'number theory', '*1500']
C. Balanced Teamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than 5.Your task is to report the maximum possible number of students in a balanced team.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of students.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is a programming skill of the i-th student.OutputPrint one integer — the maximum possible number of students in a balanced team.ExamplesInput 6 1 10 17 12 15 2 Output 3 Input 10 1337 1337 1337 1337 1337 1337 1337 1337 1337 1337 Output 10 Input 6 1 1000 10000 10 100 1000000000 Output 1 NoteIn the first example you can create a team with skills [12, 17, 15].In the second example you can take all students in a team because their programming skills are equal.In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students).
6 1 10 17 12 15 2
3
2 seconds
256 megabytes
['sortings', 'two pointers', '*1200']
B. Preparation for International Women's Daytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInternational Women's Day is coming soon! Polycarp is preparing for the holiday.There are n candy boxes in the shop for sale. The i-th box contains d_i candies.Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by k. In other words, two boxes i and j (i \ne j) can be combined as a gift if d_i + d_j is divisible by k.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them. InputThe first line of the input contains two integers n and k (1 \le n \le 2 \cdot 10^5, 1 \le k \le 100) — the number the boxes and the number the girls.The second line of the input contains n integers d_1, d_2, \dots, d_n (1 \le d_i \le 10^9), where d_i is the number of candies in the i-th box.OutputPrint one integer — the maximum number of the boxes Polycarp can give as gifts.ExamplesInput 7 2 1 2 2 3 2 4 10 Output 6 Input 8 2 1 2 2 3 2 4 6 10 Output 8 Input 7 3 1 2 2 3 2 4 5 Output 4 NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): (2, 3); (5, 6); (1, 4). So the answer is 6.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): (6, 8); (2, 3); (1, 4); (5, 7). So the answer is 8.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): (1, 2); (6, 7). So the answer is 4.
7 2 1 2 2 3 2 4 10
6
2 seconds
256 megabytes
['math', 'number theory', '*1200']
A. Middle of the Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.Polycarp wants to know the time of the midpoint of the contest. For example, if the contest lasts from 10:00 to 11:00 then the answer is 10:30, if the contest lasts from 11:10 to 11:12 then the answer is 11:11.InputThe first line of the input contains two integers h_1 and m_1 in the format hh:mm.The second line of the input contains two integers h_2 and m_2 in the same format (hh:mm).It is guaranteed that 0 \le h_1, h_2 \le 23 and 0 \le m_1, m_2 \le 59.It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.OutputPrint two integers h_3 and m_3 (0 \le h_3 \le 23, 0 \le m_3 \le 59) corresponding to the midpoint of the contest in the format hh:mm. Print each number as exactly two digits (prepend a number with leading zero if needed), separate them with ':'.ExamplesInput 10:00 11:00 Output 10:30 Input 11:10 11:12 Output 11:11 Input 01:02 03:02 Output 02:02
10:00 11:00
10:30
1 second
256 megabytes
['implementation', '*1000']
G. Greedy Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor some array c, let's denote a greedy subsequence as a sequence of indices p_1, p_2, ..., p_l such that 1 \le p_1 < p_2 < \dots < p_l \le |c|, and for each i \in [1, l - 1], p_{i + 1} is the minimum number such that p_{i + 1} > p_i and c[p_{i + 1}] > c[p_i].You are given an array a_1, a_2, \dots, a_n. For each its subsegment of length k, calculate the length of its longest greedy subsequence.InputThe first line contains two integers n and k (1 \le k \le n \le 10^6) — the length of array a and the length of subsegments.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — array a.OutputPrint n - k + 1 integers — the maximum lengths of greedy subsequences of each subsegment having length k. The first number should correspond to subsegment a[1..k], the second — to subsegment a[2..k + 1], and so on.ExamplesInput 6 4 1 5 2 5 3 6 Output 2 2 3 Input 7 6 4 5 2 5 3 6 6 Output 3 3 NoteIn the first example: [1, 5, 2, 5] — the longest greedy subsequences are 1, 2 ([c_1, c_2] = [1, 5]) or 3, 4 ([c_3, c_4] = [2, 5]). [5, 2, 5, 3] — the sequence is 2, 3 ([c_2, c_3] = [2, 5]). [2, 5, 3, 6] — the sequence is 1, 2, 4 ([c_1, c_2, c_4] = [2, 5, 6]). In the second example: [4, 5, 2, 5, 3, 6] — the longest greedy subsequences are 1, 2, 6 ([c_1, c_2, c_6] = [4, 5, 6]) or 3, 4, 6 ([c_3, c_4, c_6] = [2, 5, 6]). [5, 2, 5, 3, 6, 6] — the subsequence is 2, 3, 5 ([c_2, c_3, c_5] = [2, 5, 6]).
6 4 1 5 2 5 3 6
2 2 3
2 seconds
256 megabytes
['data structures', 'dp', 'trees', '*2400']
F. Clear the Stringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd we get the string aaccdd.Calculate the minimum number of operations to delete the whole string s.InputThe first line contains one integer n (1 \le n \le 500) — the length of string s.The second line contains the string s (|s| = n) consisting of lowercase Latin letters.OutputOutput a single integer — the minimal number of operation to delete string s.ExamplesInput 5 abaca Output 3Input 8 abcddcba Output 4
5 abaca
3
3 seconds
256 megabytes
['dp', '*2000']
E. Knapsacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a set of items, each having some integer weight not greater than 8. You denote that a subset of items is good if total weight of items in the subset does not exceed W.You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set when calculating the answer.InputThe first line contains one integer W (0 \le W \le 10^{18}) — the maximum total weight of a good subset.The second line denotes the set of items you have. It contains 8 integers cnt_1, cnt_2, ..., cnt_8 (0 \le cnt_i \le 10^{16}), where cnt_i is the number of items having weight i in the set.OutputPrint one integer — the maximum possible weight of a good subset of items.ExamplesInput 10 1 2 3 4 5 6 7 8 Output 10 Input 0 0 0 0 0 0 0 0 0 Output 0 Input 3 0 4 1 0 0 9 8 3 Output 3
10 1 2 3 4 5 6 7 8
10
2 seconds
256 megabytes
['dfs and similar', 'dp', 'greedy', '*2300']
D. Stressful Trainingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland SU holds yet another training contest for its students today. n students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers!Let students be numbered from 1 to n. Laptop of the i-th student has charge a_i at the beginning of the contest and it uses b_i of charge per minute (i.e. if the laptop has c charge at the beginning of some minute, it becomes c - b_i charge at the beginning of the next minute). The whole contest lasts for k minutes.Polycarp (the coach of Berland SU) decided to buy a single charger so that all the students would be able to successfully finish the contest. He buys the charger at the same moment the contest starts.Polycarp can choose to buy the charger with any non-negative (zero or positive) integer power output. The power output is chosen before the purchase, it can't be changed afterwards. Let the chosen power output be x. At the beginning of each minute (from the minute contest starts to the last minute of the contest) he can plug the charger into any of the student's laptops and use it for some integer number of minutes. If the laptop is using b_i charge per minute then it will become b_i - x per minute while the charger is plugged in. Negative power usage rate means that the laptop's charge is increasing. The charge of any laptop isn't limited, it can become infinitely large. The charger can be plugged in no more than one laptop at the same time.The student successfully finishes the contest if the charge of his laptop never is below zero at the beginning of some minute (from the minute contest starts to the last minute of the contest, zero charge is allowed). The charge of the laptop of the minute the contest ends doesn't matter.Help Polycarp to determine the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. Also report if no such charger exists.InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5) — the number of students (and laptops, correspondigly) and the duration of the contest in minutes.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}) — the initial charge of each student's laptop.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^7) — the power usage of each student's laptop.OutputPrint a single non-negative integer — the minimal possible power output the charger should have so that all the students are able to successfully finish the contest.If no such charger exists, print -1.ExamplesInput 2 4 3 2 4 2 Output 5 Input 1 5 4 2 Output 1 Input 1 6 4 2 Output 2 Input 2 2 2 10 3 15 Output -1 NoteLet's take a look at the state of laptops in the beginning of each minute on the first example with the charger of power 5: charge: [3, 2], plug the charger into laptop 1; charge: [3 - 4 + 5, 2 - 2] = [4, 0], plug the charger into laptop 2; charge: [4 - 4, 0 - 2 + 5] = [0, 3], plug the charger into laptop 1; charge: [0 - 4 + 5, 3 - 2] = [1, 1]. The contest ends after the fourth minute.However, let's consider the charger of power 4: charge: [3, 2], plug the charger into laptop 1; charge: [3 - 4 + 4, 2 - 2] = [3, 0], plug the charger into laptop 2; charge: [3 - 4, 0 - 2 + 4] = [-1, 2], the first laptop has negative charge, thus, the first student doesn't finish the contest. In the fourth example no matter how powerful the charger is, one of the students won't finish the contest.
2 4 3 2 4 2
5
3 seconds
256 megabytes
['binary search', 'greedy', '*2300']
C. Painting the Fencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a long fence which consists of n sections. Unfortunately, it is not painted, so you decided to hire q painters to paint it. i-th painter will paint all sections x such that l_i \le x \le r_i.Unfortunately, you are on a tight budget, so you may hire only q - 2 painters. Obviously, only painters you hire will do their work.You want to maximize the number of painted sections if you choose q - 2 painters optimally. A section is considered painted if at least one painter paints it.InputThe first line contains two integers n and q (3 \le n, q \le 5000) — the number of sections and the number of painters availible for hire, respectively.Then q lines follow, each describing one of the painters: i-th line contains two integers l_i and r_i (1 \le l_i \le r_i \le n).OutputPrint one integer — maximum number of painted sections if you hire q - 2 painters.ExamplesInput 7 5 1 4 4 5 5 6 6 7 3 5 Output 7 Input 4 3 1 1 2 2 3 4 Output 2 Input 4 4 1 1 2 2 2 3 3 4 Output 3
7 5 1 4 4 5 5 6 6 7 3 5
7
2 seconds
256 megabytes
['brute force', '*1700']
B. Discountstime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou came to a local shop and want to buy some chocolate bars. There are n bars in the shop, i-th of them costs a_i coins (and you want to buy all of them).You have m different coupons that allow you to buy chocolate bars. i-th coupon allows you to buy q_i chocolate bars while you have to pay only for the q_i - 1 most expensive ones (so, the cheapest bar of those q_i bars is for free).You can use only one coupon; if you use coupon i, you have to choose q_i bars and buy them using the coupon, and buy all the remaining n - q_i bars without any discounts.To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.InputThe first line contains one integer n (2 \le n \le 3 \cdot 10^5) — the number of chocolate bars in the shop.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9), where a_i is the cost of i-th chocolate bar.The third line contains one integer m (1 \le m \le n - 1) — the number of coupons you have.The fourth line contains m integers q_1, q_2, ..., q_m (2 \le q_i \le n), where q_i is the number of chocolate bars you have to buy using i-th coupon so that the least expensive of them will be for free. All values of q_i are pairwise distinct.OutputPrint m integers, i-th of them should be the minimum amount of money you have to pay if you buy q_i bars with i-th coupon, and all the remaining bars one by one for their full price.ExampleInput 7 7 1 3 1 4 10 8 2 3 4 Output 27 30 NoteConsider the first example.If we use the first coupon, we may choose chocolate bars having indices 1, 6 and 7, and we pay 18 coins for them and 9 coins for all other bars.If we use the second coupon, we may choose chocolate bars having indices 1, 5, 6 and 7, and we pay 25 coins for them and 5 coins for all other bars.
7 7 1 3 1 4 10 8 2 3 4
27 30
2.5 seconds
256 megabytes
['greedy', 'sortings', '*900']
A. Regular Bracket Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; "))" and ")((" are bracket sequences (but not regular ones), and "(a)" and "(1)+(1)" are not bracket sequences at all.You have a number of strings; each string is a bracket sequence of length 2. So, overall you have cnt_1 strings "((", cnt_2 strings "()", cnt_3 strings ")(" and cnt_4 strings "))". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length 2(cnt_1 + cnt_2 + cnt_3 + cnt_4). You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? Note that you may not remove any characters or strings, and you may not add anything either.InputThe input consists of four lines, i-th of them contains one integer cnt_i (0 \le cnt_i \le 10^9).OutputPrint one integer: 1 if it is possible to form a regular bracket sequence by choosing the correct order of the given strings, 0 otherwise.ExamplesInput 3 1 4 3 Output 1 Input 0 0 0 0 Output 1 Input 1 2 3 4 Output 0 NoteIn the first example it is possible to construct a string "(())()(()((()()()())))", which is a regular bracket sequence.In the second example it is possible to construct a string "", which is a regular bracket sequence.
3 1 4 3
1
1 second
256 megabytes
['greedy', 'implementation', '*1100']
G. Most Dangerous Sharktime limit per test2 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputSemyon participates in the most prestigious competition of the world ocean for the title of the most dangerous shark. During this competition sharks compete in different subjects: speed swimming, masking, map navigation and many others. Now Semyon is taking part in «destruction» contest.During it, m dominoes are placed in front of the shark. All dominoes are on the same line, but the height of the dominoes may vary. The distance between adjacent dominoes is 1. Moreover, each Domino has its own cost value, expressed as an integer. The goal is to drop all the dominoes. To do this, the shark can push any domino to the left or to the right, and it will begin falling in this direction. If during the fall the domino touches other dominoes, they will also start falling in the same direction in which the original domino is falling, thus beginning a chain reaction, as a result of which many dominoes can fall. A falling domino touches another one, if and only if the distance between them was strictly less than the height of the falling domino, the dominoes do not necessarily have to be adjacent.Of course, any shark can easily drop all the dominoes in this way, so the goal is not to drop all the dominoes, but do it with a minimum cost. The cost of the destruction is the sum of the costs of dominoes that the shark needs to push to make all the dominoes fall.Simon has already won in the previous subjects, but is not smart enough to win in this one. Help Semyon and determine the minimum total cost of the dominoes he will have to push to make all the dominoes fall.InputIn order to reduce input size, the heights and costs of the dominoes are described with blocks.The first line contains two integers n and m (1 \leq n \leq 250\,000, 1 \leq m \leq 10^7) — the number of the blocks and the total number of the dominoes Semyon must drop.Then descriptions of n blocks follow. Description of every block consists of three lines.The first line of block's description contains a single integer k_i (1 \leq k_i \leq 250\,000, \sum_{i = 1}^{n}{k_i} \leq 250\,000) — the number of dominoes in the block.The second line of block's description contains k_i integers a_j (1 \leq a_j \leq m) — the heights of the dominoes in the blocks.The third line contains k_i integers c_j (1 \leq c_j \leq 100\,000) — the costs of the dominoes in the block.Then the domino sequence is described (from left to right).The first line of this description contains a single integer q (n \leq q \leq 250\,000) — the number of blocks in the sequence of domino sequence.Each of the following q lines contains integers id_i, mul_i (1 \leq id_i \leq n, 1 \leq mul_i \leq 100\,000), denoting that the next k_{id_i} dominoes are dominoes of the block id_i, with their cost multiplied by mul_i.It's guaranteed, that \sum_{i = 1}^{q}{k_{id_i}} = m, and that's every block is used in the sequence at least once.OutputPrint exactly one integer — the minimum cost to make all the dominoes fall.ExamplesInput 2 7 3 1 2 2 1 2 1 1 3 2 3 2 2 1 3 1 1 Output 5 Input 1 1 1 1 100000 1 1 100000 Output 10000000000 NoteIn the first example, there are 7 dominoes in front of the Semyon. Their heights are equal to [3, 1, 2, 2, 1, 2, 2], and their costs are equal to [4, 3, 6, 3, 1, 2, 1]. Semyon should drop the domino with index 7 to the left, it will fall and drop the domino 6 as well. The domino 6 during the fall will drop the domino 5, however the latter will not drop any more dominoes. Then Semyon should drop domino with number 1 to the right and it will drop dominoes 2 and 3 after falling. And the domino 3 will drop the domino 4 after falling. Hence all dominoes are fallen this way.In the second example, there is a single domino of cost 10000000000.
2 7 3 1 2 2 1 2 1 1 3 2 3 2 2 1 3 1 1
5
2 seconds
768 megabytes
['data structures', 'dp', 'two pointers', '*2700']
F. Asya And Kittenstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAsya loves animals very much. Recently, she purchased n kittens, enumerated them from 1 and n and then put them into the cage. The cage consists of one row of n cells, enumerated with integers from 1 to n from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were n - 1 partitions originally. Initially, each cell contained exactly one kitten with some number.Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day i, Asya: Noticed, that the kittens x_i and y_i, located in neighboring cells want to play together. Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after n - 1 days the cage contained a single cell, having all kittens.For every day, Asya remembers numbers of kittens x_i and y_i, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into n cells.InputThe first line contains a single integer n (2 \le n \le 150\,000) — the number of kittens.Each of the following n - 1 lines contains integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) — indices of kittens, which got together due to the border removal on the corresponding day.It's guaranteed, that the kittens x_i and y_i were in the different cells before this day.OutputFor every cell from 1 to n print a single integer — the index of the kitten from 1 to n, who was originally in it.All printed integers must be distinct.It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.ExampleInput 5 1 4 2 5 3 1 4 5 Output 3 1 4 2 5 NoteThe answer for the example contains one of several possible initial arrangements of the kittens.The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells.
5 1 4 2 5 3 1 4 5
3 1 4 2 5
2 seconds
256 megabytes
['constructive algorithms', 'dsu', '*1700']
E. String Multiplicationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRoman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings s of length m and t is a string t + s_1 + t + s_2 + \ldots + t + s_m + t, where s_i denotes the i-th symbol of the string s, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings s and t is not necessarily equal to product of t and s.Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to 3, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to 1, since all neighboring symbols in it are different.In order to entertain Roman, Denis wrote down n strings p_1, p_2, p_3, \ldots, p_n on the paper and asked him to calculate the beauty of the string ( \ldots (((p_1 \cdot p_2) \cdot p_3) \cdot \ldots ) \cdot p_n, where s \cdot t denotes a multiplication of strings s and t. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most 10^9.InputThe first line contains a single integer n (2 \leq n \leq 100\,000) — the number of strings, wroted by Denis.Next n lines contain non-empty strings p_1, p_2, \ldots, p_n, consisting of lowercase english letters.It's guaranteed, that the total length of the strings p_i is at most 100\,000, and that's the beauty of the resulting product is at most 10^9.OutputPrint exactly one integer — the beauty of the product of the strings.ExamplesInput 3 a b a Output 3 Input 2 bnn a Output 1 NoteIn the first example, the product of strings is equal to "abaaaba".In the second example, the product of strings is equal to "abanana".
3 a b a
3
2 seconds
256 megabytes
['dp', 'greedy', 'strings', '*2300']
D. Gourmet choicetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n \times m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.InputThe first line contains integers n and m (1 \leq n, m \leq 1000) — the number of dishes in both days.Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=".OutputThe first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise.If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set.ExamplesInput 3 4 >>>> >>>> >>>> Output Yes 2 2 2 1 1 1 1 Input 3 3 >>> <<< >>> Output Yes 3 1 3 2 2 2 Input 3 2 == =< == Output No NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
3 4 >>>> >>>> >>>>
Yes 2 2 2 1 1 1 1
2 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'graphs', 'greedy', '*2000']
C. Birthdaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from 1 to n in a circle order, that is, for every i child with number i will stand next to the child with number i+1, also the child with number 1 stands next to the child with number n. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.InputThe first line contains a single integer n (2 \leq n \leq 100) — the number of the children who came to the cowboy Vlad's birthday.The second line contains integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) denoting heights of every child.OutputPrint exactly n integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child.If there are multiple possible answers, print any of them.ExamplesInput 5 2 1 1 3 2 Output 1 2 3 2 1 Input 3 30 10 20 Output 10 20 30 NoteIn the first example, the discomfort of the circle is equal to 1, since the corresponding absolute differences are 1, 1, 1 and 0. Note, that sequences [2, 3, 2, 1, 1] and [3, 2, 1, 1, 2] form the same circles and differ only by the selection of the starting point.In the second example, the discomfort of the circle is equal to 20, since the absolute difference of 10 and 30 is equal to 20.
5 2 1 1 3 2
1 2 3 2 1
1 second
256 megabytes
['binary search', 'greedy', 'sortings', '*1200']
B. Draw!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou still have partial information about the score during the historic football match. You are given a set of pairs (a_i, b_i), indicating that at some point during the match the score was "a_i: b_i". It is known that if the current score is «x:y», then after the goal it will change to "x+1:y" or "x:y+1". What is the largest number of times a draw could appear on the scoreboard?The pairs "a_i:b_i" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.InputThe first line contains a single integer n (1 \le n \le 10000) — the number of known moments in the match.Each of the next n lines contains integers a_i and b_i (0 \le a_i, b_i \le 10^9), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team).All moments are given in chronological order, that is, sequences x_i and y_j are non-decreasing. The last score denotes the final result of the match.OutputPrint the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.ExamplesInput32 03 13 4Output2Input30 00 00 0Output1Input15 4Output5NoteIn the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4.
Input32 03 13 4
Output2
2 seconds
256 megabytes
['greedy', 'implementation', '*1400']
A. Sea Battletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 \ge w_2. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.The rectangles are placed on field in the following way: the second rectangle is on top the first rectangle; they are aligned to the left, i.e. their left sides are on the same line; the rectangles are adjacent to each other without a gap. See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates (1, 1), the rightmost top cell of the first rectangle has coordinates (w_1, h_1), the leftmost bottom cell of the second rectangle has coordinates (1, h_1 + 1) and the rightmost top cell of the second rectangle has coordinates (w_2, h_1 + h_2).After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.InputFour lines contain integers w_1, h_1, w_2 and h_2 (1 \leq w_1, h_1, w_2, h_2 \leq 10^8, w_1 \ge w_2) — the width of the first rectangle, the height of the first rectangle, the width of the second rectangle and the height of the second rectangle. You can't rotate the rectangles.OutputPrint exactly one integer — the number of cells, which should be marked after the ship is destroyed.ExamplesInput 2 1 2 1 Output 12 Input 2 2 1 2 Output 16 NoteIn the first example the field looks as follows (the first rectangle is red, the second rectangle is blue, green shows the marked squares): In the second example the field looks as:
2 1 2 1
12
1 second
256 megabytes
['math', '*800']
C. Connecttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice lives on a flat planet that can be modeled as a square grid of size n \times n, with rows and columns enumerated from 1 to n. We represent the cell at the intersection of row r and column c with ordered pair (r, c). Each cell in the grid is either land or water. An example planet with n = 5. It also appears in the first sample test. Alice resides in land cell (r_1, c_1). She wishes to travel to land cell (r_2, c_2). At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells (r_s, c_s) and (r_t, c_t) is (r_s-r_t)^2 + (c_s-c_t)^2.For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from (r_1, c_1) to (r_2, c_2). If no tunnel needs to be created, the cost is 0.InputThe first line contains one integer n (1 \leq n \leq 50) — the width of the square grid.The second line contains two space-separated integers r_1 and c_1 (1 \leq r_1, c_1 \leq n) — denoting the cell where Alice resides.The third line contains two space-separated integers r_2 and c_2 (1 \leq r_2, c_2 \leq n) — denoting the cell to which Alice wishes to travel.Each of the following n lines contains a string of n characters. The j-th character of the i-th such line (1 \leq i, j \leq n) is 0 if (i, j) is land or 1 if (i, j) is water.It is guaranteed that (r_1, c_1) and (r_2, c_2) are land.OutputPrint an integer that is the minimum possible cost of creating at most one tunnel so that Alice could travel from (r_1, c_1) to (r_2, c_2).ExamplesInput 5 1 1 5 5 00001 11111 00111 00110 00110 Output 10 Input 3 1 3 3 1 010 101 010 Output 8 NoteIn the first sample, a tunnel between cells (1, 4) and (4, 5) should be created. The cost of doing so is (1-4)^2 + (4-5)^2 = 10, which is optimal. This way, Alice could walk from (1, 1) to (1, 4), use the tunnel from (1, 4) to (4, 5), and lastly walk from (4, 5) to (5, 5).In the second sample, clearly a tunnel between cells (1, 3) and (3, 1) needs to be created. The cost of doing so is (1-3)^2 + (3-1)^2 = 8.
5 1 1 5 5 00001 11111 00111 00110 00110
10
1 second
256 megabytes
['brute force', 'dfs and similar', 'dsu', '*1400']
B. Two Cakestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha and Dima want to buy two n-tier cakes. Each cake should consist of n different tiers: from the size of 1 to the size of n. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are 2 \cdot n houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the i-th house you can buy a tier of the size a_i (1 \le a_i \le n).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: 1, then 2, then 3 and so on up to n.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly 1.InputThe first line of the input contains an integer number n — the number of tiers in each cake (1 \le n \le 10^5).The second line contains 2 \cdot n integers a_1, a_2, \dots, a_{2n} (1 \le a_i \le n), where a_i is equal to the size of the tier, which can be bought in the i-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from 1 to n occurs in a exactly two times.OutputPrint one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy n tiers in ascending order of their sizes.ExamplesInput 3 1 1 2 2 3 3 Output 9 Input 2 2 1 1 2 Output 5 Input 4 4 1 3 2 2 3 1 4 Output 17 NoteIn the first example, the possible optimal sequence of actions is: Sasha buys a tier of size 1 near the 1-st house (a_1=1); Dima goes to the house 2; Dima buys a tier of size 1 near the 2-nd house (a_2=1); Sasha goes to the house 4; Sasha buys a tier of size 2 near the 4-th house (a_4=2); Sasha goes to the house 5; Sasha buys a tier of size 3 near the 5-th house (a_5=3); Dima goes to the house 3; Dima buys a tier of size 2 near the 3-rd house (a_3=2); Dima goes to the house 6; Dima buys a tier of size 3 near the 6-th house (a_6=3). So, Sasha goes the distance 3+1=4, and Dima goes the distance 1+1+3=5. In total, they cover a distance of 4+5=9. You can make sure that with any other sequence of actions they will walk no less distance.
3 1 1 2 2 3 3
9
1 second
256 megabytes
['greedy', '*1200']
A. Be Positivetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers: a_1, a_2, \ldots, a_n. Your task is to find some non-zero integer d (-10^3 \leq d \leq 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least \lceil\frac{n}{2}\rceil). Note that those positive numbers do not need to be an integer (e.g., a 2.5 counts as a positive number). If there are multiple values of d that satisfy the condition, you may print any of them. In case that there is no such d, print a single integer 0.Recall that \lceil x \rceil represents the smallest integer that is not less than x and that zero (0) is neither positive nor negative.InputThe first line contains one integer n (1 \le n \le 100) — the number of elements in the array.The second line contains n space-separated integers a_1, a_2, \ldots, a_n (-10^3 \le a_i \le 10^3).OutputPrint one integer d (-10^3 \leq d \leq 10^3 and d \neq 0) that satisfies the given condition. If there are multiple values of d that satisfy the condition, you may print any of them. In case that there is no such d, print a single integer 0.ExamplesInput510 0 -7 2 6Output4Input70 0 1 -1 0 0 2Output0NoteIn the first sample, n = 5, so we need at least \lceil\frac{5}{2}\rceil = 3 positive numbers after division. If d = 4, the array after division is [2.5, 0, -1.75, 0.5, 1.5], in which there are 3 positive numbers (namely: 2.5, 0.5, and 1.5).In the second sample, there is no valid d, so 0 should be printed.
Input510 0 -7 2 6
Output4
1 second
256 megabytes
['implementation', '*800']
E. Legendary Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster.To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains n vertices, enumerated from 1 through n. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two disjoint non-empty sets of vertices S and T, along with any vertex v that you like. Then, Mikaela will count and give you the number of pairs of vertices (s, t) where s \in S and t \in T such that the simple path from s to t contains v.Mikaela the Goddess is busy and will be available to answer at most 11\,111 questions.This is your only chance. Your task is to determine the tree and report its edges.InputThe first line contains an integer n (2 \leq n \leq 500) — the number of vertices in the tree.OutputWhen program has realized the tree and is ready to report the edges, print "ANSWER" in a separate line. Make sure that all letters are capitalized.Then, print n-1 lines, each containing two space-separated integers, denoting the vertices that are the endpoints of a certain edge. Each edge should be reported exactly once. Your program should then immediately terminate.InteractionFor each question that you wish to ask, interact as follows. First, print the size of S in its own line. In the following line, print |S| space-separated distinct integers, denoting the vertices in S. Similarly, print the size of T in its own line. In the following line, print |T| space-separated distinct integers, denoting the vertices in T. Then, in the final line, print v — the vertex that you choose for this question. Read Mikaela's answer from input. Be reminded that S and T must be disjoint and non-empty.After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If your program asks too many questions, asks an invalid question or does not correctly follow the interaction guideline above, it may receive an arbitrary verdict. Otherwise, your program will receive the Wrong Answer verdict if it reports an incorrect tree.Note that the tree is fixed beforehand and does not depend on your queries.HacksHacks should be formatted as follows.The first line should contain a single integer n (2 \leq n \leq 500) — the number of vertices in the tree.The following n-1 lines should each contain two space-separated integers u and v, denoting the existence of an undirected edge (u, v) (1 \leq u, v \leq n).ExampleInput55Output31 2 324 52ANSWER1 22 33 42 5NoteIn the sample, the tree is as follows. n = 5 is given to the program. The program then asks Mikaela a question where S = \{1, 2, 3\}, T = \{4, 5\}, and v = 2, to which she replies with 5 (the pairs (s, t) are (1, 4), (1, 5), (2, 4), (2, 5), and (3, 5)).
Input55
Output31 2 324 52ANSWER1 22 33 42 5
3 seconds
256 megabytes
['binary search', 'interactive', 'trees', '*3100']
D. Isolationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFind the number of ways to divide an array a of n integers into any number of disjoint non-empty segments so that, in each segment, there exist at most k distinct integers that appear exactly once.Since the answer can be large, find it modulo 998\,244\,353.InputThe first line contains two space-separated integers n and k (1 \leq k \leq n \leq 10^5) — the number of elements in the array a and the restriction from the statement.The following line contains n space-separated integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n) — elements of the array a.OutputThe first and only line contains the number of ways to divide an array a modulo 998\,244\,353.ExamplesInput 3 1 1 1 2 Output 3 Input 5 2 1 1 2 1 3 Output 14 Input 5 5 1 2 3 4 5 Output 16 NoteIn the first sample, the three possible divisions are as follows. [[1], [1], [2]] [[1, 1], [2]] [[1, 1, 2]] Division [[1], [1, 2]] is not possible because two distinct integers appear exactly once in the second segment [1, 2].
3 1 1 1 2
3
3 seconds
256 megabytes
['data structures', 'dp', '*2900']
C. Morse Codetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Morse code, an letter of English alphabet is represented as a string of some length from 1 to 4. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".Because there are 2^1+2^2+2^3+2^4 = 30 strings with length 1 to 4 containing only "0" and/or "1", not all of them correspond to one of the 26 English letters. In particular, each string of "0" and/or "1" of length at most 4 translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".You will work with a string S, which is initially empty. For m times, either a dot or a dash will be appended to S, one at a time. Your task is to find and report, after each of these modifications to string S, the number of non-empty sequences of English letters that are represented with some substring of S in Morse code.Since the answers can be incredibly tremendous, print them modulo 10^9 + 7.InputThe first line contains an integer m (1 \leq m \leq 3\,000) — the number of modifications to S. Each of the next m lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to S.OutputPrint m lines, the i-th of which being the answer after the i-th modification to S.ExamplesInput3111Output137Input510101Output14102243Input9110001101Output13102451109213421833NoteLet us consider the first sample after all characters have been appended to S, so S is "111".As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of S in Morse code, therefore, are as follows. "T" (translates into "1") "M" (translates into "11") "O" (translates into "111") "TT" (translates into "11") "TM" (translates into "111") "MT" (translates into "111") "TTT" (translates into "111") Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found here.
Input3111
Output137
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'hashing', 'sortings', 'string suffix structures', 'strings', '*2400']
B. Wrong Answertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the following problem: given an array a containing n integers (indexed from 0 to n-1), find \max\limits_{0 \leq l \leq r \leq n-1} \sum\limits_{l \leq i \leq r} (r-l+1) \cdot a_i. In this problem, 1 \leq n \leq 2\,000 and |a_i| \leq 10^6.In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it. Her implementation in pseudocode is as follows:function find_answer(n, a) # Assumes n is an integer between 1 and 2000, inclusive # Assumes a is a list containing n integers: a[0], a[1], ..., a[n-1] res = 0 cur = 0 k = -1 for i = 0 to i = n-1 cur = cur + a[i] if cur < 0 cur = 0 k = i res = max(res, (i-k)*cur) return resAlso, as you can see, Alice's idea is not entirely correct. For example, suppose n = 4 and a = [6, -8, 7, -42]. Then, find_answer(n, a) would return 7, but the correct answer is 3 \cdot (6-8+7) = 15.You told Alice that her solution is incorrect, but she did not believe what you said.Given an integer k, you are to find any sequence a of n integers such that the correct answer and the answer produced by Alice's algorithm differ by exactly k. Note that although the choice of n and the content of the sequence is yours, you must still follow the constraints earlier given: that 1 \leq n \leq 2\,000 and that the absolute value of each element does not exceed 10^6. If there is no such sequence, determine so.InputThe first and only line contains one integer k (1 \leq k \leq 10^9).OutputIf there is no sought sequence, print "-1".Otherwise, in the first line, print one integer n (1 \leq n \leq 2\,000), denoting the number of elements in the sequence.Then, in the second line, print n space-separated integers: a_0, a_1, \ldots, a_{n-1} (|a_i| \leq 10^6).ExamplesInput 8 Output 4 6 -8 7 -42 Input 612 Output 7 30 -12 -99 123 -2 245 -300 NoteThe first sample corresponds to the example given in the problem statement.In the second sample, one answer is n = 7 with a = [30, -12, -99, 123, -2, 245, -300], in which case find_answer(n, a) returns 1098, while the correct answer is 1710.
8
4 6 -8 7 -42
1 second
256 megabytes
['constructive algorithms', '*2000']
A2. Toy Traintime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 \leq i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 \leq i \leq m), now at station a_i, should be delivered to station b_i (a_i \neq b_i). The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.InputThe first line contains two space-separated integers n and m (2 \leq n \leq 5\,000; 1 \leq m \leq 20\,000) — the number of stations and the number of candies, respectively.The i-th of the following m lines contains two space-separated integers a_i and b_i (1 \leq a_i, b_i \leq n; a_i \neq b_i) — the station that initially contains candy i and the destination station of the candy, respectively.OutputIn the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.ExamplesInput 5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5 Output 10 9 10 10 9 Input 2 3 1 2 1 2 1 2 Output 5 6 NoteConsider the second sample.If the train started at station 1, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station 2. This step takes 1 second. Deliver the first candy. Proceed to station 1. This step takes 1 second. Load the second candy onto the train. Proceed to station 2. This step takes 1 second. Deliver the second candy. Proceed to station 1. This step takes 1 second. Load the third candy onto the train. Proceed to station 2. This step takes 1 second. Deliver the third candy. Hence, the train needs 5 seconds to complete the tasks.If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5
10 9 10 10 9
2 seconds
256 megabytes
['brute force', 'greedy', '*1800']
A1. Toy Train (Simplified)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 \leq i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 \leq i \leq m), now at station a_i, should be delivered to station b_i (a_i \neq b_i). The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.InputThe first line contains two space-separated integers n and m (2 \leq n \leq 100; 1 \leq m \leq 200) — the number of stations and the number of candies, respectively.The i-th of the following m lines contains two space-separated integers a_i and b_i (1 \leq a_i, b_i \leq n; a_i \neq b_i) — the station that initially contains candy i and the destination station of the candy, respectively.OutputIn the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.ExamplesInput 5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5 Output 10 9 10 10 9 Input 2 3 1 2 1 2 1 2 Output 5 6 NoteConsider the second sample.If the train started at station 1, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station 2. This step takes 1 second. Deliver the first candy. Proceed to station 1. This step takes 1 second. Load the second candy onto the train. Proceed to station 2. This step takes 1 second. Deliver the second candy. Proceed to station 1. This step takes 1 second. Load the third candy onto the train. Proceed to station 2. This step takes 1 second. Deliver the third candy. Hence, the train needs 5 seconds to complete the tasks.If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5
10 9 10 10 9
2 seconds
256 megabytes
['brute force', 'greedy', '*1700']
C. System Testingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated asd = round\left(100\cdot\frac{m}{n}\right),where round(x) = \lfloor{x + 0.5}\rfloor is a function which maps every real to the nearest integer.Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.InputThe first line contains two positive integers n and k (1 \le n \le 1000, 1 \le k \le 100) standing for the number of submissions and the number of testing processes respectively.The second line contains n positive integers a_1, a_2, \ldots, a_n (1 \le a_i \le 150), where a_i is equal to the number of tests the i-th submission is to be run on.OutputOutput the only integer — the number of interesting submissions.ExamplesInput 2 2 49 100 Output 1 Input 4 2 32 100 33 1 Output 2 Input 14 5 48 19 6 9 50 20 3 42 38 43 36 21 44 6 Output 5 NoteConsider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
2 2 49 100
1
1 second
256 megabytes
['implementation', '*1600']
B. Mike and Childrentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.Mike has n sweets with sizes a_1, a_2, \ldots, a_n. All his sweets have different sizes. That is, there is no such pair (i, j) (1 \leq i, j \leq n) such that i \ne j and a_i = a_j.Since Mike has taught for many years, he knows that if he gives two sweets with sizes a_i and a_j to one child and a_k and a_p to another, where (a_i + a_j) \neq (a_k + a_p), then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.InputThe first line contains one integer n (2 \leq n \leq 1\,000) — the number of sweets Mike has.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^5) — the sizes of the sweets. It is guaranteed that all integers are distinct.OutputPrint one integer — the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.ExamplesInput 8 1 8 3 11 4 9 2 7 Output 3 Input 7 3 1 7 11 9 2 12 Output 2 NoteIn the first example, Mike can give 9+2=11 to one child, 8+3=11 to another one, and 7+4=11 to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.In the second example, Mike can give 3+9=12 to one child and 1+11 to another one. Therefore, Mike can invite two children. Note that it is not the only solution.
8 1 8 3 11 4 9 2 7
3
2 seconds
256 megabytes
['brute force', 'implementation', '*1200']
A. Technogoblet of Firetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates.There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have k Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that k Chosen Ones would be selected by the Technogoblet.InputThe first line contains three integers n, m and k (1 \le n \le 100, 1 \le m, k \le n) — the total number of students, the number of schools and the number of the Chosen Ones.The second line contains n different integers p_1, p_2, \ldots, p_n (1 \le p_i \le n), where p_i denotes the power of i-th student. The bigger the power, the stronger the student.The third line contains n integers s_1, s_2, \ldots, s_n (1 \le s_i \le m), where s_i denotes the school the i-th student goes to. At least one student studies in each of the schools. The fourth line contains k different integers c_1, c_2, \ldots, c_k (1 \le c_i \le n)  — the id's of the Chosen Ones.OutputOutput a single integer  — the minimal number of schools to be made up by Arkady so that k Chosen Ones would be selected by the Technogoblet.ExamplesInput 7 3 1 1 5 3 4 6 7 2 1 3 1 2 1 2 3 3 Output 1 Input 8 4 4 1 2 3 4 5 6 7 8 4 3 2 1 4 3 2 1 3 4 5 6 Output 2 NoteIn the first example there's just a single Chosen One with id 3. His power is equal to 3, but in the same school 1, there's a student with id 5 and power 6, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be 4) for the Chosen One, Technogoblet would select students with ids 2 (strongest in 3), 5 (strongest in 1), 6 (strongest in 2) and 3 (strongest in 4).In the second example, you can change the school of student 3 to the made-up 5 and the school of student 4 to the made-up 6. It will cause the Technogoblet to choose students 8, 7, 6, 5, 3 and 4.
7 3 1 1 5 3 4 6 7 2 1 3 1 2 1 2 3 3
1
1 second
256 megabytes
['implementation', 'sortings', '*1100']
F. Secret Letterstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLittle W and Little P decided to send letters to each other regarding the most important events during a day. There are n events during a day: at time moment t_i something happens to the person p_i (p_i is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the other person. They can send a letter using one of the two ways: Ask Friendly O to deliver the letter directly. Friendly O takes d acorns for each letter. Leave the letter at Wise R's den. Wise R values free space, so he takes c \cdot T acorns for storing a letter for a time segment of length T. The recipient can take a letter from Wise R either when he leaves his own letter at Wise R's den, or at time moment t_{n + 1}, when everybody comes to Wise R for a tea. It is not possible to take a letter from Wise R's den at other time moments. The friends can store as many letters at Wise R's den as they want, paying for each one separately. Help the friends determine the minimum possible total cost of sending all letters.InputThe first line contains three integers n, c, d (1 \leq n \leq 10^5, 1 \leq c \leq 10^2, 1 \leq d \leq 10^8) — the number of letters, the cost of storing a letter for one time unit at Wise R's den and the cost of delivering a letter via Friendly O.The next n describe the events. The i-th of them contains an integer t_i and a character p_i (0 \leq t_i \leq 10^6, p_i is either W or P) — the time the i-th event happens and the person the event happens to.The last line contains a single integer t_{n + 1} (0 \leq t_{n+1} \leq 10^6) — the time when everybody comes to Wise R for a tea and takes all remaining letters. It is guaranteed that t_i < t_{i + 1} for all i from 1 to n.OutputPrint a single integer — the minimum possible cost of delivery of all letters.ExamplesInput 5 1 4 0 P 1 W 3 P 5 P 8 P 10 Output 16 Input 10 10 94 17 W 20 W 28 W 48 W 51 P 52 W 56 W 62 P 75 P 78 P 87 Output 916 NoteOne of optimal solutions in the first example: At time moment 0 Little P leaves the letter at Wise R's den. At time moment 1 Little W leaves his letter at Wise R's den and takes Little P's letter. This letter is at the den from time moment 0 to time moment 1, it costs 1 acorn. At time moment 3 Little P sends his letter via Friendly O, it costs 4 acorns. At time moment 5 Little P leaves his letter at the den, receiving Little W's letter which storage costs 4 acorns. At time moment 8 Little P leaves one more letter at the den. At time moment 10 Little W comes to the den for a tea and receives the two letters, paying 5 and 2 acorns.The total cost of delivery is thus 1 + 4 + 4 + 5 + 2 = 16 acorns.
5 1 4 0 P 1 W 3 P 5 P 8 P 10
16
2 seconds
512 megabytes
['data structures', 'dp', 'greedy', '*3100']
E. The very same Munchhausentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x. Find out if what Baron told can be true.InputThe only line contains a single integer a (2 \le a \le 10^3).OutputIf there is no such number n, print -1.Otherwise print any appropriate positive integer n. Your number must not consist of more than 5\cdot10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5\cdot10^5 digits.ExamplesInput 2 Output 6 Input 3 Output 6669 Input 10 Output -1
2
6
1 second
256 megabytes
['brute force', '*2600']
D. Power Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with n vertices, the root of the tree is the vertex 1. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree 1.Arkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empty set of vertices of the tree. On the second stage Vasily puts some integers into all leaves of the tree. On the third stage Arkady can perform several (possibly none) operations of the following kind: choose some vertex v he bought on the first stage and some integer x, and then add x to all integers in the leaves in the subtree of v. The integer x can be positive, negative of zero.A leaf a is in the subtree of a vertex b if and only if the simple path between a and the root goes through b.Arkady's task is to make all integers in the leaves equal to zero. What is the minimum total cost s he has to pay on the first stage to guarantee his own win independently of the integers Vasily puts on the second stage? Also, we ask you to find all such vertices that there is an optimal (i.e. with cost s) set of vertices containing this one such that Arkady can guarantee his own win buying this set on the first stage.InputThe first line contains a single integer n (2 \le n \le 200\,000) — the number of vertices in the tree.The second line contains n integers c_1, c_2, \ldots, c_n (0 \le c_i \le 10^9), where c_i is the price of the i-th vertex.Each of the next n - 1 lines contains two integers a and b (1 \le a, b \le n), denoting an edge of the tree.OutputIn the first line print two integers: the minimum possible cost s Arkady has to pay to guarantee his own win, and the number of vertices k that belong to at least one optimal set.In the second line print k distinct integers in increasing order the indices of the vertices that belong to at least one optimal set.ExamplesInput 5 5 1 3 2 1 1 2 2 3 2 4 1 5 Output 4 3 2 4 5 Input 3 1 1 1 1 2 1 3 Output 2 3 1 2 3 NoteIn the second example all sets of two vertices are optimal. So, each vertex is in at least one optimal set.
5 5 1 3 2 1 1 2 2 3 2 4 1 5
4 3 2 4 5
2 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'graphs', 'greedy', 'trees', '*2500']
C. Compress Stringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are given a string s of length n consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.To compress the string, you have to represent s as a concatenation of several non-empty strings: s = t_{1} t_{2} \ldots t_{k}. The i-th of these strings should be encoded with one of the two ways: if |t_{i}| = 1, meaning that the current string consists of a single character, you can encode it paying a coins; if t_{i} is a substring of t_{1} t_{2} \ldots t_{i - 1}, then you can encode it paying b coins. A string x is a substring of a string y if x can be obtained from y by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string s.InputThe first line contains three positive integers, separated by spaces: n, a and b (1 \leq n, a, b \leq 5000) — the length of the string, the cost to compress a one-character string and the cost to compress a string that appeared before.The second line contains a single string s, consisting of n lowercase English letters.OutputOutput a single integer — the smallest possible number of coins you need to spend to compress s.ExamplesInput 3 3 1 aba Output 7 Input 4 1 1 abcd Output 4 Input 4 10 1 aaaa Output 12 NoteIn the first sample case, you can set t_{1} = 'a', t_{2} = 'b', t_{3} = 'a' and pay 3 + 3 + 1 = 7 coins, since t_{3} is a substring of t_{1}t_{2}.In the second sample, you just need to compress every character by itself.In the third sample, you set t_{1} = t_{2} = 'a', t_{3} = 'aa' and pay 10 + 1 + 1 = 12 coins, since t_{2} is a substring of t_{1} and t_{3} is a substring of t_{1} t_{2}.
3 3 1 aba
7
3 seconds
256 megabytes
['dp', 'strings', '*2100']
B. Once in a casinotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.InputThe first line contains a single integer n (2 \le n \le 10^5) standing for the length of numbers a and b.The next two lines contain numbers a and b, each one on a separate line (10^{n-1} \le a, b < 10^n).OutputIf it is impossible to win the jackpot, print a single integer -1.Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.\min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1\le d_i\le n - 1, s_i = \pm 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.ExamplesInput 3 223 322 Output 2 1 1 2 -1 Input 2 20 42 Output 2 1 1 1 1 Input 2 35 44 Output -1 NoteIn the first example, we can make a +1 operation on the two first digits, transforming number \textbf{22}3 into \textbf{33}3, and then make a -1 operation on the last two digits, transforming 3\textbf{33} into 3\textbf{22}.It's also possible to do these operations in reverse order, which makes another correct answer.In the last example, one can show that it's impossible to transform 35 into 44.
3 223 322
2 1 1 2 -1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*2700']
A. Diana and Lianatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m \ge n \cdot k), and that means every citizen will get a wreath.Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?InputThe first line contains four integers m, k, n and s (1 \le n, k, m \le 5 \cdot 10^5, k \cdot n \le m, 1 \le s \le k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.The second line contains m integers a_1, a_2, ..., a_m (1 \le a_i \le 5 \cdot 10^5)  — types of flowers on the liana.The third line contains s integers b_1, b_2, ..., b_s (1 \le b_i \le 5 \cdot 10^5)  — the sequence in Diana's schematic.OutputIf it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.Otherwise in the first line output one integer d  — the number of flowers to be removed by Diana.In the next line output d different integers  — the positions of the flowers to be removed.If there are multiple answers, print any.ExamplesInput 7 3 2 2 1 2 3 3 2 1 2 2 2 Output 1 4 Input 13 4 3 3 3 2 6 4 1 4 4 7 1 3 3 2 4 4 3 4 Output -1 Input 13 4 1 3 3 2 6 4 1 4 4 7 1 3 3 2 4 4 3 4 Output 9 1 2 3 4 5 9 11 12 13 NoteIn the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
7 3 2 2 1 2 3 3 2 1 2 2 2
1 4
2 seconds
256 megabytes
['greedy', 'implementation', 'two pointers', '*1900']
H. Tripletime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have received your birthday gifts — n triples of integers! The i-th of them is \lbrace a_{i}, b_{i}, c_{i} \rbrace. All numbers are greater than or equal to 0, and strictly smaller than 2^{k}, where k is a fixed integer.One day, you felt tired playing with triples. So you came up with three new integers x, y, z, and then formed n arrays. The i-th array consists of a_i repeated x times, b_i repeated y times and c_i repeated z times. Thus, each array has length (x + y + z).You want to choose exactly one integer from each array such that the XOR (bitwise exclusive or) of them is equal to t. Output the number of ways to choose the numbers for each t between 0 and 2^{k} - 1, inclusive, modulo 998244353.InputThe first line contains two integers n and k (1 \leq n \leq 10^{5}, 1 \leq k \leq 17) — the number of arrays and the binary length of all numbers.The second line contains three integers x, y, z (0 \leq x,y,z \leq 10^{9}) — the integers you chose.Then n lines follow. The i-th of them contains three integers a_{i}, b_{i} and c_{i} (0 \leq a_{i} , b_{i} , c_{i} \leq 2^{k} - 1) — the integers forming the i-th array.OutputPrint a single line containing 2^{k} integers. The i-th of them should be the number of ways to choose exactly one integer from each array so that their XOR is equal to t = i-1 modulo 998244353.ExamplesInput 1 1 1 2 3 1 0 1 Output 2 4 Input 2 2 1 2 1 0 1 2 1 2 3 Output 4 2 4 6 Input 4 3 1 2 3 1 3 7 0 2 5 1 0 6 3 3 2 Output 198 198 126 126 126 126 198 198 NoteIn the first example, the array we formed is (1, 0, 0, 1, 1, 1), we have two choices to get 0 as the XOR and four choices to get 1.In the second example, two arrays are (0, 1, 1, 2) and (1, 2, 2, 3). There are sixteen (4 \cdot 4) choices in total, 4 of them (1 \oplus 1 and 2 \oplus 2, two options for each) give 0, 2 of them (0 \oplus 1 and 2 \oplus 3) give 1, 4 of them (0 \oplus 2 and 1 \oplus 3, two options for each) give 2, and finally 6 of them (0 \oplus 3, 2 \oplus 1 and four options for 1 \oplus 2) give 3.
1 1 1 2 3 1 0 1
2 4
1.5 seconds
256 megabytes
['fft', 'math', '*3200']
G. Get Ready for the Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Evlampy installed one interesting computer game, one of aspects of which is to split army into several groups and then fight with enemy's groups. Let us consider a simplified version of the battle.In the nearest battle Evlampy should fight an enemy army that consists of m groups, the i-th of which has hp_i health points.Evlampy's army consists of n equal soldiers. Before each battle he should split his army in exactly m groups (possibly, empty) so that the total size of the groups is n. The battle is played step-by-step. On each step each of Evlampy's groups attacks exactly one enemy group. Thus, each step is described with an array of m integers a_1, a_2, \ldots, a_m, meaning that the i-th Evlampy's group attacks the a_i-th enemy group. Different groups can attack same group, on each step the array a is chosen independently.After each step the health points of each enemy group decreases by the total number of soldiers in Evlampy's groups that attacked this enemy group at this step. Enemy group is destroyed once its health points are zero or negative. Evlampy's soldiers do not lose health. An example of a step. The numbers in green circles represent the number of soldiers in Evlampy's groups, the arrows represent attacks, the numbers in red circles represent health points of enemy groups, the blue numbers represent how much the health points will decrease after the step. Evlampy understands that the upcoming battle will take the whole night. He became sad because this way he won't have enough time to finish his homework. Now Evlampy wants you to write a program that will help him win in the smallest possible number of steps. Can you help him?In other words, find the smallest number of steps needed to destroy all enemy groups and show a possible way of doing this. Find the requires splitting of the army into m groups and the arrays a for each step.InputThe first line contains two integers n and m (1 \leq m \leq n \leq 10^{6}) — the number of soldiers in Evlampy's army and the number of groups in enemy army. m is also equal to the maximum possible number of groups Evlampy can split the army to.The second line contains m integers hp_1, hp_2, \ldots, hp_m (1 \leq hp_i \leq 10^{6}) — the health points of each of the enemy groups.It is guaranteed that the sum of hp_i does not exceed 10^{6}.OutputPrint a single integer t — the minimum possible number of steps needed to win the battle.After that print m integers s_1, s_2, \ldots, s_m (s_i \ge 0, s_1 + s_2 + \ldots + s_m = n), meaning that the i-th group of Evlampy's army should contain s_i soldiers.In each of the next t lines print m integers a_1, a_2, \ldots, a_m (1 \le a_i \le m) — the description of one step. The integers mean that on the corresponding step the i-th Evlampy's group should attack the a_i-th enemy group. It is allowed to attack an already destroyed group.ExamplesInput 13 7 6 4 3 7 2 1 5 Output 3 0 1 2 3 1 2 4 2 6 2 4 4 2 4 3 1 7 1 7 7 1 3 1 5 3 7 5 1 Input 6 5 3 3 3 3 3 Output 3 3 3 0 0 0 1 2 3 4 5 3 4 5 5 5 5 5 5 5 5 Input 7 4 1 5 9 2 Output 3 1 2 4 0 1 4 2 3 2 3 3 3 3 3 3 3NoteThe first example is shown below.
13 7 6 4 3 7 2 1 5
3 0 1 2 3 1 2 4 2 6 2 4 4 2 4 3 1 7 1 7 7 1 3 1 5 3 7 5 1
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*3100']
F. Niyaz and Small Degreestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNiyaz has a tree with n vertices numerated from 1 to n. A tree is a connected graph without cycles.Each edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex.Niyaz does not like when vertices in the tree have too large degrees. For each x from 0 to (n-1), he wants to find the smallest total weight of a set of edges to be deleted so that degrees of all vertices become at most x.InputThe first line contains a single integer n (2 \le n \le 250\,000) — the number of vertices in Niyaz's tree.Each of the next (n - 1) lines contains three integers a, b, c (1 \le a, b \le n, 1 \leq c \leq 10^6) — the indices of the vertices connected by this edge and its weight, respectively. It is guaranteed that the given edges form a tree.OutputPrint n integers: for each x = 0, 1, \ldots, (n-1) print the smallest total weight of such a set of edges that after one deletes the edges from the set, the degrees of all vertices become less than or equal to x.ExamplesInput 5 1 2 1 1 3 2 1 4 3 1 5 4 Output 10 6 3 1 0 Input 5 1 2 1 2 3 2 3 4 5 4 5 14 Output 22 6 0 0 0 NoteIn the first example, the vertex 1 is connected with all other vertices. So for each x you should delete the (4-x) lightest edges outgoing from vertex 1, so the answers are 1+2+3+4, 1+2+3, 1+2, 1 and 0.In the second example, for x=0 you need to delete all the edges, for x=1 you can delete two edges with weights 1 and 5, and for x \geq 2 it is not necessary to delete edges, so the answers are 1+2+5+14, 1+5, 0, 0 and 0.
5 1 2 1 1 3 2 1 4 3 1 5 4
10 6 3 1 0
3 seconds
256 megabytes
['data structures', 'dp', 'trees', '*3400']
E. Pavel and Trianglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPavel has several sticks with lengths equal to powers of two.He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.InputThe first line contains a single integer n (1 \leq n \leq 300\,000) — the number of different lengths of sticks.The second line contains n integers a_0, a_1, ..., a_{n-1} (1 \leq a_i \leq 10^9), where a_i is the number of sticks with the length equal to 2^i.OutputPrint a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.ExamplesInput 5 1 2 2 2 2 Output 3 Input 3 1 1 1 Output 0 Input 3 3 3 3 Output 3 NoteIn the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): (2^0, 2^4, 2^4), (2^1, 2^3, 2^3), (2^1, 2^2, 2^2).In the second example, Pavel cannot make a single triangle.In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): (2^0, 2^0, 2^0), (2^1, 2^1, 2^1), (2^2, 2^2, 2^2).
5 1 2 2 2 2
3
2 seconds
256 megabytes
['brute force', 'dp', 'fft', 'greedy', 'ternary search', '*1900']
D. Frets On Firetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMiyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.In return, the fleas made a bigger ukulele for her: it has n strings, and each string has (10^{18} + 1) frets numerated from 0 to 10^{18}. The fleas use the array s_1, s_2, \ldots, s_n to describe the ukulele's tuning, that is, the pitch of the j-th fret on the i-th string is the integer s_i + j.Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.Each question is in the form of: "How many different pitches are there, if we consider frets between l and r (inclusive) on all strings?"Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!Formally, you are given a matrix with n rows and (10^{18}+1) columns, where the cell in the i-th row and j-th column (0 \le j \le 10^{18}) contains the integer s_i + j. You are to answer q queries, in the k-th query you have to answer the number of distinct integers in the matrix from the l_k-th to the r_k-th columns, inclusive.InputThe first line contains an integer n (1 \leq n \leq 100\,000) — the number of strings.The second line contains n integers s_1, s_2, \ldots, s_n (0 \leq s_i \leq 10^{18}) — the tuning of the ukulele.The third line contains an integer q (1 \leq q \leq 100\,000) — the number of questions.The k-th among the following q lines contains two integers l_k,r_k (0 \leq l_k \leq r_k \leq 10^{18}) — a question from the fleas.OutputOutput one number for each question, separated by spaces — the number of different pitches.ExamplesInput63 1 4 1 5 937 70 28 17Output5 10 18Input21 50000000000000000021000000000000000000 10000000000000000000 1000000000000000000Output2 1500000000000000000NoteFor the first example, the pitches on the 6 strings are as follows. \begin{matrix} \textbf{Fret} & \textbf{0} & \textbf{1} & \textbf{2} & \textbf{3} & \textbf{4} & \textbf{5} & \textbf{6} & \textbf{7} & \ldots \\ s_1: & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & \dots \\ s_2: & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & \dots \\ s_3: & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & \dots \\ s_4: & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & \dots \\ s_5: & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & \dots \\ s_6: & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & \dots \end{matrix} There are 5 different pitches on fret 7 — 8, 10, 11, 12, 16.There are 10 different pitches on frets 0, 1, 2 — 1, 2, 3, 4, 5, 6, 7, 9, 10, 11.
Input63 1 4 1 5 937 70 28 17
Output5 10 18
1.5 seconds
256 megabytes
['binary search', 'sortings', '*1800']
C. Ramesses and Corner Inversiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRamesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.You are given two matrices A and B of size n \times m, each of which consists of 0 and 1 only. You can apply the following operation to the matrix A arbitrary number of times: take any submatrix of the matrix A that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain 0, will be replaced by 1, and all corners of the submatrix that contain 1, will be replaced by 0). You have to answer whether you can obtain the matrix B from the matrix A. An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question.A submatrix of matrix M is a matrix which consist of all elements which come from one of the rows with indices x_1, x_1+1, \ldots, x_2 of matrix M and one of the columns with indices y_1, y_1+1, \ldots, y_2 of matrix M, where x_1, x_2, y_1, y_2 are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells (x_1, y_1), (x_1, y_2), (x_2, y_1), (x_2, y_2), where the cell (i,j) denotes the cell on the intersection of the i-th row and the j-th column.InputThe first line contains two integers n and m (1 \leq n, m \leq 500) — the number of rows and the number of columns in matrices A and B.Each of the next n lines contain m integers: the j-th integer in the i-th line is the j-th element of the i-th row of the matrix A (0 \leq A_{ij} \leq 1). Each of the next n lines contain m integers: the j-th integer in the i-th line is the j-th element of the i-th row of the matrix B (0 \leq B_{ij} \leq 1). OutputPrint "Yes" (without quotes) if it is possible to transform the matrix A to the matrix B using the operations described above, and "No" (without quotes), if it is not possible. You can print each letter in any case (upper or lower).ExamplesInput 3 3 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 Output Yes Input 6 7 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 1 1 0 1 0 1 0 0 0 1 0 0 1 0 1 0 1 0 1 0 0 1 1 1 0 1 0 1 1 0 1 1 0 1 0 0 1 1 0 1 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 0 0 0 1 1 1 1 0 1 Output Yes Input 3 4 0 1 0 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 Output No NoteThe examples are explained below. Example 1. Example 2. Example 3.
3 3 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0
Yes
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1500']
B. Alyona and a Narrow Fridgetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part. An example of a fridge with h = 7 and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has n bottles of milk that she wants to put in the fridge. The i-th bottle is a_i cells tall and 1 cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer k such that she can put bottles 1, 2, ..., k in the fridge at the same time. Find this largest k.InputThe first line contains two integers n and h (1 \le n \le 10^3, 1 \le h \le 10^9) — the number of bottles and the height of the fridge.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le h) — the heights of the bottles.OutputPrint the single integer k — the maximum integer such that Alyona can put the bottles 1, 2, ..., k in the fridge at the same time. If Alyona can put all bottles in the fridge, print n. It is easy to see that Alyona can always put at least one bottle in the fridge.ExamplesInput 5 7 2 3 5 4 1 Output 3 Input 10 10 9 1 1 1 1 1 1 1 1 1 Output 4 Input 5 10 3 1 4 2 4 Output 5 NoteOne of optimal locations in the first example is shown on the picture in the statement.One of optimal locations in the second example is shown on the picture below. One of optimal locations in the third example is shown on the picture below.
5 7 2 3 5 4 1
3
1 second
256 megabytes
['binary search', 'flows', 'greedy', 'sortings', '*1300']
A. Ilya and a Colorful Walktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya lives in a beautiful city of Chordalsk.There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.The houses are colored in colors c_1, c_2, \ldots, c_n so that the i-th house is colored in the color c_i. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.Ilya wants to select two houses i and j so that 1 \leq i < j \leq n, and they have different colors: c_i \neq c_j. He will then walk from the house i to the house j the distance of (j-i) units.Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.Help Ilya, find this maximum possible distance.InputThe first line contains a single integer n (3 \leq n \leq 300\,000) — the number of cities on the street.The second line contains n integers c_1, c_2, \ldots, c_n (1 \leq c_i \leq n) — the colors of the houses.It is guaranteed that there is at least one pair of indices i and j so that 1 \leq i < j \leq n and c_i \neq c_j.OutputPrint a single integer — the maximum possible distance Ilya can walk.ExamplesInput 5 1 2 3 2 3 Output 4 Input 3 1 2 1 Output 1 Input 7 1 1 3 1 1 1 1 Output 4 NoteIn the first example the optimal way is to walk from the first house to the last one, where Ilya can walk the distance of 5-1 = 4 units.In the second example the optimal way is to either walk from the first house to the second or from the second to the third. Both these ways have the distance of 1 unit.In the third example the optimal way is to walk from the third house to the last one, where Ilya can walk the distance of 7-3 = 4 units.
5 1 2 3 2 3
4
2 seconds
256 megabytes
['greedy', 'implementation', '*1100']
F2. Tree Cutting (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected tree of n vertices. Some vertices are colored one of the k colors, some are uncolored. It is guaranteed that the tree contains at least one vertex of each of the k colors. There might be no uncolored vertices.You choose a subset of exactly k - 1 edges and remove it from the tree. Tree falls apart into k connected components. Let's call this subset of edges nice if none of the resulting components contain vertices of different colors.How many nice subsets of edges are there in the given tree? Two subsets are considered different if there is some edge that is present in one subset and absent in the other.The answer may be large, so print it modulo 998244353.InputThe first line contains two integers n and k (2 \le n \le 3 \cdot 10^5, 2 \le k \le n) — the number of vertices in the tree and the number of colors, respectively.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le k) — the colors of the vertices. a_i = 0 means that vertex i is uncolored, any other value means the vertex i is colored that color.The i-th of the next n - 1 lines contains two integers v_i and u_i (1 \le v_i, u_i \le n, v_i \ne u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one vertex of each of the k colors. There might be no uncolored vertices.OutputPrint a single integer — the number of nice subsets of edges in the given tree. Two subsets are considered different if there is some edge that is present in one subset and absent in the other.The answer may be large, so print it modulo 998244353.ExamplesInput 5 2 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 7 3 0 1 0 2 2 3 0 1 3 1 4 1 5 2 7 3 6 4 7 Output 4 NoteHere is the tree from the first example: The only nice subset is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a vertex of color 1 and the second component includes only vertices of color 2 and uncolored vertices.Here is the tree from the second example: The nice subsets are \{(1, 3), (4, 7)\}, \{(1, 3), (7, 2)\}, \{(3, 6), (4, 7)\} and \{(3, 6), (7, 2)\}.
5 2 2 0 0 1 2 1 2 2 3 2 4 2 5
1
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'dp', 'trees', '*2700']
F1. Tree Cutting (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.How many nice edges are there in the given tree?InputThe first line contains a single integer n (2 \le n \le 3 \cdot 10^5) — the number of vertices in the tree.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored.The i-th of the next n - 1 lines contains two integers v_i and u_i (1 \le v_i, u_i \le n, v_i \ne u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.OutputPrint a single integer — the number of nice edges in the given tree.ExamplesInput 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 NoteHere is the tree from the first example: The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.Here is the tree from the second example: Every edge is nice in it.Here is the tree from the third example: Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
5 2 0 0 1 2 1 2 2 3 2 4 2 5
1
2 seconds
256 megabytes
['dfs and similar', 'trees', '*1800']
E. Yet Another Ball Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe king of Berland organizes a ball! n pair are invited to the ball, they are numbered from 1 to n. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from 1 to k, inclusive.Let b_i be the color of the man's costume and g_i be the color of the woman's costume in the i-th pair. You have to choose a color for each dancer's costume (i.e. values b_1, b_2, \dots, b_n and g_1, g_2, \dots g_n) in such a way that: for every i: b_i and g_i are integers between 1 and k, inclusive; there are no two completely identical pairs, i.e. no two indices i, j (i \ne j) such that b_i = b_j and g_i = g_j at the same time; there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. b_i \ne g_i for every i; for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every i from 1 to n-1 the conditions b_i \ne b_{i + 1} and g_i \ne g_{i + 1} hold. Let's take a look at the examples of bad and good color choosing (for n=4 and k=3, man is the first in a pair and woman is the second):Bad color choosing: (1, 2), (2, 3), (3, 2), (1, 2) — contradiction with the second rule (there are equal pairs); (2, 3), (1, 1), (3, 2), (1, 3) — contradiction with the third rule (there is a pair with costumes of the same color); (1, 2), (2, 3), (1, 3), (2, 1) — contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same). Good color choosing: (1, 2), (2, 1), (1, 3), (3, 1); (1, 2), (3, 1), (2, 3), (3, 2); (3, 1), (1, 2), (2, 3), (3, 2). You have to find any suitable color choosing or say that no suitable choosing exists.InputThe only line of the input contains two integers n and k (2 \le n, k \le 2 \cdot 10^5) — the number of pairs and the number of colors.OutputIf it is impossible to find any suitable colors choosing, print "NO".Otherwise print "YES" and then the colors of the costumes of pairs in the next n lines. The i-th line should contain two integers b_i and g_i — colors of costumes of man and woman in the i-th pair, respectively.You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.ExamplesInput 4 3 Output YES 3 1 1 3 3 2 2 3 Input 10 4 Output YES 2 1 1 3 4 2 3 4 4 3 3 2 2 4 4 1 1 4 3 1 Input 13 4 Output NO
4 3
YES 3 1 1 3 3 2 2 3
3 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1700']
D2. Coffee and Coursework (Hard Version)time limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of m pages.Polycarp also has n cups of coffee. The coffee in the i-th cup Polycarp has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks k cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are a_{i_1}, a_{i_2}, \dots, a_{i_k}. Then the first cup he drinks gives him energy to write a_{i_1} pages of coursework, the second cup gives him energy to write max(0, a_{i_2} - 1) pages, the third cup gives him energy to write max(0, a_{i_3} - 2) pages, ..., the k-th cup gives him energy to write max(0, a_{i_k} - k + 1) pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.InputThe first line of the input contains two integers n and m (1 \le n \le 2 \cdot 10^5, 1 \le m \le 10^9) — the number of cups of coffee and the number of pages in the coursework.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the caffeine dosage of coffee in the i-th cup.OutputIf it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.ExamplesInput 5 8 2 3 1 1 2 Output 4 Input 7 10 1 3 4 2 1 4 2 Output 2 Input 5 15 5 5 5 5 5 Output 1 Input 5 16 5 5 5 5 5 Output 2 Input 5 26 5 5 5 5 5 Output -1 NoteIn the first example Polycarp can drink fourth cup during first day (and write 1 page), first and second cups during second day (and write 2 + (3 - 1) = 4 pages), fifth cup during the third day (and write 2 pages) and third cup during the fourth day (and write 1 page) so the answer is 4. It is obvious that there is no way to write the coursework in three or less days.In the second example Polycarp can drink third, fourth and second cups during first day (and write 4 + (2 - 1) + (3 - 2) = 6 pages) and sixth cup during second day (and write 4 pages) so the answer is 2. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write 5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15 pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write 5 + (5 - 1) + (5 - 2) + (5 - 3) = 14 pages of coursework and during second day he will write 5 pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.
5 8 2 3 1 1 2
4
2.5 seconds
256 megabytes
['binary search', 'greedy', '*1700']
D1. Coffee and Coursework (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of m pages.Polycarp also has n cups of coffee. The coffee in the i-th cup has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work.Let's consider some day of Polycarp's work. Consider Polycarp drinks k cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are a_{i_1}, a_{i_2}, \dots, a_{i_k}. Then the first cup he drinks gives him energy to write a_{i_1} pages of coursework, the second cup gives him energy to write max(0, a_{i_2} - 1) pages, the third cup gives him energy to write max(0, a_{i_3} - 2) pages, ..., the k-th cup gives him energy to write max(0, a_{i_k} - k + 1) pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.InputThe first line of the input contains two integers n and m (1 \le n \le 100, 1 \le m \le 10^4) — the number of cups of coffee and the number of pages in the coursework.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the caffeine dosage of coffee in the i-th cup.OutputIf it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.ExamplesInput 5 8 2 3 1 1 2 Output 4 Input 7 10 1 3 4 2 1 4 2 Output 2 Input 5 15 5 5 5 5 5 Output 1 Input 5 16 5 5 5 5 5 Output 2 Input 5 26 5 5 5 5 5 Output -1 NoteIn the first example Polycarp can drink fourth cup during first day (and write 1 page), first and second cups during second day (and write 2 + (3 - 1) = 4 pages), fifth cup during the third day (and write 2 pages) and third cup during the fourth day (and write 1 page) so the answer is 4. It is obvious that there is no way to write the coursework in three or less days in this test.In the second example Polycarp can drink third, fourth and second cups during first day (and write 4 + (2 - 1) + (3 - 2) = 6 pages) and sixth cup during second day (and write 4 pages) so the answer is 2. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write 5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15 pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write 5 + (5 - 1) + (5 - 2) + (5 - 3) = 14 pages of coursework and during second day he will write 5 pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.
5 8 2 3 1 1 2
4
1 second
256 megabytes
['brute force', 'greedy', '*1700']
C. Palindromic Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given n^2 integers. Put them into a matrix of n rows and n columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".InputThe first line contains one integer n (1 \le n \le 20).The second line contains n^2 integers a_1, a_2, \dots, a_{n^2} (1 \le a_i \le 1000) — the numbers to put into a matrix of n rows and n columns.OutputIf it is possible to put all of the n^2 numbers into a matrix of n rows and n columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print n lines with n space-separated numbers — the resulting matrix.If it's impossible to construct any matrix, then print "NO".You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.ExamplesInput 4 1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1 Output YES 1 2 2 1 8 2 2 8 8 2 2 8 1 2 2 1 Input 3 1 1 1 1 1 3 3 3 3 Output YES 1 3 1 3 1 3 1 3 1 Input 4 1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1 Output NO Input 1 10 Output YES 10 NoteNote that there exist multiple answers for the first two examples.
4 1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1
YES 1 2 2 1 8 2 2 8 8 2 2 8 1 2 2 1
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1700']
B. Tanya and Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya has n candies numbered from 1 to n. The i-th candy has the weight a_i.She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies i (let's call these candies good) that if dad gets the i-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, n=4 and weights are [1, 4, 3, 3]. Consider all possible cases to give a candy to dad: Tanya gives the 1-st candy to dad (a_1=1), the remaining candies are [4, 3, 3]. She will eat a_2=4 in the first day, a_3=3 in the second day, a_4=3 in the third day. So in odd days she will eat 4+3=7 and in even days she will eat 3. Since 7 \ne 3 this case shouldn't be counted to the answer (this candy isn't good). Tanya gives the 2-nd candy to dad (a_2=4), the remaining candies are [1, 3, 3]. She will eat a_1=1 in the first day, a_3=3 in the second day, a_4=3 in the third day. So in odd days she will eat 1+3=4 and in even days she will eat 3. Since 4 \ne 3 this case shouldn't be counted to the answer (this candy isn't good). Tanya gives the 3-rd candy to dad (a_3=3), the remaining candies are [1, 4, 3]. She will eat a_1=1 in the first day, a_2=4 in the second day, a_4=3 in the third day. So in odd days she will eat 1+3=4 and in even days she will eat 4. Since 4 = 4 this case should be counted to the answer (this candy is good). Tanya gives the 4-th candy to dad (a_4=3), the remaining candies are [1, 4, 3]. She will eat a_1=1 in the first day, a_2=4 in the second day, a_3=3 in the third day. So in odd days she will eat 1+3=4 and in even days she will eat 4. Since 4 = 4 this case should be counted to the answer (this candy is good). In total there 2 cases which should counted (these candies are good), so the answer is 2.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of candies.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^4), where a_i is the weight of the i-th candy.OutputPrint one integer — the number of such candies i (good candies) that if dad gets the i-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.ExamplesInput 7 5 5 4 5 5 5 6 Output 2 Input 8 4 8 8 7 8 4 4 5 Output 2 Input 9 2 3 4 2 2 3 2 2 4 Output 3 NoteIn the first example indices of good candies are [1, 2].In the second example indices of good candies are [2, 3].In the third example indices of good candies are [4, 5, 9].
7 5 5 4 5 5 5 6
2
1 second
256 megabytes
['implementation', '*1200']
A. Water Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.There are only two types of water bottles in the nearby shop — 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs a burles and the bottle of the second type costs b burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly n liters of water in the nearby shop if the bottle of the first type costs a burles and the bottle of the second type costs b burles. You also have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries.The next q lines contain queries. The i-th query is given as three space-separated integers n_i, a_i and b_i (1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000) — how many liters Polycarp needs in the i-th query, the cost (in burles) of the bottle of the first type in the i-th query and the cost (in burles) of the bottle of the second type in the i-th query, respectively.OutputPrint q integers. The i-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly n_i liters of water in the nearby shop if the bottle of the first type costs a_i burles and the bottle of the second type costs b_i burles.ExampleInput 4 10 1 3 7 3 2 1 1000 1 1000000000000 42 88 Output 10 9 1000 42000000000000
4 10 1 3 7 3 2 1 1000 1 1000000000000 42 88
10 9 1000 42000000000000
1 second
256 megabytes
['math', '*800']
G. Recursive Queriestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \dots, p_n. You should answer q queries. Each query is a pair (l_i, r_i), and you should calculate f(l_i, r_i).Let's denote m_{l, r} as the position of the maximum in subsegment p_l, p_{l+1}, \dots, p_r.Then f(l, r) = (r - l + 1) + f(l, m_{l,r} - 1) + f(m_{l,r} + 1, r) if l \le r or 0 otherwise.InputThe first line contains two integers n and q (1 \le n \le 10^6, 1 \le q \le 10^6) — the size of the permutation p and the number of queries.The second line contains n pairwise distinct integers p_1, p_2, \dots, p_n (1 \le p_i \le n, p_i \neq p_j for i \neq j) — permutation p.The third line contains q integers l_1, l_2, \dots, l_q — the first parts of the queries.The fourth line contains q integers r_1, r_2, \dots, r_q — the second parts of the queries.It's guaranteed that 1 \le l_i \le r_i \le n for all queries.OutputPrint q integers — the values f(l_i, r_i) for the corresponding queries.ExampleInput 4 5 3 1 4 2 2 1 1 2 1 2 3 4 4 1 Output 1 6 8 5 1 NoteDescription of the queries: f(2, 2) = (2 - 2 + 1) + f(2, 1) + f(3, 2) = 1 + 0 + 0 = 1; f(1, 3) = (3 - 1 + 1) + f(1, 2) + f(4, 3) = 3 + (2 - 1 + 1) + f(1, 0) + f(2, 2) = 3 + 2 + (2 - 2 + 1) = 6; f(1, 4) = (4 - 1 + 1) + f(1, 2) + f(4, 4) = 4 + 3 + 1 = 8; f(2, 4) = (4 - 2 + 1) + f(2, 2) + f(4, 4) = 3 + 1 + 1 = 5; f(1, 1) = (1 - 1 + 1) + 0 + 0 = 1.
4 5 3 1 4 2 2 1 1 2 1 2 3 4 4 1
1 6 8 5 1
4 seconds
256 megabytes
['data structures', '*2500']
F. Crisp Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string of length n. Each character is one of the first p lowercase Latin letters.You are also given a matrix A with binary values of size p \times p. This matrix is symmetric (A_{ij} = A_{ji}). A_{ij} = 1 means that the string can have the i-th and j-th letters of Latin alphabet adjacent.Let's call the string crisp if all of the adjacent characters in it can be adjacent (have 1 in the corresponding cell of matrix A).You are allowed to do the following move. Choose any letter, remove all its occurrences and join the remaining parts of the string without changing their order. For example, removing letter 'a' from "abacaba" will yield "bcb".The string you are given is crisp. The string should remain crisp after every move you make.You are allowed to do arbitrary number of moves (possible zero). What is the shortest resulting string you can obtain?InputThe first line contains two integers n and p (1 \le n \le 10^5, 1 \le p \le 17) — the length of the initial string and the length of the allowed prefix of Latin alphabet.The second line contains the initial string. It is guaranteed that it contains only first p lowercase Latin letters and that is it crisp. Some of these p first Latin letters might not be present in the string.Each of the next p lines contains p integer numbers — the matrix A (0 \le A_{ij} \le 1, A_{ij} = A_{ji}). A_{ij} = 1 means that the string can have the i-th and j-th letters of Latin alphabet adjacent.OutputPrint a single integer — the length of the shortest string after you make arbitrary number of moves (possible zero).ExamplesInput 7 3 abacaba 0 1 1 1 0 0 1 0 0 Output 7 Input 7 3 abacaba 1 1 1 1 0 0 1 0 0 Output 0 Input 7 4 bacadab 0 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 Output 5 Input 3 3 cbc 0 0 0 0 0 1 0 1 0 Output 0 NoteIn the first example no letter can be removed from the initial string.In the second example you can remove letters in order: 'b', 'c', 'a'. The strings on the intermediate steps will be: "abacaba" \rightarrow "aacaa" \rightarrow "aaaa" \rightarrow "".In the third example you can remove letter 'b' and that's it.In the fourth example you can remove letters in order 'c', 'b', but not in the order 'b', 'c' because two letters 'c' can't be adjacent.
7 3 abacaba 0 1 1 1 0 0 1 0 0
7
2 seconds
256 megabytes
['bitmasks', 'dp', '*2500']
E. Decypher the Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.You are given a string t consisting of n lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string s consisting of n lowercase Latin letters. Then they applied a sequence of no more than n (possibly zero) operations. i-th operation is denoted by two integers a_i and b_i (1 \le a_i, b_i \le n), and means swapping two elements of the string with indices a_i and b_i. All operations were done in the order they were placed in the sequence. For example, if s is xyz and 2 following operations are performed: a_1 = 1, b_1 = 2; a_2 = 2, b_2 = 3, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so t is yzx.You are asked to restore the original string s. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is n, and get the resulting string after those operations.Can you guess the original string s asking the testing system to run the sequence of swaps no more than 3 times?The string s and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution.InputInitially the testing system sends one string t, consisting of lowercase Latin letters (1 \le |t| = n \le 10^4).OutputTo give the answer, your program should print one line ! s with a line break in the end. After that, it should flush the output and terminate gracefully.InteractionBefore giving the answer, you may submit no more than 3 queries. To ask a query, print one line in the following format: ? s', where s' should be a string consisting of exaclty n lowercase Latin letters. The line should be ended with a line break character. After submitting a query, flush the output and read the answer to your query — a string t' consisting of n lowercase Latin letters, which is the result of applying the sequence of swaps to string s'. This string will be given on a separate line ended by a line break character.If you submit an incorrect query (or ask more than 3 queries), the answer to it will be one string 0. After receiving such an answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer".ExampleInput yzx aab baa abaOutput ? baa ? aba ? aab ! xyz NoteIn the sample, the testcase described in the statement is used. The participant asks the first query with string baa, which is transformed to aab. The second query contains string aba, which is transformed to baa. The third query contains string aab, which is transformed to aba. The participant can deduce that the initial string s was xyz.Note for hacking phase:To submit a test in hacking phase, you should provide it in the following format:The first line should contain the string s you guess, consisting of n \in [1, 10000] lowercase Latin letters.The second line should contain k (0 \le k \le n) — the number of swap operations in the sequence.Then k lines should follow, i-th of them should denote i-th operation with two integers a_i and b_i (1 \le a_i, b_i \le n).For example, the sample test would look like that:xyz21 22 3
yzx aab baa aba
? baa ? aba ? aab ! xyz
2 seconds
256 megabytes
['bitmasks', 'chinese remainder theorem', 'constructive algorithms', 'interactive', 'math', '*2200']
D. Magic Gemstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split.Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic gem is chosen and split, it takes M units of space (since it is split into M gems); if a magic gem is not split, it takes 1 unit.How many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is N units? Print the answer modulo 1000000007 (10^9+7). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ.InputThe input contains a single line consisting of 2 integers N and M (1 \le N \le 10^{18}, 2 \le M \le 100).OutputPrint one integer, the total number of configurations of the resulting set of gems, given that the total amount of space taken is N units. Print the answer modulo 1000000007 (10^9+7).ExamplesInput 4 2 Output 5 Input 3 2 Output 3 NoteIn the first example each magic gem can split into 2 normal gems, and we know that the total amount of gems are 4.Let 1 denote a magic gem, and 0 denote a normal gem.The total configurations you can have is: 1 1 1 1 (None of the gems split); 0 0 1 1 (First magic gem splits into 2 normal gems); 1 0 0 1 (Second magic gem splits into 2 normal gems); 1 1 0 0 (Third magic gem splits into 2 normal gems); 0 0 0 0 (First and second magic gems split into total 4 normal gems). Hence, answer is 5.
4 2
5
3 seconds
256 megabytes
['dp', 'math', 'matrices', '*2100']
C. Magic Shiptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2).You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2).InputThe first line contains two integers x_1, y_1 (0 \le x_1, y_1 \le 10^9) — the initial coordinates of the ship.The second line contains two integers x_2, y_2 (0 \le x_2, y_2 \le 10^9) — the coordinates of the destination point.It is guaranteed that the initial coordinates and destination point coordinates are different.The third line contains a single integer n (1 \le n \le 10^5) — the length of the string s.The fourth line contains the string s itself, consisting only of letters U, D, L and R.OutputThe only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2).If it's impossible then print "-1".ExamplesInput 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) \rightarrow (1, 1) \rightarrow (2, 2) \rightarrow (3, 3) \rightarrow (4, 4) \rightarrow (4, 6).In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) \rightarrow (0, 3) \rightarrow (0, 1) \rightarrow (0, 0).In the third example the ship can never reach the point (0, 1).
0 0 4 6 3 UUU
5
2 seconds
256 megabytes
['binary search', '*1900']
B. Emotestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only m times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than k times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes i and j (i \ne j) such that a_i = a_j are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.InputThe first line of the input contains three integers n, m and k (2 \le n \le 2 \cdot 10^5, 1 \le k \le m \le 2 \cdot 10^9) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is value of the happiness of the i-th emote.OutputPrint one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.ExamplesInput 6 9 2 1 3 3 7 4 2 Output 54 Input 3 1000000000 1 1000000000 987654321 1000000000 Output 1000000000000000000 NoteIn the first example you may use emotes in the following sequence: 4, 4, 5, 4, 4, 5, 4, 4, 5.
6 9 2 1 3 3 7 4 2
54
1 second
256 megabytes
['greedy', 'math', 'sortings', '*1000']
A. Best Subsegmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given array a_1, a_2, \dots, a_n. Find the subsegment a_l, a_{l+1}, \dots, a_r (1 \le l \le r \le n) with maximum arithmetic mean \frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).If there are many such subsegments find the longest one.InputThe first line contains single integer n (1 \le n \le 10^5) — length of the array a.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9) — the array a.OutputPrint the single integer — the length of the longest subsegment with maximum possible arithmetic mean.ExampleInput 5 6 1 6 6 0 Output 2 NoteThe subsegment [3, 4] is the longest among all subsegments with maximum arithmetic mean.
5 6 1 6 6 0
2
1 second
256 megabytes
['implementation', 'math', '*1100']
F. Please, another Queries on Array?time limit per test5.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n.You need to perform q queries of the following two types: "MULTIPLY l r x" — for every i (l \le i \le r) multiply a_i by x. "TOTIENT l r" — print \varphi(\prod \limits_{i=l}^{r} a_i) taken modulo 10^9+7, where \varphi denotes Euler's totient function. The Euler's totient function of a positive integer n (denoted as \varphi(n)) is the number of integers x (1 \le x \le n) such that \gcd(n,x) = 1.InputThe first line contains two integers n and q (1 \le n \le 4 \cdot 10^5, 1 \le q \le 2 \cdot 10^5) — the number of elements in array a and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 300) — the elements of array a.Then q lines follow, describing queries in the format given in the statement. "MULTIPLY l r x" (1 \le l \le r \le n, 1 \le x \le 300) — denotes a multiplication query. "TOTIENT l r" (1 \le l \le r \le n) — denotes a query on the value of Euler's totient function. It is guaranteed that there is at least one "TOTIENT" query.OutputFor each "TOTIENT" query, print the answer to it.ExampleInput4 45 9 1 2TOTIENT 3 3TOTIENT 3 4MULTIPLY 4 4 3TOTIENT 4 4Output112NoteIn the first example, \varphi(1) = 1 for the first query, \varphi(2) = 1 for the second query and \varphi(6) = 2 for the third one.
Input4 45 9 1 2TOTIENT 3 3TOTIENT 3 4MULTIPLY 4 4 3TOTIENT 4 4
Output112
5.5 seconds
256 megabytes
['bitmasks', 'data structures', 'divide and conquer', 'math', 'number theory', '*2400']
E. Arithmetic Progressiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element (x_i - x_{i - 1}, where i \ge 2) is constant — such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form x_i = x_1 + (i - 1) d, where d is a common difference of the sequence.There is a secret list of n integers a_1, a_2, \ldots, a_n.It is guaranteed that all elements a_1, a_2, \ldots, a_n are between 0 and 10^9, inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference (d > 0). For example, the list [14, 24, 9, 19] satisfies this requirement, after sorting it makes a list [9, 14, 19, 24], which can be produced as x_n = 9 + 5 \cdot (n - 1).Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most 60 queries of following two types: Given a value i (1 \le i \le n), the device will show the value of the a_i. Given a value x (0 \le x \le 10^9), the device will return 1 if an element with a value strictly greater than x exists, and it will return 0 otherwise.Your can use this special device for at most 60 queries. Could you please find out the smallest element and the common difference of the sequence? That is, values x_1 and d in the definition of the arithmetic progression. Note that the array a is not sorted.InteractionThe interaction starts with a single integer n (2 \le n \le 10^6), the size of the list of integers.Then you can make queries of two types: "? i" (1 \le i \le n) — to get the value of a_i. "> x" (0 \le x \le 10^9) — to check whether there exists an element greater than xAfter the query read its result r as an integer. For the first query type, the r satisfies 0 \le r \le 10^9. For the second query type, the r is either 0 or 1. In case you make more than 60 queries or violated the number range in the queries, you will get a r = -1. If you terminate after receiving the -1, you will get the "Wrong answer" verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream. When you find out what the smallest element x_1 and common difference d, print "! x_1 d" And quit after that. This query is not counted towards the 60 queries limit.After printing any query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.HacksFor hack, use the following format:The first line should contain an integer n (2 \le n \le 10^6) — the list's size.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the elements of the list.Also, after the sorting the list must form an arithmetic progression with positive common difference.ExampleInput 4 0 1 14 24 9 19 Output > 25 > 15 ? 1 ? 2 ? 3 ? 4 ! 9 5NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The list in the example test is [14, 24, 9, 19].
4 0 1 14 24 9 19
> 25 > 15 ? 1 ? 2 ? 3 ? 4 ! 9 5
2 seconds
256 megabytes
['binary search', 'interactive', 'number theory', 'probabilities', '*2200']
D. Flood Filltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a line of n colored squares in a row, numbered from 1 to n from left to right. The i-th square initially has the color c_i.Let's say, that two squares i and j belong to the same connected component if c_i = c_j, and c_i = c_k for all k satisfying i < k < j. In other words, all squares on the segment from i to j should have the same color.For example, the line [3, 3, 3] has 1 connected component, while the line [5, 2, 4, 4] has 3 connected components.The game "flood fill" is played on the given line as follows: At the start of the game you pick any starting square (this is not counted as a turn). Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color.InputThe first line contains a single integer n (1 \le n \le 5000) — the number of squares.The second line contains integers c_1, c_2, \ldots, c_n (1 \le c_i \le 5000) — the initial colors of the squares.OutputPrint a single integer — the minimum number of the turns needed.ExamplesInput 4 5 2 2 1 Output 2 Input 8 4 5 2 2 1 3 5 5 Output 4 Input 1 4 Output 0 NoteIn the first example, a possible way to achieve an optimal answer is to pick square with index 2 as the starting square and then play as follows: [5, 2, 2, 1] [5, 5, 5, 1] [1, 1, 1, 1] In the second example, a possible way to achieve an optimal answer is to pick square with index 5 as the starting square and then perform recoloring into colors 2, 3, 5, 4 in that order.In the third example, the line already consists of one color only.
4 5 2 2 1
2
2 seconds
256 megabytes
['dp', '*1900']
C. Trailing Loves (or L'oeufs?)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis. Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n\,! (factorial of n). InputThe only line of the input contains two integers n and b (1 \le n \le 10^{18}, 2 \le b \le 10^{12}).OutputPrint an only integer — the number of trailing zero digits in the b-ary representation of n!ExamplesInput6 9Output1Input38 11Output3Input5 2Output3Input5 10Output1NoteIn the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.The representation of the number x in the b-ary base is d_1, d_2, \ldots, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + \ldots + d_k b^0, where d_i are integers and 0 \le d_i \le b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 \cdot 9^2 + 8 \cdot 9 + 0 \cdot 1.You can read more about bases here.
Input6 9
Output1
2 seconds
256 megabytes
['brute force', 'implementation', 'math', 'number theory', '*1700']
B. Yet Another Array Partitioning Tasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, \ldots, a_r for some l, r.Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example: For array x = [4, 3, 1, 5, 2] and m = 3, the 3 largest elements of x are 5, 4 and 3, so the beauty of x is 5 + 4 + 3 = 12. For array x = [10, 10, 10] and m = 2, the beauty of x is 10 + 10 = 20.You are given an array a_1, a_2, \ldots, a_n, the value of the said constant m and an integer k. Your need to split the array a into exactly k subarrays such that: Each element from a belongs to exactly one subarray. Each subarray has at least m elements. The sum of all beauties of k subarrays is maximum possible.InputThe first line contains three integers n, m and k (2 \le n \le 2 \cdot 10^5, 1 \le m, 2 \le k, m \cdot k \le n) — the number of elements in a, the constant m in the definition of beauty and the number of subarrays to split to.The second line contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9).OutputIn the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition.In the second line, print k-1 integers p_1, p_2, \ldots, p_{k-1} (1 \le p_1 < p_2 < \ldots < p_{k-1} < n) representing the partition of the array, in which: All elements with indices from 1 to p_1 belong to the first subarray. All elements with indices from p_1 + 1 to p_2 belong to the second subarray. \ldots. All elements with indices from p_{k-1} + 1 to n belong to the last, k-th subarray.If there are several optimal partitions, print any of them.ExamplesInput 9 2 3 5 2 5 2 4 1 1 3 2 Output 21 3 5 Input 6 1 4 4 1 3 2 2 3 Output 12 1 3 5 Input 2 1 2 -1000000000 1000000000 Output 0 1 NoteIn the first example, one of the optimal partitions is [5, 2, 5], [2, 4], [1, 1, 3, 2]. The beauty of the subarray [5, 2, 5] is 5 + 5 = 10. The beauty of the subarray [2, 4] is 2 + 4 = 6. The beauty of the subarray [1, 1, 3, 2] is 3 + 2 = 5. The sum of their beauties is 10 + 6 + 5 = 21.In the second example, one optimal partition is [4], [1, 3], [2, 2], [3].
9 2 3 5 2 5 2 4 1 1 3 2
21 3 5
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1500']
A. Got Any Grapes?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Duck songFor simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively. Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only. On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes. Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?It is not required to distribute all the grapes, so it's possible that some of them will remain unused.InputThe first line contains three integers x, y and z (1 \le x, y, z \le 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.The second line contains three integers a, b, c (1 \le a, b, c \le 10^5) — the number of green, purple and black grapes in the box.OutputIf there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".ExamplesInput1 6 24 3 3OutputYESInput5 1 14 3 2OutputNONoteIn the first example, there is only one possible distribution:Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Input1 6 24 3 3
OutputYES
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*800']
B. Sasha and Magnetic Machinestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer x, then choose one machine and reduce the power of its machine by x times, and at the same time increase the power of one another machine by x times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices i and j, and one integer x such that x is a divisor of a_i, and change powers as following: a_i = \frac{a_i}{x}, a_j = a_j \cdot xSasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!InputThe first line contains one integer n (2 \le n \le 5 \cdot 10^4) — the number of machines.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 100) — the powers of the machines.OutputPrint one integer — minimum total power.ExamplesInput 5 1 2 3 4 5 Output 14 Input 4 4 2 4 4 Output 14 Input 5 2 4 2 3 7 Output 18 NoteIn the first example, the farmer can reduce the power of the 4-th machine by 2 times, and increase the power of the 1-st machine by 2 times, then the powers will be: [2, 2, 3, 2, 5].In the second example, the farmer can reduce the power of the 3-rd machine by 2 times, and increase the power of the 2-nd machine by 2 times. At the same time, the farmer can leave is be as it is and the total power won't change.In the third example, it is optimal to leave it be as it is.
5 1 2 3 4 5
14
1 second
256 megabytes
['greedy', 'number theory', '*1300']
A. Sasha and His Triptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in the country are directed, it's possible to reach the city y from the city x only if x < y. Once Sasha decided to go on a trip around the country and to visit all n cities. He will move with the help of his car, Cheetah-2677. The tank capacity of this model is v liters, and it spends exactly 1 liter of fuel for 1 kilometer of the way. At the beginning of the journey, the tank is empty. Sasha is located in the city with the number 1 and wants to get to the city with the number n. There is a gas station in each city. In the i-th city, the price of 1 liter of fuel is i dollars. It is obvious that at any moment of time, the tank can contain at most v liters of fuel.Sasha doesn't like to waste money, that's why he wants to know what is the minimum amount of money is needed to finish the trip if he can buy fuel in any city he wants. Help him to figure it out!InputThe first line contains two integers n and v (2 \le n \le 100, 1 \le v \le 100)  — the number of cities in the country and the capacity of the tank.OutputPrint one integer — the minimum amount of money that is needed to finish the trip.ExamplesInput 4 2 Output 4 Input 7 6 Output 6 NoteIn the first example, Sasha can buy 2 liters for 2 dollars (1 dollar per liter) in the first city, drive to the second city, spend 1 liter of fuel on it, then buy 1 liter for 2 dollars in the second city and then drive to the 4-th city. Therefore, the answer is 1+1+2=4.In the second example, the capacity of the tank allows to fill the tank completely in the first city, and drive to the last city without stops in other cities.
4 2
4
1 second
256 megabytes
['dp', 'greedy', 'math', '*900']
E. Treetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n nodes and q queries.Every query starts with three integers k, m and r, followed by k nodes of the tree a_1, a_2, \ldots, a_k. To answer a query, assume that the tree is rooted at r. We want to divide the k given nodes into at most m groups such that the following conditions are met: Each node should be in exactly one group and each group should have at least one node. In any group, there should be no two distinct nodes such that one node is an ancestor (direct or indirect) of the other. You need to output the number of ways modulo 10^{9}+7 for every query.InputThe first line contains two integers n and q (1 \le n, q \le 10^{5}) — the number of vertices in the tree and the number of queries, respectively.Each of the next n-1 lines contains two integers u and v (1 \le u, v \le n, u \ne v), denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree.Each of the next q lines starts with three integers k, m and r (1 \le k, r \le n, 1 \le m \le min(300,k)) — the number of nodes, the maximum number of groups and the root of the tree for the current query, respectively. They are followed by k distinct integers a_1, a_2, \ldots, a_k (1 \le a_i \le n), denoting the nodes of the current query.It is guaranteed that the sum of k over all queries does not exceed 10^{5}.OutputPrint q lines, where the i-th line contains the answer to the i-th query.ExamplesInput 7 2 5 4 2 6 5 3 1 2 7 5 4 6 3 3 2 7 4 3 3 1 4 6 2 1 Output 2 0 Input 7 2 4 7 2 5 4 1 5 1 5 6 4 3 3 3 2 7 1 4 2 1 6 3 2 Output 1 1 Input 5 2 3 5 4 5 4 2 1 4 2 2 3 1 2 2 2 4 5 4 Output 2 1 NoteConsider the first example.In the first query, we have to divide the three given nodes (7, 4 and 3), into the maximum of three groups assuming that the tree is rooted at 2. When the tree is rooted at 2, 4 is an ancestor of both 3 and 7. So we can't put all the nodes into one group. There is only 1 way to divide the given nodes into two groups, which are [4] and [3, 7]. Also, there is only one way to divide the given nodes into three groups, which are [7], [4] and [3]. So, there are total 2 ways to divide the given nodes into a maximum of three groups.In the second query, when the tree is rooted at 4, 6 is an ancestor of 2 and 2 is an ancestor of 1. So, we can't put all the given nodes into one group.
7 2 5 4 2 6 5 3 1 2 7 5 4 6 3 3 2 7 4 3 3 1 4 6 2 1
2 0
1.5 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'graphs', 'trees', '*2500']
D. Destroy the Colonytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.Each colony arrangement can be expressed as a string of even length, where the i-th character of the string represents the type of villain in the i-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.Now Iron Man asks Jarvis q questions. In each question, he gives Jarvis two numbers x and y. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in x-th hole or y-th hole live in the same half and the Iron Man can destroy that colony arrangement.Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.InputThe first line contains a string s (2 \le |s| \le 10^{5}), representing the initial colony arrangement. String s can have both lowercase and uppercase English letters and its length is even.The second line contains a single integer q (1 \le q \le 10^{5}) — the number of questions.The i-th of the next q lines contains two integers x_i and y_i (1 \le x_i, y_i \le |s|, x_i \ne y_i) — the two numbers given to the Jarvis for the i-th question.OutputFor each question output the number of arrangements possible modulo 10^9+7.ExamplesInput abba 2 1 4 1 2 Output 2 0 Input AAaa 2 1 2 1 3 Output 2 0 Input abcd 1 1 3 Output 8 NoteConsider the first example. For the first question, the possible arrangements are "aabb" and "bbaa", and for the second question, index 1 contains 'a' and index 2 contains 'b' and there is no valid arrangement in which all 'a' and 'b' are in the same half.
abba 2 1 4 1 2
2 0
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*2600']
C. Creative Snaptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B \cdot n_a \cdot l amount of power, where n_a is the number of avengers and l is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.InputThe first line contains four integers n, k, A and B (1 \leq n \leq 30, 1 \leq k \leq 10^5, 1 \leq A,B \leq 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.The second line contains k integers a_{1}, a_{2}, a_{3}, \ldots, a_{k} (1 \leq a_{i} \leq 2^n), where a_{i} represents the position of avenger in the base.OutputOutput one integer — the minimum power needed to destroy the avengers base.ExamplesInput 2 2 1 2 1 3 Output 6 Input 3 2 1 2 1 7 Output 8 NoteConsider the first example.One option for Thanos is to burn the whole base 1-4 with power 2 \cdot 2 \cdot 4 = 16.Otherwise he can divide the base into two parts 1-2 and 3-4.For base 1-2, he can either burn it with power 2 \cdot 1 \cdot 2 = 4 or divide it into 2 parts 1-1 and 2-2.For base 1-1, he can burn it with power 2 \cdot 1 \cdot 1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4. Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
2 2 1 2 1 3
6
1 second
256 megabytes
['binary search', 'brute force', 'divide and conquer', 'math', '*1700']
B. Average Superhero Gang Power time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are n superheroes in avengers team having powers a_1, a_2, \ldots, a_n, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by 1. They can do at most m operations. Also, on a particular superhero at most k operations can be done.Can you help the avengers team to maximize the average power of their crew?InputThe first line contains three integers n, k and m (1 \le n \le 10^{5}, 1 \le k \le 10^{5}, 1 \le m \le 10^{7}) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^{6}) — the initial powers of the superheroes in the cast of avengers.OutputOutput a single number — the maximum final average power.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExamplesInput 2 4 6 4 7 Output 11.00000000000000000000 Input 4 2 6 1 3 2 3 Output 5.00000000000000000000 NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by 2 each.
2 4 6 4 7
11.00000000000000000000
1 second
256 megabytes
['brute force', 'implementation', 'math', '*1700']
A. Superhero Transformationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other consonant. Multiple changes can be made.In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.Given the names of two superheroes, determine if the superhero with name s can be transformed to the Superhero with name t.InputThe first line contains the string s having length between 1 and 1000, inclusive.The second line contains the string t having length between 1 and 1000, inclusive.Both strings s and t are guaranteed to be different and consist of lowercase English letters only.OutputOutput "Yes" (without quotes) if the superhero with name s can be transformed to the superhero with name t and "No" (without quotes) otherwise.You can print each letter in any case (upper or lower).ExamplesInput a u Output Yes Input abc ukm Output Yes Input akm ua Output No NoteIn the first sample, since both 'a' and 'u' are vowels, it is possible to convert string s to t.In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string s to t.
a u
Yes
1 second
256 megabytes
['implementation', 'strings', '*1000']
H. Modest Substringstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given two integers l and r.Let's call an integer x modest, if l \le x \le r.Find a string of length n, consisting of digits, which has the largest possible number of substrings, which make a modest integer. Substring having leading zeros are not counted. If there are many answers, find lexicographically smallest one.If some number occurs multiple times as a substring, then in the counting of the number of modest substrings it is counted multiple times as well.InputThe first line contains one integer l (1 \le l \le 10^{800}).The second line contains one integer r (l \le r \le 10^{800}).The third line contains one integer n (1 \le n \le 2\,000).OutputIn the first line, print the maximum possible number of modest substrings.In the second line, print a string of length n having exactly that number of modest substrings.If there are multiple such strings, print the lexicographically smallest of them.ExamplesInput 1 10 3 Output 3 101 Input 1 11 3 Output 5 111 Input 12345 12346 6 Output 1 012345 NoteIn the first example, string «101» has modest substrings «1», «10», «1».In the second example, string «111» has modest substrings «1» (3 times) and «11» (2 times).
1 10 3
3 101
5 seconds
1024 megabytes
['dp', 'strings', '*3500']
G. Tree-Tac-Toe time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe tic-tac-toe game is starting on a tree of n vertices. Some vertices are already colored in white while the remaining are uncolored.There are two players — white and black. The players make moves alternatively. The white player starts the game. In his turn, a player must select one uncolored vertex and paint it in his color.The player wins if he paints some path of three vertices in his color. In case all vertices are colored and neither player won, the game ends in a draw.Could you please find who will win the game or whether it ends as a draw, assuming both players play optimally? InputThe first line contains a single integer T (1 \le T \le 50\,000) — the number of test cases. Then descriptions of T test cases follow.The first line of each test contains a single integer n (1 \le n \le 5 \cdot 10^5) — the number of vertices in the tree.Each of the following n - 1 lines contains integers v, u (1 \le v, u \le n) denoting an edge of the tree connecting vertices v and u.The last line of a test case contains a string of letters 'W' (for white) and 'N' (for not colored) of length n denoting already colored vertices. Vertexes already colored in white are denoted as 'W'.It's guaranteed that the given edges form a tree, that there is at least one uncolored vertex and that there is no path of three white vertices.It's guaranteed that sum of all n among all test cases is at most 5 \cdot 10^5.OutputFor every test case, print either "White", "Draw" or "Black", depending on the result of the game.ExampleInput 2 4 1 2 1 3 1 4 NNNW 5 1 2 2 3 3 4 4 5 NNNNN Output White Draw NoteIn the first example, vertex 4 is already colored in white. The white player can win by coloring the vertex 1 in white first and the remaining vertex on his second turn. The process is illustrated with the pictures below. In the second example, we can show that no player can enforce their victory.
2 4 1 2 1 3 1 4 NNNW 5 1 2 2 3 3 4 4 5 NNNNN
White Draw
3 seconds
256 megabytes
['constructive algorithms', 'games', 'trees', '*3100']
F. Nearest Leaftime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number 1 and then recursively runs from all vertices which are connected with an edge with the current vertex and are not yet visited in increasing numbers order. Formally, you can describe this function using the following pseudocode:next_id = 1id = array of length n filled with -1visited = array of length n filled with falsefunction dfs(v): visited[v] = true id[v] = next_id next_id += 1 for to in neighbors of v in increasing order: if not visited[to]: dfs(to)You are given a weighted tree, the vertices of which were enumerated with integers from 1 to n using the algorithm described above.A leaf is a vertex of the tree which is connected with only one other vertex. In the tree given to you, the vertex 1 is not a leaf. The distance between two vertices in the tree is the sum of weights of the edges on the simple path between them.You have to answer q queries of the following type: given integers v, l and r, find the shortest distance from vertex v to one of the leaves with indices from l to r inclusive. InputThe first line contains two integers n and q (3 \leq n \leq 500\,000, 1 \leq q \leq 500\,000) — the number of vertices in the tree and the number of queries, respectively.The (i - 1)-th of the following n - 1 lines contains two integers p_i and w_i (1 \leq p_i < i, 1 \leq w_i \leq 10^9), denoting an edge between vertices p_i and i with the weight w_i.It's guaranteed that the given edges form a tree and the vertices are enumerated in the Eulerian traversal order and that the vertex with index 1 is not a leaf.The next q lines describe the queries. Each of them contains three integers v_i, l_i, r_i (1 \leq v_i \leq n, 1 \leq l_i \leq r_i \leq n), describing the parameters of the query. It is guaranteed that there is at least one leaf with index x such that l_i \leq x \leq r_i.OutputOutput q integers — the answers for the queries in the order they are given in the input.ExamplesInput 5 3 1 10 1 1 3 2 3 3 1 1 5 5 4 5 4 1 2 Output 3 0 13 Input 5 3 1 1000000000 2 1000000000 1 1000000000 1 1000000000 3 4 5 2 1 5 2 4 5 Output 3000000000 1000000000 2000000000 Input 11 8 1 7 2 1 1 20 1 2 5 6 6 2 6 3 5 1 9 10 9 11 5 1 11 1 1 4 9 4 8 6 1 4 9 7 11 9 10 11 8 1 11 11 4 5 Output 8 8 9 16 9 10 0 34 NoteIn the first example, the tree looks like this: In the first query, the nearest leaf for the vertex 1 is vertex 4 with distance 3. In the second query, the nearest leaf for vertex 5 is vertex 5 with distance 0. In the third query the nearest leaf for vertex 4 is vertex 4; however, it is not inside interval [1, 2] of the query. The only leaf in interval [1, 2] is vertex 2 with distance 13 from vertex 4.
5 3 1 10 1 1 3 2 3 3 1 1 5 5 4 5 4 1 2
3 0 13
4 seconds
512 megabytes
['data structures', 'trees', '*2600']
E. Magic Stonestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGrigory has n magic stones, conveniently numbered from 1 to n. The charge of the i-th stone is equal to c_i.Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index i, where 2 \le i \le n - 1), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge c_i changes to c_i' = c_{i + 1} + c_{i - 1} - c_i.Andrew, Grigory's friend, also has n stones with charges t_i. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes c_i into t_i for all i?InputThe first line contains one integer n (2 \le n \le 10^5) — the number of magic stones.The second line contains integers c_1, c_2, \ldots, c_n (0 \le c_i \le 2 \cdot 10^9) — the charges of Grigory's stones.The second line contains integers t_1, t_2, \ldots, t_n (0 \le t_i \le 2 \cdot 10^9) — the charges of Andrew's stones.OutputIf there exists a (possibly empty) sequence of synchronization operations, which changes all charges to the required ones, print "Yes".Otherwise, print "No".ExamplesInput 4 7 2 4 12 7 15 10 12 Output Yes Input 3 4 4 4 1 2 3 Output No NoteIn the first example, we can perform the following synchronizations (1-indexed): First, synchronize the third stone [7, 2, \mathbf{4}, 12] \rightarrow [7, 2, \mathbf{10}, 12]. Then synchronize the second stone: [7, \mathbf{2}, 10, 12] \rightarrow [7, \mathbf{15}, 10, 12]. In the second example, any operation with the second stone will not change its charge.
4 7 2 4 12 7 15 10 12
Yes
1 second
256 megabytes
['constructive algorithms', 'math', 'sortings', '*2200']
D. Jongmahtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have n tiles in your hand. Each tile has an integer between 1 and m written on it.To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, 7, 7, 7 is a valid triple, and so is 12, 13, 14, but 2,2,3 or 2,4,6 are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple.To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.InputThe first line contains two integers integer n and m (1 \le n, m \le 10^6) — the number of tiles in your hand and the number of tiles types.The second line contains integers a_1, a_2, \ldots, a_n (1 \le a_i \le m), where a_i denotes the number written on the i-th tile.OutputPrint one integer: the maximum number of triples you can form.ExamplesInput10 62 3 3 3 4 4 4 5 5 6Output3Input12 61 5 3 3 3 4 3 5 3 2 3 3Output3Input13 51 1 5 1 2 3 3 2 4 2 3 4 5Output4NoteIn the first example, we have tiles 2, 3, 3, 3, 4, 4, 4, 5, 5, 6. We can form three triples in the following way: 2, 3, 4; 3, 4, 5; 4, 5, 6. Since there are only 10 tiles, there is no way we could form 4 triples, so the answer is 3.In the second example, we have tiles 1, 2, 3 (7 times), 4, 5 (2 times). We can form 3 triples as follows: 1, 2, 3; 3, 3, 3; 3, 4, 5. One can show that forming 4 triples is not possible.
Input10 62 3 3 3 4 4 4 5 5 6
Output3
3 seconds
256 megabytes
['dp', '*2200']
C. Meaningless Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCan the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the greatest common divisor (GCD) of integers a \oplus b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function:f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.Here \oplus denotes the bitwise XOR operation, and \& denotes the bitwise AND operation.The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder.You are given q integers a_1, a_2, \ldots, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). InputThe first line contains an integer q (1 \le q \le 10^3) — the number of integers you need to compute the answer for.After that q integers are given, one per line: a_1, a_2, \ldots, a_q (2 \le a_i \le 2^{25} - 1) — the integers you need to compute the answer for. OutputFor each integer, print the answer in the same order as the integers are given in input.ExampleInput 3 2 3 5 Output 3 1 7 NoteFor the first integer the optimal choice is b = 1, then a \oplus b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3.For the second integer one optimal choice is b = 2, then a \oplus b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1.For the third integer the optimal choice is b = 2, then a \oplus b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7.
3 2 3 5
3 1 7
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1500']
B. Tapetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length t placed at some position s will cover segments s, s+1, \ldots, s+t-1.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most k continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?InputThe first line contains three integers n, m and k (1 \le n \le 10^5, n \le m \le 10^9, 1 \le k \le n) — the number of broken segments, the length of the stick and the maximum number of pieces you can use.The second line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le m) — the positions of the broken segments. These integers are given in increasing order, that is, b_1 < b_2 < \ldots < b_n.OutputPrint the minimum total length of the pieces.ExamplesInput4 100 220 30 75 80Output17Input5 100 31 2 4 60 87Output6NoteIn the first example, you can use a piece of length 11 to cover the broken segments 20 and 30, and another piece of length 6 to cover 75 and 80, for a total length of 17.In the second example, you can use a piece of length 4 to cover broken segments 1, 2 and 4, and two pieces of length 1 to cover broken segments 60 and 87.
Input4 100 220 30 75 80
Output17
1 second
256 megabytes
['greedy', 'sortings', '*1400']
A. Paritytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n (n \ge 0) represented with k digits in base (radix) b. So,n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.For example, if b=17, k=3 and a=[11, 15, 7] then n=11\cdot17^2+15\cdot17+7=3179+255+7=3441.Determine whether n is even or odd.InputThe first line contains two integers b and k (2\le b\le 100, 1\le k\le 10^5) — the base of the number and the number of digits.The second line contains k integers a_1, a_2, \ldots, a_k (0\le a_i < b) — the digits of n.The representation of n contains no unnecessary leading zero. That is, a_1 can be equal to 0 only if k = 1.OutputPrint "even" if n is even, otherwise print "odd".You can print each letter in any case (upper or lower).ExamplesInput13 33 2 7OutputevenInput10 91 2 3 4 5 6 7 8 9OutputoddInput99 532 92 85 74 4OutputoddInput2 21 0OutputevenNoteIn the first example, n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540, which is even.In the second example, n = 123456789 is odd.In the third example, n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155 is odd.In the fourth example n = 2.
Input13 33 2 7
Outputeven
1 second
256 megabytes
['math', '*900']
F. Sasha and Algorithm of Silence's Soundstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Let's divide the park into 1 \times 1 meter squares and call them cells, and numerate rows from 1 to n from up to down, and columns from 1 to m from left to right. And now, every cell can be described with a pair of two integers (x, y), where x — the number of the row, and y — the number of the column. Sasha knows that the level of silence in the cell (i, j) equals to f_{i,j}, and all f_{i,j} form a permutation of numbers from 1 to n \cdot m. Sasha decided to count, how many are there pleasant segments of silence?Let's take some segment [l \ldots r]. Denote S as the set of cells (i, j) that l \le f_{i,j} \le r. Then, the segment of silence [l \ldots r] is pleasant if there is only one simple path between every pair of cells from S (path can't contain cells, which are not in S). In other words, set S should look like a tree on a plain. Sasha has done this task pretty quickly, and called the algorithm — "algorithm of silence's sounds".Time passed, and the only thing left from the algorithm is a legend. To prove the truthfulness of this story, you have to help Sasha and to find the number of different pleasant segments of silence. Two segments [l_1 \ldots r_1], [l_2 \ldots r_2] are different, if l_1 \neq l_2 or r_1 \neq r_2 or both at the same time.InputThe first line contains two integers n and m (1 \le n, m \le 1000, 1 \le n \cdot m \le 2 \cdot 10^5) — the size of the park.Each from next n lines contains m integers f_{i,j} (1 \le f_{i,j} \le n \cdot m) — the level of silence in the cell with number (i, j).It is guaranteed, that all f_{i,j} are different.OutputPrint one integer — the number of pleasant segments of silence.ExamplesInput1 51 2 3 4 5Output15Input2 31 2 34 5 6Output15Input4 44 3 2 161 13 14 155 7 8 126 11 9 10Output50NoteIn the first example, all segments of silence are pleasant.In the second example, pleasant segments of silence are the following:
Input1 51 2 3 4 5
Output15
1.5 seconds
256 megabytes
['data structures', 'trees', '*3200']
E. Sasha and a Very Easy Testtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEgor likes math, and not so long ago he got the highest degree of recognition in the math community — Egor became a red mathematician. In this regard, Sasha decided to congratulate Egor and give him a math test as a present. This test contains an array a of integers of length n and exactly q queries. Queries were of three types: "1 l r x" — multiply each number on the range from l to r by x. "2 p x" — divide the number at the position p by x (divisibility guaranteed). "3 l r" — find the sum of all elements on the range from l to r. The sum can be big, so Sasha asked Egor to calculate the sum modulo some integer mod. But since Egor is a red mathematician, he doesn't have enough time to solve such easy tasks, at the same time he doesn't want to anger Sasha, that's why he asked you to help and to find answers for all queries of the 3-rd type.InputThe first line contains two integers n and mod (1 \le n \le 10^5, 2 \le mod \le 10^9 + 9) — the size of the array and the number mod.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5) — the array itself.The third line contains one integer q(1 \le q \le 10^5) — the number of queries.Next q lines satisfy one of the following formats: 1 l r x (1 \le l \le r \le n, 1 \le x \le 10^5), means that you must multiply each number on the range from l to r by x. 2 p x (1 \le p \le n, 1 \le x \le 10^5), means that you must divide number at the position p by x (divisibility guaranteed). 3 l r (1 \le l \le r \le n), means that you must find the sum of elements on the range from l to r. It is guaranteed that there is at least one query of the 3-rd type.OutputFor each query of the 3-rd type print the answer on a new line modulo mod.ExamplesInput 5 100 4 1 2 3 5 5 3 1 5 1 2 3 6 3 1 2 1 1 5 1 3 2 4 Output 15 10 21 Input 5 2 4 1 2 3 5 7 3 1 5 1 2 3 6 3 1 2 1 1 5 1 3 2 4 2 3 4 3 3 4 Output 1 0 1 0 Input 5 2100 1 2 3 4 5 10 1 1 3 12 1 1 5 10 2 5 50 3 2 4 1 4 4 28 2 4 7 3 1 2 3 3 4 2 3 3 3 1 5 Output 640 360 520 641 NoteThe first example:Inital array is [4, 1, 2, 3, 5] In the first query, you must calculate the sum of the whole array, it's equal to (4 + 1 + 2 + 3 + 5) \bmod 100 = 15 \bmod 100 = 15 In the second query, you must multiply each number on the range from 2 to 3 by 6. The resulting array will be [4, 6, 12, 3, 5] In the third query, you must calculate the sum on the range from 1 to 2, it's equal to (4 + 6) \bmod 100 = 10 \bmod 100 = 10 In the fourth query, you must multiply each number on the range from 1 to 5 by 1. Multiplication by 1 doesn't affect the array. In the fifth query, you must calculate the sum on the range from 2 to 4, it's equal to (6 + 12 + 3) \bmod 100 = 21 \bmod 100 = 21 The second example:Inital array is [4, 1, 2, 3, 5] In the first query, you must calculate the sum of the whole array, it's equal to (4 + 1 + 2 + 3 + 5) \bmod 2 = 15 \bmod 2 = 1 In the second query, you must multiply each number on the range from 2 to 3 by 6. The resulting array will be [4, 6, 12, 3, 5] In the third query, you must calculate the sum on the range from 1 to 2, it's equal to (4 + 6) \bmod 2 = 10 \bmod 2 = 0 In the fourth query, you must multiply each number on the range from 1 to 5 by 1. Multiplication by 1 doesn't affect the array. In the fifth query, you must calculate the sum on the range from 2 to 4, it's equal to (6 + 12 + 3) \bmod 2 = 21 \bmod 2 = 1 In the sixth query, you must divide number at the position 3 by 4. \frac{12}{4}=3, so the array will be [4, 6, 3, 3, 5]. In the seventh, query you must calculate the sum on the range form 3 to 4, it's equal to (3 + 3) \bmod 2 = 6 \bmod 2 = 0
5 100 4 1 2 3 5 5 3 1 5 1 2 3 6 3 1 2 1 1 5 1 3 2 4
15 10 21
2.5 seconds
256 megabytes
['data structures', 'number theory', '*2700']
D. Sasha and Interesting Fact from Graph Theorytime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees. In this task, a tree is a weighted connected graph, consisting of n vertices and n-1 edges, and weights of edges are integers from 1 to m. Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices — vertices with numbers a and b, and counts the distance between them. The distance between two vertices x and y is the sum of weights of edges on the simple path from x to y. If the distance between two vertices a and b is equal to m, then the tree is beautiful.Sasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's weight matters.Kefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo 10^9 + 7.InputThe first line contains four integers n, m, a, b (2 \le n \le 10^6, 1 \le m \le 10^6, 1 \le a, b \le n, a \neq b) — the number of vertices in the tree, the maximum weight of an edge and two Kefa's favorite vertices.OutputPrint one integer — the number of beautiful trees modulo 10^9+7.ExamplesInput 3 2 1 3 Output 5 Input 3 1 1 2 Output 2 Input 5 15 1 5 Output 345444 NoteThere are 5 beautiful trees in the first example:In the second example the following trees are beautiful:
3 2 1 3
5
2.5 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'math', 'trees', '*2400']