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
F. Delivery Oligopolytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe whole delivery market of Berland is controlled by two rival companies: BerEx and BerPS. They both provide fast and reliable delivery services across all the cities of Berland.The map of Berland can be represented as an undirected graph. The cities are vertices and the roads are edges between them. Each pair of cities has no more than one road between them. Each road connects different cities.BerEx and BerPS are so competitive that for each pair of cities (v, u) they have set up their paths from v to u in such a way that these two paths don't share a single road. It is guaranteed that it was possible.Now Berland government decided to cut down the road maintenance cost by abandoning some roads. Obviously, they want to maintain as little roads as possible. However, they don't want to break the entire delivery system. So BerEx and BerPS should still be able to have their paths between every pair of cities non-intersecting.What is the minimal number of roads Berland government can maintain?More formally, given a 2-edge connected undirected graph, what is the minimum number of edges that can be left in it so that the resulting graph is also 2-edge connected?InputThe first line contains two integers n and m (3 \le n \le 14, n \le m \le \frac{n(n - 1)}{2}) — the number of cities and the number of roads between them.Each of the next m lines contains two integers v and u (1 \le v, u \le n, v \ne u) — the cities connected by the next road. It is guaranteed that each pair of cities has no more than one road between them. It is guaranteed that each pair of cities have at least two paths between them that don't share a single road.OutputThe first line should contain a single integer k — the minimum number of roads Berland government can maintain so that BerEx and BerPS are still able to have their paths between every pair of cities non-intersecting.The next k lines should contain the list of roads which are being maintained. Each line of form "v~u", where v and u are cities connected by the next road.If there are multiple lists of minimum size, print any of them. The order of roads in the list doesn't matter.ExamplesInput 3 3 1 2 2 3 3 1 Output 3 1 3 3 2 1 2 Input 4 5 1 2 1 4 2 3 4 3 1 3 Output 4 1 4 4 3 3 2 1 2 Input 6 10 1 2 2 3 3 1 3 4 4 5 5 6 4 6 2 5 1 6 3 5 Output 6 1 6 6 5 5 4 4 3 3 2 1 2 NoteHere are graphs from the examples, red edges are the maintained ones.
3 3 1 2 2 3 3 1
3 1 3 3 2 1 2
2 seconds
256 megabytes
['brute force', 'dp', 'graphs', '*2800']
E. Guess the Roottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJury picked a polynomial f(x) = a_0 + a_1 \cdot x + a_2 \cdot x^2 + \dots + a_k \cdot x^k. k \le 10 and all a_i are integer numbers and 0 \le a_i < 10^6 + 3. It's guaranteed that there is at least one i such that a_i > 0.Now jury wants you to find such an integer x_0 that f(x_0) \equiv 0 \mod (10^6 + 3) or report that there is not such x_0.You can ask no more than 50 queries: you ask value x_q and jury tells you value f(x_q) \mod (10^6 + 3).Note that printing the answer doesn't count as a query.InteractionTo ask a question, print "? x_q" (0 \le x_q < 10^6 + 3). The judge will respond with a single integer f(x_q) \mod (10^6 + 3). If you ever get a result of −1 (because you printed an invalid query), exit immediately to avoid getting other verdicts.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. When you are ready to answer, print "! x_0" where x_0 is the answer or -1 if there is no such x_0.You can ask at most 50 questions per test case.Hack FormatTo hack, use the following format.The only line should contain 11 integers a_0, a_1, \dots, a_{10} (0 \le a_i < 10^6 + 3, \max\limits_{0 \le i \le 10}{a_i} > 0) — corresponding coefficients of the polynomial.ExamplesInput 1000002 0 Output ? 0 ? 1 ! 1Input 5 2 1 Output ? 2 ? 1 ? 0 ! -1NoteThe polynomial in the first sample is 1000002 + x^2.The polynomial in the second sample is 1 + x^2.
1000002 0
? 0 ? 1 ! 1
2 seconds
256 megabytes
['brute force', 'interactive', 'math', '*2200']
D. Beautiful Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.You may choose at most one consecutive subarray of a and multiply all values contained in this subarray by x. You want to maximize the beauty of array after applying at most one such operation.InputThe first line contains two integers n and x (1 \le n \le 3 \cdot 10^5, -100 \le x \le 100) — the length of array a and the integer x respectively.The second line contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9) — the array a.OutputPrint one integer — the maximum possible beauty of array a after multiplying all values belonging to some consecutive subarray x.ExamplesInput 5 -2 -3 8 -2 1 -6 Output 22 Input 12 -3 1 3 3 7 1 3 3 7 1 3 3 7 Output 42 Input 5 10 -1 -2 -3 -4 -5 Output 0 NoteIn the first test case we need to multiply the subarray [-2, 1, -6], and the array becomes [-3, 8, 4, -2, 12] with beauty 22 ([-3, 8, 4, -2, 12]).In the second test case we don't need to multiply any subarray at all.In the third test case no matter which subarray we multiply, the beauty of array will be equal to 0.
5 -2 -3 8 -2 1 -6
22
2 seconds
256 megabytes
['brute force', 'data structures', 'divide and conquer', 'dp', 'greedy', '*1900']
C. Alarm Clocks Everywheretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, \dots, x_n, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as y) and the interval between two consecutive signals (let's denote it by p). After the clock is set, it will ring during minutes y, y + p, y + 2p, y + 3p and so on.Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of p. He has to pick it among the given values p_1, p_2, \dots, p_m (his phone does not support any other options for this setting).So Ivan has to choose the first minute y when the alarm clock should start ringing and the interval between two consecutive signals p_j in such a way that it will ring during all given minutes x_1, x_2, \dots, x_n (and it does not matter if his alarm clock will ring in any other minutes).Your task is to tell the first minute y and the index j such that if Ivan sets his alarm clock with properties y and p_j it will ring during all given minutes x_1, x_2, \dots, x_n or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.InputThe first line of the input contains two integers n and m (2 \le n \le 3 \cdot 10^5, 1 \le m \le 3 \cdot 10^5) — the number of events and the number of possible settings for the interval between signals.The second line of the input contains n integers x_1, x_2, \dots, x_n (1 \le x_i \le 10^{18}), where x_i is the minute when i-th event starts. It is guaranteed that all x_i are given in increasing order (i. e. the condition x_1 < x_2 < \dots < x_n holds).The third line of the input contains m integers p_1, p_2, \dots, p_m (1 \le p_j \le 10^{18}), where p_j is the j-th option for the interval between two consecutive signals.OutputIf it's impossible to choose such values y and j so all constraints are satisfied, print "NO" in the first line.Otherwise print "YES" in the first line. Then print two integers y (1 \le y \le 10^{18}) and j (1 \le j \le m) in the second line, where y is the first minute Ivan's alarm clock should start ringing and j is the index of the option for the interval between two consecutive signals (options are numbered from 1 to m in the order they are given input). These values should be chosen in such a way that the alarm clock will ring during all given minutes x_1, x_2, \dots, x_n. If there are multiple answers, you can print any.ExamplesInput 3 5 3 12 18 2 6 5 3 3 Output YES 3 4 Input 4 2 1 5 17 19 4 5 Output NO Input 4 2 1 5 17 19 2 1 Output YES 1 1
3 5 3 12 18 2 6 5 3 3
YES 3 4
3 seconds
256 megabytes
['math', 'number theory', '*1300']
B. Game with Telephone Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA telephone number is a sequence of exactly 11 digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string s becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).InputThe first line contains one integer n (13 \le n < 10^5, n is odd) — the length of string s.The second line contains the string s (|s| = n) consisting only of decimal digits.OutputIf Vasya has a strategy that guarantees him victory, print YES.Otherwise print NO.ExamplesInput 13 8380011223344 Output YES Input 15 807345619350641 Output NO NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
13 8380011223344
YES
1 second
256 megabytes
['games', 'greedy', 'implementation', '*1200']
A. Reverse a Substringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from position l to position r is s[l; r] = s_l s_{l + 1} \dots s_r.You have to choose exactly one of the substrings of the given string and reverse it (i. e. make s[l; r] = s_r s_{r - 1} \dots s_l) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.String x is lexicographically less than string y, if either x is a prefix of y (and x \ne y), or there exists such i (1 \le i \le min(|x|, |y|)), that x_i < y_i, and for any j (1 \le j < i) x_j = y_j. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.InputThe first line of the input contains one integer n (2 \le n \le 3 \cdot 10^5) — the length of s.The second line of the input contains the string s of length n consisting only of lowercase Latin letters.OutputIf it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices l and r (1 \le l < r \le n) denoting the substring you have to reverse. If there are multiple answers, you can print any.ExamplesInput 7 abacaba Output YES 2 5 Input 6 aabcfg Output NO NoteIn the first testcase the resulting string is "aacabba".
7 abacaba
YES 2 5
2 seconds
256 megabytes
['implementation', 'sortings', 'strings', '*1000']
G. Minimum Possible LCMtime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers a_1, a_2, \dots, a_n.Your problem is to find such pair of indices i, j (1 \le i < j \le n) that lcm(a_i, a_j) is minimum possible.lcm(x, y) is the least common multiple of x and y (minimum positive number such that both x and y are divisors of this number).InputThe first line of the input contains one integer n (2 \le n \le 10^6) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^7), where a_i is the i-th element of a.OutputPrint two integers i and j (1 \le i < j \le n) such that the value of lcm(a_i, a_j) is minimum among all valid pairs i, j. If there are multiple answers, you can print any.ExamplesInput 5 2 4 8 3 6 Output 1 2 Input 5 5 2 11 3 7 Output 2 4 Input 6 2 5 10 1 10 2 Output 1 4
5 2 4 8 3 6
1 2
4 seconds
1024 megabytes
['brute force', 'greedy', 'math', 'number theory', '*2200']
F. Shovels Shoptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n shovels in the nearby shop. The i-th shovel costs a_i bourles.Misha has to buy exactly k shovels. Each shovel can be bought no more than once.Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.InputThe first line of the input contains three integers n, m and k (1 \le n, m \le 2 \cdot 10^5, 1 \le k \le min(n, 2000)) — the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2 \cdot 10^5), where a_i is the cost of the i-th shovel.The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 \le y_i \le x_i \le n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.OutputPrint one integer — the minimum cost of buying k shovels if Misha buys them optimally.ExamplesInput 7 4 5 2 5 4 2 6 3 1 2 1 6 5 2 1 3 1 Output 7 Input 9 4 8 6 8 5 1 8 1 1 2 1 9 2 8 4 5 3 9 7 Output 17 Input 5 1 4 2 5 7 4 6 5 4 Output 17 NoteIn the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
7 4 5 2 5 4 2 6 3 1 2 1 6 5 2 1 3 1
7
2 seconds
256 megabytes
['dp', 'greedy', 'sortings', '*2100']
E. Two Teamstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive.Firstly, the first coach will choose the student with maximum programming skill among all students not taken into any team, and k closest students to the left of him and k closest students to the right of him (if there are less than k students to the left or to the right, all of them will be chosen). All students that are chosen leave the row and join the first team. Secondly, the second coach will make the same move (but all students chosen by him join the second team). Then again the first coach will make such move, and so on. This repeats until the row becomes empty (i. e. the process ends when each student becomes to some team).Your problem is to determine which students will be taken into the first team and which students will be taken into the second team.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the number of students and the value determining the range of chosen students during each move, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the programming skill of the i-th student. It is guaranteed that all programming skills are distinct.OutputPrint a string of n characters; i-th character should be 1 if i-th student joins the first team, or 2 otherwise.ExamplesInput 5 2 2 4 5 3 1 Output 11111 Input 5 1 2 1 3 5 4 Output 22111 Input 7 1 7 2 1 3 5 4 6 Output 1121122 Input 5 1 2 4 5 3 1 Output 21112 NoteIn the first example the first coach chooses the student on a position 3, and the row becomes empty (all students join the first team).In the second example the first coach chooses the student on position 4, and the row becomes [2, 1] (students with programming skills [3, 4, 5] join the first team). Then the second coach chooses the student on position 1, and the row becomes empty (and students with programming skills [1, 2] join the second team).In the third example the first coach chooses the student on position 1, and the row becomes [1, 3, 5, 4, 6] (students with programming skills [2, 7] join the first team). Then the second coach chooses the student on position 5, and the row becomes [1, 3, 5] (students with programming skills [4, 6] join the second team). Then the first coach chooses the student on position 3, and the row becomes [1] (students with programming skills [3, 5] join the first team). And then the second coach chooses the remaining student (and the student with programming skill 1 joins the second team).In the fourth example the first coach chooses the student on position 3, and the row becomes [2, 1] (students with programming skills [3, 4, 5] join the first team). Then the second coach chooses the student on position 1, and the row becomes empty (and students with programming skills [1, 2] join the second team).
5 2 2 4 5 3 1
11111
2 seconds
256 megabytes
['data structures', 'implementation', 'sortings', '*1800']
D. Walking Robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are exposed to sunlight: if segment i is exposed, then s_i = 1, otherwise s_i = 0.The robot has one battery of capacity b and one accumulator of capacity a. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.You understand that it is not always possible to walk to X=n. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.InputThe first line of the input contains three integers n, b, a (1 \le n, b, a \le 2 \cdot 10^5) — the robot's destination point, the battery capacity and the accumulator capacity, respectively.The second line of the input contains n integers s_1, s_2, \dots, s_n (0 \le s_i \le 1), where s_i is 1 if the i-th segment of distance is exposed to sunlight, and 0 otherwise.OutputPrint one integer — the maximum number of segments the robot can pass if you control him optimally.ExamplesInput 5 2 1 0 1 0 1 0 Output 5 Input 6 2 1 1 0 0 1 0 1 Output 3 NoteIn the first example the robot can go through the first segment using the accumulator, and charge levels become b=2 and a=0. The second segment can be passed using the battery, and charge levels become b=1 and a=1. The third segment can be passed using the accumulator, and charge levels become b=1 and a=0. The fourth segment can be passed using the battery, and charge levels become b=0 and a=1. And the fifth segment can be passed using the accumulator.In the second example the robot can go through the maximum number of segments using battery two times and accumulator one time in any order.
5 2 1 0 1 0 1 0
5
2 seconds
256 megabytes
['greedy', '*1500']
C. Gourmet Cattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: on Mondays, Thursdays and Sundays he eats fish food; on Tuesdays and Saturdays he eats rabbit stew; on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: a daily rations of fish food; b daily rations of rabbit stew; c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.InputThe first line of the input contains three positive integers a, b and c (1 \le a, b, c \le 7\cdot10^8) — the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly.OutputPrint the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.ExamplesInput 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 NoteIn the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday — rabbit stew and during Wednesday — chicken stake. So, after four days of the trip all food will be eaten.In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack.In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
2 1 1
4
1 second
256 megabytes
['implementation', 'math', '*1400']
B. Make Them Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a_1, a_2, \dots, a_n consisting of n integers.You can choose any non-negative integer D (i.e. D \ge 0), and for each a_i you can: add D (only once), i. e. perform a_i := a_i + D, or subtract D (only once), i. e. perform a_i := a_i - D, or leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative.Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=\dots=a_n).Print the required D or, if it is impossible to choose such value D, print -1.For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4].InputThe first line of the input contains one integer n (1 \le n \le 100) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100) — the sequence a.OutputPrint one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal.If it is impossible to choose such value D, print -1.ExamplesInput 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3
6 1 4 4 7 4 1
3
2 seconds
256 megabytes
['math', '*1200']
A. Restoring Three Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.You have to guess three numbers a, b and c using given numbers. Print three guessed integers in any order.Pay attention that some given numbers a, b and c can be equal (it is also possible that a=b=c).InputThe only line of the input contains four positive integers x_1, x_2, x_3, x_4 (2 \le x_i \le 10^9) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number x_1, x_2, x_3, x_4.OutputPrint such positive integers a, b and c that four numbers written on a board are values a+b, a+c, b+c and a+b+c written in some order. Print a, b and c in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.ExamplesInput 3 6 5 4 Output 2 1 3 Input 40 40 40 60 Output 20 20 20 Input 201 101 101 200 Output 1 100 100
3 6 5 4
2 1 3
1 second
256 megabytes
['math', '*800']
F. Serval and Bonus Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGetting closer and closer to a mathematician, Serval becomes a university student on math major in Japari University. On the Calculus class, his teacher taught him how to calculate the expected length of a random subsegment of a given segment. Then he left a bonus problem as homework, with the award of a garage kit from IOI. The bonus is to extend this problem to the general case as follows.You are given a segment with length l. We randomly choose n segments by choosing two points (maybe with non-integer coordinates) from the given segment equiprobably and the interval between the two points forms a segment. You are given the number of random segments n, and another integer k. The 2n endpoints of the chosen segments split the segment into (2n+1) intervals. Your task is to calculate the expected total length of those intervals that are covered by at least k segments of the n random segments.You should find the answer modulo 998244353.InputFirst line contains three space-separated positive integers n, k and l (1\leq k \leq n \leq 2000, 1\leq l\leq 10^9).OutputOutput one integer — the expected total length of all the intervals covered by at least k segments of the n random segments modulo 998244353.Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput 1 1 1 Output 332748118 Input 6 2 1 Output 760234711 Input 7 5 3 Output 223383352 Input 97 31 9984524 Output 267137618 NoteIn the first example, the expected total length is \int_0^1 \int_0^1 |x-y| \,\mathrm{d}x\,\mathrm{d}y = {1\over 3}, and 3^{-1} modulo 998244353 is 332748118.
1 1 1
332748118
1 second
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*2600']
E. Serval and Snaketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a n \times n grid. The snake has a head and a tail in different cells, and its body is a series of adjacent cells connecting the head and the tail without self-intersecting. If Serval hits its head or tail, the snake will bite him and he will die.Luckily, he has a special device which can answer the following question: you can pick a rectangle, it will tell you the number of times one needs to cross the border of the rectangle walking cell by cell along the snake from the head to the tail. The pictures below show a possible snake and a possible query to it, which will get an answer of 4. Today Serval got up too late and only have time to make 2019 queries. As his best friend, can you help him find the positions of the head and the tail?Note that two cells are adjacent if and only if they have a common edge in the grid, and a snake can have a body of length 0, that means it only has adjacent head and tail.Also note that the snake is sleeping, so it won't move while Serval using his device. And what's obvious is that the snake position does not depend on your queries.InputThe first line contains a single integer n (2\leq n \leq 1000) — the size of the grid.OutputWhen you are ready to answer, you should print ! x1 y1 x2 y2, where (x_1, y_1) represents the position of the head and (x_2,y_2) represents the position of the tail. You can print head and tail in any order.InteractionTo make a query, you should print ? x1 y1 x2 y2 (1 \leq x_1 \leq x_2 \leq n, 1\leq y_1 \leq y_2 \leq n), representing a rectangle consisting of all cells (x,y) such that x_1 \leq x \leq x_2 and y_1 \leq y \leq y_2. You will get a single integer as the answer.After printing a query, do not forget to output the 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 -1 instead of a valid answer means that you made an invalid query or exceeded the maximum number of queries. Exit immediately after receiving -1 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.If your program cannot find out the head and tail of the snake correctly, you will also get a Wrong Answer verdict.HacksTo make a hack, print a single integer n (2 \leq n \leq 1000) in the first line, indicating the size of the grid.Then print an integer k (2 \leq k \leq n^2) in the second line, indicating the length of the snake.In the next k lines, print k pairs of integers x_i, y_i (1 \leq x_i, y_i \leq n), each pair in a single line, indicating the i-th cell of snake, such that the adjacent pairs are adjacent, and all k pairs are distinct.ExamplesInput 2 1 0 0 Output ? 1 1 1 1 ? 1 2 1 2 ? 2 2 2 2 ! 1 1 2 1Input 3 2 0 Output ? 2 2 2 2 ? 2 1 2 3 ! 2 1 2 3Note The pictures above show our queries and the answers in the first example. We first made a query for (1,1) and got an answer 1, then found that it must be connected to exactly one other cell. Then we made a query for (1,2) and got an answer of 0, then knew that the snake never entered it. So the cell connected to (1,1) must be (2,1). Then we made a query for (2,2) and got an answer 0, then knew that it never entered (2,2) as well. So the snake cannot leave (2,1), which implies that the answer is (1,1) and (2,1). The pictures above show our queries and the answers in the second example. By making query to (2,2) and receiving 2, we found that the snake occupies (2,2). And by making query to rectangle from (2,1) to (2,3) and receiving answer 0, we knew that it never goes out of the rectangle from (2,1) to (2,3). Since the first answer is 2, both (2,1) and (2,3) must be occupied but none of others, so the answer is (2,1) and (2,3).
2 1 0 0
? 1 1 1 1 ? 1 2 1 2 ? 2 2 2 2 ! 1 1 2 1
1 second
256 megabytes
['binary search', 'brute force', 'interactive', '*2200']
D. Serval and Rooted Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all nodes for which v is the parent. A vertex is a leaf if it has no children.The rooted tree Serval owns has n nodes, node 1 is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation \max or \min written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively. Assume that there are k leaves in the tree. Serval wants to put integers 1, 2, \ldots, k to the k leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?InputThe first line contains an integer n (2 \leq n \leq 3\cdot 10^5), the size of the tree.The second line contains n integers, the i-th of them represents the operation in the node i. 0 represents \min and 1 represents \max. If the node is a leaf, there is still a number of 0 or 1, but you can ignore it.The third line contains n-1 integers f_2, f_3, \ldots, f_n (1 \leq f_i \leq i-1), where f_i represents the parent of the node i.OutputOutput one integer — the maximum possible number in the root of the tree.ExamplesInput 6 1 0 1 1 0 1 1 2 2 2 2 Output 1 Input 5 1 0 1 0 1 1 1 1 1 Output 4 Input 8 1 0 0 1 0 1 1 0 1 1 2 2 3 3 3 Output 4 Input 9 1 1 0 0 1 0 1 0 1 1 1 2 2 3 3 4 4 Output 5 NotePictures below explain the examples. The numbers written in the middle of the nodes are their indices, and the numbers written on the top are the numbers written in the nodes.In the first example, no matter how you arrange the numbers, the answer is 1. In the second example, no matter how you arrange the numbers, the answer is 4. In the third example, one of the best solution to achieve 4 is to arrange 4 and 5 to nodes 4 and 5. In the fourth example, the best solution is to arrange 5 to node 5.
6 1 0 1 1 0 1 1 2 2 2 2
1
2 seconds
256 megabytes
['binary search', 'dfs and similar', 'dp', 'greedy', 'trees', '*1900']
C. Serval and Parenthesis Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputServal soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.In his favorite math class, the teacher taught him the following interesting definitions.A parenthesis sequence is a string, containing only characters "(" and ")".A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, parenthesis sequences "()()", "(())" are correct (the resulting expressions are: "(1+1)+(1+1)", "((1+1)+1)"), while ")(" and ")" are not. Note that the empty string is a correct parenthesis sequence by definition.We define that |s| as the length of string s. A strict prefix s[1\dots l] (1\leq l< |s|) of a string s = s_1s_2\dots s_{|s|} is string s_1s_2\dots s_l. Note that the empty string and the whole string are not strict prefixes of any string by the definition.Having learned these definitions, he comes up with a new problem. He writes down a string s containing only characters "(", ")" and "?". And what he is going to do, is to replace each of the "?" in s independently by one of "(" and ")" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.InputThe first line contains a single integer |s| (1\leq |s|\leq 3 \cdot 10^5), the length of the string.The second line contains a string s, containing only "(", ")" and "?".OutputA single line contains a string representing the answer.If there are many solutions, any of them is acceptable.If there is no answer, print a single line containing ":(" (without the quotes).ExamplesInput 6 (????? Output (()())Input 10 (???(???(? Output :( NoteIt can be proved that there is no solution for the second sample, so print ":(".
6 (?????
(()())
1 second
256 megabytes
['greedy', 'strings', '*1700']
B. Serval and Toy Brickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many 1 \times 1 \times 1 toy bricks, he builds up a 3-dimensional object. We can describe this object with a n \times m matrix, such that in each cell (i,j), there are h_{i,j} bricks standing on the top of each other.However, Serval doesn't give you any h_{i,j}, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are m columns, and in the i-th of them, the height is the maximum of h_{1,i},h_{2,i},\dots,h_{n,i}. It is similar for the left view, where there are n columns. And in the top view, there is an n \times m matrix t_{i,j}, where t_{i,j} is 0 or 1. If t_{i,j} equals 1, that means h_{i,j}>0, otherwise, h_{i,j}=0.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?InputThe first line contains three positive space-separated integers n, m, h (1\leq n, m, h \leq 100) — the length, width and height.The second line contains m non-negative space-separated integers a_1,a_2,\dots,a_m, where a_i is the height in the i-th column from left to right of the front view (0\leq a_i \leq h).The third line contains n non-negative space-separated integers b_1,b_2,\dots,b_n (0\leq b_j \leq h), where b_j is the height in the j-th column from left to right of the left view.Each of the following n lines contains m numbers, each is 0 or 1, representing the top view, where j-th number of i-th row is 1 if h_{i, j}>0, and 0 otherwise.It is guaranteed that there is at least one structure satisfying the input.OutputOutput n lines, each of them contains m integers, the j-th number in the i-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.ExamplesInput 3 7 3 2 3 0 0 2 0 1 2 1 3 1 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 Output 1 0 0 0 2 0 0 0 0 0 0 0 0 1 2 3 0 0 0 0 0 Input 4 5 5 3 5 2 0 4 4 2 5 4 0 0 0 0 1 1 0 1 0 0 0 1 0 0 0 1 1 1 0 0 Output 0 0 0 0 4 1 0 2 0 0 0 5 0 0 0 3 4 1 0 0 Note The graph above illustrates the object in the first example. The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.
3 7 3 2 3 0 0 2 0 1 2 1 3 1 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0
1 0 0 0 2 0 0 0 0 0 0 0 0 1 2 3 0 0 0 0 0
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1200']
A. Serval and Bustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time t, and there are n bus routes which stop at this station. For the i-th bus route, the first bus arrives at time s_i minutes, and each bus of this route comes d_i minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.InputThe first line contains two space-separated integers n and t (1\leq n\leq 100, 1\leq t\leq 10^5) — the number of bus routes and the time Serval goes to the station. Each of the next n lines contains two space-separated integers s_i and d_i (1\leq s_i,d_i\leq 10^5) — the time when the first bus of this route arrives and the interval between two buses of this route.OutputPrint one number — what bus route Serval will use. If there are several possible answers, you can print any of them.ExamplesInput 2 2 6 4 9 5 Output 1 Input 5 5 3 3 2 5 5 6 4 9 6 1 Output 3 Input 3 7 2 2 2 3 2 4 Output 1 NoteIn the first example, the first bus of the first route arrives at time 6, and the first bus of the second route arrives at time 9, so the first route is the answer.In the second example, a bus of the third route arrives at time 5, so it is the answer.In the third example, buses of the first route come at times 2, 4, 6, 8, and so fourth, buses of the second route come at times 2, 5, 8, and so fourth and buses of the third route come at times 2, 6, 10, and so on, so 1 and 2 are both acceptable answers while 3 is not.
2 2 6 4 9 5
1
1 second
256 megabytes
['brute force', 'math', '*1000']
F2. Neko Rules the Catniverse (Large Version)time limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is same as the previous one, but has larger constraints.Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.There are n planets in the Catniverse, numbered from 1 to n. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs k - 1 moves, where in each move Neko is moved from the current planet x to some other planet y such that: Planet y is not visited yet. 1 \leq y \leq x + m (where m is a fixed constant given in the input) This way, Neko will visit exactly k different planets. Two ways of visiting planets are called different if there is some index i such that, the i-th planet visited in the first way is different from the i-th planet visited in the second way.What is the total number of ways to visit k planets this way? Since the answer can be quite large, print it modulo 10^9 + 7.InputThe only line contains three integers n, k and m (1 \le n \le 10^9, 1 \le k \le \min(n, 12), 1 \le m \le 4) — the number of planets in the Catniverse, the number of planets Neko needs to visit and the said constant m.OutputPrint exactly one integer — the number of different ways Neko can visit exactly k planets. Since the answer can be quite large, print it modulo 10^9 + 7.ExamplesInput 3 3 1 Output 4 Input 4 2 1 Output 9 Input 5 5 4 Output 120 Input 100 1 2 Output 100 NoteIn the first example, there are 4 ways Neko can visit all the planets: 1 \rightarrow 2 \rightarrow 3 2 \rightarrow 3 \rightarrow 1 3 \rightarrow 1 \rightarrow 2 3 \rightarrow 2 \rightarrow 1 In the second example, there are 9 ways Neko can visit exactly 2 planets: 1 \rightarrow 2 2 \rightarrow 1 2 \rightarrow 3 3 \rightarrow 1 3 \rightarrow 2 3 \rightarrow 4 4 \rightarrow 1 4 \rightarrow 2 4 \rightarrow 3 In the third example, with m = 4, Neko can visit all the planets in any order, so there are 5! = 120 ways Neko can visit all the planets.In the fourth example, Neko only visit exactly 1 planet (which is also the planet he initially located), and there are 100 ways to choose the starting planet for Neko.
3 3 1
4
7 seconds
256 megabytes
['bitmasks', 'dp', 'matrices', '*3000']
F1. Neko Rules the Catniverse (Small Version)time limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is same as the next one, but has smaller constraints.Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.There are n planets in the Catniverse, numbered from 1 to n. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs k - 1 moves, where in each move Neko is moved from the current planet x to some other planet y such that: Planet y is not visited yet. 1 \leq y \leq x + m (where m is a fixed constant given in the input) This way, Neko will visit exactly k different planets. Two ways of visiting planets are called different if there is some index i such that the i-th planet visited in the first way is different from the i-th planet visited in the second way.What is the total number of ways to visit k planets this way? Since the answer can be quite large, print it modulo 10^9 + 7.InputThe only line contains three integers n, k and m (1 \le n \le 10^5, 1 \le k \le \min(n, 12), 1 \le m \le 4) — the number of planets in the Catniverse, the number of planets Neko needs to visit and the said constant m.OutputPrint exactly one integer — the number of different ways Neko can visit exactly k planets. Since the answer can be quite large, print it modulo 10^9 + 7.ExamplesInput 3 3 1 Output 4 Input 4 2 1 Output 9 Input 5 5 4 Output 120 Input 100 1 2 Output 100 NoteIn the first example, there are 4 ways Neko can visit all the planets: 1 \rightarrow 2 \rightarrow 3 2 \rightarrow 3 \rightarrow 1 3 \rightarrow 1 \rightarrow 2 3 \rightarrow 2 \rightarrow 1 In the second example, there are 9 ways Neko can visit exactly 2 planets: 1 \rightarrow 2 2 \rightarrow 1 2 \rightarrow 3 3 \rightarrow 1 3 \rightarrow 2 3 \rightarrow 4 4 \rightarrow 1 4 \rightarrow 2 4 \rightarrow 3 In the third example, with m = 4, Neko can visit all the planets in any order, so there are 5! = 120 ways Neko can visit all the planets.In the fourth example, Neko only visit exactly 1 planet (which is also the planet he initially located), and there are 100 ways to choose the starting planet for Neko.
3 3 1
4
7 seconds
256 megabytes
['bitmasks', 'dp', 'matrices', '*2800']
E. Neko and Flashbacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length k is a sequence of k integers from 1 to k containing each integer exactly once. For example, the sequence [3, 1, 2] is a permutation of length 3.When Neko was five, he thought of an array a of n positive integers and a permutation p of length n - 1. Then, he performed the following: Constructed an array b of length n-1, where b_i = \min(a_i, a_{i+1}). Constructed an array c of length n-1, where c_i = \max(a_i, a_{i+1}). Constructed an array b' of length n-1, where b'_i = b_{p_i}. Constructed an array c' of length n-1, where c'_i = c_{p_i}. For example, if the array a was [3, 4, 6, 5, 7] and permutation p was [2, 4, 1, 3], then Neko would have constructed the following arrays: b = [3, 4, 5, 5] c = [4, 6, 6, 7] b' = [4, 5, 3, 5] c' = [6, 7, 4, 6] Then, he wrote two arrays b' and c' on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays b' and c' written on it. However he can't remember the array a and permutation p he used.In case Neko made a mistake and there is no array a and permutation p resulting in such b' and c', print -1. Otherwise, help him recover any possible array a. InputThe first line contains an integer n (2 \leq n \leq 10^5) — the number of elements in array a.The second line contains n-1 integers b'_1, b'_2, \ldots, b'_{n-1} (1 \leq b'_i \leq 10^9).The third line contains n-1 integers c'_1, c'_2, \ldots, c'_{n-1} (1 \leq c'_i \leq 10^9).OutputIf Neko made a mistake and there is no array a and a permutation p leading to the b' and c', print -1. Otherwise, print n positive integers a_i (1 \le a_i \le 10^9), denoting the elements of the array a.If there are multiple possible solutions, print any of them. ExamplesInput 5 4 5 3 5 6 7 4 6 Output 3 4 6 5 7 Input 3 2 4 3 2 Output -1 Input 8 2 3 1 1 2 4 3 3 4 4 2 5 5 4 Output 3 4 5 2 1 4 3 2 NoteThe first example is explained is the problem statement.In the third example, for a = [3, 4, 5, 2, 1, 4, 3, 2], a possible permutation p is [7, 1, 5, 4, 3, 2, 6]. In that case, Neko would have constructed the following arrays: b = [3, 4, 2, 1, 1, 3, 2] c = [4, 5, 5, 2, 4, 4, 3] b' = [2, 3, 1, 1, 2, 4, 3] c' = [3, 4, 4, 2, 5, 5, 4]
5 4 5 3 5 6 7 4 6
3 4 6 5 7
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2400']
D. Neko and Aki's Pranktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNeko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a trie of all correct bracket sequences of length 2n.The definition of correct bracket sequence is as follows: The empty sequence is a correct bracket sequence, If s is a correct bracket sequence, then (\,s\,) is a correct bracket sequence, If s and t are a correct bracket sequence, then st is also a correct bracket sequence. For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo 10^9 + 7.InputThe only line contains a single integer n (1 \le n \le 1000).OutputPrint exactly one integer — the size of the maximum matching in the trie. Since the answer can be quite large, print it modulo 10^9 + 7.ExamplesInput 1 Output 1 Input 2 Output 3 Input 3 Output 9 NoteThe pictures below illustrate tries in the first two examples (for clarity, the round brackets are replaced with angle brackets). The maximum matching is highlighted with blue.  
1
1
1 second
256 megabytes
['dp', 'greedy', 'trees', '*2100']
C. Neko does Mathstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNeko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs to choose the smallest one.Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?InputThe only line contains two integers a and b (1 \le a, b \le 10^9).OutputPrint the smallest non-negative integer k (k \ge 0) such that the lowest common multiple of a+k and b+k is the smallest possible.If there are many possible integers k giving the same value of the least common multiple, print the smallest one.ExamplesInput 6 10 Output 2Input 21 31 Output 9Input 5 10 Output 0NoteIn the first test, one should choose k = 2, as the least common multiple of 6 + 2 and 10 + 2 is 24, which is the smallest least common multiple possible.
6 10
2
1 second
256 megabytes
['brute force', 'math', 'number theory', '*1800']
B. Neko Performs Cat Furrier Transformtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-negative integer m. For example, the numbers 0, 1, 3, 7, 15 and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on x: (Operation A): you select any non-negative integer n and replace x with x \oplus (2^n - 1), with \oplus being a bitwise XOR operator. (Operation B): replace x with x + 1. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most 40 operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than 40 operations.InputThe only line contains a single integer x (1 \le x \le 10^6).OutputThe first line should contain a single integer t (0 \le t \le 40) — the number of operations to apply.Then for each odd-numbered operation print the corresponding number n_i in it. That is, print \lceil \frac{t}{2} \rceil integers n_i (0 \le n_i \le 30), denoting the replacement x with x \oplus (2^{n_i} - 1) in the corresponding step.If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.ExamplesInput 39 Output 4 5 3 Input 1 Output 0 Input 7 Output 0 NoteIn the first test, one of the transforms might be as follows: 39 \to 56 \to 57 \to 62 \to 63. Or more precisely: Pick n = 5. x is transformed into 39 \oplus 31, or 56. Increase x by 1, changing its value to 57. Pick n = 3. x is transformed into 57 \oplus 7, or 62. Increase x by 1, changing its value to 63 = 2^6 - 1. In the second and third test, the number already satisfies the goal requirement.
39
4 5 3
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'dfs and similar', 'math', '*1300']
A. Neko Finds Grapestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j \equiv 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.Find the maximum number of chests Neko can open.InputThe first line contains integers n and m (1 \leq n, m \leq 10^5) — the number of chests and the number of keys.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the numbers written on the treasure chests.The third line contains m integers b_1, b_2, \ldots, b_m (1 \leq b_i \leq 10^9) — the numbers written on the keys.OutputPrint the maximum number of chests you can open.ExamplesInput 5 4 9 14 6 2 11 8 4 7 20 Output 3Input 5 1 2 4 6 8 10 5 Output 1Input 1 4 10 20 30 40 50 Output 0NoteIn the first example, one possible way to unlock 3 chests is as follows: Use first key to unlock the fifth chest, Use third key to unlock the second chest, Use fourth key to unlock the first chest. In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).In the third example, no key can unlock the given chest.
5 4 9 14 6 2 11 8 4 7 20
3
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*800']
F. Sonya and Informaticstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens: Two numbers i and j are chosen equiprobable such that (1 \leq i < j \leq n). The numbers in the i and j positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem.It can be shown that the desired probability is either 0 or it can be represented as \dfrac{P}{Q}, where P and Q are coprime integers and Q \not\equiv 0~\pmod {10^9+7}.InputThe first line contains two integers n and k (2 \leq n \leq 100, 1 \leq k \leq 10^9) — the length of the array a and the number of operations.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 1) — the description of the array a.OutputIf the desired probability is 0, print 0, otherwise print the value P \cdot Q^{-1} \pmod {10^9+7}, where P and Q are defined above.ExamplesInput 3 2 0 1 0 Output 333333336Input 5 1 1 1 1 0 0 Output 0Input 6 4 1 0 0 1 1 0 Output 968493834NoteIn the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is \dfrac{3}{9}=\dfrac{1}{3}.In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0.
3 2 0 1 0
333333336
1 second
256 megabytes
['combinatorics', 'dp', 'matrices', 'probabilities', '*2300']
E. Number of Componentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 \leq i < n there is an edge between the vertices of i and i+1.Denote the function f(l, r), which takes two integers l and r (l \leq r):    We leave in the tree only vertices whose values ​​range from l to r.    The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: \sum_{l=1}^{n} \sum_{r=l}^{n} f(l, r) InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of vertices in the tree.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n) — the values of the vertices.OutputPrint one number — the answer to the problem.ExamplesInput 3 2 1 3 Output 7Input 4 2 1 1 3 Output 11Input 10 1 5 2 5 5 3 10 6 5 1 Output 104NoteIn the first example, the function values ​​will be as follows: f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) f(1, 2)=1 (there are vertices 1 and 2 that form one component) f(1, 3)=1 (all vertices remain, one component is obtained) f(2, 2)=1 (only vertex number 1) f(2, 3)=2 (there are vertices 1 and 3 that form two components) f(3, 3)=1 (only vertex 3) Totally out 7.In the second example, the function values ​​will be as follows: f(1, 1)=1 f(1, 2)=1 f(1, 3)=1 f(1, 4)=1 f(2, 2)=1 f(2, 3)=2 f(2, 4)=2 f(3, 3)=1 f(3, 4)=1 f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
3 2 1 3
7
1 second
256 megabytes
['combinatorics', 'data structures', 'dp', 'math', '*2100']
D. Stas and the Queue at the Buffettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of n high school students numbered from 1 to n. Initially, each student i is on position i. Each student i is characterized by two numbers — a_i and b_i. Dissatisfaction of the person i equals the product of a_i by the number of people standing to the left of his position, add the product b_i by the number of people standing to the right of his position. Formally, the dissatisfaction of the student i, which is on the position j, equals a_i \cdot (j-1) + b_i \cdot (n-j).The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.Although Stas is able to solve such problems, this was not given to him. He turned for help to you.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of people in the queue.Each of the following n lines contains two integers a_i and b_i (1 \leq a_i, b_i \leq 10^8) — the characteristic of the student i, initially on the position i.OutputOutput one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.ExamplesInput 3 4 2 2 3 6 1 Output 12Input 4 2 4 3 3 7 1 2 3 Output 25Input 10 5 10 12 4 31 45 20 55 30 17 29 30 41 32 7 1 5 5 3 15 Output 1423NoteIn the first example it is optimal to put people in this order: (3, 1, 2). The first person is in the position of 2, then his dissatisfaction will be equal to 4 \cdot 1+2 \cdot 1=6. The second person is in the position of 3, his dissatisfaction will be equal to 2 \cdot 2+3 \cdot 0=4. The third person is in the position of 1, his dissatisfaction will be equal to 6 \cdot 0+1 \cdot 2=2. The total dissatisfaction will be 12.In the second example, you need to put people in this order: (3, 2, 4, 1). The total dissatisfaction will be 25.
3 4 2 2 3 6 1
12
1 second
256 megabytes
['greedy', 'math', 'sortings', '*1600']
C. Problem for Nazartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, \ldots), and the second set consists of even positive numbers (2, 4, 6, 8, \ldots). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: 1, 2, 4, 3, 5, 7, 9, 6, 8, 10. Let's number the numbers written, starting with one.The task is to find the sum of numbers with numbers from l to r for given integers l and r. The answer may be big, so you need to find the remainder of the division by 1000000007 (10^9+7).Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.InputThe first line contains two integers l and r (1 \leq l \leq r \leq 10^{18}) — the range in which you need to find the sum.OutputPrint a single integer — the answer modulo 1000000007 (10^9+7).ExamplesInput 1 3 Output 7Input 5 14 Output 105Input 88005553535 99999999999 Output 761141116NoteIn the first example, the answer is the sum of the first three numbers written out (1 + 2 + 4 = 7).In the second example, the numbers with numbers from 5 to 14: 5, 7, 9, 6, 8, 10, 12, 14, 16, 18. Their sum is 105.
1 3
7
1 second
256 megabytes
['constructive algorithms', 'math', '*1800']
B. Dima and a Bad XORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudent Dima from Kremland has a matrix a of size n \times m filled with non-negative integers.He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!Formally, he wants to choose an integers sequence c_1, c_2, \ldots, c_n (1 \leq c_j \leq m) so that the inequality a_{1, c_1} \oplus a_{2, c_2} \oplus \ldots \oplus a_{n, c_n} > 0 holds, where a_{i, j} is the matrix element from the i-th row and the j-th column.Here x \oplus y denotes the bitwise XOR operation of integers x and y.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 the matrix a.Each of the next n lines contains 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, i.e. a_{i, j} (0 \leq a_{i, j} \leq 1023). OutputIf there is no way to choose one integer from each row so that their bitwise exclusive OR is strictly greater than zero, print "NIE".Otherwise print "TAK" in the first line, in the next line print n integers c_1, c_2, \ldots c_n (1 \leq c_j \leq m), so that the inequality a_{1, c_1} \oplus a_{2, c_2} \oplus \ldots \oplus a_{n, c_n} > 0 holds. If there is more than one possible answer, you may output any.ExamplesInput 3 2 0 0 0 0 0 0 Output NIE Input 2 3 7 7 7 7 7 10 Output TAK 1 3 NoteIn the first example, all the numbers in the matrix are 0, so it is impossible to select one number in each row of the table so that their bitwise exclusive OR is strictly greater than zero.In the second example, the selected numbers are 7 (the first number in the first line) and 10 (the third number in the second line), 7 \oplus 10 = 13, 13 is more than 0, so the answer is found.
3 2 0 0 0 0 0 0
NIE
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dp', '*1600']
A. Maxim and Biologytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".Help Maxim solve the problem that the teacher gave him.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.InputThe first line contains a single integer n (4 \leq n \leq 50) — the length of the string s.The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.OutputOutput the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.ExamplesInput 4 ZCTH Output 2Input 5 ZDATG Output 5Input 6 AFBAKC Output 16NoteIn the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
4 ZCTH
2
1 second
256 megabytes
['brute force', 'strings', '*1000']
B. Tiling Challengetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n rows and n columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?InputThe first line of the input contains a single integer n (3 \leq n \leq 50) — the size of the board.The following n lines describe the board. The i-th line (1 \leq i \leq n) contains a single string of length n. Its j-th character (1 \leq j \leq n) is equal to "." if the cell in the i-th row and the j-th column is free; it is equal to "#" if it's occupied.You can assume that the board contains at least one free cell.OutputOutput YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).ExamplesInput 3 #.# ... #.# Output YES Input 4 ##.# #... #### ##.# Output NO Input 5 #.### ....# #.... ###.# ##### Output YES Input 5 #.### ....# #.... ....# #..## Output NO NoteThe following sketches show the example boards and their tilings if such tilings exist:
3 #.# ... #.#
YES
2 seconds
256 megabytes
['greedy', 'implementation', '*900']
A. Stock Arbitragingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWelcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price of s_i bourles.In the evening, there are m opportunities to sell shares. The i-th of them allows to sell as many shares as you want, each at the price of b_i bourles. You can't sell more shares than you have.It's morning now and you possess r bourles and no shares.What is the maximum number of bourles you can hold after the evening?InputThe first line of the input contains three integers n, m, r (1 \leq n \leq 30, 1 \leq m \leq 30, 1 \leq r \leq 1000) — the number of ways to buy the shares on the market, the number of ways to sell the shares on the market, and the number of bourles you hold now.The next line contains n integers s_1, s_2, \dots, s_n (1 \leq s_i \leq 1000); s_i indicates the opportunity to buy shares at the price of s_i bourles.The following line contains m integers b_1, b_2, \dots, b_m (1 \leq b_i \leq 1000); b_i indicates the opportunity to sell shares at the price of b_i bourles.OutputOutput a single integer — the maximum number of bourles you can hold after the evening.ExamplesInput 3 4 11 4 2 5 4 4 5 4 Output 26 Input 2 2 50 5 7 4 2 Output 50 NoteIn the first example test, you have 11 bourles in the morning. It's optimal to buy 5 shares of a stock at the price of 2 bourles in the morning, and then to sell all of them at the price of 5 bourles in the evening. It's easy to verify that you'll have 26 bourles after the evening.In the second example test, it's optimal not to take any action.
3 4 11 4 2 5 4 4 5 4
26
1 second
256 megabytes
['greedy', 'implementation', '*800']
E. Election Promisestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Byteland, there are two political parties fighting for seats in the Parliament in the upcoming elections: Wrong Answer Party and Time Limit Exceeded Party. As they want to convince as many citizens as possible to cast their votes on them, they keep promising lower and lower taxes.There are n cities in Byteland, connected by m one-way roads. Interestingly enough, the road network has no cycles — it's impossible to start in any city, follow a number of roads, and return to that city. Last year, citizens of the i-th city had to pay h_i bourles of tax.Parties will now alternately hold the election conventions in various cities. If a party holds a convention in city v, the party needs to decrease the taxes in this city to a non-negative integer amount of bourles. However, at the same time they can arbitrarily modify the taxes in each of the cities that can be reached from v using a single road. The only condition that must be fulfilled that the tax in each city has to remain a non-negative integer amount of bourles.The first party to hold the convention is Wrong Answer Party. It's predicted that the party to hold the last convention will win the election. Can Wrong Answer Party win regardless of Time Limit Exceeded Party's moves?InputThe first line of the input contains two integers n, m (1 \leq n \leq 200\,000, 0 \leq m \leq 200\,000) — the number of cities and roads in Byteland.The next line contains n space-separated integers h_1, h_2, \dots, h_n (0 \leq h_i \leq 10^9); h_i denotes the amount of taxes paid in the i-th city.Each of the following m lines contains two integers (1 \leq u, v \leq n, u \neq v), and describes a one-way road leading from the city u to the city v. There will be no cycles in the road network. No two roads will connect the same pair of cities.We can show that the conventions cannot be held indefinitely for any correct test case.OutputIf Wrong Answer Party can win the election, output WIN in the first line of your output. In this case, you're additionally asked to produce any convention allowing the party to win regardless of the opponent's actions. The second line should contain n non-negative integers h'_1, h'_2, \dots, h'_n (0 \leq h'_i \leq 2 \cdot 10^{18}) describing the amount of taxes paid in consecutive cities after the convention. If there are multiple answers, output any. We guarantee that if the party has any winning move, there exists a move after which no city has to pay more than 2 \cdot 10^{18} bourles.If the party cannot assure their victory, output LOSE in the first and only line of the output.ExamplesInput 4 2 2 1 1 5 1 2 3 4 Output WIN 1 5 1 5 Input 4 2 1 5 1 5 1 2 3 4 Output LOSE Input 3 3 314 159 265 1 2 1 3 3 2 Output WIN 0 0 0 Input 6 4 2 2 5 5 6 6 1 3 2 4 3 5 4 6 Output LOSE NoteIn the first example, Wrong Answer Party should hold the convention in the city 1. The party will decrease the taxes in this city to 1 bourle. As the city 2 is directly reachable from 1, we can arbitrarily modify the taxes in this city. The party should change the tax to 5 bourles. It can be easily proved that Time Limit Exceeded cannot win the election after this move if Wrong Answer Party plays optimally.The second example test presents the situation we created after a single move in the previous test; as it's Wrong Answer Party's move now, the party cannot win.In the third test, we should hold the convention in the first city. This allows us to change the taxes in any city to any desired value; we can for instance decide to set all the taxes to zero, which allows the Wrong Answer Party to win the election immediately.
4 2 2 1 1 5 1 2 3 4
WIN 1 5 1 5
2 seconds
256 megabytes
['games', 'graphs', '*3200']
D. Abandoning Roadstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCodefortia is a small island country located somewhere in the West Pacific. It consists of n settlements connected by m bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to a or b seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads.Codefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that: it will be possible to travel between each pair of cities using the remaining roads only, the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight), among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement 1) and the parliament house (in settlement p) using the remaining roads only will be minimum possible. The king, however, forgot where the parliament house was. For each settlement p = 1, 2, \dots, n, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement p) after some roads are abandoned?InputThe first line of the input contains four integers n, m, a and b (2 \leq n \leq 70, n - 1 \leq m \leq 200, 1 \leq a < b \leq 10^7) — the number of settlements and gravel roads in Codefortia, and two possible travel times. Each of the following lines contains three integers u, v, c (1 \leq u, v \leq n, u \neq v, c \in \{a, b\}) denoting a single gravel road between the settlements u and v, which requires c minutes to travel.You can assume that the road network is connected and has no loops or multiedges.OutputOutput a single line containing n integers. The p-th of them should denote the minimum possible time required to travel from 1 to p after the selected roads are abandoned. Note that for each p you can abandon a different set of roads.ExamplesInput 5 5 20 25 1 2 25 2 3 25 3 4 20 4 5 20 5 1 20 Output 0 25 60 40 20 Input 6 7 13 22 1 2 13 2 3 13 1 4 22 3 4 13 4 5 13 5 6 13 6 1 13 Output 0 13 26 39 26 13 NoteThe minimum possible sum of times required to pass each road in the first example is 85 — exactly one of the roads with passing time 25 must be abandoned. Note that after one of these roads is abandoned, it's now impossible to travel between settlements 1 and 3 in time 50.
5 5 20 25 1 2 25 2 3 25 3 4 20 4 5 20 5 1 20
0 25 60 40 20
5 seconds
512 megabytes
['brute force', 'dp', 'graphs', 'greedy', '*3000']
C. Tree Generator™time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOwl Pacino has always been into trees — unweighted rooted trees in particular. He loves determining the diameter of every tree he sees — that is, the maximum length of any simple path in the tree.Owl Pacino's owl friends decided to present him the Tree Generator™ — a powerful machine creating rooted trees from their descriptions. An n-vertex rooted tree can be described by a bracket sequence of length 2(n - 1) in the following way: find any walk starting and finishing in the root that traverses each edge exactly twice — once down the tree, and later up the tree. Then follow the path and write down "(" (an opening parenthesis) if an edge is followed down the tree, and ")" (a closing parenthesis) otherwise.The following figure shows sample rooted trees and their descriptions: Owl wrote down the description of an n-vertex rooted tree. Then, he rewrote the description q times. However, each time he wrote a new description, he picked two different characters in the description he wrote the last time, swapped them and wrote down the resulting string. He always made sure that each written string was the description of a rooted tree.Pacino then used Tree Generator™ for each description he wrote down. What is the diameter of each constructed tree?InputThe first line of the input contains two integers n, q (3 \le n \le 100\,000, 1 \le q \le 100\,000) — the number of vertices in the tree and the number of changes to the tree description. The following line contains a description of the initial tree — a string of length 2(n-1) consisting of opening and closing parentheses.Each of the following q lines describes a single change to the description and contains two space-separated integers a_i, b_i (2 \leq a_i, b_i \leq 2n-3) which identify the indices of two brackets to be swapped. You can assume that the description will change after each query, and that after each change a tree can be constructed from the description.OutputOutput q + 1 integers — the diameter of each constructed tree, in the order their descriptions have been written down.ExamplesInput 5 5 (((()))) 4 5 3 4 5 6 3 6 2 5 Output 4 3 3 2 4 4 Input 6 4 (((())())) 6 7 5 4 6 4 7 4 Output 4 4 4 5 3 NoteThe following figure shows each constructed tree and its description in the first example test:
5 5 (((()))) 4 5 3 4 5 6 3 6 2 5
4 3 3 2 4 4
2 seconds
256 megabytes
['data structures', 'implementation', 'trees', '*2700']
B. Three Religionstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: 1, 2, 3, so that each character is painted in at most one color, and the description of the i-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color i.The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.InputThe first line of the input contains two integers n, q (1 \leq n \leq 100\,000, 1 \leq q \leq 1000) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length n consisting of lowercase English characters.Each of the following line describes a single evolution and is in one of the following formats: + i c (i \in \{1, 2, 3\}, c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}: append the character c to the end of i-th religion description. - i (i \in \{1, 2, 3\}) – remove the last character from the i-th religion description. You can assume that the pattern is non-empty. You can assume that no religion will have description longer than 250 characters.OutputWrite q lines. The i-th of them should be YES if the religions could coexist in peace after the i-th evolution, or NO otherwise.You can print each character in any case (either upper or lower).ExamplesInput 6 8 abdabc + 1 a + 1 d + 2 b + 2 c + 3 a + 3 b + 1 c - 2 Output YES YES YES YES YES YES NO YES Input 6 8 abbaab + 1 a + 2 a + 3 a + 1 b + 2 b + 3 b - 1 + 2 z Output YES YES YES YES YES NO YES NO NoteIn the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe:
6 8 abdabc + 1 a + 1 d + 2 b + 2 c + 3 a + 3 b + 1 c - 2
YES YES YES YES YES YES NO YES
3 seconds
256 megabytes
['dp', 'implementation', 'strings', '*2200']
A. Prefix Sum Primestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting!InputThe first line of the input contains a single integer n (1 \leq n \leq 200\,000) — the number of number tiles in the bag. The following line contains n space-separated integers a_1, a_2, \dots, a_n (a_i \in \{1, 2\}) — the values written on the tiles.OutputOutput a permutation b_1, b_2, \dots, b_n of the input sequence (a_1, a_2, \dots, a_n) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.ExamplesInput 5 1 2 1 2 1 Output 1 1 1 2 2 Input 9 1 1 2 1 1 1 2 1 1 Output 1 1 1 2 1 1 1 2 1 NoteThe first solution produces the prefix sums 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}} (four primes constructed), while the prefix sums in the second solution are 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}} (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.
5 1 2 1 2 1
1 1 1 2 2
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', 'number theory', '*1200']
H. Holy Diver time limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an array which is initially empty. You need to perform n operations of the given format: "a l r k": append a to the end of the array. After that count the number of integer pairs x, y such that l \leq x \leq y \leq r and \operatorname{mex}(a_{x}, a_{x+1}, \ldots, a_{y}) = k. The elements of the array are numerated from 1 in the order they are added to the array.To make this problem more tricky we don't say your real parameters of the queries. Instead your are given a', l', r', k'. To get a, l, r, k on the i-th operation you need to perform the following: a := (a' + lans) \bmod(n + 1), l := (l' + lans) \bmod{i} + 1, r := (r' + lans) \bmod{i} + 1, if l > r swap l and r, k := (k' + lans) \bmod(n + 1), where lans is the answer to the previous operation, initially lans is equal to zero. i is the id of the operation, operations are numbered from 1.The \operatorname{mex}(S), where S is a multiset of non-negative integers, is the smallest non-negative integer which does not appear in the set. For example, \operatorname{mex}(\{2, 2, 3\}) = 0 and \operatorname{mex} (\{0, 1, 4, 1, 6\}) = 2. InputThe first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array.The next n lines contain the description of queries.Each of them n lines contains four non-negative integers a', l', r', k' (0, \leq a', l', r', k' \leq 10^9), describing one operation.OutputFor each query print a single integer — the answer to this query.ExamplesInput 5 0 0 0 1 0 1 0 5 5 2 1 0 5 2 1 0 2 4 3 3 Output 1 1 2 6 3 Input 5 2 0 0 2 2 0 1 1 0 0 2 0 3 2 2 0 0 2 3 0 Output 0 0 3 0 0 NoteFor the first example the decoded values of a, l, r, k are the following:a_1=0,l_1=1,r_1=1,k_1=1a_2=1,l_2=1,r_2=2,k_2=0a_3=0,l_3=1,r_3=3,k_3=1a_4=1,l_4=1,r_4=4,k_4=2a_5=2,l_5=1,r_5=5,k_5=3For the second example the decoded values of a, l, r, k are the following:a_1=2,l_1=1,r_1=1,k_1=2a_2=2,l_2=1,r_2=2,k_2=1a_3=0,l_3=1,r_3=3,k_3=0a_4=0,l_4=2,r_4=2,k_4=3a_5=0,l_5=3,r_5=4,k_5=0
5 0 0 0 1 0 1 0 5 5 2 1 0 5 2 1 0 2 4 3 3
1 1 2 6 3
3 seconds
1024 megabytes
['data structures', '*3500']
G. Gold Experiencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputConsider an undirected graph G with n vertices. There is a value a_i in each vertex.Two vertices i and j are connected with an edge if and only if gcd(a_i, a_j) > 1, where gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.Consider a set of vertices. Let's call a vertex in this set fair if it is connected with an edge with all other vertices in this set.You need to find a set of k vertices (where k is a given integer, 2 \cdot k \le n) where all vertices are fair or all vertices are not fair. One can show that such a set always exists.InputThe first line contains integers n and k (6 \leq 2 \cdot k \leq n \leq 10^5) — the number of vertices and parameter k.The second line contains n integers a_1, a_2, \ldots, a_n (2 \le a_i \le 10^7) — the values in the vertices.OutputPrint exactly k distinct integers — the indices of the vertices in the chosen set in any order.ExamplesInput 6 3 6 15 10 8 14 12 Output 1 3 6 Input 8 4 11 15 10 6 21 15 10 6 Output 1 2 3 4 Input 10 5 3003 17017 3230 49742 546 41990 17765 570 21945 36465 Output 4 6 9 10 1 NoteIn the first test case, set \{2, 4, 5\} is an example of set where no vertices are fair. The vertex 2 does not share an edge with vertex 4 since gcd(15, 8) = 1. The vertex 4 does not share an edge with vertex 2. The vertex 5 does not share an edge with vertex 2.In the second test case, set \{8, 5, 6, 4\} is an example of a set where all vertices are fair.
6 3 6 15 10 8 14 12
1 3 6
2 seconds
1024 megabytes
['constructive algorithms', 'graphs', 'math', 'number theory', 'probabilities', '*3300']
F. Foo Fighterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n objects. Each object has two integer properties: val_i — its price — and mask_i. It is guaranteed that the sum of all prices is initially non-zero.You want to select a positive integer s. All objects will be modified after that. The i-th object will be modified using the following procedure: Consider mask_i and s in binary notation, Compute the bitwise AND of s and mask_i (s \,\&\, mask_i), If (s \,\&\, mask_i) contains an odd number of ones, replace the val_i with -val_i. Otherwise do nothing with the i-th object. You need to find such an integer s that when the modification above is done the sum of all prices changes sign (if it was negative, it should become positive, and vice-versa; it is not allowed for it to become zero). The absolute value of the sum can be arbitrary.InputThe first line contains a single integer n (1 \leq n \leq 3 \cdot 10^5) — the number of objects.The i-th of next n lines contains integers val_i and mask_i (-10^9 \leq val_i \leq 10^9, 1 \le mask_i \le 2^{62} - 1) — the price of the object and its mask.It is guaranteed that the sum of val_i is initially non-zero.OutputPrint an integer s (1 \le s \le 2^{62} - 1), such that if we modify the objects as described above, the sign of the sum of val_i changes its sign.If there are multiple such s, print any of them. One can show that there is always at least one valid s.ExamplesInput 5 17 206 -6 117 -2 151 9 93 6 117 Output 64 Input 1 1 1 Output 1 NoteIn the first test sample all objects will change their prices except for the object with mask 151. So their total sum will change its sign: initially 24, after modifications — -28.In the second test sample the only object will change its price. So the total sum will change its sign.
5 17 206 -6 117 -2 151 9 93 6 117
64
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', '*2700']
E. Earth Wind and Firetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n stones arranged on an axis. Initially the i-th stone is located at the coordinate s_i. There may be more than one stone in a single place.You can perform zero or more operations of the following type: take two stones with indices i and j so that s_i \leq s_j, choose an integer d (0 \leq 2 \cdot d \leq s_j - s_i), and replace the coordinate s_i with (s_i + d) and replace coordinate s_j with (s_j - d). In other words, draw stones closer to each other. You want to move the stones so that they are located at positions t_1, t_2, \ldots, t_n. The order of the stones is not important — you just want for the multiset of the stones resulting positions to be the same as the multiset of t_1, t_2, \ldots, t_n.Detect whether it is possible to move the stones this way, and if yes, construct a way to do so. You don't need to minimize the number of moves.InputThe first line contains a single integer n (1 \le n \le 3 \cdot 10^5) – the number of stones.The second line contains integers s_1, s_2, \ldots, s_n (1 \le s_i \le 10^9) — the initial positions of the stones.The second line contains integers t_1, t_2, \ldots, t_n (1 \le t_i \le 10^9) — the target positions of the stones.OutputIf it is impossible to move the stones this way, print "NO".Otherwise, on the first line print "YES", on the second line print the number of operations m (0 \le m \le 5 \cdot n) required. You don't have to minimize the number of operations.Then print m lines, each containing integers i, j, d (1 \le i, j \le n, s_i \le s_j, 0 \leq 2 \cdot d \leq s_j - s_i), defining the operations.One can show that if an answer exists, there is an answer requiring no more than 5 \cdot n operations.ExamplesInput 5 2 2 7 4 9 5 4 5 5 5 Output YES 4 4 3 1 2 3 1 2 5 2 1 5 2Input 3 1 5 10 3 5 7 Output NONoteConsider the first example. After the first move the locations of stones is [2, 2, 6, 5, 9]. After the second move the locations of stones is [2, 3, 5, 5, 9]. After the third move the locations of stones is [2, 5, 5, 5, 7]. After the last move the locations of stones is [4, 5, 5, 5, 5].
5 2 2 7 4 9 5 4 5 5 5
YES 4 4 3 1 2 3 1 2 5 2 1 5 2
4 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'sortings', 'two pointers', '*2300']
D. Dirty Deeds Done Dirt Cheaptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n pairs of integers (a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n). All of the integers in the pairs are distinct and are in the range from 1 to 2 \cdot n inclusive.Let's call a sequence of integers x_1, x_2, \ldots, x_{2k} good if either x_1 < x_2 > x_3 < \ldots < x_{2k-2} > x_{2k-1} < x_{2k}, or x_1 > x_2 < x_3 > \ldots > x_{2k-2} < x_{2k-1} > x_{2k}. You need to choose a subset of distinct indices i_1, i_2, \ldots, i_t and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \ldots, a_{i_t}, b_{i_t}), this sequence is good.What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence i_1, i_2, \ldots, i_t.InputThe first line contains single integer n (2 \leq n \leq 3 \cdot 10^5) — the number of pairs.Each of the next n lines contain two numbers — a_i and b_i (1 \le a_i, b_i \le 2 \cdot n) — the elements of the pairs.It is guaranteed that all integers in the pairs are distinct, that is, every integer from 1 to 2 \cdot n is mentioned exactly once.OutputIn the first line print a single integer t — the number of pairs in the answer.Then print t distinct integers i_1, i_2, \ldots, i_t — the indexes of pairs in the corresponding order.ExamplesInput 5 1 7 6 4 2 10 9 8 3 5 Output 3 1 5 3 Input 3 5 4 3 2 6 1 Output 3 3 2 1 NoteThe final sequence in the first example is 1 < 7 > 3 < 5 > 2 < 10.The final sequence in the second example is 6 > 1 < 3 > 2 < 5 > 4.
5 1 7 6 4 2 10 9 8 3 5
3 1 5 3
3 seconds
256 megabytes
['greedy', 'sortings', '*1800']
C. Crazy Diamondtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of integers from 1 to n, where n is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: take two indices i and j such that 2 \cdot |i - j| \geq n and swap p_i and p_j. There is no need to minimize the number of operations, however you should use no more than 5 \cdot n operations. One can show that it is always possible to do that.InputThe first line contains a single integer n (2 \leq n \leq 3 \cdot 10^5, n is even) — the length of the permutation. The second line contains n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the given permutation.OutputOn the first line print m (0 \le m \le 5 \cdot n) — the number of swaps to perform.Each of the following m lines should contain integers a_i, b_i (1 \le a_i, b_i \le n, |a_i - b_i| \ge \frac{n}{2}) — the indices that should be swapped in the corresponding swap.Note that there is no need to minimize the number of operations. We can show that an answer always exists.ExamplesInput 2 2 1 Output 1 1 2Input 4 3 4 1 2 Output 4 1 4 1 4 1 3 2 4 Input 6 2 5 3 1 4 6 Output 3 1 5 2 5 1 4 NoteIn the first example, when one swap elements on positions 1 and 2, the array becomes sorted.In the second example, pay attention that there is no need to minimize number of swaps.In the third example, after swapping elements on positions 1 and 5 the array becomes: [4, 5, 3, 1, 2, 6]. After swapping elements on positions 2 and 5 the array becomes [4, 2, 3, 1, 5, 6] and finally after swapping elements on positions 1 and 4 the array becomes sorted: [1, 2, 3, 4, 5, 6].
2 2 1
1 1 2
3 seconds
256 megabytes
['constructive algorithms', 'sortings', '*1700']
B. Born This Waytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are n flights from A to B, they depart at time moments a_1, a_2, a_3, ..., a_n and arrive at B t_a moments later.There are m flights from B to C, they depart at time moments b_1, b_2, b_3, ..., b_m and arrive at C t_b moments later.The connection time is negligible, so one can use the i-th flight from A to B and the j-th flight from B to C if and only if b_j \ge a_i + t_a.You can cancel at most k flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel k flights. If you can cancel k or less flights in such a way that it is not possible to reach C at all, print -1.InputThe first line contains five integers n, m, t_a, t_b and k (1 \le n, m \le 2 \cdot 10^5, 1 \le k \le n + m, 1 \le t_a, t_b \le 10^9) — the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively.The second line contains n distinct integers in increasing order a_1, a_2, a_3, ..., a_n (1 \le a_1 < a_2 < \ldots < a_n \le 10^9) — the times the flights from A to B depart.The third line contains m distinct integers in increasing order b_1, b_2, b_3, ..., b_m (1 \le b_1 < b_2 < \ldots < b_m \le 10^9) — the times the flights from B to C depart.OutputIf you can cancel k or less flights in such a way that it is not possible to reach C at all, print -1.Otherwise print the earliest time Arkady can arrive at C if you cancel k flights in such a way that maximizes this time.ExamplesInput 4 5 1 1 2 1 3 5 7 1 2 3 9 10 Output 11 Input 2 2 4 4 2 1 10 10 20 Output -1 Input 4 3 2 3 1 1 999999998 999999999 1000000000 3 4 1000000000 Output 1000000003 NoteConsider the first example. The flights from A to B depart at time moments 1, 3, 5, and 7 and arrive at B at time moments 2, 4, 6, 8, respectively. The flights from B to C depart at time moments 1, 2, 3, 9, and 10 and arrive at C at time moments 2, 3, 4, 10, 11, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment 4, and take the last flight from B to C arriving at C at time moment 11.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C.
4 5 1 1 2 1 3 5 7 1 2 3 9 10
11
1 second
256 megabytes
['binary search', 'brute force', 'two pointers', '*1600']
A. Another One Bites The Dusttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.What is the length of the longest good string you can obtain this way?InputThe first line contains three positive integers a, b, c (1 \leq a, b, c \leq 10^9) — the number of strings "a", "b" and "ab" respectively.OutputPrint a single number — the maximum possible length of the good string you can obtain.ExamplesInput 1 1 1 Output 4 Input 2 1 2 Output 7 Input 3 5 2 Output 11 Input 2 2 1 Output 6 Input 1000000000 1000000000 1000000000 Output 4000000000 NoteIn the first example the optimal string is "baba".In the second example the optimal string is "abababa".In the third example the optimal string is "bababababab".In the fourth example the optimal string is "ababab".
1 1 1
4
1 second
256 megabytes
['greedy', '*800']
F. Zigzag Gametime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a complete bipartite graph with 2n nodes, with n nodes on each side of the bipartition. Nodes 1 through n are on one side of the bipartition, and nodes n+1 to 2n are on the other side. You are also given an n \times n matrix a describing the edge weights. a_{ij} denotes the weight of the edge between nodes i and j+n. Each edge has a distinct weight.Alice and Bob are playing a game on this graph. First Alice chooses to play as either "increasing" or "decreasing" for herself, and Bob gets the other choice. Then she places a token on any node of the graph. Bob then moves the token along any edge incident to that node. They now take turns playing the following game, with Alice going first.The current player must move the token from the current vertex to some adjacent unvisited vertex. Let w be the last weight of the last edge that was traversed. The edge that is traversed must be strictly greater than w if the player is playing as "increasing", otherwise, it must be strictly less. The first player unable to make a move loses.You are given n and the edge weights of the graph. You can choose to play as either Alice or Bob, and you will play against the judge. You must win all the games for your answer to be judged correct.InteractionEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 50). Description of the test cases follows.Each test starts with an integer n (1 \leq n \leq 50) — the number of nodes on each side of the bipartition.The next n lines contain n integers a_{ij} (1 \leq a_{ij} \leq n^2). a_{ij} denotes the weight of the edge between node i and node j+n. All a_{ij} will be distinct.You first print a string "A" or "B", denoting which player you want to play ("A" for Alice and "B" for Bob).If playing as Alice, first print either "I" or "D" (denoting whether you choose "increasing" or "decreasing"). Then, print the node that you wish to start at.If playing as Bob, read in a character "I" or "D" (denoting whether the judge chose "increasing" or "decreasing"), then the node that the judge chooses to start at.To make a move, print the index of the node that you wish to go to. To read what move the judge made, read an integer from standard in.If the judge responds with -1, then that means the judge has determined it has no legal moves (or it may have just given up) and that you won the case. Stop processing this case immediately and start processing the next case.If the judge responds with -2, that means that the judge has determined that you made an invalid move, so you should exit immediately to avoid getting other verdicts.If you are unable to make a move or give up, print -1 and then exit immediately. This will give you a Wrong answer verdict.After printing a move 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.Hack FormatTo hack, use the following format. Note that you can only hack with one test case.The first line should contain a single integer t (t=1).The second line should contain an integer n (1 \leq n \leq 50).The next n lines should contain n integers each, the a_{ij} (1 \leq a_{ij} \leq n^2). a_{ij} denotes the weight of the edge between node i and node j+n. All a_{ij} must be distinct.The judge will play a uniformly random legal move with this case versus the hacked program. If it has no legal moves left, it will give up and declare the player as the winner.ExampleInput 2 3 3 1 9 2 5 7 6 4 8 6 -1 1 1 I 1 -1Output A D 3 2 B 2NoteThe first example has two test cases. In the first test case, the graph looks like the following. In the sample output, the player decides to play as Alice and chooses "decreasing" and starting at node 3. The judge responds by moving to node 6. After, the player moves to node 2. At this point, the judge has no more moves (since the weight must "increase"), so it gives up and prints -1.In the next case, we have two nodes connected by an edge of weight 1. The player decides to play as Bob. No matter what the judge chooses, the player can move the token to the other node and the judge has no moves so will lose.
2 3 3 1 9 2 5 7 6 4 8 6 -1 1 1 I 1 -1
A D 3 2 B 2
5 seconds
256 megabytes
['games', 'interactive', '*3500']
E. Rainbow Coinstime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCarl has n coins of various colors, and he would like to sort them into piles. The coins are labeled 1,2,\ldots,n, and each coin is exactly one of red, green, or blue. He would like to sort the coins into three different piles so one pile contains all red coins, one pile contains all green coins, and one pile contains all blue coins.Unfortunately, Carl is colorblind, so this task is impossible for him. Luckily, he has a friend who can take a pair of coins and tell Carl if they are the same color or not. Using his friend, Carl believes he can now sort the coins. The order of the piles doesn't matter, as long as all same colored coins are in the one pile, and no two different colored coins are in the same pile.His friend will answer questions about multiple pairs of coins in batches, and will answer about all of those pairs in parallel. Each coin should be in at most one pair in each batch. The same coin can appear in different batches.Carl can use only 7 batches. Help him find the piles of coins after sorting.InteractionYou will be given multiple test cases. The first line contains an integer t (1 \leq t \leq 5) — the number of test cases.The first line of each test case contains one integer n (1 \leq n \leq 10^5) — the number of coins. If you read in a value of -1 here, that means that you printed an invalid answer in the previous case and exit immediately to avoid getting other verdicts.To ask a question, print "Q k\ x_1\ y_1\ \ldots\ x_k\ y_k" (1 \leq k \leq n/2, 1 \leq x_i,y_i \leq n, x_i \neq y_i). k denotes the number of pairs in the batch, and x_i, y_i denote the i-th pair of coins in the batch. A coin can only appear at most once in a batch. All x_i and y_i should be distinct.The judge will respond with a bitstring of length k, where the i-th character is "1" if x_i and y_i are the same color, and "0" otherwise. The judge will respond with -1 if you ever ask an invalid query. Make sure to exit immediately to avoid getting other verdicts.When you are ready to answer, print four lines.The first line contains "A k_1\ k_2\ k_3" (0 \leq k_1,k_2,k_3 and k_1+k_2+k_3 = n). These denote the sizes of the three piles.The next line has k_1 integers, the labels of the coins in the first pile.The next line has k_2 integers, the labels of the coins in the second pile.The next line has k_3 integers, the labels coins in the third pile.Each coin must appear in exactly one pile.You may only ask at most 7 batches per test case.After printing a query and the answer 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.Hack FormatTo hack, use the following format. Note that you can only hack with one test case.The first line should contain a single integer t (t=1).The second line should contain a single string s consisting of only the characters "R", "G", "B" (1 \leq |s| \leq 10^5). The i-th character in this string represents the color of the i-th coin.ExampleInput 3 3 1 1 1 3 1 0 0 6 000 010 100 001 000 Output Q 1 1 2 Q 1 2 3 Q 1 1 3 A 3 0 0 1 2 3 Q 1 1 3 Q 1 2 3 Q 1 1 2 A 2 0 1 1 3 2 Q 3 1 2 3 4 5 6 Q 3 1 3 2 5 4 6 Q 3 1 4 2 6 3 5 Q 3 1 5 2 4 3 6 Q 3 1 6 2 3 4 5 A 2 2 2 1 4 2 5 3 6NoteIn the example, there are three test cases.In the first test case, there are three coins. We ask about the pairs (1,2), (2,3), and (1,3) in different batches and get that they are all the same color. Thus, we know all the coins are the same color, so we can put them all in one pile. Note that some piles can be empty and those are denoted with an empty line.In the second test case, there are three coins again. This time, we only get that (1,3) are the same and (1,2) and (2,3) are different. So, one possible scenario is that coins 1 and 3 are red and coin 2 is green.In the last case, there are 6 coins. The case shows how to ask and receive answers for multiple pairs in one batch.
3 3 1 1 1 3 1 0 0 6 000 010 100 001 000
Q 1 1 2 Q 1 2 3 Q 1 1 3 A 3 0 0 1 2 3 Q 1 1 3 Q 1 2 3 Q 1 1 2 A 2 0 1 1 3 2 Q 3 1 2 3 4 5 6 Q 3 1 3 2 5 4 6 Q 3 1 4 2 6 3 5 Q 3 1 5 2 4 3 6 Q 3 1 6 2 3 4 5 A 2 2 2 1 4 2 5 3 6
6 seconds
256 megabytes
['interactive', '*3000']
D. Palindrome XORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of characters "1", "0", and "?". The first character of s is guaranteed to be "1". Let m be the number of characters in s.Count the number of ways we can choose a pair of integers a, b that satisfies the following: 1 \leq a < b < 2^m When written without leading zeros, the base-2 representations of a and b are both palindromes. The base-2 representation of bitwise XOR of a and b matches the pattern s. We say that t matches s if the lengths of t and s are the same and for every i, the i-th character of t is equal to the i-th character of s, or the i-th character of s is "?". Compute this count modulo 998244353. InputThe first line contains a single string s (1 \leq |s| \leq 1\,000). s consists only of characters "1", "0" and "?". It is guaranteed that the first character of s is a "1".OutputPrint a single integer, the count of pairs that satisfy the conditions modulo 998244353.ExamplesInput 10110 Output 3 Input 1?0???10 Output 44 Input 1????????????????????????????????????? Output 519569202 Input 1 Output 0 NoteFor the first example, the pairs in base-2 are (111, 10001), (11, 10101), (1001, 11111).
10110
3
1 second
256 megabytes
['dfs and similar', 'graphs', '*2400']
C. Thanos Nimtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.Alice and Bob will play a game alternating turns with Alice going first.On a player's turn, they must choose exactly \frac{n}{2} nonempty piles and independently remove a positive number of stones from each of the chosen piles. They can remove a different number of stones from the piles in a single turn. The first player unable to make a move loses (when there are less than \frac{n}{2} nonempty piles).Given the starting configuration, determine who will win the game.InputThe first line contains one integer n (2 \leq n \leq 50) — the number of piles. It is guaranteed that n is an even number.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 50) — the number of stones in the piles.OutputPrint a single string "Alice" if Alice wins; otherwise, print "Bob" (without double quotes).ExamplesInput 2 8 8 Output Bob Input 4 3 1 4 1 Output Alice NoteIn the first example, each player can only remove stones from one pile (\frac{2}{2}=1). Alice loses, since Bob can copy whatever Alice does on the other pile, so Alice will run out of moves first.In the second example, Alice can remove 2 stones from the first pile and 3 stones from the third pile on her first move to guarantee a win.
2 8 8
Bob
1 second
256 megabytes
['games', '*2000']
B. Chladni Figuretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 \leq i < n) are adjacent, and so are points n and 1.There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 \leq k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.InputThe first line contains two space-separated integers n and m (2 \leq n \leq 100\,000, 1 \leq m \leq 200\,000) — the number of points and the number of segments, 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) that describe a segment connecting points a_i and b_i.It is guaranteed that no segments coincide.OutputOutput one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).You can output each letter in any case (upper or lower).ExamplesInput 12 6 1 3 3 7 5 7 7 11 9 11 11 3 Output Yes Input 9 6 4 5 5 6 7 8 8 9 1 2 2 3 Output Yes Input 10 3 1 2 3 2 7 2 Output No Input 10 2 1 6 2 7 Output Yes NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
12 6 1 3 3 7 5 7 7 11 9 11 11 3
Yes
3 seconds
256 megabytes
['brute force', 'strings', '*1900']
A. Hide and Seektime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers x_1, x_2, \ldots, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given n and Bob's questions x_1, \ldots, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i \neq a_j or b_i \neq b_j.InputThe first line contains two integers n and k (1 \leq n,k \leq 10^5) — the number of cells and the number of questions Bob asked.The second line contains k integers x_1, x_2, \ldots, x_k (1 \leq x_i \leq n) — Bob's questions.OutputPrint a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.ExamplesInput 5 3 5 1 4 Output 9 Input 4 8 1 2 3 4 4 3 2 1 Output 0 Input 100000 1 42 Output 299997 NoteThe notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question. (4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all (i,j) where |i-j| \leq 1 except for (42, 42) are valid scenarios.
5 3 5 1 4
9
1 second
256 megabytes
['graphs', '*1500']
H. Satanic Panictime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of n points in a 2D plane. No three points are collinear.A pentagram is a set of 5 points A,B,C,D,E that can be arranged as follows. Note the length of the line segments don't matter, only that those particular intersections exist.Count the number of ways to choose 5 points from the given set that form a pentagram.InputThe first line contains an integer n (5 \leq n \leq 300) — the number of points.Each of the next n lines contains two integers x_i, y_i (-10^6 \leq x_i,y_i \leq 10^6) — the coordinates of the i-th point. It is guaranteed that no three points are collinear.OutputPrint a single integer, the number of sets of 5 points that form a pentagram.ExamplesInput 5 0 0 0 2 2 0 2 2 1 3 Output 1 Input 5 0 0 4 0 0 4 4 4 2 3 Output 0 Input 10 841746 527518 595261 331297 -946901 129987 670374 -140388 -684770 309555 -302589 415564 -387435 613331 -624940 -95922 945847 -199224 24636 -565799 Output 85 NoteA picture of the first sample: A picture of the second sample: A picture of the third sample:
5 0 0 0 2 2 0 2 2 1 3
1
4 seconds
256 megabytes
['dp', 'geometry', '*2900']
G. Zoning Restrictionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are planning to build housing on a street. There are n spots available on the street on which you can build a house. The spots are labeled from 1 to n from left to right. In each spot, you can build a house with an integer height between 0 and h.In each spot, if a house has height a, you can gain a^2 dollars from it.The city has m zoning restrictions though. The i-th restriction says that if the tallest house from spots l_i to r_i is strictly more than x_i, you must pay a fine of c_i.You would like to build houses to maximize your profit (sum of dollars gained minus fines). Determine the maximum profit possible.InputThe first line contains three integers n,h,m (1 \leq n,h,m \leq 50) — the number of spots, the maximum height, and the number of restrictions, respectively.Each of the next m lines contains four integers l_i, r_i, x_i, c_i (1 \leq l_i \leq r_i \leq n, 0 \leq x_i \leq h, 1 \leq c_i \leq 5\,000).OutputPrint a single integer denoting the maximum profit you can make.ExamplesInput 3 3 3 1 1 1 1000 2 2 3 1000 3 3 2 1000 Output 14 Input 4 10 2 2 3 8 76 3 4 7 39 Output 289 NoteIn the first example, it's optimal to build houses with heights [1, 3, 2]. We get a gain of 1^2+3^2+2^2 = 14. We don't violate any restrictions, so there are no fees, so the total profit is 14 - 0 = 14.In the second example, it's optimal to build houses with heights [10, 8, 8, 10]. We get a gain of 10^2+8^2+8^2+10^2 = 328, and we violate the second restriction for a fee of 39, thus the total profit is 328-39 = 289. Note that even though there isn't a restriction on building 1, we must still limit its height to be at most 10.
3 3 3 1 1 1 1000 2 2 3 1000 3 3 2 1000
14
1 second
256 megabytes
['dp', 'flows', 'graphs', '*2700']
F. Leaf Partitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with n nodes, labeled from 1 to n. The tree is rooted at node 1. The parent of the i-th node is p_i. A leaf is node with no children. For a given set of leaves L, let f(L) denote the smallest connected subgraph that contains all leaves L.You would like to partition the leaves such that for any two different sets x, y of the partition, f(x) and f(y) are disjoint. Count the number of ways to partition the leaves, modulo 998244353. Two ways are different if there are two leaves such that they are in the same set in one way but in different sets in the other.InputThe first line contains an integer n (2 \leq n \leq 200\,000) — the number of nodes in the tree.The next line contains n-1 integers p_2, p_3, \ldots, p_n (1 \leq p_i < i). OutputPrint a single integer, the number of ways to partition the leaves, modulo 998244353.ExamplesInput 5 1 1 1 1 Output 12 Input 10 1 2 3 4 5 6 7 8 9 Output 1 NoteIn the first example, the leaf nodes are 2,3,4,5. The ways to partition the leaves are in the following image In the second example, the only leaf is node 10 so there is only one partition. Note that node 1 is not a leaf.
5 1 1 1 1
12
1 second
256 megabytes
['dp', 'trees', '*2500']
E. Hot is Coldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a_1, a_2, \ldots, a_n.You will perform q operations. In the i-th operation, you have a symbol s_i which is either "<" or ">" and a number x_i.You make a new array b such that b_j = -a_j if a_j s_i x_i and b_j = a_j otherwise (i.e. if s_i is '>', then all a_j > x_i will be flipped). After doing all these replacements, a is set to be b.You want to know what your final array looks like after all operations.InputThe first line contains two integers n,q (1 \leq n,q \leq 10^5) — the number of integers and the number of queries.The next line contains n integers a_1, a_2, \ldots, a_n (-10^5 \leq a_i \leq 10^5) — the numbers.Each of the next q lines contains a character and an integer s_i, x_i. (s_i \in \{<, >\}, -10^5 \leq x_i \leq 10^5) – the queries.OutputPrint n integers c_1, c_2, \ldots, c_n representing the array after all operations.ExamplesInput 11 3 -5 -4 -3 -2 -1 0 1 2 3 4 5 > 2 > -4 < 5 Output 5 4 -3 -2 -1 0 1 2 -3 4 5 Input 5 5 0 1 -2 -1 2 < -2 < -1 < 0 < 1 < 2 Output 0 -1 2 -1 2 NoteIn the first example, the array goes through the following changes: Initial: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] > 2: [-5, -4, -3, -2, -1, 0, 1, 2, -3, -4, -5] > -4: [-5, -4, 3, 2, 1, 0, -1, -2, 3, -4, -5] < 5: [5, 4, -3, -2, -1, 0, 1, 2, -3, 4, 5]
11 3 -5 -4 -3 -2 -1 0 1 2 3 4 5 > 2 > -4 < 5
5 4 -3 -2 -1 0 1 2 -3 4 5
1 second
256 megabytes
['bitmasks', 'data structures', 'divide and conquer', 'implementation', '*2400']
D. Frog Jumpingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA frog is initially at position 0 on the number line. The frog has two positive integers a and b. From a position k, it can either jump to position k+a or k-b.Let f(x) be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval [0, x]. The frog doesn't need to visit all these integers in one trip, that is, an integer is counted if the frog can somehow reach it if it starts from 0.Given an integer m, find \sum_{i=0}^{m} f(i). That is, find the sum of all f(i) for i from 0 to m.InputThe first line contains three integers m, a, b (1 \leq m \leq 10^9, 1 \leq a,b \leq 10^5).OutputPrint a single integer, the desired sum.ExamplesInput 7 5 3 Output 19 Input 1000000000 1 2019 Output 500000001500000001 Input 100 100000 1 Output 101 Input 6 4 5 Output 10 NoteIn the first example, we must find f(0)+f(1)+\ldots+f(7). We have f(0) = 1, f(1) = 1, f(2) = 1, f(3) = 1, f(4) = 1, f(5) = 3, f(6) = 3, f(7) = 8. The sum of these values is 19.In the second example, we have f(i) = i+1, so we want to find \sum_{i=0}^{10^9} i+1.In the third example, the frog can't make any jumps in any case.
7 5 3
19
2 seconds
256 megabytes
['dfs and similar', 'math', 'number theory', '*2100']
C. Tree Diametertime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes.Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x \in p and y \in q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes.InteractionEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1\,000). Description of the test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 100) — the number of nodes in the tree.To ask a question, print "k_1\ k_2\ a_1\ a_2\ \ldots\ a_{k_1}\ b_1\ b_2\ \ldots\ b_{k_2}" (k_1, k_2 \geq 1 and k_1+k_2 \leq n). These two sets must be nonempty and disjoint. The judge will respond with a single integer \max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts.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.When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes.You can only ask at most 9 questions per test case.Hack FormatTo hack, use the following format. Note that you can only hack with one test case.The first line should contain a single integer t (t=1).The second line should contain a single integer n (2 \leq n \leq 100).Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1\leq a_i, b_i\leq n, 1 \leq c_i \leq 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree.ExampleInput 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99NoteIn the first example, the first tree looks as follows: In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5).The second tree is a tree with two nodes with an edge with weight 99 between them.
2 5 9 6 10 9 10 2 99
1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99
4 seconds
256 megabytes
['bitmasks', 'graphs', 'interactive', '*1700']
B. Hate "A"time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example).You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique.InputThe first line of input contains a string t (1 \leq |t| \leq 10^5) consisting of lowercase English letters.OutputPrint a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).ExamplesInput aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( NoteIn the first example, we have s = "aaaaa", and s' = "".In the second example, no such s can work that will generate the given t.In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
aaaaa
aaaaa
1 second
256 megabytes
['implementation', 'strings', '*1100']
A. Love "A"time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not.Alice can erase some characters from her string s. She would like to know what is the longest string remaining after erasing some characters (possibly zero) to get a good string. It is guaranteed that the string has at least one "a" in it, so the answer always exists.InputThe first line contains a string s (1 \leq |s| \leq 50) consisting of lowercase English letters. It is guaranteed that there is at least one "a" in s.OutputPrint a single integer, the length of the longest good string that Alice can get after erasing some characters from s.ExamplesInput xaxxxxa Output 3 Input aaabaa Output 6 NoteIn the first example, it's enough to erase any four of the "x"s. The answer is 3 since that is the maximum number of characters that can remain.In the second example, we don't need to erase any characters.
xaxxxxa
3
1 second
256 megabytes
['implementation', 'strings', '*800']
D. Pigeon d'Ortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFrom "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons? The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as rocing for our entertainment and, historically, deliverirg wartime post. Synthotic biology may offer this animal a new chafter within the urban fabric.Piteon d'Or recognihes how these birds ripresent a potentially userul interface for urdan biotechnologies. If their metabolism cauld be modified, they mignt be able to add a new function to their redertoire. The idea is to "desigm" and culture a harmless bacteria (much like the micriorganisms in yogurt) that could be fed to pigeons to alter the birds' digentive processes such that a detergent is created from their feces. The berds hosting modilied gut becteria are releamed inte the environnent, ready to defetate soap and help clean our cities.InputThe first line of input data contains a single integer n (5 \le n \le 10).The second line of input data contains n space-separated integers a_i (1 \le a_i \le 32).OutputOutput a single integer.ExampleInput 5 1 2 3 4 5 Output 4 NoteWe did not proofread this statement at all.
5 1 2 3 4 5
4
1 second
256 megabytes
['implementation']
C. Mystery Circuittime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output InputThe input contains a single integer a (0 \le a \le 15).OutputOutput a single integer.ExampleInput 3 Output 13
3
13
1 second
256 megabytes
['bitmasks', 'brute force']
B. Kanban Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input contains a single integer a (1 \le a \le 99).OutputOutput "YES" or "NO".ExamplesInput 5 Output YES Input 13 Output NO Input 24 Output NO Input 46 Output YES
5
YES
1 second
256 megabytes
['brute force']
A. Thanos Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort?*Infinity Gauntlet required.InputThe first line of input contains a single number n (1 \le n \le 16) — the size of the array. n is guaranteed to be a power of 2.The second line of input contains n space-separated integers a_i (1 \le a_i \le 100) — the elements of the array.OutputReturn the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order.ExamplesInput 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 NoteIn the first example the array is already sorted, so no finger snaps are required.In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array.In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.
4 1 2 2 4
4
1 second
256 megabytes
['implementation']
G. Two Merged Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo integer sequences existed initially, one of them was strictly increasing, and another one — strictly decreasing.Strictly increasing sequence is a sequence of integers [x_1 < x_2 < \dots < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > \dots > y_l]. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.Elements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) without changing the order. For example, sequences [1, 3, 4] and [10, 4, 2] can produce the following resulting sequences: [10, \textbf{1}, \textbf{3}, 4, 2, \textbf{4}], [\textbf{1}, \textbf{3}, \textbf{4}, 10, 4, 2]. The following sequence cannot be the result of these insertions: [\textbf{1}, 10, \textbf{4}, 4, \textbf{3}, 2] because the order of elements in the increasing sequence was changed.Let the obtained sequence be a. This sequence a is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing, and another one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence a into one increasing sequence and one decreasing sequence, print "NO".InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2 \cdot 10^5), where a_i is the i-th element of a.OutputIf there is a contradiction in the input and it is impossible to split the given sequence a into one increasing sequence and one decreasing sequence, print "NO" in the first line.Otherwise print "YES" in the first line. In the second line, print a sequence of n integers res_1, res_2, \dots, res_n, where res_i should be either 0 or 1 for each i from 1 to n. The i-th element of this sequence should be 0 if the i-th element of a belongs to the increasing sequence, and 1 otherwise. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.ExamplesInput 9 5 1 3 6 8 2 9 0 10 Output YES 1 0 0 0 0 1 0 1 0 Input 5 1 2 4 0 2 Output NO
9 5 1 3 6 8 2 9 0 10
YES 1 0 0 0 0 1 0 1 0
2 seconds
256 megabytes
['dp', 'greedy', '*2400']
F. Graph Without Long Directed Pathstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph.You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).InputThe first line contains two integer numbers n and m (2 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5) — the number of vertices and edges, respectively.The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 \le u_i, v_i \le n, u_i \ne v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph).OutputIf it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line.Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input.ExampleInput 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 NoteThe picture corresponding to the first example: And one of possible answers:
6 5 1 5 2 1 1 4 3 1 6 1
YES 10100
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1700']
E. Median Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t.Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For example, for k=2, s="az" and t="bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than s and not greater than t.InputThe first line of the input contains one integer k (1 \le k \le 2 \cdot 10^5) — the length of strings.The second line of the input contains one string s consisting of exactly k lowercase Latin letters.The third line of the input contains one string t consisting of exactly k lowercase Latin letters.It is guaranteed that s is lexicographically less than t.It is guaranteed that there is an odd number of strings lexicographically not less than s and not greater than t.OutputPrint one string consisting exactly of k lowercase Latin letters — the median (the middle element) of list of strings of length k lexicographically not less than s and not greater than t.ExamplesInput 2 az bf Output bc Input 5 afogk asdji Output alvuw Input 6 nijfvj tvqhwp Output qoztvz
2 az bf
bc
2 seconds
256 megabytes
['bitmasks', 'math', 'number theory', 'strings', '*1900']
D. Equalize Them Alltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i - |a_i - a_j|. The value |x| means the absolute value of x. For example, |4| = 4, |-3| = 3.Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.It is guaranteed that you always can obtain the array of equal elements using such operations.Note that after each operation each element of the current array should not exceed 10^{18} by absolute value.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2 \cdot 10^5), where a_i is the i-th element of a.OutputIn the first line print one integer k — the minimum number of operations required to obtain the array of equal elements.In the next k lines print operations itself. The p-th operation should be printed as a triple of integers (t_p, i_p, j_p), where t_p is either 1 or 2 (1 means that you perform the operation of the first type, and 2 means that you perform the operation of the second type), and i_p and j_p are indices of adjacent elements of the array such that 1 \le i_p, j_p \le n, |i_p - j_p| = 1. See the examples for better understanding.Note that after each operation each element of the current array should not exceed 10^{18} by absolute value.If there are many possible answers, you can print any.ExamplesInput 5 2 4 6 6 6 Output 2 1 2 3 1 1 2 Input 3 2 8 10 Output 2 2 2 1 2 3 2 Input 4 1 1 1 1 Output 0
5 2 4 6 6 6
2 1 2 3 1 1 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1400']
C. Two Shuffled Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.Strictly increasing sequence is a sequence of integers [x_1 < x_2 < \dots < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > \dots > y_l]. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.They were merged into one sequence a. After that sequence a got shuffled. For example, some of the possible resulting sequences a for an increasing sequence [1, 3, 4] and a decreasing sequence [10, 4, 2] are sequences [1, 2, 3, 4, 4, 10] or [4, 2, 1, 10, 4, 3].This shuffled sequence a is given in the input.Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence a to increasing and decreasing sequences, print "NO".InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2 \cdot 10^5), where a_i is the i-th element of a.OutputIf there is a contradiction in the input and it is impossible to split the given sequence a to increasing and decreasing sequences, print "NO" in the first line.Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.In the second line print n_i — the number of elements in the strictly increasing sequence. n_i can be zero, in this case the increasing sequence is empty.In the third line print n_i integers inc_1, inc_2, \dots, inc_{n_i} in the increasing order of its values (inc_1 < inc_2 < \dots < inc_{n_i}) — the strictly increasing sequence itself. You can keep this line empty if n_i = 0 (or just print the empty line).In the fourth line print n_d — the number of elements in the strictly decreasing sequence. n_d can be zero, in this case the decreasing sequence is empty.In the fifth line print n_d integers dec_1, dec_2, \dots, dec_{n_d} in the decreasing order of its values (dec_1 > dec_2 > \dots > dec_{n_d}) — the strictly decreasing sequence itself. You can keep this line empty if n_d = 0 (or just print the empty line).n_i + n_d should be equal to n and the union of printed sequences should be a permutation of the given sequence (in case of "YES" answer).ExamplesInput 7 7 2 7 3 3 1 4 Output YES 2 3 7 5 7 4 3 2 1 Input 5 4 3 1 5 3 Output YES 1 3 4 5 4 3 1 Input 5 1 1 2 1 2 Output NO Input 5 0 1 2 3 4 Output YES 0 5 4 3 2 1 0
7 7 2 7 3 3 1 4
YES 2 3 7 5 7 4 3 2 1
2 seconds
256 megabytes
['constructive algorithms', 'sortings', '*1000']
B. Parity Alternated Deletionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has an array a consisting of n integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally: If it is the first move, he chooses any element and deletes it; If it is the second or any next move: if the last deleted element was odd, Polycarp chooses any even element and deletes it; if the last deleted element was even, Polycarp chooses any odd element and deletes it. If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.InputThe first line of the input contains one integer n (1 \le n \le 2000) — the number of elements of a.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^6), where a_i is the i-th element of a.OutputPrint one integer — the minimum possible sum of non-deleted elements of the array after end of the game.ExamplesInput 5 1 5 7 8 2 Output 0 Input 6 5 1 2 4 6 3 Output 0 Input 2 1000000 1000000 Output 1000000
5 1 5 7 8 2
0
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*900']
A. Diverse Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are not adjacent.Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).You are given a sequence of strings. For each string, if it is diverse, print "Yes". Otherwise, print "No".InputThe first line contains integer n (1 \le n \le 100), denoting the number of strings to process. The following n lines contains strings, one string per line. Each string contains only lowercase Latin letters, its length is between 1 and 100, inclusive.OutputPrint n lines, one line per a string in the input. The line should contain "Yes" if the corresponding string is diverse and "No" if the corresponding string is not diverse. You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.ExampleInput 8 fced xyz r dabcef az aa bad babc Output Yes Yes Yes Yes No No No No
8 fced xyz r dabcef az aa bad babc
Yes Yes Yes Yes No No No No
1 second
256 megabytes
['implementation', 'strings', '*800']
C. Queentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of vertices in the tree.The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 \le p_i \le n, 0 \le c_i \le 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices.OutputIn case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1.ExamplesInput 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 NoteThe deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; the vertex 2 will be connected with the vertex 3 after deletion; then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; the vertex 4 will be connected with the vertex 3; then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth); you will just delete the vertex 4; there are no more vertices to delete. In the second example you don't need to delete any vertex: vertices 2 and 3 have children that respect them; vertices 4 and 5 respect ancestors. In the third example the tree will change this way:
5 3 1 1 1 -1 0 2 1 3 0
1 2 4
1 second
256 megabytes
['dfs and similar', 'trees', '*1400']
B. Nirvanatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.Help Kurt find the maximum possible product of digits among all integers from 1 to n.InputThe only input line contains the integer n (1 \le n \le 2\cdot10^9).OutputPrint the maximum product of digits among all integers from 1 to n.ExamplesInput 390 Output 216 Input 7 Output 7 Input 1000000000 Output 387420489 NoteIn the first example the maximum product is achieved for 389 (the product of digits is 3\cdot8\cdot9=216).In the second example the maximum product is achieved for 7 (the product of digits is 7).In the third example the maximum product is achieved for 999999999 (the product of digits is 9^9=387420489).
390
216
1 second
256 megabytes
['brute force', 'math', 'number theory', '*1200']
A. The Doorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThree years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index k such that Mr. Black can exit the house after opening the first k doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.InputThe first line contains integer n (2 \le n \le 200\,000) — the number of doors.The next line contains n integers: the sequence in which Mr. Black opened the doors. The i-th of these integers is equal to 0 in case the i-th opened door is located in the left exit, and it is equal to 1 in case it is in the right exit.It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.OutputPrint the smallest integer k such that after Mr. Black opened the first k doors, he was able to exit the house.ExamplesInput 5 0 0 1 0 0 Output 3 Input 4 1 0 0 1 Output 3 NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.
5 0 0 1 0 0
3
1 second
256 megabytes
['implementation', '*800']
E. Pink Floydtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive task.Scientists are about to invent a new optimization for the Floyd-Warshall algorithm, which will allow it to work in linear time. There is only one part of the optimization still unfinished.It is well known that the Floyd-Warshall algorithm takes a graph with n nodes and exactly one edge between each pair of nodes. The scientists have this graph, what is more, they have directed each edge in one of the two possible directions.To optimize the algorithm, exactly m edges are colored in pink color and all the rest are colored in green. You know the direction of all m pink edges, but the direction of green edges is unknown to you. In one query you can ask the scientists about the direction of exactly one green edge, however, you can perform at most 2 \cdot n such queries.Your task is to find the node from which every other node can be reached by a path consisting of edges of same color. Be aware that the scientists may have lied that they had fixed the direction of all edges beforehand, so their answers may depend on your queries.InputThe first line contains two integers n and m (1 \le n \le 100\,000, 0 \le m \le 100\,000) — the number of nodes and the number of pink edges.The next m lines describe the pink edges, the i-th of these lines contains two integers u_i, v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — the start and the end of the i-th pink edge. It is guaranteed, that all unordered pairs (u_i, v_i) are distinct.OutputWhen you found the answer, print "!" and the number of the node from which every other node can be reached by a single-colored path.InteractionTo ask the direction of the green edge between nodes a and b, print "?", a and b in single line, separated by the space characters. In answer to this read a single integer, which will be 1 if the edge is directed from a to b and 0 if the edge is directed from b to a.You can ask at most 2 \cdot n queries, otherwise you will get Wrong Answer.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 -1 instead of 0 or 1 means that you made an invalid query or exceeded the query limit. Exit immediately after receiving -1 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.HacksHacks should be formatted as follows.The first line should contain two integers n and m (1 \le n \le 300, 0 \le m \le n \cdot (n - 1) / 2) — the number of nodes and number of pink edges.The next m lines should describe the pink edges, the i-th line should contain 2 integers a_i, b_i (1 \le a_i, b_i \le n, a_i \ne b_i), which means that there is a pink edge from a_i to b_i. All unordered pairs (a_i, b_i) should be distinct.The next (n \cdot (n - 1) / 2 - m) lines should describe the green edges, the i-th line should contain two integers a_i, b_i (1 \le a_i, b_i \le n, a_i \ne b_i)), which means that there is a green edge from a_i to b_i. All unordered pairs of (a_i, b_i) should be distinct and should also be different from the pairs for the pink edges.ExampleInput 4 2 1 2 3 4 0 1 1Output ? 1 3 ? 4 2 ? 3 2 ! 3NoteIn the example above the answer for the query "? 1 3" is 0, so the edge is directed from 3 to 1. The answer for the query "? 4 2" is 1, so the edge is directed from 4 to 2. The answer for the query "? 3 2" is 1, so the edge is directed from 3 to 2. So there are green paths from node 3 to nodes 1 and 2 and there is a pink path from node 3 to node 4.
4 2 1 2 3 4 0 1 1
? 1 3 ? 4 2 ? 3 2 ! 3
4 seconds
256 megabytes
['graphs', 'interactive', '*3200']
D. Foreignertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTraveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner.You define inadequate numbers as follows: all integers from 1 to 9 are inadequate; for an integer x \ge 10 to be inadequate, it is required that the integer \lfloor x / 10 \rfloor is inadequate, but that's not the only condition. Let's sort all the inadequate integers. Let \lfloor x / 10 \rfloor have number k in this order. Then, the integer x is inadequate only if the last digit of x is strictly less than the reminder of division of k by 11. Here \lfloor x / 10 \rfloor denotes x/10 rounded down.Thus, if x is the m-th in increasing order inadequate number, and m gives the remainder c when divided by 11, then integers 10 \cdot x + 0, 10 \cdot x + 1 \ldots, 10 \cdot x + (c - 1) are inadequate, while integers 10 \cdot x + c, 10 \cdot x + (c + 1), \ldots, 10 \cdot x + 9 are not inadequate.The first several inadequate integers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 30, 31, 32 \ldots. After that, since 4 is the fourth inadequate integer, 40, 41, 42, 43 are inadequate, while 44, 45, 46, \ldots, 49 are not inadequate; since 10 is the 10-th inadequate number, integers 100, 101, 102, \ldots, 109 are all inadequate. And since 20 is the 11-th inadequate number, none of 200, 201, 202, \ldots, 209 is inadequate.You wrote down all the prices you have seen in a trip. Unfortunately, all integers got concatenated in one large digit string s and you lost the bounds between the neighboring integers. You are now interested in the number of substrings of the resulting string that form an inadequate number. If a substring appears more than once at different positions, all its appearances are counted separately.InputThe only line contains the string s (1 \le |s| \le 10^5), consisting only of digits. It is guaranteed that the first digit of s is not zero.OutputIn the only line print the number of substrings of s that form an inadequate number.ExamplesInput 4021 Output 6 Input 110 Output 3 NoteIn the first example the inadequate numbers in the string are 1, 2, 4, 21, 40, 402. In the second example the inadequate numbers in the string are 1 and 10, and 1 appears twice (on the first and on the second positions).
4021
6
1 second
256 megabytes
['dp', '*2800']
C. U2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.Vasya drew several distinct points with integer coordinates on a plane and then drew an U-shaped parabola through each pair of the points that have different x coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.The internal area of an U-shaped parabola is the part of the plane that lies strictly above the parabola when the y axis is directed upwards.InputThe first line contains a single integer n (1 \le n \le 100\,000) — the number of points.The next n lines describe the points, the i-th of them contains two integers x_i and y_i — the coordinates of the i-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed 10^6 by absolute value.OutputIn the only line print a single integer — the number of U-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).ExamplesInput 3 -1 0 0 2 1 0 Output 2 Input 5 1 0 1 -1 0 -1 -1 0 -1 -1 Output 1 NoteOn the pictures below all U-shaped parabolas that pass through at least two given points are drawn for each of the examples. The U-shaped parabolas that do not have any given point inside their internal area are drawn in red. The first example. The second example.
3 -1 0 0 2 1 0
2
1 second
256 megabytes
['geometry', '*2400']
B. Lynyrd Skynyrdtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.A cyclic shift of a permutation (p_1, p_2, \ldots, p_n) is a permutation (p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, \ldots, a_{i_k} for some i_1, i_2, \ldots, i_k such that l \leq i_1 < i_2 < \ldots < i_k \leq r.InputThe first line contains three integers n, m, q (1 \le n, m, q \le 2 \cdot 10^5) — the length of the permutation p, the length of the array a and the number of queries.The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 \le l_i \le r_i \le m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.OutputPrint a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.ExamplesInput3 6 32 1 31 2 3 1 2 31 52 63 5Output110Input2 4 32 11 1 2 21 22 33 4Output010NoteIn the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Input3 6 32 1 31 2 3 1 2 31 52 63 5
Output110
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'math', 'trees', '*2000']
A. The Beatlestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n \cdot k cities. The cities are numerated from 1 to n \cdot k, the distance between the neighboring cities is exactly 1 km.Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on the circle, they are located in the 1-st, the (k + 1)-st, the (2k + 1)-st, and so on, the ((n-1)k + 1)-st cities, i.e. the distance between the neighboring cities with fast food restaurants is k km.Sergey began his journey at some city s and traveled along the circle, making stops at cities each l km (l > 0), until he stopped in s once again. Sergey then forgot numbers s and l, but he remembers that the distance from the city s to the nearest fast food restaurant was a km, and the distance from the city he stopped at after traveling the first l km from s to the nearest fast food restaurant was b km. Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions.Now Sergey is interested in two integers. The first integer x is the minimum number of stops (excluding the first) Sergey could have done before returning to s. The second integer y is the maximum number of stops (excluding the first) Sergey could have done before returning to s.InputThe first line contains two integers n and k (1 \le n, k \le 100\,000) — the number of fast food restaurants on the circle and the distance between the neighboring restaurants, respectively.The second line contains two integers a and b (0 \le a, b \le \frac{k}{2}) — the distances to the nearest fast food restaurants from the initial city and from the city Sergey made the first stop at, respectively.OutputPrint the two integers x and y.ExamplesInput 2 3 1 1 Output 1 6 Input 3 2 0 0 Output 1 3 Input 1 10 5 3 Output 5 5 NoteIn the first example the restaurants are located in the cities 1 and 4, the initial city s could be 2, 3, 5, or 6. The next city Sergey stopped at could also be at cities 2, 3, 5, 6. Let's loop through all possible combinations of these cities. If both s and the city of the first stop are at the city 2 (for example, l = 6), then Sergey is at s after the first stop already, so x = 1. In other pairs Sergey needs 1, 2, 3, or 6 stops to return to s, so y = 6.In the second example Sergey was at cities with fast food restaurant both initially and after the first stop, so l is 2, 4, or 6. Thus x = 1, y = 3.In the third example there is only one restaurant, so the possible locations of s and the first stop are: (6, 8) and (6, 4). For the first option l = 2, for the second l = 8. In both cases Sergey needs x=y=5 stops to go to s.
2 3 1 1
1 6
1 second
256 megabytes
['brute force', 'math', '*1700']
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of n cities and n-1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed k and the number of companies taking part in the privatization is minimal.Choose the number of companies r such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most k. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal r that there is such assignment to companies from 1 to r that the number of cities which are not good doesn't exceed k. The picture illustrates the first example (n=6, k=2). The answer contains r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 3) is not good. The number of such vertices (just one) doesn't exceed k=2. It is impossible to have at most k=2 not good cities in case of one company. InputThe first line contains two integers n and k (2 \le n \le 200000, 0 \le k \le n - 1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n-1 lines contain roads, one road per line. Each line contains a pair of integers x_i, y_i (1 \le x_i, y_i \le n), where x_i, y_i are cities connected with the i-th road.OutputIn the first line print the required r (1 \le r \le n - 1). In the second line print n-1 numbers c_1, c_2, \dots, c_{n-1} (1 \le c_i \le r), where c_i is the company to own the i-th road. If there are multiple answers, print any of them.ExamplesInput 6 2 1 4 4 3 3 5 3 6 5 2 Output 2 1 2 1 1 2 Input 4 2 3 1 1 4 1 2 Output 1 1 1 1 Input 10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 Output 3 1 1 2 3 2 3 1 3 1
6 2 1 4 4 3 3 5 3 6 5 2
2 1 2 1 1 2
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'trees', '*1900']
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions, which differ exclusively in the constraints on the number n.You are given an array of integers a[1], a[2], \dots, a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], \dots, a[r] (1 \le l \le r \le n). Thus, a block is defined by a pair of indices (l, r).Find a set of blocks (l_1, r_1), (l_2, r_2), \dots, (l_k, r_k) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i \neq j either r_i < l_j or r_j < l_i. For each block the sum of its elements is the same. Formally, a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]= \dots = a[l_k]+a[l_k+1]+\dots+a[r_k]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer n (1 \le n \le 1500) — the length of the given array. The second line contains the sequence of elements a[1], a[2], \dots, a[n] (-10^5 \le a_i \le 10^5).OutputIn the first line print the integer k (1 \le k \le n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 \le l_i \le r_i \le n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInput 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3
7 4 1 2 2 1 5 3
3 7 7 2 3 4 5
3 seconds
256 megabytes
['data structures', 'greedy', '*1900']
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions, which differ exclusively in the constraints on the number n.You are given an array of integers a[1], a[2], \dots, a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], \dots, a[r] (1 \le l \le r \le n). Thus, a block is defined by a pair of indices (l, r).Find a set of blocks (l_1, r_1), (l_2, r_2), \dots, (l_k, r_k) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (l_i, r_i) and (l_j, r_j) where i \neq j either r_i < l_j or r_j < l_i. For each block the sum of its elements is the same. Formally, a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]= \dots = a[l_k]+a[l_k+1]+\dots+a[r_k]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}') satisfying the above two requirements with k' > k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer n (1 \le n \le 50) — the length of the given array. The second line contains the sequence of elements a[1], a[2], \dots, a[n] (-10^5 \le a_i \le 10^5).OutputIn the first line print the integer k (1 \le k \le n). The following k lines should contain blocks, one per line. In each line print a pair of indices l_i, r_i (1 \le l_i \le r_i \le n) — the bounds of the i-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInput 7 4 1 2 2 1 5 3 Output 3 7 7 2 3 4 5 Input 11 -5 -4 -3 -2 -1 0 1 2 3 4 5 Output 2 3 4 1 1 Input 4 1 1 1 1 Output 4 4 4 1 1 2 2 3 3
7 4 1 2 2 1 5 3
3 7 7 2 3 4 5
2 seconds
256 megabytes
['greedy', '*1900']
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of n numbers: d_1, d_2, \dots, d_n (-10^6 \le d_i \le 10^6). The i-th element means that monster's hp (hit points) changes by the value d_i during the i-th minute of each round. Formally, if before the i-th minute of a round the monster's hp is h, then after the i-th minute it changes to h := h + d_i.The monster's initial hp is H. It means that before the battle the monster has H hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 0. Print -1 if the battle continues infinitely.InputThe first line contains two integers H and n (1 \le H \le 10^{12}, 1 \le n \le 2\cdot10^5). The second line contains the sequence of integers d_1, d_2, \dots, d_n (-10^6 \le d_i \le 10^6), where d_i is the value to change monster's hp in the i-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer k such that k is the first minute after which the monster is dead.ExamplesInput 1000 6 -100 -200 -300 125 77 -4 Output 9 Input 1000000000000 5 -1 0 0 0 0 Output 4999999999996 Input 10 4 -3 -6 5 4 Output -1
1000 6 -100 -200 -300 125 77 -4
9
2 seconds
256 megabytes
['math', '*1700']
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains n (1 \le n \le 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.OutputPrint k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following k lines should contain pairs a_j, b_j (1 \le a_j, b_j \le n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInput 10 codeforces dodivthree Output 5 7 8 4 9 2 2 9 10 3 1 Input 7 abaca?b zabbbcc Output 5 6 5 2 3 4 6 7 4 1 2 Input 9 bambarbia hellocode Output 0 Input 10 code?????? ??????test Output 10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
10 codeforces dodivthree
5 7 8 4 9 2 2 9 10 3 1
2 seconds
256 megabytes
['greedy', 'implementation', '*1500']
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p_1, p_2, \dots, p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].Polycarp invented a really cool permutation p_1, p_2, \dots, p_n of length n. It is very disappointing, but he forgot this permutation. He only remembers the array q_1, q_2, \dots, q_{n-1} of length n-1, where q_i=p_{i+1}-p_i.Given n and q=q_1, q_2, \dots, q_{n-1}, help Polycarp restore the invented permutation.InputThe first line contains the integer n (2 \le n \le 2\cdot10^5) — the length of the permutation to restore. The second line contains n-1 integers q_1, q_2, \dots, q_{n-1} (-n < q_i < n).OutputPrint the integer -1 if there is no such permutation of length n which corresponds to the given array q. Otherwise, if it exists, print p_1, p_2, \dots, p_n. Print any such permutation if there are many of them.ExamplesInput 3 -2 1 Output 3 1 2 Input 5 1 1 1 1 Output 1 2 3 4 5 Input 4 -1 2 2 Output -1
3 -2 1
3 1 2
2 seconds
256 megabytes
['math', '*1500']
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a_1, a_2, \dots, a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains n (1 \le n \le 2\cdot10^5) — number of hours per day.The second line contains n integer numbers a_1, a_2, \dots, a_n (0 \le a_i \le 1), where a_i=0 if the i-th hour in a day is working and a_i=1 if the i-th hour is resting. It is guaranteed that a_i=0 for at least one i.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInput 5 1 0 1 0 1 Output 2 Input 6 0 1 0 1 1 0 Output 2 Input 7 1 0 1 1 1 0 1 Output 3 Input 3 0 0 0 Output 0 NoteIn the first example, the maximal rest starts in last hour and goes to the first hour of the next day.In the second example, Polycarp has maximal rest from the 4-th to the 5-th hour.In the third example, Polycarp has maximal rest from the 3-rd to the 5-th hour.In the fourth example, Polycarp has no rest at all.
5 1 0 1 0 1
2
2 seconds
256 megabytes
['implementation', '*900']
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers n and m (1 \le n \le m \le 5\cdot10^8).OutputPrint the number of moves to transform n to m, or -1 if there is no solution.ExamplesInput 120 51840 Output 7 Input 42 42 Output 0 Input 48 72 Output -1 NoteIn the first example, the possible sequence of moves is: 120 \rightarrow 240 \rightarrow 720 \rightarrow 1440 \rightarrow 4320 \rightarrow 12960 \rightarrow 25920 \rightarrow 51840. The are 7 steps in total.In the second example, no moves are needed. Thus, the answer is 0.In the third example, it is impossible to transform 48 to 72.
120 51840
7
1 second
256 megabytes
['implementation', 'math', '*1000']
G. Double Treetime limit per test10 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a special undirected graph. It consists of 2n vertices numbered from 1 to 2n. The following properties hold for the graph: there are exactly 3n-2 edges in the graph: n edges connect vertices having odd numbers with vertices having even numbers, n - 1 edges connect vertices having odd numbers with each other, and n - 1 edges connect vertices having even numbers with each other; for each edge (u, v) between a pair of vertices with odd numbers, there exists an edge (u + 1, v + 1), and vice versa; for each odd number u \in [1, 2n - 1], there exists an edge (u, u + 1); the graph is connected; moreover, if we delete all vertices with even numbers from it, and all edges incident to them, the graph will become a tree (the same applies to deleting odd vertices).So, the graph can be represented as two trees having the same structure, and n edges connecting each vertex of the first tree to the corresponding vertex of the second tree.Edges of the graph are weighted. The length of some simple path in the graph is the sum of weights of traversed edges.You are given q queries to this graph; in each query, you are asked to compute the length of the shortest path between some pair of vertices in this graph. Can you answer all of the queries?InputThe first line of the input contains one integer n (2 \le n \le 3 \cdot 10^5).The second line contains n integers w_{1, 2}, w_{3,4}, ..., w_{2n - 1, 2n} (1 \le w_{i, i + 1} \le 10^{12}). These integers describe the weights of the edges connecting odd vertices with even ones.Then n-1 lines follow. i-th line contains four integers x_i, y_i, w_{i, 1} and w_{i, 2} (1 \le x_i, y_i \le n, x_i \ne y_i, 1 \le w_{i, j} \le 10^{12}); it describes two edges: one connecting 2x_i - 1 with 2y_i - 1 and having weight w_{i, 1}; another connecting 2x_i with 2y_i and having weight w_{i, 2}.The next line contains one integer q (1 \le q \le 6 \cdot 10^5) — the number of queries.Then q lines follow, i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le 2n, u_i \ne v_i), describing a query "compute the length of the shortest path between vertices u_i and v_i".OutputPrint q integers, i-th integer should be equal to the answer to the i-th query.ExampleInput 5 3 6 15 4 8 1 2 5 4 2 3 5 7 1 4 1 5 1 5 2 1 3 1 2 5 6 1 10 Output 3 15 4 NoteThe graph in the first test looks like that:
5 3 6 15 4 8 1 2 5 4 2 3 5 7 1 4 1 5 1 5 2 1 3 1 2 5 6 1 10
3 15 4
10 seconds
1024 megabytes
['data structures', 'divide and conquer', 'shortest paths', 'trees', '*2700']
F. Extending Set of Pointstime limit per test3.5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFor a given set of two-dimensional points S, let's denote its extension E(S) as the result of the following algorithm:Create another set of two-dimensional points R, which is initially equal to S. Then, while there exist four numbers x_1, y_1, x_2 and y_2 such that (x_1, y_1) \in R, (x_1, y_2) \in R, (x_2, y_1) \in R and (x_2, y_2) \notin R, add (x_2, y_2) to R. When it is impossible to find such four integers, let R be the result of the algorithm.Now for the problem itself. You are given a set of two-dimensional points S, which is initially empty. You have to process two types of queries: add some point to S, or remove some point from it. After each query you have to compute the size of E(S).InputThe first line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.Then q lines follow, each containing two integers x_i, y_i (1 \le x_i, y_i \le 3 \cdot 10^5), denoting i-th query as follows: if (x_i, y_i) \in S, erase it from S, otherwise insert (x_i, y_i) into S.OutputPrint q integers. i-th integer should be equal to the size of E(S) after processing first i queries.ExampleInput 7 1 1 1 2 2 1 2 2 1 2 1 3 2 1 Output 1 2 4 4 4 6 3
7 1 1 1 2 2 1 2 2 1 2 1 3 2 1
1 2 4 4 4 6 3
3.5 seconds
1024 megabytes
['data structures', 'divide and conquer', 'dsu', '*2600']
E. Palindrome-less Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote that some array b is bad if it contains a subarray b_l, b_{l+1}, \dots, b_{r} of odd length more than 1 (l < r and r - l + 1 is odd) such that \forall i \in \{0, 1, \dots, r - l\} b_{l + i} = b_{r - i}.If an array is not bad, it is good.Now you are given an array a_1, a_2, \dots, a_n. Some elements are replaced by -1. Calculate the number of good arrays you can obtain by replacing each -1 with some integer from 1 to k.Since the answer can be large, print it modulo 998244353.InputThe first line contains two integers n and k (2 \le n, k \le 2 \cdot 10^5) — the length of array a and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace -1.The second line contains n integers a_1, a_2, \dots, a_n (a_i = -1 or 1 \le a_i \le k) — the array a.OutputPrint one integer — the number of good arrays you can get, modulo 998244353.ExamplesInput 2 3 -1 -1 Output 9 Input 5 2 1 -1 -1 1 2 Output 0 Input 5 3 1 -1 -1 1 2 Output 2 Input 4 200000 -1 -1 12345 -1 Output 735945883
2 3 -1 -1
9
2 seconds
256 megabytes
['combinatorics', 'divide and conquer', 'dp', '*2200']
D. Minimum Triangulationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.Calculate the minimum weight among all triangulations of the polygon.InputThe first line contains single integer n (3 \le n \le 500) — the number of vertices in the regular polygon.OutputPrint one integer — the minimum weight among all triangulations of the given polygon.ExamplesInput 3 Output 6 Input 4 Output 18 NoteAccording to Wiki: polygon triangulation is the decomposition of a polygonal area (simple polygon) P into a set of triangles, i. e., finding a set of triangles with pairwise non-intersecting interiors whose union is P.In the first example the polygon is a triangle, so we don't need to cut it further, so the answer is 1 \cdot 2 \cdot 3 = 6.In the second example the polygon is a rectangle, so it should be divided into two triangles. It's optimal to cut it using diagonal 1-3 so answer is 1 \cdot 2 \cdot 3 + 1 \cdot 3 \cdot 4 = 6 + 12 = 18.
3
6
2 seconds
256 megabytes
['dp', 'greedy', 'math', '*1200']
C. Playlisttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) \cdot 6 = 96.You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.InputThe first line contains two integers n and k (1 \le k \le n \le 3 \cdot 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.Each of the next n lines contains two integers t_i and b_i (1 \le t_i, b_i \le 10^6) — the length and beauty of i-th song.OutputPrint one integer — the maximum pleasure you can get.ExamplesInput 4 3 4 7 15 1 3 6 6 8 Output 78 Input 5 3 12 31 112 4 100 100 13 55 55 50 Output 10000 NoteIn the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) \cdot 6 = 78.In the second test case we can choose song 3. The total pleasure will be equal to 100 \cdot 100 = 10000.
4 3 4 7 15 1 3 6 6 8
78
2 seconds
256 megabytes
['brute force', 'data structures', 'sortings', '*1600']
B. Good Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to n - 1, but not the whole string). You need to calculate the minimum number of characters to be deleted from string s so that it becomes good.InputThe first line contains one integer t (1 \le t \le 100) – the number of test cases. Each test case is represented by two lines.The first line of i-th test case contains one integer n (1 \le n \le 100) – the length of string s.The second line of i-th test case contains string s, consisting of only characters > and <.OutputFor each test case print one line.For i-th test case print the minimum number of characters to be deleted from string s so that it becomes good.ExampleInput 3 2 <> 3 ><< 1 > Output 1 0 0 NoteIn the first test case we can delete any character in string <>.In the second test case we don't need to delete any characters. The string > < < is good, because we can perform the following sequence of operations: > < < \rightarrow < < \rightarrow <.
3 2 <> 3 ><< 1 >
1 0 0
1 second
256 megabytes
['implementation', 'strings', '*1200']
A. Detective Booktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i \ge i).Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page i such that Ivan already has read it, but hasn't read page a_i). After that, he closes the book and continues to read it on the following day from the next page.How many days will it take to read the whole book?InputThe first line contains single integer n (1 \le n \le 10^4) — the number of pages in the book.The second line contains n integers a_1, a_2, \dots, a_n (i \le a_i \le n), where a_i is the number of page which contains the explanation of the mystery on page i.OutputPrint one integer — the number of days it will take to read the whole book.ExampleInput 9 1 3 3 6 7 6 8 8 9 Output 4 NoteExplanation of the example test:During the first day Ivan will read only the first page. During the second day Ivan will read pages number 2 and 3. During the third day — pages 4-8. During the fourth (and the last) day Ivan will read remaining page number 9.
9 1 3 3 6 7 6 8 8 9
4
2 seconds
256 megabytes
['implementation', '*1000']
F. Dish Shoppingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are m people living in a city. There are n dishes sold in the city. Each dish i has a price p_i, a standard s_i and a beauty b_i. Each person j has an income of inc_j and a preferred beauty pref_j. A person would never buy a dish whose standard is less than the person's income. Also, a person can't afford a dish with a price greater than the income of the person. In other words, a person j can buy a dish i only if p_i \leq inc_j \leq s_i.Also, a person j can buy a dish i, only if |b_i-pref_j| \leq (inc_j-p_i). In other words, if the price of the dish is less than the person's income by k, the person will only allow the absolute difference of at most k between the beauty of the dish and his/her preferred beauty. Print the number of dishes that can be bought by each person in the city.InputThe first line contains two integers n and m (1 \leq n \leq 10^5, 1 \leq m \leq 10^5), the number of dishes available in the city and the number of people living in the city.The second line contains n integers p_i (1 \leq p_i \leq 10^9), the price of each dish.The third line contains n integers s_i (1 \leq s_i \leq 10^9), the standard of each dish.The fourth line contains n integers b_i (1 \leq b_i \leq 10^9), the beauty of each dish.The fifth line contains m integers inc_j (1 \leq inc_j \leq 10^9), the income of every person.The sixth line contains m integers pref_j (1 \leq pref_j \leq 10^9), the preferred beauty of every person.It is guaranteed that for all integers i from 1 to n, the following condition holds: p_i \leq s_i.OutputPrint m integers, the number of dishes that can be bought by every person living in the city.ExamplesInput 3 3 2 1 3 2 4 4 2 1 1 2 2 3 1 2 4 Output 1 2 0 Input 4 3 1 2 1 1 3 3 1 3 2 1 3 2 1 1 3 1 2 1 Output 0 2 3 NoteIn the first example, the first person can buy dish 2, the second person can buy dishes 1 and 2 and the third person can buy no dishes.In the second example, the first person can buy no dishes, the second person can buy dishes 1 and 4, and the third person can buy dishes 1, 2 and 4.
3 3 2 1 3 2 4 4 2 1 1 2 2 3 1 2 4
1 2 0
2 seconds
256 megabytes
['data structures', 'divide and conquer', '*2500']
E. Maximize Mextime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students and m clubs in a college. The clubs are numbered from 1 to m. Each student has a potential p_i and is a member of the club with index c_i. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next d days. There is a coding competition every day in the technical fest. Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming d days. Thus, every day the director chooses such team, that the team strength is maximized.The mex of the multiset S is the smallest non-negative integer that is not present in S. For example, the mex of the \{0, 1, 1, 2, 4, 5, 9\} is 3, the mex of \{1, 2, 3\} is 0 and the mex of \varnothing (empty set) is 0.InputThe first line contains two integers n and m (1 \leq m \leq n \leq 5000), the number of students and the number of clubs in college.The second line contains n integers p_1, p_2, \ldots, p_n (0 \leq p_i < 5000), where p_i is the potential of the i-th student.The third line contains n integers c_1, c_2, \ldots, c_n (1 \leq c_i \leq m), which means that i-th student is initially a member of the club with index c_i.The fourth line contains an integer d (1 \leq d \leq n), number of days for which the director wants to know the maximum possible strength of the team. Each of the next d lines contains an integer k_i (1 \leq k_i \leq n), which means that k_i-th student lefts their club on the i-th day. It is guaranteed, that the k_i-th student has not left their club earlier.OutputFor each of the d days, print the maximum possible strength of the team on that day.ExamplesInput 5 3 0 1 2 2 0 1 2 2 3 2 5 3 2 4 5 1 Output 3 1 1 1 0 Input 5 3 0 1 2 2 1 1 3 2 3 2 5 4 2 3 5 1 Output 3 2 2 1 0 Input 5 5 0 1 2 4 5 1 2 3 4 5 4 2 3 5 4 Output 1 1 1 1 NoteConsider the first example:On the first day, student 3 leaves their club. Now, the remaining students are 1, 2, 4 and 5. We can select students 1, 2 and 4 to get maximum possible strength, which is 3. Note, that we can't select students 1, 2 and 5, as students 2 and 5 belong to the same club. Also, we can't select students 1, 3 and 4, since student 3 has left their club.On the second day, student 2 leaves their club. Now, the remaining students are 1, 4 and 5. We can select students 1, 4 and 5 to get maximum possible strength, which is 1.On the third day, the remaining students are 1 and 5. We can select students 1 and 5 to get maximum possible strength, which is 1.On the fourth day, the remaining student is 1. We can select student 1 to get maximum possible strength, which is 1. On the fifth day, no club has students and so the maximum possible strength is 0.
5 3 0 1 2 2 0 1 2 2 3 2 5 3 2 4 5 1
3 1 1 1 0
2 seconds
256 megabytes
['flows', 'graph matchings', 'graphs', '*2400']
D. Steps to Onetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVivek initially has an empty array a and some integer constant m.He performs the following algorithm: Select a random integer x uniformly in range from 1 to m and append it to the end of a. Compute the greatest common divisor of integers in a. In case it equals to 1, break Otherwise, return to step 1. Find the expected length of a. It can be shown that it can be represented as \frac{P}{Q} where P and Q are coprime integers and Q\neq 0 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} \pmod{10^9+7}.InputThe first and only line contains a single integer m (1 \leq m \leq 100000).OutputPrint a single integer — the expected length of the array a written as P \cdot Q^{-1} \pmod{10^9+7}.ExamplesInput 1 Output 1 Input 2 Output 2 Input 4 Output 333333338 NoteIn the first example, since Vivek can choose only integers from 1 to 1, he will have a=[1] after the first append operation, and after that quit the algorithm. Hence the length of a is always 1, so its expected value is 1 as well.In the second example, Vivek each time will append either 1 or 2, so after finishing the algorithm he will end up having some number of 2's (possibly zero), and a single 1 in the end. The expected length of the list is 1\cdot \frac{1}{2} + 2\cdot \frac{1}{2^2} + 3\cdot \frac{1}{2^3} + \ldots = 2.
1
1
2 seconds
256 megabytes
['dp', 'math', 'number theory', 'probabilities', '*2300']
C. Edgy Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red.You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, \ldots, a_k] good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from a_1 and ending at a_k. Start at a_1, then go to a_2 using the shortest path between a_1 and a_2, then go to a_3 in a similar way, and so on, until you travel the shortest path between a_{k-1} and a_k. If you walked over at least one black edge during this process, then the sequence is good. Consider the tree on the picture. If k=3 then the following sequences are good: [1, 4, 7], [5, 5, 3] and [2, 3, 7]. The following sequences are not good: [1, 4, 6], [5, 5, 5], [3, 7, 3].There are n^k sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo 10^9+7.InputThe first line contains two integers n and k (2 \le n \le 10^5, 2 \le k \le 100), the size of the tree and the length of the vertex sequence.Each of the next n - 1 lines contains three integers u_i, v_i and x_i (1 \le u_i, v_i \le n, x_i \in \{0, 1\}), where u_i and v_i denote the endpoints of the corresponding edge and x_i is the color of this edge (0 denotes red edge and 1 denotes black edge).OutputPrint the number of good sequences modulo 10^9 + 7.ExamplesInput 4 4 1 2 1 2 3 1 3 4 1 Output 252Input 4 6 1 2 0 1 3 0 1 4 0 Output 0Input 3 5 1 2 1 2 3 0 Output 210NoteIn the first example, all sequences (4^4) of length 4 except the following are good: [1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3] [4, 4, 4, 4] In the second example, all edges are red, hence there aren't any good sequences.
4 4 1 2 1 2 3 1 3 4 1
252
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'math', 'trees', '*1500']
B. Chocolatestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 \le x_i \le a_i), then for all 1 \le j < i at least one of the following must hold: x_j = 0 (you bought zero chocolates of type j) x_j < x_i (you bought less chocolates of type j than of type i) For example, the array x = [0, 0, 1, 2, 10] satisfies the requirement above (assuming that all a_i \ge x_i), while arrays x = [0, 1, 0], x = [5, 5] and x = [3, 2] don't.Calculate the maximum number of chocolates you can buy.InputThe first line contains an integer n (1 \le n \le 2 \cdot 10^5), denoting the number of types of chocolate.The next line contains n integers a_i (1 \le a_i \le 10^9), denoting the number of chocolates of each type.OutputPrint the maximum number of chocolates you can buy.ExamplesInput 5 1 2 1 3 6 Output 10Input 5 3 2 5 4 10 Output 20Input 4 1 1 1 1 Output 1NoteIn the first example, it is optimal to buy: 0 + 0 + 1 + 3 + 6 chocolates.In the second example, it is optimal to buy: 1 + 2 + 3 + 4 + 10 chocolates.In the third example, it is optimal to buy: 0 + 0 + 0 + 1 chocolates.
5 1 2 1 3 6
10
2 seconds
256 megabytes
['greedy', 'implementation', '*1000']