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
|
---|---|---|---|---|---|
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string s of length n. He decides to make the following modification to the string: Pick an integer k, (1 \leq k \leq n). For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 2) weqr (after reversing the second substring of length 2) werq (after reversing the last substring of length 2) Hence, the resulting string after modifying s with k = 2 is werq. Vasya wants to choose a k such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of k. Among all such k, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 5000). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 5000) — the length of the string s.The second line of each test case contains the string s of n lowercase latin letters.It is guaranteed that the sum of n over all test cases does not exceed 5000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s' achievable after the above-mentioned modification. In the second line output the appropriate value of k (1 \leq k \leq n) that you chose for performing the modification. If there are multiple values of k that give the lexicographically smallest string, output the smallest value of k among them.ExampleInput
6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
Output
abab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample, the string modification results for the sample abab are as follows : for k = 1 : abab for k = 2 : baba for k = 3 : abab for k = 4 : babaThe lexicographically smallest string achievable through modification is abab for k = 1 and 3. Smallest value of k needed to achieve is hence 1. | 6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
| abab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'sortings', 'strings', '*1400'] |
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0 \leq a_{i} \leq m The average score of the class doesn't change. You are student 1 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 200). The description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n \leq 10^{3}, 1 \leq m \leq 10^{5}) — the number of students and the highest possible score respectively.The second line of each testcase contains n integers a_1, a_2, \dots, a_n ( 0 \leq a_{i} \leq m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInput
2
4 10
1 2 3 4
4 5
1 2 3 4
Output
10
5
NoteIn the first case, a = [1,2,3,4] , with average of 2.5. You can change array a to [10,0,0,0]. Average remains 2.5, and all conditions are satisfied.In the second case, 0 \leq a_{i} \leq 5. You can change a to [5,1,1,3]. You cannot increase a_{1} further as it will violate condition 0\le a_i\le m. | 2
4 10
1 2 3 4
4 5
1 2 3 4
| 10 5 | 1 second | 256 megabytes | ['implementation', '*800'] |
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b_1, b_2, \ldots, b_n. Find the lexicographically minimal permutation a_1, a_2, \ldots, a_{2n} such that b_i = \min(a_{2i-1}, a_{2i}), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 100).The first line of each test case consists of one integer n — the number of elements in the sequence b (1 \le n \le 100).The second line of each test case consists of n different integers b_1, \ldots, b_n — elements of the sequence b (1 \le b_i \le 2n).It is guaranteed that the sum of n by all test cases doesn't exceed 100.OutputFor each test case, if there is no appropriate permutation, print one number -1.Otherwise, print 2n integers a_1, \ldots, a_{2n} — required lexicographically minimal permutation of numbers from 1 to 2n.ExampleInput
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| 5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
| 1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10 | 1 second | 256 megabytes | ['greedy', '*1200'] |
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string s of length n, where s_i = \texttt{A}, if there is a bus station at i-th crossroad, and s_i = \texttt{B}, if there is a tram station at i-th crossroad. Currently Petya is at the first crossroad (which corresponds to s_1) and his goal is to get to the last crossroad (which corresponds to s_n).If for two crossroads i and j for all crossroads i, i+1, \ldots, j-1 there is a bus station, one can pay a roubles for the bus ticket, and go from i-th crossroad to the j-th crossroad by the bus (it is not necessary to have a bus station at the j-th crossroad). Formally, paying a roubles Petya can go from i to j if s_t = \texttt{A} for all i \le t < j. If for two crossroads i and j for all crossroads i, i+1, \ldots, j-1 there is a tram station, one can pay b roubles for the tram ticket, and go from i-th crossroad to the j-th crossroad by the tram (it is not necessary to have a tram station at the j-th crossroad). Formally, paying b roubles Petya can go from i to j if s_t = \texttt{B} for all i \le t < j.For example, if s="AABBBAB", a=4 and b=3 then Petya needs: buy one bus ticket to get from 1 to 3, buy one tram ticket to get from 3 to 6, buy one bus ticket to get from 6 to 7. Thus, in total he needs to spend 4+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character s_n) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the n-th crossroad. After the party he has left with p roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad i to go on foot the first, so he has enough money to get from the i-th crossroad to the n-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 10^4).The first line of each test case consists of three integers a, b, p (1 \le a, b, p \le 10^5) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string s, where s_i = \texttt{A}, if there is a bus station at i-th crossroad, and s_i = \texttt{B}, if there is a tram station at i-th crossroad (2 \le |s| \le 10^5).It is guaranteed, that the sum of the length of strings s by all test cases in one test doesn't exceed 10^5.OutputFor each test case print one number — the minimal index i of a crossroad Petya should go on foot. The rest of the path (i.e. from i to n he should use public transport).ExampleInput
5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
Output
2
1
3
1
6
| 5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
| 2 1 3 1 6 | 1 second | 256 megabytes | ['binary search', 'dp', 'greedy', 'strings', '*1300'] |
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a \times b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 \le x < a, 0 \le y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer t (1 \le t \le 10^4) — the number of test cases in the test. In the next lines you are given descriptions of t test cases.Each test case contains a single line which consists of 4 integers a, b, x and y (1 \le a, b \le 10^4; 0 \le x < a; 0 \le y < b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2 (e.g. a=b=1 is impossible).OutputPrint t integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInput
6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
Output
56
6
442
1
45
80
NoteIn the first test case, the screen resolution is 8 \times 8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | 6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
| 56 6 442 1 45 80 | 1 second | 256 megabytes | ['implementation', '*800'] |
E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 \leq l_1 \leq r_1 \leq n) and a segment [l_2, r_2] (1 \leq l_2 \leq r_2 \leq n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} \ldots a_{r_1} b_{l_2} b_{l_2 + 1} \ldots b_{r_2}.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 \leq x \leq r_1 and l_2 \leq x \leq r_2; the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. InputThe first line contains integers n and m (1 \leq n \leq 500\,000, 2 \leq m \leq 2 \cdot n) — the length of strings a and b and the length of the string s.The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m.All strings consist of lowercase English letters.OutputPrint one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInput6 5aabbaabaaaabaaaaaOutput4Input5 4azazazazazazazOutput11Input9 12abcabcabcxyzxyzxyzabcabcayzxyzOutput2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2, 2] and [2, 5]; [1, 2] and [2, 4]; [5, 5] and [2, 5]; [5, 6] and [3, 5]; | Input6 5aabbaabaaaabaaaaa | Output4 | 2 seconds | 512 megabytes | ['data structures', 'hashing', 'strings', 'two pointers', '*2700'] |
D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were m children lined up in front of him. Let's number them from 1 to m. Grandfather Frost knows n spells. The i-th spell gives a candy to every child whose place is in the [L_i, R_i] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most k candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of n, m, and k (1 \leq n \leq 100\,000, 1 \leq m \leq 10^9, 1 \leq k \leq 8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by n lines, each containing integers L_i and R_i (1 \leq L_i \leq R_i \leq m) — the parameters of the i spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInput3 5 31 32 43 5Output4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | Input3 5 31 32 43 5 | Output4 | 2 seconds | 512 megabytes | ['bitmasks', 'dp', 'implementation', '*2500'] |
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n \le 500\,000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 \le a_i \le m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer n (1 \leq n \leq 500\,000) — the number of plots.The second line contains the integers m_1, m_2, \ldots, m_n (1 \leq m_i \leq 10^9) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint n integers a_i — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInput51 2 3 2 1Output1 2 3 2 1 Input310 6 8Output10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | Input51 2 3 2 1 | Output1 2 3 2 1 | 3 seconds | 512 megabytes | ['data structures', 'dp', 'greedy', '*1900'] |
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n \le 1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 \le a_i \le m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer n (1 \leq n \leq 1000) — the number of plots.The second line contains the integers m_1, m_2, \ldots, m_n (1 \leq m_i \leq 10^9) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint n integers a_i — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInput51 2 3 2 1Output1 2 3 2 1 Input310 6 8Output10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. | Input51 2 3 2 1 | Output1 2 3 2 1 | 1 second | 512 megabytes | ['brute force', 'data structures', 'dp', 'greedy', '*1500'] |
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be n participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took x-th place and in the second round — y-th place. Then the total score of the participant A is sum x + y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every i from 1 to n exactly one participant took i-th place in first round and exactly one participant took i-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got x-th place in first round and y-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases to solve.Each of the following t lines contains integers n, x, y (1 \leq n \leq 10^9, 1 \le x, y \le n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInput15 1 3Output1 3Input16 3 4Output2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | Input15 1 3 | Output1 3 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'math', '*1700'] |
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work, Denis decided to open a fast food restaurant.On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer t (1 \le t \le 500) — the number of test cases to solve.Each of the remaining t lines contains integers a, b and c (0 \leq a, b, c \leq 10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInput71 2 10 0 09 1 72 2 32 3 23 2 24 4 4Output3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | Input71 2 10 0 09 1 72 2 32 3 23 2 24 4 4 | Output3045557 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', '*900'] |
G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings S. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is t, choose some lowercase Latin letter c and append it to the back of t, so the current string becomes t + c. This action takes 1 second; use autocompletion. When you try to autocomplete the current string t, a list of all strings s \in S such that t is a prefix of s is shown to you. This list includes t itself, if t is a string from S, and the strings are ordered lexicographically. You can transform t into the i-th string from this list in i seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from S?Note that the strings from S are given in an unusual way.InputThe first line contains one integer n (1 \le n \le 10^6).Then n lines follow, the i-th line contains one integer p_i (0 \le p_i < i) and one lowercase Latin character c_i. These lines form some set of strings such that S is its subset as follows: there are n + 1 strings, numbered from 0 to n; the 0-th string is an empty string, and the i-th string (i \ge 1) is the result of appending the character c_i to the string p_i. It is guaranteed that all these strings are distinct.The next line contains one integer k (1 \le k \le n) — the number of strings in S.The last line contains k integers a_1, a_2, ..., a_k (1 \le a_i \le n, all a_i are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set S — formally, if we denote the i-th generated string as s_i, then S = {s_{a_1}, s_{a_2}, \dots, s_{a_k}}.OutputPrint k integers, the i-th of them should be equal to the minimum number of seconds required to type the string s_{a_i}.ExamplesInput
10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
Output
2 4 1 3 3
Input
8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
Output
1 2 2 4 4
NoteIn the first example, S consists of the following strings: ieh, iqgp, i, iqge, ier. | 10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
| 2 4 1 3 3 | 7 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'dp', '*2600'] |
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders); an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders); a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers n, x, y and z (1 \le n \le 3 \cdot 10^5, 1 \le x, y, z \le 5). The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^{18}).It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 \cdot 10^5.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).ExamplesInput
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2
| 3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
| 2 3 0 | 3 seconds | 512 megabytes | ['games', 'two pointers', '*2500'] |
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements a_i = a_{i + 1} (if there is at least one such pair). Replace them by one element with value a_i + 1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array a you can get?InputThe first line contains the single integer n (1 \le n \le 500) — the initial length of the array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 1000) — the initial array a.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInput
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
NoteIn the first test, this is one of the optimal sequences of operations: 4 3 2 2 3 \rightarrow 4 3 3 3 \rightarrow 4 4 3 \rightarrow 5 3.In the second test, this is one of the optimal sequences of operations: 3 3 4 4 4 3 3 \rightarrow 4 4 4 4 3 3 \rightarrow 4 4 4 4 4 \rightarrow 5 4 4 4 \rightarrow 5 5 4 \rightarrow 6 4.In the third and fourth tests, you can't perform the operation at all. | 5
4 3 2 2 3
| 2 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*2100'] |
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains n elements; each element is an integer from 1 to m; for each array, there is exactly one pair of equal elements; for each array a, there exists an index i such that the array is strictly ascending before the i-th element and strictly descending after it (formally, it means that a_j < a_{j + 1}, if j < i, and a_j > a_{j + 1}, if j \ge i). InputThe first line contains two integers n and m (2 \le n \le m \le 2 \cdot 10^5).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353.ExamplesInput
3 4
Output
6
Input
3 5
Output
10
Input
42 1337
Output
806066790
Input
100000 200000
Output
707899035
NoteThe arrays in the first example are: [1, 2, 1]; [1, 3, 1]; [1, 4, 1]; [2, 3, 2]; [2, 4, 2]; [3, 4, 3]. | 3 4
| 6 | 2 seconds | 512 megabytes | ['combinatorics', 'math', '*1700'] |
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v_1, v_2, \dots, v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can: either choose position pos (1 \le pos \le n) and increase v_{pos} by k^i; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array v equal to the given array a (v_j = a_j for each j) after some step?InputThe first line contains one integer T (1 \le T \le 1000) — the number of test cases. Next 2T lines contain test cases — two lines per test case.The first line of each test case contains two integers n and k (1 \le n \le 30, 2 \le k \le 100) — the size of arrays v and a and value k used in the algorithm.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^{16}) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array a after some step or NO (case insensitive) otherwise.ExampleInput
5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
Output
YES
YES
NO
NO
YES
NoteIn the first test case, you can stop the algorithm before the 0-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k^0 to v_1 and stop the algorithm.In the third test case, you can't make two 1 in the array v.In the fifth test case, you can skip 9^0 and 9^1, then add 9^2 and 9^3 to v_3, skip 9^4 and finally, add 9^5 to v_2. | 5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
| YES YES NO NO YES | 2 seconds | 256 megabytes | ['bitmasks', 'greedy', 'implementation', 'math', 'number theory', 'ternary search', '*1400'] |
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots , a_n. Array is good if for each pair of indexes i < j the condition j - a_j \ne i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 100) — the length of array a.The second line of each test case contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le 100).OutputFor each test case print the shuffled version of the array a which is good.ExampleInput
3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
Output
7
1 5 1 3
2 4 6 1 3 5
| 3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
| 7 1 5 1 3 2 4 6 1 3 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'sortings', '*1000'] |
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with m vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.The next t lines describe test cases. Each test case is given as two space-separated integers n and m (3 \le m < n \le 100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with m vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInput
2
6 3
7 3
Output
YES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | 2
6 3
7 3
| YES NO | 1 second | 256 megabytes | ['geometry', 'greedy', 'math', 'number theory', '*800'] |
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t \cdot v_i.Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0.Your task is to calculate the value \sum\limits_{1 \le i < j \le n} d(i, j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of points.The second line of the input contains n integers x_1, x_2, \dots, x_n (1 \le x_i \le 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.The third line of the input contains n integers v_1, v_2, \dots, v_n (-10^8 \le v_i \le 10^8), where v_i is the speed of the i-th point.OutputPrint one integer — the value \sum\limits_{1 \le i < j \le n} d(i, j) (the sum of minimum distances over all pairs of points).ExamplesInput
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
| 3
1 3 2
-100 2 3
| 3 | 2 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'implementation', 'sortings', '*1900'] |
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases.The only line of each test case contains two integers n and d (2 \le n, d \le 5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (\sum n \le 5000, \sum d \le 5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, \dots, p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.ExampleInput
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | 3
5 7
10 19
10 18
| YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'trees', '*2200'] |
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a \le b \le c.In one move, you can add +1 or -1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A \le B \le C such that B is divisible by A and C is divisible by B.You have to answer t independent test cases. InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases.The next t lines describe test cases. Each test case is given on a separate line as three space-separated integers a, b and c (1 \le a \le b \le c \le 10^4).OutputFor each test case, print the answer. In the first line print res — the minimum number of operations you have to perform to obtain three integers A \le B \le C such that B is divisible by A and C is divisible by B. On the second line print any suitable triple A, B and C.ExampleInput
8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
Output
1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| 8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
| 1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48 | 2 seconds | 256 megabytes | ['brute force', 'math', '*2000'] |
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend m wrong tries to perform the combo and during the i-th try you will make a mistake right after p_i-th button (1 \le p_i < n) (i.e. you will press first p_i buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1-th try you press all buttons right and finally perform the combo.I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.Then t test cases follow.The first line of each test case contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5) — the length of s and the number of tries correspondingly.The second line of each test case contains the string s consisting of n lowercase Latin letters.The third line of each test case contains m integers p_1, p_2, \dots, p_m (1 \le p_i < n) — the number of characters pressed right during the i-th try.It is guaranteed that the sum of n and the sum of m both does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5, \sum m \le 2 \cdot 10^5).It is guaranteed that the answer for each letter does not exceed 2 \cdot 10^9.OutputFor each test case, print the answer — 26 integers: the number of times you press the button 'a', the number of times you press the button 'b', \dots, the number of times you press the button 'z'.ExampleInput
3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
Output
4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is 4, 'b' is 2 and 'c' is 2.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 9, 'd' is 4, 'e' is 5, 'f' is 3, 'o' is 9, 'r' is 3 and 's' is 1. | 3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
| 4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 | 2 seconds | 256 megabytes | ['brute force', '*1300'] |
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n.You are also given a set of distinct positions p_1, p_2, \dots, p_m, where 1 \le p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 \le a_2 \le \dots \le a_n) using only allowed swaps.For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3] (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally, we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases.Then t test cases follow. The first line of each test case contains two integers n and m (1 \le m < n \le 100) — the number of elements in a and the number of elements in p. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100). The third line of the test case contains m integers p_1, p_2, \dots, p_m (1 \le p_i < n, all p_i are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a_1 \le a_2 \le \dots \le a_n) using only allowed swaps. Otherwise, print "NO".ExampleInput
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
Output
YES
NO
YES
YES
NO
YES
| 6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
| YES NO YES YES NO YES | 2 seconds | 256 megabytes | ['dfs and similar', 'sortings', '*1200'] |
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers a and b.In one move, you can change a in the following way: Choose any positive odd integer x (x > 0) and replace a with a+x; choose any positive even integer y (y > 0) and replace a with a-y. You can perform as many such operations as you want. You can choose the same numbers x and y in different moves.Your task is to find the minimum number of moves required to obtain b from a. It is guaranteed that you can always obtain b from a.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.Then t test cases follow. Each test case is given as two space-separated integers a and b (1 \le a, b \le 10^9).OutputFor each test case, print the answer — the minimum number of moves required to obtain b from a if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain b from a.ExampleInput
5
2 3
10 10
2 4
7 4
9 3
Output
1
0
2
2
1
NoteIn the first test case, you can just add 1.In the second test case, you don't need to do anything.In the third test case, you can add 1 two times.In the fourth test case, you can subtract 4 and add 1.In the fifth test case, you can just subtract 6. | 5
2 3
10 10
2 4
7 4
9 3
| 1 0 2 2 1 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*800'] |
F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements a and b. One need to fun such x that a^x = b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 2^{2^k} - 1 for some positive integer k . Bitwise exclusive or (\oplus) operation is used as addition. One of ways to define multiplication operation (\odot) is following properties: 0 \odot a = a \odot 0 = 0 1 \odot a = a \odot 1 = a a \odot b = b \odot a a \odot (b \odot c)= (a \odot b) \odot c a \odot (b \oplus c) = (a \odot b) \oplus (a \odot c) If a = 2^{2^n} for some integer n > 0, and b < a, then a \odot b = a \cdot b. If a = 2^{2^n} for some integer n > 0, then a \odot a = \frac{3}{2}\cdot a. For example: 4 \odot 4 = 6 8 \odot 8 = 4 \odot 2 \odot 4 \odot 2 = 4 \odot 4 \odot 2 \odot 2 = 6 \odot 3 = (4 \oplus 2) \odot 3 = (4 \odot 3) \oplus (2 \odot (2 \oplus 1)) = (4 \odot 3) \oplus (2 \odot 2) \oplus (2 \odot 1) = 12 \oplus 3 \oplus 2 = 13. 32 \odot 64 = (16 \odot 2) \odot (16 \odot 4) = (16 \odot 16) \odot (2 \odot 4) = 24 \odot 8 = (16 \oplus 8) \odot 8 = (16 \odot 8) \oplus (8 \odot 8) = 128 \oplus 13 = 141 5 \odot 6 = (4 \oplus 1) \odot (4 \oplus 2) = (4\odot 4) \oplus (4 \odot 2) \oplus (4 \odot 1) \oplus (1 \odot 2) = 6 \oplus 8 \oplus 4 \oplus 2 = 8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a^{\odot k} = \underbrace{a \odot a \odot \cdots \odot a}_{k~\texttt{times}}.You need to analyze the proposed scheme strength. For pairs of numbers a and b you need to find such x, that a^{\odot x} = b, or determine that it doesn't exist. InputIn the first line of input there is single integer t (1 \le t \le 100) — number of pairs, for which you need to find the discrete logarithm.In each of next t line there is a pair of integers a b (1 \le a, b < 2^{64}). OutputFor each pair you should print one integer x (0 \le x < 2^{64}), such that a^{\odot x} = b, or -1 if no such x exists. It can be shown, that if any such x exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInput
7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
Output
1
1
2
4
-1
6148914691236517205
68943624821423112
| 7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
| 1 1 2 4 -1 6148914691236517205 68943624821423112 | 3 seconds | 512 megabytes | ['math', 'number theory', '*3400'] |
E. Strange Functiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the function f of multiset a as the multiset of number of occurences of every number, that is present in a.E.g., f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}.Let's define f^k(a), as applying f to array a k times: f^k(a) = f(f^{k-1}(a)), f^0(a) = a. E.g., f^2(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 2, 2\}.You are given integers n, k and you are asked how many different values the function f^k(a) can have, where a is arbitrary non-empty array with numbers of size no more than n. Print the answer modulo 998\,244\,353.InputThe first and only line of input consists of two integers n, k (1 \le n, k \le 2020).OutputPrint one number — the number of different values of function f^k(a) on all possible non-empty arrays with no more than n elements modulo 998\,244\,353.ExamplesInput
3 1
Output
6
Input
5 6
Output
1
Input
10 1
Output
138
Input
10 2
Output
33
| 3 1
| 6 | 2 seconds | 512 megabytes | ['dp', '*2900'] |
D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with n cities numbered from 1 to n. She lives in the city number 1. There is a direct train route between each pair of distinct cities i and j, where i \neq j. In total there are n(n-1) distinct routes. Every route has a cost, cost for route from i to j may be different from the cost of route from j to i.Masha wants to start her journey in city 1, take exactly k routes from one city to another and as a result return to the city 1. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city v, take odd number of routes used by Masha in her journey and return to the city v, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,k (2 \leq n \leq 80; 2 \leq k \leq 10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that k is even.Next n lines hold route descriptions: j-th number in i-th line represents the cost of route from i to j if i \neq j, and is 0 otherwise (there are no routes i \to i). All route costs are integers from 0 to 10^8.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInput
5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
Output
2
Input
3 2
0 1 1
2 0 1
2 2 0
Output
3
| 5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
| 2 | 3 seconds | 256 megabytes | ['dp', 'graphs', 'probabilities', '*2300'] |
C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string s written on its side. This part of the office is supposed to be split into m meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of s written on its side.For each possible arrangement of m meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kth label of the delivery?InputIn the first line, you are given three integer numbers n, m, k — length of string s, number of planned meeting rooms to split s into and number of the interesting label (2 \le n \le 1\,000; 1 \le m \le 1\,000; 1 \le k \le 10^{18}).Second input line has string s, consisting of n lowercase english letters.For given n, m, k there are at least k ways to split s into m substrings.OutputOutput single string – name of meeting room printed on k-th label of the delivery.ExamplesInput
4 2 1
abac
Output
aba
Input
19 5 1821
aupontrougevkoffice
Output
au
NoteIn the first example, delivery consists of the labels "aba", "ab", "a".In the second example, delivery consists of 3060 labels. The first label is "aupontrougevkof" and the last one is "a". | 4 2 1
abac
| aba | 2 seconds | 512 megabytes | ['binary search', 'dp', 'strings', '*2800'] |
B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2^n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 1 to 2^n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2^{n-1} teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2^k teams play a game with each other (teams are split into games by team numbers). 2^{k-1} loosing teams are eliminated from the championship, 2^{k-1} winning teams are playing 2^{k-1} teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2^{k-1} teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a_1, a_2, ..., a_k. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n, k — 2^n teams are competing in the championship. You are a fan of k teams (2 \le n \le 17; 0 \le k \le 2^n).Second input line has k distinct integers a_1, \ldots, a_k — numbers of teams you're a fan of (1 \le a_i \le 2^n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInput
3 1
6
Output
6
Input
3 3
1 7 8
Output
11
Input
3 4
1 3 5 7
Output
14
NoteOn the image, each game of the championship is denoted with an English letter (a to n). Winner of game i is denoted as Wi, loser is denoted as Li. Teams you're a fan of are highlighted with red background.In the first example, team 6 will play in 6 games if it looses the first upper bracket game (game c) and wins all lower bracket games (games h, j, l, m). In the second example, teams 7 and 8 have to play with each other in the first game of upper bracket (game d). Team 8 can win all remaining games in upper bracket, when teams 1 and 7 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship. | 3 1
6
| 6 | 2 seconds | 512 megabytes | ['dp', 'implementation', '*2500'] |
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer n — the number of news categories (1 \le n \le 200\,000).The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 \le a_i \le 10^9).The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 \le t_i \le 10^5).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInput
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications. | 5
3 7 9 7 8
5 2 5 7 5
| 6 | 2 seconds | 512 megabytes | ['data structures', 'greedy', 'sortings', '*1700'] |
G. Cow and Exercisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is obsessed with making Bessie exercise more!Bessie is out grazing on the farm, which consists of n fields connected by m directed roads. Each road takes some time w_i to cross. She is currently at field 1 and will return to her home at field n at the end of the day.Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed x_i for the i-th plan. Determine the maximum he can make the shortest path from 1 to n for each of the q independent plans.InputThe first line contains integers n and m (2 \le n \le 50, 1 \le m \le n \cdot (n-1)) — the number of fields and number of roads, respectively.Each of the following m lines contains 3 integers, u_i, v_i, and w_i (1 \le u_i, v_i \le n, 1 \le w_i \le 10^6), meaning there is an road from field u_i to field v_i that takes w_i time to cross.It is guaranteed that there exists a way to get to field n from field 1. It is guaranteed that the graph does not contain self-loops or parallel edges. It is possible to have a road from u to v and a road from v to u.The next line contains a single integer q (1 \le q \le 10^5), the number of plans.Each of the following q lines contains a single integer x_i, the query (0 \le x_i \le 10^5).OutputFor each query, output the maximum Farmer John can make the shortest path if the total increase does not exceed x_i.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExampleInput
3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
Output
3.0000000000
4.0000000000
4.5000000000
5.0000000000
5.5000000000
| 3 3
1 2 2
2 3 2
1 3 3
5
0
1
2
3
4
| 3.0000000000 4.0000000000 4.5000000000 5.0000000000 5.5000000000 | 1 second | 256 megabytes | ['flows', 'graphs', 'shortest paths', '*3100'] |
F. Cow and Vacationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is planning a vacation! In Cow-lifornia, there are n cities, with n-1 bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering v possible vacation plans, with the i-th one consisting of a start city a_i and destination city b_i.It is known that only r of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than k consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?InputThe first line contains three integers n, k, and r (2 \le n \le 2 \cdot 10^5, 1 \le k,r \le n) — the number of cities, the maximum number of roads Bessie is willing to travel through in a row without resting, and the number of rest stops.Each of the following n-1 lines contain two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \neq y_i), meaning city x_i and city y_i are connected by a road. The next line contains r integers separated by spaces — the cities with rest stops. Each city will appear at most once.The next line contains v (1 \le v \le 2 \cdot 10^5) — the number of vacation plans.Each of the following v lines contain two integers a_i and b_i (1 \le a_i, b_i \le n, a_i \ne b_i) — the start and end city of the vacation plan. OutputIf Bessie can reach her destination without traveling across more than k roads without resting for the i-th vacation plan, print YES. Otherwise, print NO.ExamplesInput
6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
Output
YES
YES
NO
Input
8 3 3
1 2
2 3
3 4
4 5
4 6
6 7
7 8
2 5 8
2
7 1
8 1
Output
YES
NO
NoteThe graph for the first example is shown below. The rest stop is denoted by red.For the first query, Bessie can visit these cities in order: 1, 2, 3.For the second query, Bessie can visit these cities in order: 3, 2, 4, 5. For the third query, Bessie cannot travel to her destination. For example, if she attempts to travel this way: 3, 2, 4, 5, 6, she travels on more than 2 roads without resting. The graph for the second example is shown below. | 6 2 1
1 2
2 3
2 4
4 5
5 6
2
3
1 3
3 5
3 6
| YES YES NO | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'trees', '*3300'] |
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of n units of grass, each with a sweetness s_i. Farmer John has m cows, each with a favorite sweetness f_i and a hunger value h_i. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats h_i units. The moment a cow eats h_i units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 10^9+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers n and m (1 \le n \le 5000, 1 \le m \le 5000) — the number of units of grass and the number of cows. The second line contains n integers s_1, s_2, \ldots, s_n (1 \le s_i \le n) — the sweetness values of the grass.The i-th of the following m lines contains two integers f_i and h_i (1 \le f_i, h_i \le n) — the favorite sweetness and hunger value of the i-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 10^9+7. ExamplesInput
5 2
1 1 1 1 1
1 2
1 3
Output
2 2
Input
5 2
1 1 1 1 1
1 2
1 4
Output
1 4
Input
3 2
2 3 2
3 1
2 1
Output
2 4
Input
5 1
1 1 1 1 1
2 5
Output
0 1
NoteIn the first example, FJ can line up the cows as follows to achieve 2 sleeping cows: Cow 1 is lined up on the left side and cow 2 is lined up on the right side. Cow 2 is lined up on the left side and cow 1 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 1 sleeping cow: Cow 1 is lined up on the left side. Cow 2 is lined up on the left side. Cow 1 is lined up on the right side. Cow 2 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 2 sleeping cows: Cow 1 and 2 are lined up on the left side. Cow 1 and 2 are lined up on the right side. Cow 1 is lined up on the left side and cow 2 is lined up on the right side. Cow 1 is lined up on the right side and cow 2 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side. | 5 2
1 1 1 1 1
1 2
1 3
| 2 2 | 1 second | 256 megabytes | ['binary search', 'combinatorics', 'dp', 'greedy', 'implementation', 'math', '*2500'] |
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 1 to field n. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers n, m, and k (2 \le n \le 2 \cdot 10^5, n-1 \le m \le 2 \cdot 10^5, 2 \le k \le n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains k integers a_1, a_2, \ldots, a_k (1 \le a_i \le n) — the special fields. All a_i are distinct.The i-th of the following m lines contains integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i), representing a bidirectional road between fields x_i and y_i. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 1 to n after Farmer John installs one road optimally.ExamplesInput
5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
Output
3
Input
5 4 2
2 4
1 2
2 3
3 4
4 5
Output
3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 3 and 5, and the resulting shortest path from 1 to 5 is length 3. The graph for the second example is shown below. Farmer John must add a road between fields 2 and 4, and the resulting shortest path from 1 to 5 is length 3. | 5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
| 3 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'graphs', 'greedy', 'shortest paths', 'sortings', '*1900'] |
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6.InputThe first line contains a string s of lowercase Latin letters (1 \le |s| \le 10^5) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInput
aaabb
Output
6
Input
usaco
Output
1
Input
lol
Output
2
NoteIn the first example, these are all the hidden strings and their indice sets: a occurs at (1), (2), (3) b occurs at (4), (5) ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) aa occurs at (1,2), (1,3), (2,3) bb occurs at (4,5) aab occurs at (1,3,5), (2,3,4) aaa occurs at (1,2,3) abb occurs at (3,4,5) aaab occurs at (1,2,3,4) aabb occurs at (2,3,4,5) aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l. | aaabb
| 6 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'math', 'strings', '*1500'] |
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its n favorite numbers: a_1, a_2, \ldots, a_n. What is the minimum number of hops Rabbit needs to get from (0,0) to (x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (x_i, y_i) and (x_j, y_j) is \sqrt{(x_i-x_j)^2+(y_i-y_j)^2}.For example, if Rabbit has favorite numbers 1 and 3 he could hop from (0,0) to (4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0) in 2 hops (e.g. (0,0) \rightarrow (2,-\sqrt{5}) \rightarrow (4,0)). Here is a graphic for the first example. Both hops have distance 3, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number a_i and hops with distance equal to a_i in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases. Next 2t lines contain test cases — two lines per test case.The first line of each test case contains two integers n and x (1 \le n \le 10^5, 1 \le x \le 10^9) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of n over all the test cases will not exceed 10^5.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInput
42 41 33 123 4 51 552 1015 4Output
2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,\sqrt{5}), then to (4,0) for a total of two hops. Each hop has a distance of 3, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 3 times is: (0,0) \rightarrow (4,0) \rightarrow (8,0) \rightarrow (12,0).In the third test case of the sample, Rabbit can hop from (0,0) to (5,0).In the fourth test case of the sample, Rabbit can hop: (0,0) \rightarrow (5,10\sqrt{2}) \rightarrow (10,0). | 42 41 33 123 4 51 552 1015 4 | 2 3 1 2 | 2 seconds | 256 megabytes | ['geometry', 'greedy', 'math', '*1300'] |
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices i and j (1 \le i, j \le n) such that |i-j|=1 and a_i>0 and apply a_i = a_i - 1, a_j = a_j + 1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 1 (i.e. to maximize a_1), and she only has d days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 1 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 100) — the number of test cases. Next 2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers n and d (1 \le n,d \le 100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 1 after d days if Bessie acts optimally.ExampleInput
3
4 5
1 0 3 2
2 2
100 1
1 8
0
Output
3
101
0
NoteIn the first test case of the sample, this is one possible way Bessie can end up with 3 haybales in pile 1: On day one, move a haybale from pile 3 to pile 2 On day two, move a haybale from pile 3 to pile 2 On day three, move a haybale from pile 2 to pile 1 On day four, move a haybale from pile 2 to pile 1 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 2 to pile 1 on the second day. | 3
4 5
1 0 3 2
2 2
100 1
1 8
0
| 3 101 0 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*800'] |
H. Kuroni the Private Tutortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a professional private tutor, Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.The exam consists of n questions, and m students have taken the exam. Each question was worth 1 point. Question i was solved by at least l_i and at most r_i students. Additionally, you know that the total score of all students is t.Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from 1 to m, where rank 1 has the highest score and rank m has the lowest score. Ties were broken arbitrarily.You know that the student at rank p_i had a score of s_i for 1 \le i \le q.You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank 1, and the maximum possible score for rank 1 achieving this maximum number of students.InputThe first line of input contains two integers (1 \le n, m \le 10^{5}), denoting the number of questions of the exam and the number of students respectively.The next n lines contain two integers each, with the i-th line containing l_{i} and r_{i} (0 \le l_{i} \le r_{i} \le m).The next line contains a single integer q (0 \le q \le m). The next q lines contain two integers each, denoting p_{i} and s_{i} (1 \le p_{i} \le m, 0 \le s_{i} \le n). It is guaranteed that all p_{i} are distinct and if p_{i} \le p_{j}, then s_{i} \ge s_{j}.The last line contains a single integer t (0 \le t \le nm), denoting the total score of all students.OutputOutput two integers: the maximum number of students who could have gotten as many points as the student with rank 1, and the maximum possible score for rank 1 achieving this maximum number of students. If there is no valid arrangement that fits the given data, output -1 -1.ExamplesInput
5 4
2 4
2 3
1 1
0 1
0 0
1
4 1
7
Output
3 2
Input
5 6
0 6
0 6
2 5
6 6
4 6
1
3 3
30
Output
-1 -1
NoteFor the first sample, here is one possible arrangement that fits the data:Students 1 and 2 both solved problems 1 and 2.Student 3 solved problems 2 and 3.Student 4 solved problem 4.The total score of all students is T = 7. Note that the scores of the students are 2, 2, 2 and 1 respectively, which satisfies the condition that the student at rank 4 gets exactly 1 point. Finally, 3 students tied for first with a maximum score of 2, and it can be proven that we cannot do better with any other arrangement. | 5 4
2 4
2 3
1 1
0 1
0 0
1
4 1
7
| 3 2 | 3 seconds | 256 megabytes | ['binary search', 'greedy', '*3500'] |
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 0 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). n people have heard about Antihype recently, the i-th person's age is a_i. Some of them are friends, but friendship is a weird thing now: the i-th person is a friend of the j-th person if and only if a_i \text{ AND } a_j = 0, where \text{AND} denotes the bitwise AND operation.Nobody among the n people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer n (1\le n \le 2\cdot 10^5) — the number of people.The second line contains n integers a_1, a_2, \dots, a_n (0\le a_i \le 2\cdot 10^5) — the ages of the people.OutputOutput exactly one integer — the maximum possible combined gainings of all n people.ExampleInput
3
1 2 3
Output
2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one, getting 2 for it. | 3
1 2 3
| 2 | 3 seconds | 256 megabytes | ['bitmasks', 'brute force', 'dp', 'dsu', 'graphs', '*3500'] |
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array a consisting of n positive integers. An operation consists of choosing an element and either adding 1 to it or subtracting 1 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 1. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer n (2 \le n \le 2 \cdot 10^5) — the number of elements in the array.The second line contains n integers a_1, a_2, \dots, a_n. (1 \le a_i \le 10^{12}) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInput
3
6 2 4
Output
0
Input
5
9 8 7 3 1
Output
4
NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is 2.In the second example, we may apply the following operations: Add 1 to the second element, making it equal to 9. Subtract 1 from the third element, making it equal to 6. Add 1 to the fifth element, making it equal to 2. Add 1 to the fifth element again, making it equal to 3. The greatest common divisor of all elements will then be equal to 3, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | 3
6 2 4
| 0 | 2.5 seconds | 256 megabytes | ['math', 'number theory', 'probabilities', '*2500'] |
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round.The round consists of n problems, numbered from 1 to n. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a_1, a_2, \dots, a_n, where a_i is the score of i-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 10^9. A harder problem should grant a strictly higher score than an easier problem. In other words, 1 \leq a_1 < a_2 < \dots < a_n \leq 10^9. The balance of the score distribution, defined as the number of triples (i, j, k) such that 1 \leq i < j < k \leq n and a_i + a_j = a_k, should be exactly m. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output -1.InputThe first and single line contains two integers n and m (1 \le n \le 5000, 0 \leq m \leq 10^9) — the number of problems and the required balance.OutputIf there is no solution, print a single integer -1.Otherwise, print a line containing n integers a_1, a_2, \dots, a_n, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInput
5 3
Output
4 5 9 13 18Input
8 0
Output
10 11 12 13 14 15 16 17
Input
4 10
Output
-1
NoteIn the first example, there are 3 triples (i, j, k) that contribute to the balance of the score distribution. (1, 2, 3) (1, 3, 4) (2, 4, 5) | 5 3
| 4 5 9 13 18 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'math', '*2200'] |
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with n vertices. The tree is rooted at vertex r, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices u and v, and it'll return a vertex w, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most \lfloor \frac{n}{2} \rfloor times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer n (2 \le n \le 1000), the number of vertices of the tree.Then you will read n-1 lines, the i-th of them has two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i), denoting there is an edge connecting vertices x_i and y_i. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1 \le u, v \le n) to find the lowest common ancestor of vertex u and v.After the query, read the result w as an integer.In case your query is invalid or you asked more than \lfloor \frac{n}{2} \rfloor queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex r, print "! r" and quit after that. This query does not count towards the \lfloor \frac{n}{2} \rfloor limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might 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 the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers n and r (2 \le n \le 1000, 1 \le r \le n), denoting the number of vertices and the vertex with Kuroni's hotel.The i-th of the next n-1 lines should contain two integers x_i and y_i (1 \le x_i, y_i \le n) — denoting there is an edge connecting vertex x_i and y_i.The edges presented should form a tree.ExampleInput
6
1 4
4 2
5 3
6 3
2 3
3
4
4
Output
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | 6
1 4
4 2
5 3
6 3
2 3
3
4
4
| ? 5 6 ? 3 1 ? 1 2 ! 4 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'interactive', 'trees', '*1900'] |
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces, Kuroni has to solve the following problem.He is given n numbers a_1, a_2, \dots, a_n. Help Kuroni to calculate \prod_{1\le i<j\le n} |a_i - a_j|. As result can be very big, output it modulo m.If you are not familiar with short notation, \prod_{1\le i<j\le n} |a_i - a_j| is equal to |a_1 - a_2|\cdot|a_1 - a_3|\cdot \dots \cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot \dots \cdot|a_2 - a_n| \cdot \dots \cdot |a_{n-1} - a_n|. In other words, this is the product of |a_i - a_j| for all 1\le i < j \le n.InputThe first line contains two integers n, m (2\le n \le 2\cdot 10^5, 1\le m \le 1000) — number of numbers and modulo.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).OutputOutput the single number — \prod_{1\le i<j\le n} |a_i - a_j| \bmod m.ExamplesInput
2 10
8 5
Output
3Input
3 12
1 4 5
Output
0Input
3 7
1 4 9
Output
1NoteIn the first sample, |8 - 5| = 3 \equiv 3 \bmod 10.In the second sample, |1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12.In the third sample, |1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7. | 2 10
8 5
| 3 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'math', 'number theory', '*1600'] |
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by n characters '(' or ')' is simple if its length n is even and positive, its first \frac{n}{2} characters are '(', and its last \frac{n}{2} characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string s (1 \le |s| \le 1000) formed by characters '(' and ')', where |s| is the length of s.OutputIn the first line, print an integer k — the minimum number of operations you have to apply. Then, print 2k lines describing the operations in the following format:For each operation, print a line containing an integer m — the number of characters in the subsequence you will remove.Then, print a line containing m integers 1 \le a_1 < a_2 < \dots < a_m — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest k, you may print any of them.ExamplesInput
(()((
Output
1
2
1 3
Input
)(
Output
0
Input
(()())
Output
1
4
1 2 5 6
NoteIn the first sample, the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '(((', and no more operations can be performed on it. Another valid answer is choosing indices 2 and 3, which results in the same final string.In the second sample, it is already impossible to perform any operations. | (()((
| 1 2 1 3 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'strings', 'two pointers', '*1200'] |
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets: the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different), the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the i-th daughter receives a necklace with brightness x_i and a bracelet with brightness y_i, then the sums x_i + y_i should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a = [1, 7, 5] and b = [6, 1, 2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a_3 + b_1 = 11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a_1 + b_3 = 3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a_2 + b_2 = 8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a_1 + b_1 = 7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a_2 + b_2 = 8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a_3 + b_3 = 7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer t (1 \le t \le 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 100) — the number of daughters, necklaces and bracelets.The second line of each test case contains n distinct integers a_1, a_2, \dots, a_n (1 \le a_i \le 1000) — the brightnesses of the necklaces.The third line of each test case contains n distinct integers b_1, b_2, \dots, b_n (1 \le b_i \le 1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing n integers x_1, x_2, \dots, x_n, representing that the i-th daughter receives a necklace with brightness x_i. In the next line print n integers y_1, y_2, \dots, y_n, representing that the i-th daughter receives a bracelet with brightness y_i.The sums x_1 + y_1, x_2 + y_2, \dots, x_n + y_n should all be distinct. The numbers x_1, \dots, x_n should be equal to the numbers a_1, \dots, a_n in some order, and the numbers y_1, \dots, y_n should be equal to the numbers b_1, \dots, b_n in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInput
2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
Output
1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case, it is enough to give the i-th necklace and the i-th bracelet to the i-th daughter. The corresponding sums are 1 + 8 = 9, 8 + 4 = 12, and 5 + 5 = 10.The second test case is described in the statement. | 2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
| 1 8 5 8 4 5 5 1 7 6 2 1 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'sortings', '*800'] |
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on k.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for n days, starting from day 1 to day n. The forest can be divided into m areas, numbered from 1 to m. He'll use the cameras in the following way: On every odd day (1-st, 3-rd, 5-th, ...), bring the red camera to the forest and record a video for 2 days. On every even day (2-nd, 4-th, 6-th, ...), bring the blue camera to the forest and record a video for 2 days. If he starts recording on the n-th day with one of the cameras, the camera records for only one day. Each camera can observe k consecutive areas of the forest. For example, if m=5 and k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3], [2,4], and [3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for n days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers n, m, and k (1 \le n \le 50, 1 \le m \le 2 \cdot 10^4, 1 \le k \le m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next n lines contain m integers each. The j-th integer in the i+1-st line is the number of animals that can be seen on the i-th day in the j-th area. Each number of animals is between 0 and 1000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInput
4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
Output
25
Input
3 3 1
1 2 3
4 5 6
7 8 9
Output
31
Input
3 3 2
1 2 3
4 5 6
7 8 9
Output
44
Input
3 3 3
1 2 3
4 5 6
7 8 9
Output
45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | 4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
| 25 | 3 seconds | 512 megabytes | ['data structures', 'dp', 'greedy', '*2400'] |
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on k.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for n days, starting from day 1 to day n. The forest can be divided into m areas, numbered from 1 to m. He'll use the cameras in the following way: On every odd day (1-st, 3-rd, 5-th, ...), bring the red camera to the forest and record a video for 2 days. On every even day (2-nd, 4-th, 6-th, ...), bring the blue camera to the forest and record a video for 2 days. If he starts recording on the n-th day with one of the cameras, the camera records for only one day. Each camera can observe k consecutive areas of the forest. For example, if m=5 and k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3], [2,4], and [3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for n days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers n, m, and k (1 \le n \le 50, 1 \le m \le 2 \cdot 10^4, 1 \le k \le min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next n lines contain m integers each. The j-th integer in the i+1-st line is the number of animals that can be seen on the i-th day in the j-th area. Each number of animals is between 0 and 1000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInput
4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
Output
25
Input
3 3 1
1 2 3
4 5 6
7 8 9
Output
31
Input
3 3 2
1 2 3
4 5 6
7 8 9
Output
44
Input
3 3 3
1 2 3
4 5 6
7 8 9
Output
45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | 4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
| 25 | 3 seconds | 512 megabytes | ['data structures', 'dp', '*2300'] |
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer n (3 \le n \le 10^5), the number of vertices of the tree.Next n-1 lines contain two integers u and v (1 \le u,v \le n, u \ne v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.Next line contains an integer q (1 \le q \le 10^5), the number of queries Gildong wants to ask.Next q lines contain five integers x, y, a, b, and k each (1 \le x,y,a,b \le n, x \ne y, 1 \le k \le 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInput
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 1-st query: 1 – 3 – 2 2-nd query: 1 – 2 – 3 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3 | 5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
| YES YES NO YES NO | 4 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'shortest paths', 'trees', '*2000'] |
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(n\log{n}) time for a sequence of length n. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of n distinct integers between 1 and n, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n-1, consisting of characters '<' and '>' only. The i-th (1-indexed) character is the comparison result between the i-th element and the i+1-st element of the sequence. If the i-th character of the string is '<', then the i-th element of the sequence is less than the i+1-st element. If the i-th character of the string is '>', then the i-th element of the sequence is greater than the i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of n distinct integers between 1 and n, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 10^4).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is n (2 \le n \le 2 \cdot 10^5), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n-1.It is guaranteed that the sum of all n in all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print two lines with n integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 1 and n, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInput
3
3 <<
7 >><>><
5 >>><
Output
1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case, 1 2 3 is the only possible answer.In the second case, the shortest length of the LIS is 2, and the longest length of the LIS is 3. In the example of the maximum LIS sequence, 4 '3' 1 7 '5' 2 '6' can be one of the possible LIS. | 3
3 <<
7 >><>><
5 >>><
| 1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 | 3 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', 'two pointers', '*1800'] |
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: t_i — the time (in minutes) when the i-th customer visits the restaurant, l_i — the lower bound of their preferred temperature range, and h_i — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the i-th customer is satisfied if and only if the temperature is between l_i and h_i (inclusive) in the t_i-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases q (1 \le q \le 500). Description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n \le 100, -10^9 \le m \le 10^9), where n is the number of reserved customers and m is the initial temperature of the restaurant.Next, n lines follow. The i-th line of them contains three integers t_i, l_i, and h_i (1 \le t_i \le 10^9, -10^9 \le l_i \le h_i \le 10^9), where t_i is the time when the i-th customer visits, l_i is the lower bound of their preferred temperature range, and h_i is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 0.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInput
4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
Output
YES
NO
YES
NO
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At 0-th minute, change the state to heating (the temperature is 0). At 2-nd minute, change the state to off (the temperature is 2). At 5-th minute, change the state to heating (the temperature is 2, the 1-st customer is satisfied). At 6-th minute, change the state to off (the temperature is 3). At 7-th minute, change the state to cooling (the temperature is 3, the 2-nd customer is satisfied). At 10-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 0-th minute and leave it be. Then all customers will be satisfied. Note that the 1-st customer's visit time equals the 2-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | 4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
| YES NO YES NO | 1 second | 256 megabytes | ['dp', 'greedy', 'implementation', 'sortings', 'two pointers', '*1500'] |
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers n and m (1 \le n \le 100, 1 \le m \le 50) — the number of strings and the length of each string.Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInput
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
NoteIn the first example, "battab" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string. | 3 3
tab
one
bat
| 6 tabbat | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'implementation', 'strings', '*1100'] |
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position x, and the shorter rabbit is currently on position y (x \lt y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by a, and the shorter rabbit hops to the negative direction by b. For example, let's say x=0, y=10, a=2, and b=3. At the 1-st second, each rabbit will be at position 2 and 7. At the 2-nd second, both rabbits will be at position 4.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 1000).Each test case contains exactly one line. The line consists of four integers x, y, a, b (0 \le x \lt y \le 10^9, 1 \le a,b \le 10^9) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print -1.ExampleInput
5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
Output
2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case, each rabbit will be at position 3 and 7 respectively at the 1-st second. But in the 2-nd second they will be at 6 and 4 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | 5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
| 2 -1 10 -1 1 | 1 second | 256 megabytes | ['math', '*800'] |
G. Sum of Prefix Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe define the sum of prefix sums of an array [s_1, s_2, \dots, s_k] as s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + \dots + (s_1 + s_2 + \dots + s_k).You are given a tree consisting of n vertices. Each vertex i has an integer a_i written on it. We define the value of the simple path from vertex u to vertex v as follows: consider all vertices appearing on the path from u to v, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.InputThe first line contains one integer n (2 \le n \le 150000) — the number of vertices in the tree.Then n - 1 lines follow, representing the edges of the tree. Each line contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i), denoting an edge between vertices u_i and v_i. It is guaranteed that these edges form a tree.The last line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^6).OutputPrint one integer — the maximum value over all paths in the tree.ExampleInput
4
4 2
3 2
4 1
1 3 3 7
Output
36
NoteThe best path in the first example is from vertex 3 to vertex 1. It gives the sequence [3, 3, 7, 1], and the sum of prefix sums is 36. | 4
4 2
3 2
4 1
1 3 3 7
| 36 | 6 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'geometry', 'trees', '*2700'] |
F. Number of Componentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix n \times m, initially filled with zeroes. We define a_{i, j} as the element in the i-th row and the j-th column of the matrix.Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence s_1, s_2, ..., s_k such that s_1 is the first cell, s_k is the second cell, and for every i \in [1, k - 1], s_i and s_{i + 1} are connected.You are given q queries of the form x_i y_i c_i (i \in [1, q]). For every such query, you have to do the following: replace the element a_{x, y} with c; count the number of connected components in the matrix. There is one additional constraint: for every i \in [1, q - 1], c_i \le c_{i + 1}.InputThe first line contains three integers n, m and q (1 \le n, m \le 300, 1 \le q \le 2 \cdot 10^6) — the number of rows, the number of columns and the number of queries, respectively.Then q lines follow, each representing a query. The i-th line contains three integers x_i, y_i and c_i (1 \le x_i \le n, 1 \le y_i \le m, 1 \le c_i \le \max(1000, \lceil \frac{2 \cdot 10^6}{nm} \rceil)). For every i \in [1, q - 1], c_i \le c_{i + 1}.OutputPrint q integers, the i-th of them should be equal to the number of components in the matrix after the first i queries are performed.ExampleInput
3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
Output
2
4
3
3
4
4
4
2
2
4
| 3 2 10
2 1 1
1 2 1
2 2 1
1 1 2
3 1 2
1 2 2
2 2 2
2 1 2
3 2 4
2 1 5
| 2 4 3 3 4 4 4 2 2 4 | 4 seconds | 256 megabytes | ['dsu', 'implementation', '*2800'] |
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s. You can build new string p from s using the following operation no more than two times: choose any subsequence s_{i_1}, s_{i_2}, \dots, s_{i_k} where 1 \le i_1 < i_2 < \dots < i_k \le |s|; erase the chosen subsequence from s (s can become empty); concatenate chosen subsequence to the right of the string p (in other words, p = p + s_{i_1}s_{i_2}\dots s_{i_k}). Of course, initially the string p is empty. For example, let s = \text{ababcd}. At first, let's choose subsequence s_1 s_4 s_5 = \text{abc} — we will get s = \text{bad} and p = \text{abc}. At second, let's choose s_1 s_2 = \text{ba} — we will get s = \text{d} and p = \text{abcba}. So we can build \text{abcba} from \text{ababcd}.Can you build a given string t using the algorithm above?InputThe first line contains the single integer T (1 \le T \le 100) — the number of test cases.Next 2T lines contain test cases — two per test case. The first line contains string s consisting of lowercase Latin letters (1 \le |s| \le 400) — the initial string.The second line contains string t consisting of lowercase Latin letters (1 \le |t| \le |s|) — the string you'd like to build.It's guaranteed that the total length of strings s doesn't exceed 400.OutputPrint T answers — one per test case. Print YES (case insensitive) if it's possible to build t and NO (case insensitive) otherwise.ExampleInput
4
ababcd
abcba
a
b
defi
fed
xyz
x
Output
YES
NO
NO
YES
| 4
ababcd
abcba
a
b
defi
fed
xyz
x
| YES NO NO YES | 2 seconds | 256 megabytes | ['dp', 'strings', '*2200'] |
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into two parts of size 16, and then divide the box of size 16. So you can fill the bag with boxes of size 1, 1 and 8.Calculate the minimum number of divisions required to fill the bag of size n.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and m (1 \le n \le 10^{18}, 1 \le m \le 10^5) — the size of bag and the number of boxes, respectively.The second line of each test case contains m integers a_1, a_2, \dots , a_m (1 \le a_i \le 10^9) — the sizes of boxes. It is guaranteed that each a_i is a power of two.It is also guaranteed that sum of all m over all test cases does not exceed 10^5.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size n (or -1, if it is impossible).ExampleInput
3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
Output
2
-1
0
| 3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
| 2 -1 0 | 2 seconds | 256 megabytes | ['bitmasks', 'greedy', '*1900'] |
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all 26 lowercase Latin letters will be arranged in some order.Polycarp uses the same password s on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in s, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in s, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer T (1 \le T \le 1000) — the number of test cases.Then T lines follow, each containing one string s (1 \le |s| \le 200) representing the test case. s consists of lowercase Latin letters only. There are no two adjacent equal characters in s.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 26 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInput
5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
Output
YES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| 5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
| YES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO | 2 seconds | 256 megabytes | ['dfs and similar', 'greedy', 'implementation', '*1600'] |
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, \dots, g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer T (1 \le T \le 10^4) — the number of test cases.Next T lines contain test cases — one per line. Each line contains three integers n, g and b (1 \le n, g, b \le 10^9) — the length of the highway and the number of good and bad days respectively.OutputPrint T integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInput
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
NoteIn the first test case, you can just lay new asphalt each day, since days 1, 3, 5 are good.In the second test case, you can also lay new asphalt each day, since days 1-8 are good. | 3
5 1 1
8 10 10
1000000 1 1000000
| 5 8 499999500000 | 2 seconds | 256 megabytes | ['math', '*1400'] |
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Then t lines follow, each representing a test case. Each line contains one string s (1 \le |s| \le 100); each character of s is either 0 or 1.OutputPrint t integers, where the i-th integer is the answer to the i-th testcase (the minimum number of 0's that you have to erase from s).ExampleInput
3
010011
0
1111000
Output
2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | 3
010011
0
1111000
| 2 0 0 | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
F. Keep talking and nobody explodes – easytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an unusual problem in an unusual contest, here is the announcement: http://codeforces.com/blog/entry/73543You have the safe lock which consists of 5 decimal digits. If you rotate some digit, it increases by one, except 9 which becomes 0.Initially, the lock contains number x. To unlock the safe you must do the following operations in order (and be careful, don't mix up if and else statements).If sum of digits on positions 1 and 4 is greater than 10, rotate digit on position 1 by 3 times, else rotate digit on position 4 by 8 times.If sum of digits on positions 3 and 2 is greater than 8, rotate digit on position 4 by 9 times, else rotate digit on position 5 by 8 times.If digit on position 3 is odd, rotate digit on position 3 by 3 times, else rotate digit on position 3 by 4 times.If digit on position 5 is greater than digit on position 2, rotate digit on position 4 by 1 times, else rotate digit on position 2 by 7 times.If digit on position 1 is odd, rotate digit on position 1 by 3 times, else rotate digit on position 3 by 5 times.If digit on position 4 is odd, rotate digit on position 4 by 7 times, else rotate digit on position 1 by 9 times.If digit on position 4 is greater than digit on position 1, rotate digit on position 4 by 9 times, else rotate digit on position 4 by 2 times.If digit on position 1 is greater than digit on position 3, rotate digit on position 2 by 1 times, else rotate digit on position 3 by 1 times.If digit on position 5 is greater than digit on position 3, rotate digit on position 4 by 5 times, else rotate digit on position 5 by 8 times.If sum of digits on positions 1 and 3 is greater than 8, rotate digit on position 4 by 5 times, else rotate digit on position 2 by 5 times.If digit on position 1 is greater than digit on position 4, rotate digit on position 4 by 3 times, else rotate digit on position 2 by 3 times.If sum of digits on positions 3 and 1 is greater than 9, rotate digit on position 2 by 9 times, else rotate digit on position 2 by 2 times.If sum of digits on positions 4 and 3 is greater than 10, rotate digit on position 4 by 7 times, else rotate digit on position 5 by 7 times.If digit on position 3 is greater than digit on position 2, rotate digit on position 3 by 2 times, else rotate digit on position 4 by 6 times.If digit on position 1 is greater than digit on position 3, rotate digit on position 1 by 9 times, else rotate digit on position 2 by 9 times.If digit on position 3 is odd, rotate digit on position 3 by 9 times, else rotate digit on position 1 by 5 times.If sum of digits on positions 3 and 5 is greater than 9, rotate digit on position 3 by 4 times, else rotate digit on position 3 by 9 times.If digit on position 3 is greater than digit on position 1, rotate digit on position 5 by 1 times, else rotate digit on position 5 by 7 times.If digit on position 1 is greater than digit on position 3, rotate digit on position 2 by 9 times, else rotate digit on position 4 by 6 times.If sum of digits on positions 2 and 3 is greater than 10, rotate digit on position 2 by 2 times, else rotate digit on position 3 by 6 times.InputInput contains single number x consisting of exactly 5 digits, leading zeroes are allowed.OutputOutput the number after applying all operations.ExamplesInput
00000
Output
61376
Input
12345
Output
07769
| 00000
| 61376 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'expression parsing'] |
C. Segment tree or Fenwick?time limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an unusual problem in an unusual contest, here is the announcement: http://codeforces.com/blog/entry/73543You are given an array A of length n, initially filled with zeros. You need to process q queries to the array, each of one of the following types: 1 x y: you need to assign A_x=y; 2 l r: you need to print \sum\limits_{i=l}^r A_i. Furthermore, there are T independent tests you need to process.InputThe first line contains an integer T (1 \leq T \leq 10^5) — the number of test cases.Each test case description starts with two integers n, q (1 \leq n, q \leq 10^5) — the length of the array and the number of queries. The following q lines contain the description of queries: 1~x~y (1 \leq x \leq n, 0 \leq y \leq 10^9) for queries of the first type and 2~l~r (1 \leq l \leq r \leq n) for queries of the second type. It is guaranteed that the sum of n as well as the sum of q does not exceed 10^6.OutputFor each query of the second type print its result on a separate line.ExampleInput
2
6 5
2 1 6
1 3 2
2 2 4
1 6 3
2 1 6
5 3
1 3 7
1 1 4
2 1 5
Output
0
2
5
11
| 2
6 5
2 1 6
1 3 2
2 2 4
1 6 3
2 1 6
5 3
1 3 7
1 1 4
2 1 5
| 0 2 5 11 | 2.5 seconds | 256 megabytes | ['data structures'] |
B. DAGtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an unusual problem in an unusual contest, here is the announcement: http://codeforces.com/blog/entry/73543You are given a directed acyclic graph G with n vertices and m edges. Denote by R(v) the set of all vertices u reachable from v by moving along the edges of G. Find \sum\limits_{v=1}^n |R(v)|^2.InputThe first line contains two integers n, m (1 \leq n, m \leq 5 \cdot 10^4) denoting the number of vertices and the number of edges of G.Each of the next m lines contains two integers u, v (1 \leq u \neq v \leq n), denoting the edge from u to v. It's guaranteed that the given graph does not contain any cycles.OutputPrint one integer — the answer to the problem.ExamplesInput
5 4
1 2
2 3
3 4
4 5
Output
55
Input
12 6
1 2
3 4
5 6
8 7
10 9
12 11
Output
30
Input
7 6
1 2
1 3
2 4
2 5
3 6
3 7
Output
45
| 5 4
1 2
2 3
3 4
4 5
| 55 | 3 seconds | 256 megabytes | ['constructive algorithms'] |
F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with n rows and m columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 1 and k. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do q missions. In every mission he will be in the city at row r_1 and column c_1, and he should help someone in the city at row r_2 and column c_2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers n, m and k (1 \leq n, m \leq 1000, 1 \leq k \leq min(40 , n \cdot m)) — the number of rows, columns and colors.Each of the next n lines contains m integers. In the i-th line, the j-th integer is a_{ij} (1 \leq a_{ij} \leq k), which is the color assigned to the city in the i-th row and j-th column.The next line contains one integer q (1 \leq q \leq 10^{5}) — the number of missions.For the next q lines, every line contains four integers r_1, c_1, r_2, c_2 (1 \leq r_1 , r_2 \leq n, 1 \leq c_1 , c_2 \leq m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 1 and k there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r_2, c_2) starting from city at the cell (r_1, c_1).ExamplesInput
3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
Output
2
0
Input
4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
Output
2
3
3
4
NoteIn the first example: mission 1: Jaber should go from the cell (1,1) to the cell (3,3) because they have the same colors, then from the cell (3,3) to the cell (3,4) because they are adjacent by side (two moves in total); mission 2: Jaber already starts in the finishing cell. In the second example: mission 1: (1,1) \rightarrow (1,2) \rightarrow (2,2); mission 2: (1,1) \rightarrow (3,2) \rightarrow (3,3) \rightarrow (3,4); mission 3: (1,1) \rightarrow (3,2) \rightarrow (3,3) \rightarrow (2,4); mission 4: (1,1) \rightarrow (1,2) \rightarrow (1,3) \rightarrow (1,4) \rightarrow (4,4). | 3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
| 2 0 | 5 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'implementation', 'shortest paths', '*2600'] |
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers n, m and q (1 \leq n , m \leq 500, 1 \leq q \leq 3 \cdot 10^{5}) — the number of row, the number columns and the number of options.For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 \leq r_1 \leq r_2 \leq n, 1 \leq c_1 \leq c_2 \leq m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0.ExamplesInput
5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
Output
16
4
4
4
0
Input
6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
Output
36
4
16
16
16
Input
8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
Output
64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. | 5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
| 16 4 4 4 0 | 2 seconds | 512 megabytes | ['binary search', 'data structures', 'dp', 'implementation', '*2500'] |
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to: in the case 'U' to the cell (i-1, j); in the case 'D' to the cell (i+1, j); in the case 'L' to the cell (i, j-1); in the case 'R' to the cell (i, j+1); He wants to run exactly k kilometers, so he wants to make exactly k moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?InputThe only line contains three integers n, m and k (1 \leq n, m \leq 500, 1 \leq k \leq 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer a (1 \leq a \leq 3000) — the number of steps, then print a lines describing the steps.To describe a step, print an integer f (1 \leq f \leq 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.ExamplesInput
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running): | 3 3 4
| YES 2 2 R 2 L | 1 second | 256 megabytes | ['constructive algorithms', 'graphs', 'implementation', '*2000'] |
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 \leq l \leq r \leq |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, \ldots, s_r is equal to "1". For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers n, m (1 \leq n \leq 10^{9}, 0 \leq m \leq n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".ExampleInput
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
NoteIn the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.In the second test case, the string s with the maximum value is "101".In the third test case, the string s with the maximum value is "111".In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement. | 5
3 1
3 2
3 3
4 0
5 2
| 4 5 6 0 12 | 1 second | 256 megabytes | ['binary search', 'combinatorics', 'greedy', 'math', 'strings', '*1700'] |
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer k (0 \leq k \leq 10^{9}) and replaces all missing elements in the array a with k.Let m be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |a_i - a_{i+1}| for all 1 \leq i \leq n - 1) in the array a after Dark replaces all missing elements with k.Dark should choose an integer k so that m is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer n (2 \leq n \leq 10^{5}) — the size of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-1 \leq a_i \leq 10 ^ {9}). If a_i = -1, then the i-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of n for all test cases does not exceed 4 \cdot 10 ^ {5}.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of m and an integer k (0 \leq k \leq 10^{9}) that makes the maximum absolute difference between adjacent elements in the array a equal to m.Make sure that after replacing all the missing elements with k, the maximum absolute difference between adjacent elements becomes m.If there is more than one possible k, you can print any of them.ExampleInput
7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
Output
1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 11 the array becomes [11, 10, 11, 12, 11]. The absolute difference between any adjacent elements is 1. It is impossible to choose a value of k, such that the absolute difference between any adjacent element will be \leq 0. So, the answer is 1.In the third test case after replacing all missing elements with 6 the array becomes [6, 6, 9, 6, 3, 6]. |a_1 - a_2| = |6 - 6| = 0; |a_2 - a_3| = |6 - 9| = 3; |a_3 - a_4| = |9 - 6| = 3; |a_4 - a_5| = |6 - 3| = 3; |a_5 - a_6| = |3 - 6| = 3. So, the maximum difference between any adjacent elements is 3. | 7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
| 1 11 5 35 3 6 0 42 0 0 1 2 3 4 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'ternary search', '*1500'] |
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i.For every i (1 \leq i \leq n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly n swap operations, each of them either c_i \leftrightarrow a_i or c_i \leftrightarrow b_i (i iterates over all integers between 1 and n, inclusive).For example, if a is "code", b is "true", and c is "help", you can make c equal to "crue" taking the 1-st and the 4-th letters from a and the others from b. In this way a becomes "hodp" and b becomes "tele".Is it possible that after these swaps the string a becomes exactly the same as the string b?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters a.The second line of each test case contains a string of lowercase English letters b.The third line of each test case contains a string of lowercase English letters c.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100.OutputPrint t lines with answers for all test cases. For each test case:If it is possible to make string a equal to string b print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInput
4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
Output
NO
YES
YES
NO
NoteIn the first test case, it is impossible to do the swaps so that string a becomes exactly the same as string b.In the second test case, you should swap c_i with a_i for all possible i. After the swaps a becomes "bca", b becomes "bca" and c becomes "abc". Here the strings a and b are equal.In the third test case, you should swap c_1 with a_1, c_2 with b_2, c_3 with b_3 and c_4 with a_4. Then string a becomes "baba", string b becomes "baba" and string c becomes "abab". Here the strings a and b are equal.In the fourth test case, it is impossible to do the swaps so that string a becomes exactly the same as string b. | 4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
| NO YES YES NO | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a_1, a_2, \dots, a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, \dots, b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}.There are 2n students, the i-th student has skill level a_i. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 2 classes such that each class has odd number of students (not divisible by 2). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of students halved.The second line of each test case contains 2n integers a_1, a_2, \dots, a_{2 n} (1 \le a_i \le 10^9) — skill levels of students.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInput
3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
Output
0
1
5
NoteIn the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1 - 1| = 0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6, 4, 2], so that the skill level of the first class will be 4, and second with [5, 1, 3], so that the skill level of the second class will be 3. Absolute difference will be |4 - 3| = 1.Note that you can't assign like [2, 3], [6, 5, 4, 1] or [], [6, 5, 4, 1, 2, 3] because classes have even number of students.[2], [1, 3, 4] is also not possible because students with skills 5 and 6 aren't assigned to a class.In the third test you can assign the students in the following way: [3, 4, 13, 13, 20], [2, 5, 8, 16, 17] or [3, 8, 17], [2, 4, 5, 13, 13, 16, 20]. Both divisions give minimal possible absolute difference. | 3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
| 0 1 5 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1000'] |
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array a of n integers [a_1, a_2, \dots, a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 \le i \le n) and do a_i := a_i + 1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a_1 + a_2 + \dots + a_n \ne 0 and a_1 \cdot a_2 \cdot \dots \cdot a_n \ne 0.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3). The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 100) — the size of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-100 \le a_i \le 100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInput
4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
Output
1
2
0
2
NoteIn the first test case, the sum is 0. If we add 1 to the first element, the array will be [3,-1,-1], the sum will be equal to 1 and the product will be equal to 3.In the second test case, both product and sum are 0. If we add 1 to the second and the third element, the array will be [-1,1,1,1], the sum will be equal to 2 and the product will be equal to -1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 1 twice to the first element the array will be [2,-2,1], the sum will be 1 and the product will be -4. | 4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
| 1 2 0 2 | 1 second | 256 megabytes | ['implementation', 'math', '*800'] |
E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p_1, p_2, \dots, p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries:? k a_1 a_2 \dots a_k.In response, you will learn if the average of elements with indexes a_1, a_2, \dots, a_k is an integer. In other words, you will receive 1 if \frac{p_{a_1} + p_{a_2} + \dots + p_{a_k}}{k} is integer, and 0 otherwise. You have to guess the permutation. You can ask not more than 18n queries.Note that permutations [p_1, p_2, \dots, p_k] and [n + 1 - p_1, n + 1 - p_2, \dots, n + 1 - p_k] are indistinguishable. Therefore, you are guaranteed that p_1 \le \frac{n}{2}.Note that the permutation p is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer n (2 \le n \le 800, n is even).InteractionYou begin the interaction by reading n.To ask a question about elements on positions a_1, a_2, \dots, a_k, in a separate line output? k a_1 a_2 ... a_kNumbers in the query have to satisfy 1 \le a_i \le n, and all a_i have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 1 if \frac{p_{a_1} + p_{a_2} + \dots + p_{a_k}}{k} is integer, and 0 otherwise. In case your query is invalid or you asked more than 18n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output ! p_1 p_2 ... p_nAfter 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.Hack formatFor the hacks use the following format:The first line has to contain a single integer n (2 \le n \le 800, n is even).In the next line output n integers p_1, p_2, \dots, p_n — the valid permutation of numbers from 1 to n. p_1 \le \frac{n}{2} must hold.ExampleInput
2
1 2
Output
? 1 2
? 1 1
! 1 2
| 2
1 2
| ? 1 2 ? 1 1 ! 1 2 | 4 seconds | 256 megabytes | ['interactive', 'math', '*3400'] |
D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144 trips around the world.You are given a simple weighted undirected connected graph with n vertexes and m edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 3 which passes through the vertex 1. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 0 aren't exciting. You may choose any subset of edges incident to the vertex 1 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 0 which passes through the vertex 1 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 10^9+7.InputThe first line contains two integers n and m (1 \le n,m \le 10^5) — the number of vertexes and edges in the graph. The i-th of the next m lines contains three integers a_i, b_i and w_i (1 \le a_i, b_i \le n, a_i \neq b_i, 0 \le w_i < 32) — the endpoints of the i-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 3 which passes through the vertex 1.OutputOutput the answer modulo 10^9+7.ExamplesInput
6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
Output
2
Input
7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
Output
1
Input
4 4
1 2 27
1 3 1
1 4 1
3 4 0
Output
6NoteThe pictures below represent the graphs from examples. In the first example, there aren't any nontrivial cycles with cost 0, so we can either remove or keep the only edge incident to the vertex 1. In the second example, if we don't remove the edge 1-2, then there is a cycle 1-2-4-5-2-1 with cost 0; also if we don't remove the edge 1-3, then there is a cycle 1-3-2-4-5-2-3-1 of cost 0. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1-3 and 1-4 are kept. | 6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
| 2 | 2 seconds | 512 megabytes | ['bitmasks', 'combinatorics', 'dfs and similar', 'dp', 'graphs', 'graphs', 'math', 'trees', '*3000'] |
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.You can perform the following operation: choose some subsegment [l, r] (1\le l \le r \le n), and redistribute water in tanks l, l+1, \dots, r evenly. In other words, replace each of a_l, a_{l+1}, \dots, a_r by \frac{a_l + a_{l+1} + \dots + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b.InputThe first line contains an integer n (1 \le n \le 10^6) — the number of water tanks.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank.Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}.Formally, let your answer be a_1, a_2, \dots, a_n, and the jury's answer be b_1, b_2, \dots, b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{\max{(1, |b_i|)}} \le 10^{-9} for each i.ExamplesInput
4
7 5 5 7
Output
5.666666667
5.666666667
5.666666667
7.000000000
Input
5
7 8 8 10 12
Output
7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
Input
10
3 9 5 5 1 7 5 3 8 7
Output
3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample, you can get the sequence by applying the operation for subsegment [1, 3].In the second sample, you can't get any lexicographically smaller sequence. | 4
7 5 5 7
| 5.666666667 5.666666667 5.666666667 7.000000000 | 3 seconds | 256 megabytes | ['data structures', 'geometry', 'greedy', '*2100'] |
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation:Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are similar.InputThe first line of input will contain a single integer n (3 \le n \le 10^5) — the number of points.The i-th of the next n lines contains two integers x_i, y_i (|x_i|, |y_i| \le 10^9), denoting the coordinates of the i-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if P and T are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInput
4
1 0
4 1
3 4
0 3
Output
YESInput
3
100 86
50 0
150 0
Output
nOInput
8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
Output
YESNoteThe following image shows the first sample: both P and T are squares. The second sample was shown in the statements. | 4
1 0
4 1
3 4
0 3
| YES | 1 second | 256 megabytes | ['geometry', '*1800'] |
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function f: f(x, y) = (x | y) - y where | denotes the bitwise OR operation. For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a_1, a_2, \dots, a_n] is defined as f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer n (1 \le n \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9). Elements of the array are not guaranteed to be different.OutputOutput n integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInput
4
4 0 11 6
Output
11 6 4 0Input
1
13
Output
13 NoteIn the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.[11, 4, 0, 6] is also a valid answer. | 4
4 0 11 6
| 11 6 4 0 | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', '*1500'] |
I. Falling Blockstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently, Polycarp has invented a new mobile game with falling blocks.In the game, n blocks are falling down, one at a time, towards a flat surface with length d units. Each block can be represented as a rectangle with coordinates from l_i to r_i and unit height, dropped downwards from very high up. A block falls until it comes in contact with the flat surface or any other block. Let's define that block a covers block b if l_a \le l_b \le r_b \le r_a. Consider what happens when a new block i falls. If the new (upper) block i comes in contact with any block j such that block i does not cover block j, block i will stick to block j, and no blocks will disappear. Otherwise, all blocks that block i covers and is in contact with will be vaporized, and block i will continue falling with the ability to vaporize lower blocks.For example, consider what happens when three blocks (1,2), (2,3) and (1,3) fall, in that order. The first block will stick to the flat surface. Then, the second block will stick to the first block. Finally, the third block will vaporize the second block, keep falling, vaporize the first block, and stick to the flat surface. Here is a graphic for the first example. After each block falls, help Polycarp determine how many blocks will remain!InputThe first line contains two integers n and d (1 \le n, d \le 10^5) — the number of falling blocks and the length of the flat surface.The i-th of the following n lines contains integers l_i and r_i (1 \le l_i \le r_i \le d) — the coordinates of the i-th block. OutputOutput n integers. The i-th integer should be the number of blocks that will be left after the i-th block falls.ExamplesInput
3 3
1 2
2 3
1 3
Output
1
2
1
Input
8 6
1 2
3 3
2 3
1 3
2 4
3 6
1 5
1 5
Output
1
2
3
1
2
3
4
4
NoteThe first example is explained above.In the second example, this is what happens after each block falls: Block 1 will stick to the flat surface. Block 2 will stick to the flat surface. Block 3 will stick to blocks 1 and 2. Note that block 3 will not vaporize block 2 because it does not cover block 1 and is in contact with it. Block 4 will vaporize all the blocks and stick to the flat surface. Block 5 will stick to block 4 Block 6 will stick to block 5. Block 7 will stick to block 6. Note that no blocks are vaporized because although block 7 covers block 4 and block 5, they never come in contact. Block 8 vaporizes block 7 and sticks to block 6. | 3 3
1 2
2 3
1 3
| 1 2 1 | 3 seconds | 512 megabytes | ['*special problem', 'data structures'] |
H. Paint the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of lowercase Latin letters. It is required to paint each letter of the string in one of two colors (red or blue) so that if you write all the red letters from left to right and write all the blue letters from left to right, then the lexicographically maximum of the two written strings is lexicographically minimal. For each index, in the string s you can choose either of two colors.Formally, we write out: the string r (can be empty) — all red letters in the order from left to right (red subsequence), the string b (can be empty) — all blue letters in the order from left to right (blue subsequence). Your task is to paint the string such that \max(r, b) is minimal. Small reminder: the empty string is the lexicographically smallest string.InputThe first line contains an integer t (1 \le t \le 100) — the number of test cases in the test. Next, the test cases are given, one per line.Each test case is a non-empty string s of length between 2 to 100 characters, inclusive, which consists of lowercase Latin letters.OutputPrint t lines, the i-th of them should contain the answer to the i-th test case of the input. Print a string of length n, where n is the length of the given string s: the j-th character of the string should be either 'R'or 'B' depending on the color of the j-th character in the answer (painted in red or blue). If there are several possible answers, print any of them.ExampleInput
5
kotlin
codeforces
abacaba
ffccgc
yz
Output
RRRRBB
RRRRRRRBBB
RRRRBBB
RBBBBR
RR
| 5
kotlin
codeforces
abacaba
ffccgc
yz
| RRRRBB RRRRRRRBBB RRRRBBB RBBBBR RR | 1 second | 256 megabytes | ['*special problem', 'dp', 'strings'] |
G. M-numberstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a given positive integer m, a positive number is called a m-number if the product of its digits is m. For example, the beginning of a series of 24-numbers are as follows: 38, 46, 64, 83, 138, 146, 164, 183, 226 ...You are given a positive integer m and k. Print k-th among m-numbers if all m-numbers are sorted in ascending order.InputA single line of input contains two integers m and k (2 \le m \le 10^9, 1 \le k \le 10^9).OutputPrint the desired number — k-th among all m-numbers if m-numbers are sorted in ascending order. If the answer does not exist, print -1.ExamplesInput
24 9
Output
226
Input
24 1
Output
38
Input
5040 1000000000
Output
111121111315213227111
Input
2020 2020
Output
-1
| 24 9
| 226 | 3 seconds | 256 megabytes | ['*special problem', 'dp', 'math'] |
F. Movie Fantime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Polycarp has been a fan of cinema novelties and is trying not to miss them!In the near future, n new movies will be released: the i-th of them will be airing from the day a_i and to the day b_i. This means that if Polycarp wants to watch the i-th movie in the cinema, he must do so in the period from a_i to b_i inclusive.If perhaps Polycarp will not have the opportunity to watch a movie in a cinema, he can then do it after day b_i by watching it using an online service. Of course, this is an undesirable outcome for Polycarp because the whole world will have time to discuss this movie on social networks!Polycarp can watch no more than m movies per day. Help Polycarp find a movie-watching schedule such that every movie will be watched in the cinema. If such a schedule does not exist, then Polycarp wants to watch movies so that: for each movie that he doesn't have time to watch in the cinema, we will find the number of days between the end of its airing and the day when Polycarpus watches the movie, the maximum of the values from the previous point should be as small as possible. InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. The following are descriptions of the t test cases.The first line of each test case contains two integers n and m (1 \le n \le 2 \cdot 10^5, 1 \le m \le 10^9) — the number of movies and the maximum number of movies that Polycarp can view per day.In the next n lines, the movies themselves are described, one per line, by a pair of integers a_i, b_i (1 \le a_i \le b_i \le 10^9) — the first and last airing days for the i-th movie.It is guaranteed that the sum of the values n for all test cases in the input does not exceed 2 \cdot 10^5.OutputPrint t answers to given test cases in the order in which they appear in the input: the i-th answer should consist of two lines. Print the integer d in the first line of each test case answer: d=0, if there is a schedule such that all movies are watched during airing, d>0, if such a schedule does not exist — in this case, d is equal to the minimum value of maximum among all the watching "delays" after the end of airing. In the second line of the answer to each test case, print n positive integers t_1, t_2, \dots, t_n, where t_i is the number of the day when Polycarp needs to watch the i-th movie in the optimal schedule.If there are several answers, print any of them.ExampleInput
3
7 2
1 2
1 3
2 2
2 3
1 1
2 3
1 2
5 3
1 1
1 1
1 1
1 1
1 1
6 1
13 13
31 31
25 25
12 12
14 14
10 10
Output
1
1 3 2 3 1 4 2
1
1 1 1 2 2
0
13 31 25 12 14 10
| 3
7 2
1 2
1 3
2 2
2 3
1 1
2 3
1 2
5 3
1 1
1 1
1 1
1 1
1 1
6 1
13 13
31 31
25 25
12 12
14 14
10 10
| 1 1 3 2 3 1 4 2 1 1 1 1 2 2 0 13 31 25 12 14 10 | 3 seconds | 256 megabytes | ['*special problem', 'data structures', 'greedy', 'implementation', 'sortings'] |
E. Modernization of Treelandtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of n cities and n-1 two-way roads connecting pairs of cities. From every city, you can reach every other city moving only by the roads. You are right, the system of cities and roads in this country forms an undirected tree.The government has announced a program for the modernization of urban infrastructure of some cities. You have been assigned to select an arbitrary subset of cities S to upgrade (potentially all the cities) that satisfies the following requirements: the subset of cities must be "connected", that is, from any city of the subset S you can get to any other city of the subset S by roads, moving only through cities from S, the number of "dead-ends" in S must be equal to the given number k. A city is a "dead-end" if it is the only city in S or connected to exactly one another city from S. This shows one of the possible ways to select S (blue vertices) for a given configuration and k=4. Dead-ends are vertices with numbers 1, 4, 6 and 7. Help Treeland upgrade its cities. Find any of the possible subsets S or determine that such a subset does not exist.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. This is followed by the test cases themselves.Each test case begins with a line that contains two integers n and k (2 \le n \le 3 \cdot 10^5, 1 \le k \le n) — the number of cities in Treeland and the number of "dead-end" cities required in the subset S.This is followed by n-1 lines with road descriptions. Each road is given by two integers x and y (1 \le x, y \le n; x \ne y) — the numbers of the cities that are connected by this road. It is guaranteed that from every city you can reach any other, moving only by the roads.The sum of the values of n for all test cases in the input does not exceed 3 \cdot 10^5.OutputFor each test case print Yes or No (in any case, upper or lower), depending on whether the answer exists or not. If the answer exists, then print an integer m (1 \le m \le n) — the number of cities in the found subset. Then print m different numbers from 1 to n — the numbers of the cities in the found subset. City numbers can be printed in any order. If there are several answers, print any of them.ExampleInput
4
10 4
4 5
5 2
2 1
1 3
1 9
9 10
2 7
7 8
5 6
4 3
1 2
2 3
3 4
5 3
1 2
1 3
1 4
1 5
4 1
1 2
2 4
2 3
Output
Yes
9
1 2 4 5 6 7 8 9 10
No
Yes
4
1 3 4 5
Yes
1
4
| 4
10 4
4 5
5 2
2 1
1 3
1 9
9 10
2 7
7 8
5 6
4 3
1 2
2 3
3 4
5 3
1 2
1 3
1 4
1 5
4 1
1 2
2 4
2 3
| Yes 9 1 2 4 5 6 7 8 9 10 No Yes 4 1 3 4 5 Yes 1 4 | 5 seconds | 256 megabytes | ['*special problem', 'dfs and similar', 'trees'] |
D. Bonus Distribution time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor the first time, Polycarp's startup ended the year with a profit! Now he is about to distribute k burles as a bonus among n employees.It is known that the current salary of the i-th employee is a_i and all the values of a_i in the company are different.Polycarp wants to distribute the k burles between n employees so this month the i-th employee will be paid not a_i, but a_i+d_i (d_i \ge 0, d_i is an integer), where d_i is the bonus for the i-th employee. Of course, d_1+d_2+\dots+d_n=k.Polycarp will follow two rules for choosing the values d_i: the relative order of the salaries should not be changed: the employee with originally the highest salary (a_i is the maximum) should have the highest total payment after receiving their bonus (a_i+d_i is also the maximum), the employee whose salary was originally the second-largest should receive the second-largest total payment after receiving their bonus and so on. to emphasize that annual profit is a group effort, Polycarp wants to minimize the maximum total payment to an employee (i.e minimize the maximum value of a_i+d_i). Help Polycarp decide the non-negative integer bonuses d_i such that: their sum is k, for each employee, the number of those who receive strictly more than them remains unchanged (that is, if you sort employees by a_i and by a_i+d_i, you get the same order of employees), all a_i + d_i are different, the maximum of the values a_i+d_i is the minimum possible. Help Polycarp and print any of the possible answers d_1, d_2, \dots, d_n.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.The first line of each test case contains two integers n and k (1 \le n \le 10^5, 1 \le k \le 10^9) — the number of employees and the total bonus.The second line of each test case contains n different integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the current salary of the i-th employee.It is guaranteed that the sum of all n values in the input does not exceed 10^5.OutputPrint the answers to t test cases in the order they appear in the input. Print each answer as a sequence of non-negative integers d_1, d_2, \dots, d_n. If there are several answers, print any of them.ExampleInput
5
4 1
3 1 4 2
2 3
10 2
4 1000000000
987654321 1000000000 999999999 500000000
8 9
5 6 1 8 3 4 2 7
6 1
6 3 1 8 5 9
Output
0 0 1 0
0 3
134259259 121913582 121913582 621913577
2 2 0 2 0 1 0 2
1 0 0 0 0 0
| 5
4 1
3 1 4 2
2 3
10 2
4 1000000000
987654321 1000000000 999999999 500000000
8 9
5 6 1 8 3 4 2 7
6 1
6 3 1 8 5 9
| 0 0 1 0 0 3 134259259 121913582 121913582 621913577 2 2 0 2 0 1 0 2 1 0 0 0 0 0 | 3 seconds | 256 megabytes | ['*special problem', 'binary search', 'greedy', 'sortings'] |
C. Dream Teamtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is the project manager in the IT-company. Right now, he needs to choose developers for his team to start a new project. The company has n developers "on the bench" (i.e not involved in other projects). Polycarp assessed the skills of each of them: a_i (-10^4 \le a_i \le 10^4) — an integer characteristic of the i-th developer. This value can be either positive, zero or even negative (some developers cause distractions).After Polycarp chooses a subset of developers for his team, the strength of the team will be determined by the sum of a_i values for all selected developers.Polycarp fears that if he chooses a team in such a way that maximizes the sum of the characteristics of a_i, other managers may find this unacceptable. For this reason, he plans to create such a team that the sum of the a_i values for it is strictly less than the maximum possible value.Help Polycarp choose any team that: the sum of the characteristics a_i for all members of the selected team is strictly less than the maximum value that can be achieved by choosing the team in some other way and at the same time, the sum of the characteristics of a_i for all members of the selected team is the greatest possible. If, following the requirements above, you can select a team in several ways, then just find any of them. It's guaranteed that the sum of the characteristics in the desired subset is strictly positive (i.e. Polycarp can always choose a non-empty team).InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case begins with a line containing one integer n (2 \le n \le 10^5) — the number of developers "on the bench".The second line of a test case contains a sequence of integers a_1, a_2, \dots, a_n (-10^4 \le a_i \le 10^4) — the characteristics of the n developers. It is guaranteed that the characteristics are such that the sum of the characteristics in the answer is strictly positive.It is guaranteed that the sum of n over all test cases in the input doesn't exceed 10^5.OutputPrint the answers for the given t test cases in the order that they appear in the input. In the first line of each answer, print a positive integer s — the sum of the characteristics in the desired subset. The second line should contain only the characters 0 and 1 and match the answer: the character in the i-th position should be equal to 1 if the i-th developer belongs to the team; the character in the i-th position should be equal to 0 if the i-th developer does not belong to the team. If there are several answers, print any of them.ExampleInput
5
5
1 -1 1 -1 1
2
11 1
3
5 -3 4
3
5 3 -4
5
-1 0 3 -3 0
Output
2
11101
11
10
6
111
5
100
2
10100
NoteIn the first test case, the maximum subset a_1, a_3, a_5 has a sum equal to 3, so Polycarp should choose a team with the maximum total sum which is less than 3.In the second test case, the maximum subset a_1, a_2 has a sum equal to 12, so Polycarp should choose a team with the maximum total sum which is less than 12.In the third test case, the maximum subset a_1, a_3 has a sum equal to 9.In the fourth test case, the maximum subset a_1, a_2 has a sum equal to 8.In the fifth test case, there are several subsets with a maximum sum equal to 3, so Polycarp should choose a team with a lower total sum. | 5
5
1 -1 1 -1 1
2
11 1
3
5 -3 4
3
5 3 -4
5
-1 0 3 -3 0
| 2 11101 11 10 6 111 5 100 2 10100 | 3 seconds | 256 megabytes | ['*special problem', 'greedy'] |
B. Cartoonstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya likes cartoons. She knows that n new cartoons will be released in his favorite cinema: the i-th of them will be airing from the day a_i to the day b_i (1 \le a_i \le b_i \le 10^9).The cinema has a special offer: there is a huge discount every day when only one cartoon is airing.Tanya doesn't care which cartoon she will watch but she'd like to save some money. That's why she asks you to find any day x when only one cartoon will be airing. Formally: find x such that there is exactly one i (1 \le i \le n) with a_i \le x \le b_i. If there are several possible answers, print any of them. If there is no such day, print -1.InputThe first line contains single integer t (1 \le t \le 1000) — the number of test cases. The following are descriptions of the t test cases.The first line of each test case contains a single integer n (1 \le n \le 2000) — the number of cartoons.In the next n lines, the cartoons themselves are described, one per line, by a pair of integers a_i, b_i (1 \le a_i \le b_i \le 10^9) — the first and last airing days for the i-th cartoon.It is guaranteed that the sum of the values n for all test cases in the input does not exceed 2000.OutputPrint t answers to given test cases in the order in which they appear in the input: the i-th answer is such x, that only one cartoon will be airing on day x or -1 if there are no such days.ExampleInput
5
1
1 1
3
2 1000000000
2 500000000
500000002 1000000000
3
1 2
3 4
1 4
2
4 11
4 9
3
1 5
10 10
1 5
Output
1
500000001
-1
10
10
NoteIn the third test case: at day 1 and 2, first and third cartoons will be airing, and days 3 and 4, second and third cartoons will be airing. So, there is no day when only one cartoon will be airing.In the fourth test case, 11 is also a possible answer. | 5
1
1 1
3
2 1000000000
2 500000000
500000002 1000000000
3
1 2
3 4
1 4
2
4 11
4 9
3
1 5
10 10
1 5
| 1 500000001 -1 10 10 | 3 seconds | 256 megabytes | ['*special problem', 'implementation', 'sortings'] |
A. Likes Displaytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is working on the implementation of displaying likes on the Codehorses social network. The number of likes should be displayed in a format that will be easy to read by users. It was decided that for large numbers of likes the format should be like 123K (one hundred twenty-three thousand) or like 56M (fifty-six million).The following displaying strategy has been approved: the number will be displayed either as an integer number from 0 to 999, or as a positive integer number of thousands (from 1K to 999K), or as a positive integer number of millions (from 1M on), the specified exact number of likes n when displaying should be rounded to the nearest view from the case above (if rounding is ambiguous, it must be rounded up): for example, 1785 should be rounded to 2K instead of 1K, 4500000 should be rounded to 5M. Help Polycarp implement this part of the functionality: for a given non-negative integer number of likes n, print its view in the Codehorses interface.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases in the input. The following are descriptions of the t input test cases, one per line.The description of each test case consists of a single line that contains a non-negative integer n (0 \le n \le 2\cdot10^9) — the number of likes.OutputPrint t answers to the given test cases in the order from the input. Each printed value must have one of the following types: either an integer from 0 to 999 which corresponds just to the number of likes, or a number of thousands from 1K to 999K, or a number of millions from 1M to 2000M. The answer is equal to a view which is the closest (by difference) to the given number n. If this rounding is ambiguous, then round answer up (to a greater value).ExampleInput
9
999
123
0
1782
31415926
1500
999999
35499710
2000000000
Output
999
123
0
2K
31M
2K
1M
35M
2000M
NoteLet's describe some test cases: 1782 can be displayed either as 1K or as 2K but 2K is the nearest view; 1500 have same difference with 1K and 2K so it should be rounded up; 999999 should be displayed as 1M since it's closer to it than to 999K. | 9
999
123
0
1782
31415926
1500
999999
35499710
2000000000
| 999 123 0 2K 31M 2K 1M 35M 2000M | 3 seconds | 256 megabytes | ['*special problem', 'implementation'] |
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive.You asked m passengers some questions: the j-th one told you three values: his departure station a_j; his arrival station b_j; minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f_1, f_2, \dots, f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer n (2 \le n \le 5000) — the number of railway stations in Berland.The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer m (1 \le m \le 5000) — the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 \le a_j, b_j \le n; a_j \ne b_j; 1 \le g_j \le 10^6) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n-1 integers f_1, f_2, \dots, f_{n-1} (1 \le f_i \le 10^6), where f_i is some valid scenery beauty along the i-th railway section.If there are multiple answers, you can print any of them.ExamplesInput
4
1 2
3 2
3 4
2
1 2 5
1 3 3
Output
5 3 5
Input
6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
Output
5 3 1 2 1
Input
6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
Output
-1
| 4
1 2
3 2
3 4
2
1 2 5
1 3 3
| 5 3 5 | 3 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'greedy', 'sortings', 'trees', '*2100'] |
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string s consisting of n lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in s).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of s.The second line of the input contains the string s consisting of exactly n lowercase Latin letters.OutputIn the first line print one integer res (1 \le res \le n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array c of length n, where 1 \le c_i \le res and c_i means the color of the i-th character.ExamplesInput
9
abacbecfd
Output
2
1 1 2 1 2 1 2 1 2
Input
8
aaabbcbb
Output
2
1 2 1 2 1 2 1 1
Input
7
abcdedc
Output
3
1 1 1 1 1 2 3
Input
5
abcde
Output
1
1 1 1 1 1
| 9
abacbecfd
| 2 1 1 2 1 2 1 2 1 2 | 1 second | 256 megabytes | ['data structures', 'dp', '*2000'] |
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string s consisting of n lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in s).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer n (1 \le n \le 200) — the length of s.The second line of the input contains the string s consisting of exactly n lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of n characters, the i-th character should be '0' if the i-th character is colored the first color and '1' otherwise).ExamplesInput
9
abacbecfd
Output
YES
001010101
Input
8
aaabbcbb
Output
YES
01011011
Input
7
abcdedc
Output
NO
Input
5
abcde
Output
YES
00000
| 9
abacbecfd
| YES 001010101 | 1 second | 256 megabytes | ['constructive algorithms', 'dp', 'graphs', 'greedy', 'sortings', '*1800'] |
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 0.The fight with a monster happens in turns. You hit the monster by a hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by b hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most k times in total (for example, if there are two monsters and k=4, then you can use the technique 2 times on the first monster and 1 time on the second monster, but not 2 times on the first monster and 3 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n, a, b and k (1 \le n \le 2 \cdot 10^5, 1 \le a, b, k \le 10^9) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains n integers h_1, h_2, \dots, h_n (1 \le h_i \le 10^9), where h_i is the health points of the i-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInput
6 2 3 3
7 10 50 12 1 8
Output
5
Input
1 1 100 99
100
Output
1
Input
7 4 2 1
1 3 5 4 2 7 6
Output
6
| 6 2 3 3
7 10 50 12 1 8
| 5 | 1 second | 256 megabytes | ['greedy', 'sortings', '*1500'] |
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x, y) to the point (x - 1, y); 'R' (right): means that the robot moves from the point (x, y) to the point (x + 1, y); 'U' (up): means that the robot moves from the point (x, y) to the point (x, y + 1); 'D' (down): means that the robot moves from the point (x, y) to the point (x, y - 1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (x_e, y_e), then after optimization (i.e. removing some single substring from s) the robot also ends its path at the point (x_e, y_e).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string s).Recall that the substring of s is such string that can be obtained from s by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1000) — the number of test cases.The next 2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of the robot's path. The second line of the test case contains one string s consisting of n characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers l and r such that 1 \le l \le r \le n — endpoints of the substring you remove. The value r-l+1 should be minimum possible. If there are several answers, print any of them.ExampleInput
4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
Output
1 2
1 4
3 4
-1
| 4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
| 1 2 1 4 3 4 -1 | 1 second | 256 megabytes | ['data structures', 'implementation', '*1500'] |
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 \le x \le s, buy food that costs exactly x burles and obtain \lfloor\frac{x}{10}\rfloor burles as a cashback (in other words, Mishka spends x burles and obtains \lfloor\frac{x}{10}\rfloor back). The operation \lfloor\frac{a}{b}\rfloor means a divided by b rounded down.It is guaranteed that you can always buy some food that costs x for any possible value of x.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19 burles then the maximum number of burles he can spend is 21. Firstly, he can spend x=10 burles, obtain 1 burle as a cashback. Now he has s=10 burles, so can spend x=10 burles, obtain 1 burle as a cashback and spend it too.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.The next t lines describe test cases. Each test case is given on a separate line and consists of one integer s (1 \le s \le 10^9) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInput
6
1
10
19
9876
12345
1000000000
Output
1
11
21
10973
13716
1111111111
| 6
1
10
19
9876
12345
1000000000
| 1 11 21 10973 13716 1111111111 | 1 second | 256 megabytes | ['math', '*900'] |
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.In one move, you can choose two indices 1 \le i, j \le n such that i \ne j and set a_i := a_j. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose i and j and replace a_i with a_j).Your task is to say if it is possible to obtain an array with an odd (not divisible by 2) sum of elements.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2000) — the number of test cases.The next 2t lines describe test cases. The first line of the test case contains one integer n (1 \le n \le 2000) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2000), where a_i is the i-th element of a.It is guaranteed that the sum of n over all test cases does not exceed 2000 (\sum n \le 2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInput
5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
Output
YES
NO
YES
NO
NO
| 5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
| YES NO YES NO NO | 1 second | 256 megabytes | ['math', '*800'] |
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared n problems; and since the platform is very popular, 998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the i-th problem, the number of accepted solutions will be between l_i and r_i, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x, y) such that x is located earlier in the contest (x < y), but the number of accepted solutions for y is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem i, any integral number of accepted solutions for it (between l_i and r_i) is equally probable, and all these numbers are independent.InputThe first line contains one integer n (2 \le n \le 50) — the number of problems in the contest.Then n lines follow, the i-th line contains two integers l_i and r_i (0 \le l_i \le r_i \le 998244351) — the minimum and maximum number of accepted solutions for the i-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction \frac{x}{y}, where y is coprime with 998244353. Print one integer — the value of xy^{-1}, taken modulo 998244353, where y^{-1} is an integer such that yy^{-1} \equiv 1 (mod 998244353).ExamplesInput
3
1 2
1 2
1 2
Output
499122177
Input
2
42 1337
13 420
Output
578894053
Input
2
1 1
0 0
Output
1
Input
2
1 1
1 1
Output
1
NoteThe real answer in the first test is \frac{1}{2}. | 3
1 2
1 2
1 2
| 499122177 | 3 seconds | 256 megabytes | ['combinatorics', 'dp', 'probabilities', '*2700'] |
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \dots , p_n (an array where each integer from 1 to n appears exactly once). The weight of the i-th element of this permutation is a_i.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p_1, p_2, \dots , p_k, the second — p_{k+1}, p_{k+2}, \dots , p_n, where 1 \le k < n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay a_i dollars to move the element p_i.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p = [3, 1, 2] and a = [7, 1, 4], then the optimal strategy is: separate p into two parts [3, 1] and [2] and then move the 2-element into first set (it costs 4). And if p = [3, 5, 1, 6, 2, 4], a = [9, 1, 9, 9, 1, 9], then the optimal strategy is: separate p into two parts [3, 5, 1] and [6, 2, 4], and then move the 2-element into first set (it costs 1), and 5-element into second set (it also costs 1).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the length of permutation.The second line contains n integers p_1, p_2, \dots , p_n (1 \le p_i \le n). It's guaranteed that this sequence contains each element from 1 to n exactly once.The third line contains n integers a_1, a_2, \dots , a_n (1 \le a_i \le 10^9).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInput
3
3 1 2
7 1 4
Output
4
Input
4
2 4 1 3
5 9 8 3
Output
3
Input
6
3 5 1 6 2 4
9 1 9 9 1 9
Output
2
| 3
3 1 2
7 1 4
| 4 | 2 seconds | 256 megabytes | ['data structures', 'divide and conquer', '*2200'] |
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and m. Calculate the number of integers x such that 0 \le x < m and \gcd(a, m) = \gcd(a + x, m).Note: \gcd(a, b) is the greatest common divisor of a and b.InputThe first line contains the single integer T (1 \le T \le 50) — the number of test cases.Next T lines contain test cases — one per line. Each line contains two integers a and m (1 \le a < m \le 10^{10}).OutputPrint T integers — one per test case. For each test case print the number of appropriate x-s.ExampleInput
3
4 9
5 10
42 9999999967
Output
6
1
9999999966
NoteIn the first test case appropriate x-s are [0, 1, 3, 4, 6, 7].In the second test case the only appropriate x is 0. | 3
4 9
5 10
42 9999999967
| 6 1 9999999966 | 2 seconds | 256 megabytes | ['math', 'number theory', '*1800'] |
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z = ac, s = abcde, you may turn z into following strings in one operation: z = acace (if we choose subsequence ace); z = acbcd (if we choose subsequence bcd); z = acbce (if we choose subsequence bce). Note that after this operation string s doesn't change.Calculate the minimum number of such operations to turn string z into string t. InputThe first line contains the integer T (1 \le T \le 100) — the number of test cases.The first line of each testcase contains one string s (1 \le |s| \le 10^5) consisting of lowercase Latin letters.The second line of each testcase contains one string t (1 \le |t| \le 10^5) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings s and t in the input does not exceed 2 \cdot 10^5.OutputFor each testcase, print one integer — the minimum number of operations to turn string z into string t. If it's impossible print -1.ExampleInput
3
aabce
ace
abacaba
aax
ty
yyt
Output
1
-1
3
| 3
aabce
ace
abacaba
aax
ty
yyt
| 1 -1 3 | 1 second | 256 megabytes | ['dp', 'greedy', 'strings', '*1600'] |
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss \dots For example, if s = 10010, then t = 100101001010010...Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal to cnt_{0, q} - cnt_{1, q}, where cnt_{0, q} is the number of occurrences of 0 in q, and cnt_{1, q} is the number of occurrences of 1 in q. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer T (1 \le T \le 100) — the number of test cases.Next 2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers n and x (1 \le n \le 10^5, -10^9 \le x \le 10^9) — the length of string s and the desired balance, respectively.The second line contains the binary string s (|s| = n, s_i \in \{\text{0}, \text{1}\}).It's guaranteed that the total sum of n doesn't exceed 10^5.OutputPrint T integers — one per test case. For each test case print the number of prefixes or -1 if there is an infinite number of such prefixes.ExampleInput
4
6 10
010010
5 3
10101
1 0
0
2 0
01
Output
3
0
1
-1
NoteIn the first test case, there are 3 good prefixes of t: with length 28, 30 and 32. | 4
6 10
010010
5 3
10101
1 0
0
2 0
01
| 3 0 1 -1 | 2 seconds | 256 megabytes | ['math', 'strings', '*1700'] |
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 10 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 1, you have to turn on 2 segments of the screen, and if you want to display 8, all 7 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than n segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than n segments.Your program should be able to process t different test cases.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer n (2 \le n \le 10^5) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of n over all test cases in the input does not exceed 10^5.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than n segments of the screen. Note that the answer may not fit in the standard 32-bit or 64-bit integral data type.ExampleInput
2
3
4
Output
7
11
| 2
3
4
| 7 11 | 1 second | 256 megabytes | ['greedy', '*900'] |
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number n (3 \le n \le 2 \cdot 10^5) — the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 \le a_i, b_i \le n, a_i \ne b_i). It is guaranteed that given graph is a tree.OutputIn the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.In the second line print three integers a, b, c such that 1 \le a, b, c \le n and a \ne, b \ne c, a \ne c.If there are several answers, you can print any.ExampleInput
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | 8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
| 5 1 8 6 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'trees', '*2000'] |
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n \times m consisting of integers from 1 to 2 \cdot 10^5.In one move, you can: choose any element of the matrix and change its value to any integer between 1 and n \cdot m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some j (1 \le j \le m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j} simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m (i.e. a_{i, j} = (i - 1) \cdot m + j) with the minimum number of moves performed.InputThe first line of the input contains two integers n and m (1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5) — the size of the matrix.The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 \le a_{i, j} \le 2 \cdot 10^5).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m (a_{i, j} = (i - 1)m + j).ExamplesInput
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
NoteIn the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 0.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2. | 3 3
3 2 1
1 2 3
4 5 6
| 6 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*1900'] |
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array; for the array [1, 2, 3, 4] MEX equals to 0 because 0 is the minimum non-negative integer not presented in the array; for the array [0, 1, 4, 3] MEX equals to 2 because 2 is the minimum non-negative integer not presented in the array. You are given an empty array a=[] (in other words, a zero-length array). You are also given a positive integer x.You are also given q queries. The j-th query consists of one integer y_j and means that you have to append one element y_j to the array. The array length increases by 1 after a query.In one move, you can choose any index i and set a_i := a_i + x or a_i := a_i - x (i.e. increase or decrease any element of the array by x). The only restriction is that a_i cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of q queries (i.e. the j-th answer corresponds to the array of length j).Operations are discarded before each query. I.e. the array a after the j-th query equals to [y_1, y_2, \dots, y_j].InputThe first line of the input contains two integers q, x (1 \le q, x \le 4 \cdot 10^5) — the number of queries and the value of x.The next q lines describe queries. The j-th query consists of one integer y_j (0 \le y_j \le 10^9) and means that you have to append one element y_j to the array.OutputPrint the answer to the initial problem after each query — for the query j print the maximum value of MEX after first j queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInput
7 3
0
1
2
2
0
0
10
Output
1
2
3
3
4
4
7
Input
4 3
1
2
1
2
Output
0
0
0
0
NoteIn the first example: After the first query, the array is a=[0]: you don't need to perform any operations, maximum possible MEX is 1. After the second query, the array is a=[0, 1]: you don't need to perform any operations, maximum possible MEX is 2. After the third query, the array is a=[0, 1, 2]: you don't need to perform any operations, maximum possible MEX is 3. After the fourth query, the array is a=[0, 1, 2, 2]: you don't need to perform any operations, maximum possible MEX is 3 (you can't make it greater with operations). After the fifth query, the array is a=[0, 1, 2, 2, 0]: you can perform a[4] := a[4] + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3]. Now MEX is maximum possible and equals to 4. After the sixth query, the array is a=[0, 1, 2, 2, 0, 0]: you can perform a[4] := a[4] + 3 = 0 + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3, 0]. Now MEX is maximum possible and equals to 4. After the seventh query, the array is a=[0, 1, 2, 2, 0, 0, 10]. You can perform the following operations: a[3] := a[3] + 3 = 2 + 3 = 5, a[4] := a[4] + 3 = 0 + 3 = 3, a[5] := a[5] + 3 = 0 + 3 = 3, a[5] := a[5] + 3 = 3 + 3 = 6, a[6] := a[6] - 3 = 10 - 3 = 7, a[6] := a[6] - 3 = 7 - 3 = 4. The resulting array will be a=[0, 1, 2, 5, 3, 6, 4]. Now MEX is maximum possible and equals to 7. | 7 3
0
1
2
2
0
0
10
| 1 2 3 3 4 4 7 | 3 seconds | 256 megabytes | ['data structures', 'greedy', 'implementation', 'math', '*1600'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.