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
G. A Battle Against a Dragontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA squad of n warriors is defending a castle from a dragon attack. There are m barricades between the castle and the dragon.The warriors are numbered from 1 to n. The i-th warrior knows k_i attacks: the j-th of them deals a_{i,j} damage to the dragon and can only be applied if there are exactly b_{i,j} barricades between the castle and the dragon.The warriors make turns one after another, starting from warrior 1. After warrior n makes his turn, the total damage to the dragon is calculated. The i-th warrior performs exactly one of three possible moves in his turn: destroys one barricade (if there are any left); deploys one of his k_i attacks; skips a turn. The total damage is the sum of damages dealt by the warriors who chose to deploy their attacks in their turn. What is the maximum total damage the warriors can deal to the dragon?InputThe first line contains two integers n and m (1 \le n, m \le 3 \cdot 10^5) — the number of warriors and the initial number of barricades.Then the descriptions of attacks for each warrior follow. The i-th description consists of three lines.The first line contains a single integer k_i (1 \le k_i \le m + 1) — the number of attacks the i-th warrior knows.The second line contains k_i integers a_{i,1}, a_{i,2}, \dots, a_{i,k_i} (1 \le a_{i,j} \le 10^9) — the damage of each attack.The third line contains k_i integers b_{i,1}, b_{i,2}, \dots, b_{i,k_i} (0 \le b_{i,j} \le m) — the required number of barricades for each attack. b_{i,j} for the i-th warrior are pairwise distinct. The attacks are listed in the increasing order of the barricades requirement, so b_{i,1} < b_{i,2} < \dots < b_{i,k_i}.The sum of k_i over all warriors doesn't exceed 3 \cdot 10^5.OutputPrint a single integer — the maximum total damage the warriors can deal to the dragon.ExamplesInput 2 4 1 2 4 2 10 5 3 4 Output 10 Input 3 3 1 1 0 1 20 2 1 100 3 Output 100 Input 2 1 2 10 10 0 1 2 30 20 0 1 Output 30 NoteIn the first example, the optimal choice is the following: warrior 1 destroys a barricade, now there are 3 barricades left; warrior 2 deploys his first attack (he can do it because b_{1,1}=3, which is the current number of barricades). The total damage is 10.If the first warrior used his attack or skipped his turn, then the second warrior would only be able to deploy his second attack. Thus, the total damage would be 2+5=7 or 5.In the second example, the first warrior skips his move, the second warrior skips his move and the third warrior deploys his only attack.In the third example, two equivalent options are: both warriors deploy their second attacks; the first warrior destroys one barricade and the second warrior deploys his first attack. Both options yield 30 total damage.
2 4 1 2 4 2 10 5 3 4
10
4 seconds
256 megabytes
['*special problem', 'data structures', 'dp', '*2500']
F. Kotlinforcestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKotlinforces is a web platfrom that hosts programming competitions.The staff of Kotlinforces is asked to schedule n programming competitions on the next m days. Each competition is held in multiple stages; the regulations of the i-th competition state that this competition should consist of exactly k_i stages, and each stage, starting from the second one, should be scheduled exactly t_i days after the previous stage. In other words, if the first stage of the i-th competition is scheduled on day x, the second stage should be scheduled on day x+t_i, the third stage — on day x+2t_i, ..., the k_i-th stage (which is the last one) — on day x+(k_i-1)t_i.All n competitions should be scheduled in such a way that they start and finish during the next m days, and on any of these m days, at most one stage of one competition is held (two stages of different competitions should not be scheduled on the same day).Is it possible to schedule all n competitions to meet these constraints?InputThe first line contains two integers n and m (1 \le n, m \le 5000) — the number of competitions and the number of days, respectively.Then n lines follow, each describing a competition which should be scheduled. The i-th line contains two integers k_i and t_i (2 \le k_i \le 5000; 1 \le t_i \le 2) — the parameters of the i-th competition.OutputIf it is impossible to schedule all n competitions on the next m days so that there is at most one stage during each day, print -1.Otherwise, print n integers. The i-th integer should represent the day when the first stage of the i-th competition is scheduled; days are numbered from 1 to m. If there are multiple answers, print any of them.ExamplesInput 3 7 3 2 2 2 2 2 Output 2 5 1 Input 1 7 4 2 Output 1 Input 1 7 5 2 Output -1 Input 2 4 2 1 2 2 Output -1 Input 2 5 2 1 2 2 Output 4 1
3 7 3 2 2 2 2 2
2 5 1
2 seconds
512 megabytes
['*special problem', 'constructive algorithms', 'dp', '*2000']
E. Fix the Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); bracket sequences ")(", "(" and ")" are not. You are given two strings s and a, the string s has length n, the string a has length n - 3. The string s is a bracket sequence (i. e. each element of this string is either an opening bracket character or a closing bracket character). The string a is a binary string (i. e. each element of this string is either 1 or 0).The string a imposes some constraints on the string s: for every i such that a_i is 1, the string s_i s_{i+1} s_{i+2} s_{i+3} should be a regular bracket sequence. Characters of a equal to 0 don't impose any constraints.Initially, the string s may or may not meet these constraints. You can perform the following operation any number of times: replace some character of s with its inverse (i. e. you can replace an opening bracket with a closing bracket, or vice versa).Determine if it is possible to change some characters in s so that it meets all of the constraints, and if it is possible, calculate the minimum number of characters to be changed.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of three lines. The first line contains one integer n (4 \le n \le 2 \cdot 10^5). The second line contains the string s, consisting of exactly n characters; each character of s is either '(' or ')'. The third line contains the string a, consisting of exactly n - 3 characters; each character of a is either '1' or '0'.Additional constraint on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer: the minimum number of characters that need to be changed in s, or -1 if it is impossible.ExampleInput 6 4 ))(( 1 4 ))(( 0 4 ()() 0 6 ))(()( 101 6 ))(()( 001 5 ((((( 11 Output 2 0 0 4 1 -1
6 4 ))(( 1 4 ))(( 0 4 ()() 0 6 ))(()( 101 6 ))(()( 001 5 ((((( 11
2 0 0 4 1 -1
2 seconds
256 megabytes
['*special problem', 'bitmasks', 'dp', 'greedy', '*1700']
D. Sweepstaketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKotlin Heroes competition is nearing completion. This time n programmers took part in the competition. Now organizers are thinking how to entertain spectators as well. One of the possibilities is holding sweepstakes. So for now they decided to conduct a survey among spectators.In total, organizers asked m viewers two questions: Who will take the first place? Who will take the last place? After receiving answers, organizers ranked all spectators based on the number of programmers they guessed right. Suppose, there are c_2 viewers who guessed right both first and last place, c_1 viewers who guessed either first or last place right and c_0 viewers who didn't guess at all. All c_2 viewers will get rank 1, all viewers with one right answer will get rank c_2 + 1 and all remaining viewers — rank c_2 + c_1 + 1.You were one of the interviewed spectators. Also, as one of the organizers, you have access to survey results, but not to competition results. Calculate, what is the worst rank you can possibly get according to organizers' ranking system?InputThe first line contains two integers n and m (2 \le n \le 1000; 1 \le m \le 2 \cdot 10^5) — the number of programmers participating in the competition and the number of surveyed spectators.Next m lines contain answers of spectators. The i-th line contains two integers f_i and l_i (1 \le f_i, l_i \le n; f_i \ne l_i) — the indices of programmers who will take the first and last places in opinion of the i-th viewer.For simplicity, you are the first among spectators, so your answers are f_1 and l_1.OutputPrint the single integer — the worst rank among spectators you can possibly get according to organizers' ranking system (bigger rank — worse, of course).ExamplesInput 2 3 1 2 2 1 2 1 Output 3 Input 3 6 3 1 3 2 2 1 3 2 3 2 3 1 Output 4 NoteIn the first example, if the second programmer takes first place, while the first programmer takes last place, you'll have 0 right answers while the other two spectators — 2 right answers. That's why your rank (in the worst case) will be c_2 + c_1 + 1 = 2 + 0 + 1 = 3.In the second example, for example, if the third programmer takes the first place and the second programmer takes the last place, then you'll have 1 right answer. The spectators 2, 4 and 5 will have 2 right answers, spectator 6 — 1 right answer and spectator 3 — 0 right answers. As a result, your rank will be equal to c_2 + 1 = 3 + 1 = 4. (Note that spectator 6 will have the same rank 4).
2 3 1 2 2 1 2 1
3
2 seconds
256 megabytes
['*special problem', 'brute force', 'constructive algorithms', 'implementation', 'math', '*1800']
C. Rhymetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's say that two strings s and t rhyme if both strings have length at least k, and their last k characters are equal. For example, if k = 3, the strings abcd and cebcd rhyme, the strings ab and ab don't rhyme, the strings aaaa and aaaaa rhyme, the strings abcd and abce don't rhyme.You have n pairs of strings (s_i, t_i), and for each pair of strings you know, should they rhyme or should not.Find all possible non-negative integer values for k such that pairs that have to rhyme, rhyme and pairs that must not rhyme, don't rhyme.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). 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 string pairs.Next n lines contains descriptions of pairs — one per line. The i-th line contains space-separated strings s_i and t_i and marker r_i. Strings are non-empty, consist of lowercase Latin letters and each have length at most 2 \cdot 10^5. The marker r_i equals to 1 if strings have to rhyme, or 0 if they must not rhyme.It's guaranteed that for each test case there is at least one pair with r_i equal to 1 and that the total length of all strings over all test cases doesn't exceed 4 \cdot 10^5.OutputFor each test case, firstly print integer m — the number of possible non-negative integer values of k such that pairs that have to rhyme, rhyme and pairs that must not rhyme, don't rhyme. Next, print all these values of k (without repetitions). You can print them in any order.ExampleInput 3 1 kotlin heroes 1 2 join kotlin 1 episode eight 0 4 abc abcdef 0 xyz zzz 1 aaa bba 0 c d 0 Output 1 0 2 1 2 0 NoteIn the first test case, if k is at least 1 then kotlin and heroes don't rhyme.In the second test case, for k = 2 join and kotlin rhyme, and episode and eight don't rhyme.
3 1 kotlin heroes 1 2 join kotlin 1 episode eight 0 4 abc abcdef 0 xyz zzz 1 aaa bba 0 c d 0
1 0 2 1 2 0
2 seconds
256 megabytes
['*special problem', 'implementation', '*1800']
B. Epic Noveltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex has bought a new novel that was published in n volumes. He has read these volumes one by one, and each volume has taken him several (maybe one) full days to read. So, on the first day, he was reading the first volume, and on each of the following days, he was reading either the same volume he had been reading on the previous day, or the next volume.Let v_i be the number of the volume Alex was reading on the i-th day. Here are some examples: one of the possible situations is v_1 = 1, v_2 = 1, v_3 = 2, v_4 = 3, v_5 = 3 — this situation means that Alex has spent two days (1-st and 2-nd) on the first volume, one day (3-rd) on the second volume, and two days (4-th and 5-th) on the third volume; a situation v_1 = 2, v_2 = 2, v_3 = 3 is impossible, since Alex started with the first volume (so v_1 cannot be anything but 1); a situation v_1 = 1, v_2 = 2, v_3 = 3, v_4 = 1 is impossible, since Alex won't return to the first volume after reading the third one; a situation v_1 = 1, v_2 = 3 is impossible, since Alex doesn't skip volumes. You know that Alex was reading the volume v_a on the day a, and the volume v_c on the day c. Now you want to guess which volume was he reading on the day b, which is between the days a and c (so a < b < c). There may be some ambiguity, so you want to make any valid guess (i. e. choose some volume number v_b so it's possible that Alex was reading volume v_a on day a, volume v_b on day b, and volume v_c on day c).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). 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 volumes the novel consists of.The second line of each test case contains two integers a and v_a (1 \le a \le 98; 1 \le v_a \le a) denoting that Alex was reading volume v_a at day a.The third line of each test case contains two integers c and v_c (a + 2 \le c \le 100; v_a \le v_c \le c) denoting that Alex was reading volume v_c at day c.The fourth line of each test case contains one integer b (a < b < c) — the day you are interested in.It's guaranteed that the input is not controversial, in other words, Alex could read volume v_a at day a and volume v_c at day c.OutputFor each test case, print the possible index of volume Alex could read at day b. If there are multiple answers, print any.ExampleInput 4 1 1 1 100 1 99 4 10 1 20 4 16 100 1 1 100 100 42 100 1 1 100 2 99 Output 1 2 42 1NoteIn the first test case, since Alex was reading volume 1 both at day 1 and at day 100 then he was reading volume 1 at any day between them.In the second test case, Alex could read any volume from 1 to 4 at day 16. For example, he could read volume 1 from day 1 to day 15, volume 2 at days 16 and 17, volume 3 at day 18 and volume 4 at days 19 and 20.In the third test case, there is only one possible situation: Alex read one volume per day, so at day 42 he read volume 42.
4 1 1 1 100 1 99 4 10 1 20 4 16 100 1 1 100 100 42 100 1 1 100 2 99
1 2 42 1
2 seconds
256 megabytes
['*special problem', 'math', '*1300']
A. Sequence of Comparisonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time, Petya had an array of integers a of length n. But over time, the array itself was lost, and only n-1 results of comparisons of neighboring array elements remained. In other words, for every i from 1 to n-1, Petya knows exactly one of these three facts: a_i < a_{i+1}; a_i = a_{i+1}; a_i > a_{i+1}. Petya wonders if it is possible to uniquely determine the result of comparing a_1 and a_n.You have to help Petya determine the result of comparing a_1 and a_n or report that the result cannot be determined unambiguously.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The only line of the test case contains the string s (1 \le |s| \le 100), where s_i is: <, if a_i < a_{i + 1}; >, if a_i > a_{i + 1}; =, if a_i = a_{i + 1}. OutputFor each test case, print a single string equal to: <, if a_1 < a_n; >, if a_1 > a_n; =, if a_1 = a_n; ?, if it is impossible to uniquely determine the result of the comparison. ExampleInput 4 >>> <><=< = <<== Output > ? = < NoteConsider the test cases of the example: in the first test case, it's easy to see that a_1 > a_4 since a_1 > a_2 > a_3 > a_4; in the second test case, both sequences [1, 2, 0, 10, 10, 15] and [10, 11, 1, 2, 2, 5] meet the constraints; in the first one, a_1 < a_6, and in the second one, a_1 > a_6, so it's impossible to compare a_1 and a_6; in the third test case, we already know that a_1 = a_2; in the fourth test case, it's easy to see that a_3 = a_4 = a_5, and a_1 < a_2 < a_3, so a_1 < a_5.
4 >>> <><=< = <<==
> ? = <
2 seconds
256 megabytes
['*special problem', '*800']
F. Palindromic Hamiltonian Pathtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a simple undirected graph with n vertices, n is even. You are going to write a letter on each vertex. Each letter should be one of the first k letters of the Latin alphabet.A path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads the same from left to right and from right to left. A path in the graph is called palindromic if the letters on the vertices in it spell a palindromic string without changing the order.A string of length n is good if: each letter is one of the first k lowercase Latin letters; if you write the i-th letter of the string on the i-th vertex of the graph, there will exist a palindromic Hamiltonian path in the graph. Note that the path doesn't necesserily go through the vertices in order 1, 2, \dots, n.Count the number of good strings.InputThe first line contains three integers n, m and k (2 \le n \le 12; n is even; 0 \le m \le \frac{n \cdot (n-1)}{2}; 1 \le k \le 12) — the number of vertices in the graph, the number of edges in the graph and the number of first letters of the Latin alphabet that can be used.Each of the next m lines contains two integers v and u (1 \le v, u \le n; v \neq u) — the edges of the graph. The graph doesn't contain multiple edges and self-loops.OutputPrint a single integer — number of good strings.ExamplesInput 4 3 3 1 2 2 3 3 4 Output 9 Input 4 6 3 1 2 1 3 1 4 2 3 2 4 3 4 Output 21 Input 12 19 12 1 3 2 6 3 6 3 7 4 8 8 5 8 7 9 4 5 9 10 1 10 4 10 6 9 10 11 1 5 11 7 11 12 2 12 5 12 11 Output 456165084
4 3 3 1 2 2 3 3 4
9
5 seconds
256 megabytes
['brute force', 'dfs and similar', 'dp', 'graphs', 'hashing', '*3000']
E. Playoff Restorationtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{k-1} teams remain. If only one team remains, it is declared the champion; otherwise, 2^{k-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains.After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular: the winner of the tournament gets place 1; the team eliminated in the finals gets place 2; both teams eliminated in the semifinals get place 3; all teams eliminated in the quarterfinals get place 5; all teams eliminated in the 1/8 finals get place 9, and so on. For example, this picture describes one of the possible ways the tournament can go with k = 3, and the resulting places of the teams: After a tournament which was conducted by the aforementioned rules ended, its results were encoded in the following way. Let p_i be the place of the i-th team in the tournament. The hash value of the tournament h is calculated as h = (\sum \limits_{i=1}^{2^k} i \cdot A^{p_i}) \bmod 998244353, where A is some given integer.Unfortunately, due to a system crash, almost all tournament-related data was lost. The only pieces of data that remain are the values of k, A and h. You are asked to restore the resulting placing of the teams in the tournament, if it is possible at all.InputThe only line contains three integers k, A and h (1 \le k \le 5; 100 \le A \le 10^8; 0 \le h \le 998244352).OutputIf it is impossible to find any placing of the teams that is consistent with the data you have, print one integer -1.Otherwise, print 2^k integers, where i-th integer should be equal to p_i (the place of the i-th team). Note that your answer should be consistent with one of the possible ways the tournament could go, and note that the initial structure of the tournament is fixed (for example, teams 1 and 2 always play in the first phase of the tournament against each other). If there are multiple ways to restore the places of the teams which are consistent with the data you have, print any of them.ExamplesInput 3 1337 75275197 Output 5 3 5 2 1 5 5 3 Input 2 100 5040100 Output 1 3 3 2 Input 2 100 7020100 Output -1 NoteThe tournament for the first example is described in the statement.For the third example, the placing [1, 2, 3, 3] (team 1 gets place 1, team 2 gets place 2, teams 3 and 4 get place 3) could result in a hash value of 7020100 with A = 100, but no tournament can result in such placing since teams 1 and 2 play against each other in the semifinals, so they cannot get two first places.
3 1337 75275197
5 3 5 2 1 5 5 3
4 seconds
512 megabytes
['bitmasks', 'brute force', 'hashing', 'implementation', 'meet-in-the-middle', '*2600']
D. Inconvenient Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a city that can be represented as a square grid with corner points in (0, 0) and (10^6, 10^6).The city has n vertical and m horizontal streets that goes across the whole city, i. e. the i-th vertical streets goes from (x_i, 0) to (x_i, 10^6) and the j-th horizontal street goes from (0, y_j) to (10^6, y_j). All streets are bidirectional. Borders of the city are streets as well.There are k persons staying on the streets: the p-th person at point (x_p, y_p) (so either x_p equal to some x_i or y_p equal to some y_j, or both).Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them.Calculate the number of inconvenient pairs of persons (pairs (x, y) and (y, x) are the same pair).Let's recall that Manhattan distance between points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains three integers n, m and k (2 \le n, m \le 2 \cdot 10^5; 2 \le k \le 3 \cdot 10^5) — the number of vertical and horizontal streets and the number of persons.The second line of each test case contains n integers x_1, x_2, \dots, x_n (0 = x_1 < x_2 < \dots < x_{n - 1} < x_n = 10^6) — the x-coordinates of vertical streets.The third line contains m integers y_1, y_2, \dots, y_m (0 = y_1 < y_2 < \dots < y_{m - 1} < y_m = 10^6) — the y-coordinates of horizontal streets.Next k lines contains description of people. The p-th line contains two integers x_p and y_p (0 \le x_p, y_p \le 10^6; x_p \in \{x_1, \dots, x_n\} or y_p \in \{y_1, \dots, y_m\}) — the coordinates of the p-th person. All points are distinct.It guaranteed that sum of n doesn't exceed 2 \cdot 10^5, sum of m doesn't exceed 2 \cdot 10^5 and sum of k doesn't exceed 3 \cdot 10^5.OutputFor each test case, print the number of inconvenient pairs.ExampleInput 2 2 2 4 0 1000000 0 1000000 1 0 1000000 1 999999 1000000 0 999999 5 4 9 0 1 2 6 1000000 0 4 8 1000000 4 4 2 5 2 2 6 3 1000000 1 3 8 5 8 8 8 6 8 Output 2 5 NoteThe second test case is pictured below: For example, points 3 and 4 form an inconvenient pair, since the shortest path between them (shown red and equal to 7) is greater than its Manhattan distance (equal to 5).Points 3 and 5 also form an inconvenient pair: the shortest path equal to 1000001 (shown green) is greater than the Manhattan distance equal to 999999.But points 5 and 9 don't form an inconvenient pair, since the shortest path (shown purple) is equal to its Manhattan distance.
2 2 2 4 0 1000000 0 1000000 1 0 1000000 1 999999 1000000 0 999999 5 4 9 0 1 2 6 1000000 0 4 8 1000000 4 4 2 5 2 2 6 3 1000000 1 3 8 5 8 8 8 6 8
2 5
2 seconds
256 megabytes
['binary search', 'data structures', 'implementation', 'sortings', 'two pointers', '*1900']
C. Jury Meetingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people gathered to hold a jury meeting of the upcoming competition, the i-th member of the jury came up with a_i tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation p of numbers from 1 to n (an array of size n where each integer from 1 to n occurs exactly once).Then the discussion goes as follows: If a jury member p_1 has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If a jury member p_2 has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. ... If a jury member p_n has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation p is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo 998\,244\,353.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of the test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — number of jury members.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the number of problems that the i-th member of the jury came up with.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the number of nice permutations, taken modulo 998\,244\,353.ExampleInput 4 2 1 2 3 5 5 5 4 1 3 3 7 6 3 4 2 1 3 3 Output 1 6 0 540 NoteExplanation of the first test case from the example:There are two possible permutations, p = [1, 2] and p = [2, 1]. For p = [1, 2], the process is the following: the first jury member tells a task; the second jury member tells a task; the first jury member doesn't have any tasks left to tell, so they are skipped; the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice.For p = [2, 1], the process is the following: the second jury member tells a task; the first jury member tells a task; the second jury member tells a task. So, this permutation is nice.
4 2 1 2 3 5 5 5 4 1 3 3 7 6 3 4 2 1 3 3
1 6 0 540
2 seconds
256 megabytes
['combinatorics', 'math', '*1500']
B. Chess Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA chess tournament will be held soon, where n chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players.Each of the players has their own expectations about the tournament, they can be one of two types: a player wants not to lose any game (i. e. finish the tournament with zero losses); a player wants to win at least one game. You have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible.InputThe first line contains a single integer t (1 \le t \le 200) — the number of test cases.The first line of each test case contains one integer n (2 \le n \le 50) — the number of chess players.The second line contains the string s (|s| = n; s_i \in \{1, 2\}). If s_i = 1, then the i-th player has expectations of the first type, otherwise of the second type.OutputFor each test case, print the answer in the following format:In the first line, print NO if it is impossible to meet the expectations of all players.Otherwise, print YES, and the matrix of size n \times n in the next n lines.The matrix element in the i-th row and j-th column should be equal to: +, if the i-th player won in a game against the j-th player; -, if the i-th player lost in a game against the j-th player; =, if the i-th and j-th players' game resulted in a draw; X, if i = j. ExampleInput 3 3 111 2 21 4 2122 Output YES X== =X= ==X NO YES X--+ +X++ +-X- --+X
3 3 111 2 21 4 2122
YES X== =X= ==X NO YES X--+ +X++ +-X- --+X
2 seconds
256 megabytes
['constructive algorithms', '*1000']
A. Balanced Substringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of n letters, each letter is either 'a' or 'b'. The letters in the string are numbered from 1 to n.s[l; r] is a continuous substring of letters from index l to r of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings "baba" and "aabbab" are balanced and strings "aaab" and "b" are not.Find any non-empty balanced substring s[l; r] of string s. Print its l and r (1 \le l \le r \le n). If there is no such substring, then print -1 -1.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Then the descriptions of t testcases follow.The first line of the testcase contains a single integer n (1 \le n \le 50) — the length of the string.The second line of the testcase contains a string s, consisting of n letters, each letter is either 'a' or 'b'.OutputFor each testcase print two integers. If there exists a non-empty balanced substring s[l; r], then print l r (1 \le l \le r \le n). Otherwise, print -1 -1.ExampleInput 4 1 a 6 abbaba 6 abbaba 9 babbabbaa Output -1 -1 1 6 3 6 2 5 NoteIn the first testcase there are no non-empty balanced subtrings.In the second and third testcases there are multiple balanced substrings, including the entire string "abbaba" and substring "baba".
4 1 a 6 abbaba 6 abbaba 9 babbabbaa
-1 -1 1 6 3 6 2 5
2 seconds
256 megabytes
['implementation', '*800']
F. One-Four Overloadtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has an empty grid with n rows and m columns. Some of the cells are marked, and no marked cells are adjacent to the edge of the grid. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: every unmarked cell contains either the number 1 or 4; every marked cell contains the sum of the numbers in all unmarked cells adjacent to it (if a marked cell is not adjacent to any unmarked cell, this sum is 0); every marked cell contains a multiple of 5. Alice couldn't figure it out, so she asks Bob to help her. Help Bob find any such grid, or state that no such grid exists.InputThe first line of input contains two integers n and m (1 \leq n, m \leq 500) — the number of rows and the number of columns in the grid, respectively.Then n lines follow, each containing m characters. Each of these characters is either '.' or 'X' — an unmarked and a marked cell, respectively. No marked cells are adjacent to the edge of the grid.OutputOutput "'NO" if no suitable grid exists. Otherwise, output "'YES"'. Then output n lines of m space-separated integers — the integers in the grid.ExamplesInput 5 5 ..... .XXX. .X.X. .XXX. ..... Output YES 4 1 4 4 1 4 5 5 5 1 4 5 1 5 4 1 5 5 5 4 1 4 4 1 4 Input 5 5 ..... .XXX. .XXX. .XXX. ..... Output NO Input 3 2 .. .. .. Output YES 4 1 4 1 1 4 Input 9 9 ......... .XXXXX.X. .X...X... .X.XXXXX. .X.X.X.X. .X.XXX.X. .X.....X. .XXXXXXX. ......... Output YES 4 4 4 1 4 1 4 1 4 1 5 5 5 5 5 4 10 1 4 5 1 4 1 5 4 4 4 4 5 1 5 5 0 5 5 1 4 5 1 5 4 5 1 5 4 4 5 1 5 5 5 4 5 1 1 5 4 4 1 1 4 5 1 4 5 5 5 5 5 5 5 4 1 1 1 1 4 4 1 1 4 NoteIt can be shown that no such grid exists for the second test.
5 5 ..... .XXX. .X.X. .XXX. .....
YES 4 1 4 4 1 4 5 5 5 1 4 5 1 5 4 1 5 5 5 4 1 4 4 1 4
2 seconds
256 megabytes
['2-sat', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'implementation', '*2700']
E. Non-Decreasing Dilemmatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has recently received an array a_1, a_2, \dots, a_n for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too!However, soon Bob became curious, and as any sane friend would do, asked Alice to perform q operations of two types on her array: 1 x y: update the element a_x to y (set a_x = y). 2 l r: calculate how many non-decreasing subarrays exist within the subarray [a_l, a_{l+1}, \dots, a_r]. More formally, count the number of pairs of integers (p,q) such that l \le p \le q \le r and a_p \le a_{p+1} \le \dots \le a_{q-1} \le a_q. Help Alice answer Bob's queries!InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the size of the array, and the number of queries, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of Alice's array.The next q lines consist of three integers each. The first integer of the i-th line is t_i, the operation being performed on the i-th step (t_i = 1 or t_i = 2).If t_i = 1, the next two integers are x_i and y_i (1 \le x_i \le n; 1 \le y_i \le 10^9), updating the element at position x_i to y_i (setting a_{x_i} = y_i).If t_i = 2, the next two integers are l_i and r_i (1 \le l_i \le r_i \le n), the two indices Bob asks Alice about for the i-th query.It's guaranteed that there is at least one operation of the second type.OutputFor each query of type 2, print a single integer, the answer to the query.ExampleInput 5 6 3 1 4 1 5 2 2 5 2 1 3 1 4 4 2 2 5 1 2 6 2 2 5 Output 6 4 10 7 NoteFor the first query, l = 2 and r = 5, and the non-decreasing subarrays [p,q] are [2,2], [3,3], [4,4], [5,5], [2,3] and [4,5].
5 6 3 1 4 1 5 2 2 5 2 1 3 1 4 4 2 2 5 1 2 6 2 2 5
6 4 10 7
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'math', '*2200']
D. Expression Evaluation Errortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the board, Bob wrote n positive integers in base 10 with sum s (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-11 integers and adds them up (in base 11).What numbers should Bob write on the board, so Alice's sum is as large as possible?InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers s and n (1 \leq s \leq 10^9; 1 \leq n \leq \min(100, s)) — the sum and amount of numbers on the board, respectively. Numbers s and n are given in decimal notation (base 10).OutputFor each test case, output n positive integers — the numbers Bob should write on the board, so Alice's sum is as large as possible. If there are multiple answers, print any of them.ExampleInput 6 97 2 17 1 111 4 100 2 10 9 999999 3 Output 70 27 17 3 4 100 4 10 90 1 1 2 1 1 1 1 1 1 999900 90 9 NoteIn the first test case, 70_{10} + 27_{10} = 97_{10}, and Alice's sum is 70_{11} + 27_{11} = 97_{11} = 9 \cdot 11 + 7 = 106_{10}. (Here x_b represents the number x in base b.) It can be shown that it is impossible for Alice to get a larger sum than 106_{10}.In the second test case, Bob can only write a single number on the board, so he must write 17.In the third test case, 3_{10} + 4_{10} + 100_{10} + 4_{10} = 111_{10}, and Alice's sum is 3_{11} + 4_{11} + 100_{11} + 4_{11} = 110_{11} = 1 \cdot 11^2 + 1 \cdot 11 = 132_{10}. It can be shown that it is impossible for Alice to get a larger sum than 132_{10}.
6 97 2 17 1 111 4 100 2 10 9 999999 3
70 27 17 3 4 100 4 10 90 1 1 2 1 1 1 1 1 1 999900 90 9
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*2000']
C. Carrying Conundrumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum 2039 + 2976 would be as shown: However, Alice evaluates it as shown: In particular, this is what she does: add 9 and 6 to make 15, and carry the 1 to the column two columns to the left, i. e. to the column "0 9"; add 3 and 7 to make 10 and carry the 1 to the column two columns to the left, i. e. to the column "2 2"; add 1, 0, and 9 to make 10 and carry the 1 to the column two columns to the left, i. e. to the column above the plus sign; add 1, 2 and 2 to make 5; add 1 to make 1. Thus, she ends up with the incorrect result of 15005.Alice comes up to Bob and says that she has added two numbers to get a result of n. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of n. Note that pairs (a, b) and (b, a) are considered different if a \ne b.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The only line of each test case contains an integer n (2 \leq n \leq 10^9) — the number Alice shows Bob.OutputFor each test case, output one integer — the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of n. ExampleInput 5 100 12 8 2021 10000 Output 9 4 7 44 99 NoteIn the first test case, when Alice evaluates any of the sums 1 + 9, 2 + 8, 3 + 7, 4 + 6, 5 + 5, 6 + 4, 7 + 3, 8 + 2, or 9 + 1, she will get a result of 100. The picture below shows how Alice evaluates 6 + 4:
5 100 12 8 2021 10000
9 4 7 44 99
2 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', '*1600']
B. MEXor Mixuptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice gave Bob two integers a and b (a > 0 and b \ge 0). Being a curious boy, Bob wrote down an array of non-negative integers with \operatorname{MEX} value of all elements equal to a and \operatorname{XOR} value of all elements equal to b.What is the shortest possible length of the array Bob wrote?Recall that the \operatorname{MEX} (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the \operatorname{XOR} of an array is the bitwise XOR of all the elements of the array.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 5 \cdot 10^4) — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers a and b (1 \leq a \leq 3 \cdot 10^5; 0 \leq b \leq 3 \cdot 10^5) — the \operatorname{MEX} and \operatorname{XOR} of the array, respectively.OutputFor each test case, output one (positive) integer — the length of the shortest array with \operatorname{MEX} a and \operatorname{XOR} b. We can show that such an array always exists.ExampleInput 5 1 1 2 1 2 0 1 10000 2 10000 Output 3 2 3 2 3 NoteIn the first test case, one of the shortest arrays with \operatorname{MEX} 1 and \operatorname{XOR} 1 is [0, 2020, 2021].In the second test case, one of the shortest arrays with \operatorname{MEX} 2 and \operatorname{XOR} 1 is [0, 1].It can be shown that these arrays are the shortest arrays possible.
5 1 1 2 1 2 0 1 10000 2 10000
3 2 3 2 3
2 seconds
256 megabytes
['bitmasks', 'greedy', '*1000']
A. Domino Disastertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a grid with 2 rows and n columns. She fully covers the grid using n dominoes of size 1 \times 2 — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 5000) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 100) — the width of the grid.The second line of each test case contains a string s consisting of n characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid. Additional constraint on the input: each input corresponds to at least one valid tiling.OutputFor each test case, output one string — the other row of the grid, using the same format as the input string. If there are multiple answers, print any.ExampleInput 4 1 U 2 LR 5 LRDLR 6 UUUUUU Output D LR LRULR DDDDDD NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like: In the second test case, Alice shows Bob the bottom row, the whole grid may look like: In the third test case, Alice shows Bob the bottom row, the whole grid may look like: In the fourth test case, Alice shows Bob the top row, the whole grid may look like:
4 1 U 2 LR 5 LRDLR 6 UUUUUU
D LR LRULR DDDDDD
2 seconds
256 megabytes
['implementation', 'strings', '*800']
H. Xor-quiztime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.You are given two integers c and n. The jury has a randomly generated set A of distinct positive integers not greater than c (it is generated from all such possible sets with equal probability). The size of A is equal to n.Your task is to guess the set A. In order to guess it, you can ask at most \lceil 0.65 \cdot c \rceil queries.In each query, you choose a single integer 1 \le x \le c. As the answer to this query you will be given the bitwise xor sum of all y, such that y \in A and gcd(x, y) = 1 (i.e. x and y are coprime). If there is no such y this xor sum is equal to 0.You can ask all queries at the beginning and you will receive the answers to all your queries. After that, you won't have the possibility to ask queries.You should find any set A', such that |A'| = n and A' and A have the same answers for all c possible queries.InputFirstly you are given two integers c and n (100 \le c \le 10^6, 0 \le n \le c).InteractionIn the first line you should print an integer q (0 \le q \le \lceil 0.65 \cdot c \rceil) — the number of queries you want to ask. After that in the same line print q integers x_1, x_2, \ldots, x_q (1 \le x_i \le c) — the queries.For these queries you should read q integers, i-th of them is the answer to the described query for x = x_i.After that you should print n distinct integers A'_1, A'_2, \ldots, A'_n — the set A' you found.If there are different sets A' that have the same answers for all possible queries, print any of them.If you will ask more than \lceil 0.65 \cdot c \rceil queries or if the queries will be invalid, the interactor will terminate immediately and your program will receive verdict Wrong Answer.After printing the queries and answers do not forget to output end of line and flush the output buffer. Otherwise, you will get the Idleness limit exceeded verdict. To do flush use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; Read documentation for other languages. HacksYou cannot make hacks in this problem.ExampleInput 10 6 1 4 2 11 4 4 4 Output 7 10 2 3 5 7 1 6 1 4 5 6 8 10 NoteThe sample is made only for you to understand the interaction protocol. Your solution will not be tested on the sample.In the sample A = \{1, 4, 5, 6, 8, 10\}. 7 queries are made, 7 \le \lceil 0.65 \cdot 10 \rceil = 7, so the query limit is not exceeded.Answers for the queries: For 10: 1 is the only number in the set A coprime with 10, so the answer is 1 For 2: 1_{10} \oplus 5_{10} = 001_2 \oplus 101_2 = 4_{10}, where \oplus is the bitwise xor For 3: 1_{10} \oplus 4_{10} \oplus 5_{10} \oplus 8_{10} \oplus 10_{10} = 0001_2 \oplus 0100_2 \oplus 0101_2 \oplus 1000_2 \oplus 1010_2 = 2_{10} For 5: 1_{10} \oplus 4_{10} \oplus 6_{10} \oplus 8_{10} = 0001_2 \oplus 0100_2 \oplus 0110_2 \oplus 1000_2 = 11_{10} For 7: 1_{10} \oplus 4_{10} \oplus 5_{10} \oplus 6_{10} \oplus 8_{10} \oplus 10_{10} = 0001_2 \oplus 0100_2 \oplus 0101_2 \oplus 0110_2 \oplus 1000_2 \oplus 1010_2 = 4_{10} For 1: 1_{10} \oplus 4_{10} \oplus 5_{10} \oplus 6_{10} \oplus 8_{10} \oplus 10_{10} = 0001_2 \oplus 0100_2 \oplus 0101_2 \oplus 0110_2 \oplus 1000_2 \oplus 1010_2 = 4_{10} For 6: 1_{10} \oplus 5_{10} = 0001_2 \oplus 0101_2 = 4_{10}
10 6 1 4 2 11 4 4 4
7 10 2 3 5 7 1 6 1 4 5 6 8 10
4 seconds
256 megabytes
['constructive algorithms', 'dp', 'interactive', 'math', 'number theory', '*3200']
G. Four Verticestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected weighted graph, consisting of n vertices and m edges.Some queries happen with this graph: Delete an existing edge from the graph. Add a non-existing edge to the graph. At the beginning and after each query, you should find four different vertices a, b, c, d such that there exists a path between a and b, there exists a path between c and d, and the sum of lengths of two shortest paths from a to b and from c to d is minimal. The answer to the query is the sum of the lengths of these two shortest paths. The length of the path is equal to the sum of weights of edges in this path.InputThe first line contains two integers n and m (4 \le n, m \le 10^5) — the number of vertices and edges in the graph respectively.Each of the next m lines contain three integers v, u, w (1 \le v, u \le n, v \neq u, 1 \le w \le 10^9) — this triple means that there is an edge between vertices v and u with weight w.The next line contains a single integer q (0 \le q \le 10^5) — the number of queries.The next q lines contain the queries of two types: 0 v u — this query means deleting an edge between v and u (1 \le v, u \le n, v \neq u). It is guaranteed that such edge exists in the graph. 1 v u w — this query means adding an edge between vertices v and u with weight w (1 \le v, u \le n, v \neq u, 1 \le w \le 10^9). It is guaranteed that there was no such edge in the graph. It is guaranteed that the initial graph does not contain multiple edges.At the beginning and after each query, the graph doesn't need to be connected.It is guaranteed that at each moment the number of edges will be at least 4. It can be proven, that at each moment there exist some four vertices a, b, c, d such that there exists a path between vertices a and b, and there exists a path between vertices c and d.OutputPrint q + 1 integers — the minimal sum of lengths of shortest paths between chosen pairs of vertices before the queries and after each of them.ExampleInput 6 6 1 3 6 4 3 1 1 4 1 2 6 4 2 4 2 5 4 3 4 1 2 5 2 0 1 4 0 3 4 1 6 1 3 Output 4 3 3 7 5 NoteBefore the queries you can choose vertices (a, b) = (3, 2) and (c, d) = (1, 4). The sum of lengths of two shortest paths is 3 + 1 = 4.After the first query you can choose vertices (a, b) = (2, 5) and (c, d) = (1, 4). The sum of lengths of two shortest paths is 2 + 1 = 3.After the second query you can choose vertices (a, b) = (3, 4) and (c, d) = (2, 5). The sum of lengths of two shortest paths is 1 + 2 = 3.After the third query, you can choose vertices (a, b) = (2, 6) and (c, d) = (4, 5). The sum of lengths of two shortest paths is 4 + 3 = 7.After the last query you can choose vertices (a, b) = (1, 6) and (c, d) = (2, 5). The sum of lengths of two shortest paths is 3 + 2 = 5.
6 6 1 3 6 4 3 1 1 4 1 2 6 4 2 4 2 5 4 3 4 1 2 5 2 0 1 4 0 3 4 1 6 1 3
4 3 3 7 5
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'graphs', 'greedy', 'implementation', 'shortest paths', '*3100']
F. Points Movementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points and m segments on the coordinate line. The initial coordinate of the i-th point is a_i. The endpoints of the j-th segment are l_j and r_j — left and right endpoints, respectively.You can move the points. In one move you can move any point from its current coordinate x to the coordinate x - 1 or the coordinate x + 1. The cost of this move is 1.You should move the points in such a way that each segment is visited by at least one point. A point visits the segment [l, r] if there is a moment when its coordinate was on the segment [l, r] (including endpoints).You should find the minimal possible total cost of all moves such that all segments are visited.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of points and segments respectively.The next line contains n distinct integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the initial coordinates of the points.Each of the next m lines contains two integers l_j, r_j (-10^9 \le l_j \le r_j \le 10^9) — the left and the right endpoints of the j-th segment.It's guaranteed that the sum of n and the sum of m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer — the minimal total cost of all moves such that all segments are visited.ExampleInput 2 4 11 2 6 14 18 0 3 4 5 11 15 3 5 10 13 16 16 1 4 8 12 17 19 7 13 14 19 4 12 -9 -16 12 3 -20 -18 -14 -13 -10 -7 -3 -1 0 4 6 11 7 9 8 10 13 15 14 18 16 17 18 19 Output 5 22 NoteIn the first test case the points can be moved as follows: Move the second point from the coordinate 6 to the coordinate 5. Move the third point from the coordinate 14 to the coordinate 13. Move the fourth point from the coordinate 18 to the coordinate 17. Move the third point from the coordinate 13 to the coordinate 12. Move the fourth point from the coordinate 17 to the coordinate 16. The total cost of moves is 5. It is easy to see, that all segments are visited by these movements. For example, the tenth segment ([7, 13]) is visited after the second move by the third point.Here is the image that describes the first test case:
2 4 11 2 6 14 18 0 3 4 5 11 15 3 5 10 13 16 16 1 4 8 12 17 19 7 13 14 19 4 12 -9 -16 12 3 -20 -18 -14 -13 -10 -7 -3 -1 0 4 6 11 7 9 8 10 13 15 14 18 16 17 18 19
5 22
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'implementation', 'sortings', '*2600']
E. Buds Re-hangingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex v (different from root) is the previous to v vertex on the shortest path from the root to the vertex v. Children of the vertex v are all vertices for which v is the parent.A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied: it is not a root, it has at least one child, and all its children are leaves. You are given a rooted tree with n vertices. The vertex 1 is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of the vertices in the given tree.Each of the next n-1 lines contains two integers u and v (1 \le u, v \le n, u \neq v) meaning that there is an edge between vertices u and v in the tree.It is guaranteed that the given graph is a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print a single integer — the minimal number of leaves that is possible to get after some operations.ExampleInput 5 7 1 2 1 3 1 4 2 5 2 6 4 7 6 1 2 1 3 2 4 2 5 3 6 2 1 2 7 7 3 1 5 1 3 4 6 4 7 2 1 6 2 1 2 3 4 5 3 4 3 6 Output 2 2 1 2 1 NoteIn the first test case the tree looks as follows: Firstly you can choose a bud vertex 4 and re-hang it to vertex 3. After that you can choose a bud vertex 2 and re-hang it to vertex 7. As a result, you will have the following tree with 2 leaves: It can be proved that it is the minimal number of leaves possible to get.In the second test case the tree looks as follows: You can choose a bud vertex 3 and re-hang it to vertex 5. As a result, you will have the following tree with 2 leaves: It can be proved that it is the minimal number of leaves possible to get.
5 7 1 2 1 3 1 4 2 5 2 6 4 7 6 1 2 1 3 2 4 2 5 3 6 2 1 2 7 7 3 1 5 1 3 4 6 4 7 2 1 6 2 1 2 3 4 5 3 4 3 6
2 2 1 2 1
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees', '*2000']
D2. Seating Arrangements (hard version) time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the hard version of the problem. The only difference is that in this version 1 \le n \le 300.In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 \le k \le n. 12\cdotsm - 1mm + 1m + 2\cdots2 m - 12 m2m + 12m + 2\cdots3 m - 13 m\vdots\vdots\ddots\vdots\vdotsm (n - 1) + 1m (n - 1) + 2\cdotsn m - 1n m The table with seats indices There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j.After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n, m \le 300) — the number of rows and places in each row respectively.The second line of each test case contains n \cdot m integers a_1, a_2, \ldots, a_{n \cdot m} (1 \le a_i \le 10^9), where a_i is the sight level of i-th person.It's guaranteed that the sum of n \cdot m over all test cases does not exceed 10^5.OutputFor each test case print a single integer — the minimal total inconvenience that can be achieved.ExampleInput 7 1 2 1 2 3 2 1 1 2 2 3 3 3 3 3 4 4 1 1 1 1 1 2 2 2 1 1 2 1 4 2 50 50 50 50 3 50 50 50 4 2 6 6 6 6 2 2 9 6 2 9 1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3 Output 1 0 4 0 0 0 1 NoteIn the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is 1.In the second test case the optimal seating looks like this: In the third test case the optimal seating looks like this: The number in a cell is the person's index that sits on this place.
7 1 2 1 2 3 2 1 1 2 2 3 3 3 3 3 4 4 1 1 1 1 1 2 2 2 1 1 2 1 4 2 50 50 50 50 3 50 50 50 4 2 6 6 6 6 2 2 9 6 2 9 1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3
1 0 4 0 0 0 1
1 second
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', 'two pointers', '*1600']
D1. Seating Arrangements (easy version) time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the easy version of the problem. The only difference is that in this version n = 1.In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 \le k \le n. 12\cdotsm - 1mm + 1m + 2\cdots2 m - 12 m2m + 12m + 2\cdots3 m - 13 m\vdots\vdots\ddots\vdots\vdotsm (n - 1) + 1m (n - 1) + 2\cdotsn m - 1n m The table with seats indices There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j.After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (n = 1, 1 \le m \le 300) — the number of rows and places in each row respectively.The second line of each test case contains n \cdot m integers a_1, a_2, \ldots, a_{n \cdot m} (1 \le a_i \le 10^9), where a_i is the sight level of i-th person.It's guaranteed that the sum of n \cdot m over all test cases does not exceed 10^5.OutputFor each test case print a single integer — the minimal total inconvenience that can be achieved.ExampleInput 4 1 3 1 2 3 1 5 2 1 5 3 3 1 2 2 1 1 6 2 3 2 1 1 1 Output 3 6 0 1 NoteIn the first test case, there is a single way to arrange people, because all sight levels are distinct. The first person will sit on the first seat, the second person will sit on the second place, the third person will sit on the third place. So inconvenience of the first person will be 0, inconvenience of the second person will be 1 and inconvenience of the third person will be 2. The total inconvenience is 0 + 1 + 2 = 3.In the second test case, people should sit as follows: s_1 = 2, s_2 = 1, s_3 = 5, s_4 = 4, s_5 = 3. The total inconvenience will be 6.
4 1 3 1 2 3 1 5 2 1 5 3 3 1 2 2 1 1 6 2 3 2 1 1 1
3 6 0 1
1 second
256 megabytes
['data structures', 'greedy', 'sortings', '*1100']
C. MAX-MEX Cuttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string is a string that consists of characters 0 and 1. A bi-table is a table that has exactly two rows of equal length, each being a binary string.Let \operatorname{MEX} of a bi-table be the smallest digit among 0, 1, or 2 that does not occur in the bi-table. For example, \operatorname{MEX} for \begin{bmatrix} 0011\\ 1010 \end{bmatrix} is 2, because 0 and 1 occur in the bi-table at least once. \operatorname{MEX} for \begin{bmatrix} 111\\ 111 \end{bmatrix} is 0, because 0 and 2 do not occur in the bi-table, and 0 < 2.You are given a bi-table with n columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table.What is the maximal sum of \operatorname{MEX} of all resulting bi-tables can be?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.The first line of the description of each test case contains a single integer n (1 \le n \le 10^5) — the number of columns in the bi-table.Each of the next two lines contains a binary string of length n — the rows of the bi-table.It's guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print a single integer — the maximal sum of \operatorname{MEX} of all bi-tables that it is possible to get by cutting the given bi-table optimally.ExampleInput 4 7 0101000 1101100 5 01100 10101 2 01 01 6 000000 111111 Output 8 8 2 12 NoteIn the first test case you can cut the bi-table as follows: \begin{bmatrix} 0\\ 1 \end{bmatrix}, its \operatorname{MEX} is 2. \begin{bmatrix} 10\\ 10 \end{bmatrix}, its \operatorname{MEX} is 2. \begin{bmatrix} 1\\ 1 \end{bmatrix}, its \operatorname{MEX} is 0. \begin{bmatrix} 0\\ 1 \end{bmatrix}, its \operatorname{MEX} is 2. \begin{bmatrix} 0\\ 0 \end{bmatrix}, its \operatorname{MEX} is 1. \begin{bmatrix} 0\\ 0 \end{bmatrix}, its \operatorname{MEX} is 1.The sum of \operatorname{MEX} is 8.
4 7 0101000 1101100 5 01100 10101 2 01 01 6 000000 111111
8 8 2 12
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'greedy', '*1000']
B. MIN-MEX Cuttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string is a string that consists of characters 0 and 1.Let \operatorname{MEX} of a binary string be the smallest digit among 0, 1, or 2 that does not occur in the string. For example, \operatorname{MEX} of 001011 is 2, because 0 and 1 occur in the string at least once, \operatorname{MEX} of 1111 is 0, because 0 and 2 do not occur in the string and 0 < 2.A binary string s is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.What is the minimal sum of \operatorname{MEX} of all substrings pieces can be?InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.Each test case contains a single binary string s (1 \le |s| \le 10^5).It's guaranteed that the sum of lengths of s over all test cases does not exceed 10^5.OutputFor each test case print a single integer — the minimal sum of \operatorname{MEX} of all substrings that it is possible to get by cutting s optimally.ExampleInput 6 01 1111 01100 101 0000 01010 Output 1 0 2 1 1 2 NoteIn the first test case the minimal sum is \operatorname{MEX}(0) + \operatorname{MEX}(1) = 1 + 0 = 1.In the second test case the minimal sum is \operatorname{MEX}(1111) = 0.In the third test case the minimal sum is \operatorname{MEX}(01100) = 2.
6 01 1111 01100 101 0000 01010
1 0 2 1 1 2
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'greedy', '*800']
A. Median Maximizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers n and s. Find the maximum possible median of an array of n non-negative integers (not necessarily distinct), such that the sum of its elements is equal to s.A median of an array of integers of length m is the number standing on the \lceil {\frac{m}{2}} \rceil-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from 1. For example, a median of the array [20,40,20,50,50,30] is the \lceil \frac{m}{2} \rceil-th element of [20,20,30,40,50,50], so it is 30. There exist other definitions of the median, but in this problem we use the described definition.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Description of the test cases follows.Each test case contains a single line with two integers n and s (1 \le n, s \le 10^9) — the length of the array and the required sum of the elements.OutputFor each test case print a single integer — the maximum possible median.ExampleInput 8 1 5 2 5 3 5 2 1 7 17 4 14 1 1000000000 1000000000 1 Output 5 2 2 0 4 4 1000000000 0 NotePossible arrays for the first three test cases (in each array the median is underlined): In the first test case [\underline{5}] In the second test case [\underline{2}, 3] In the third test case [1, \underline{2}, 2]
8 1 5 2 5 3 5 2 1 7 17 4 14 1 1000000000 1000000000 1
5 2 2 0 4 4 1000000000 0
1 second
256 megabytes
['binary search', 'greedy', 'math', '*800']
F. Tubular Bellstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDo you know what tubular bells are? They are a musical instrument made up of cylindrical metal tubes. In an orchestra, tubular bells are used to mimic the ringing of bells.Mike has tubular bells, too! They consist of n tubes, and each of the tubes has a length that can be expressed by a integer from l to r inclusive. It is clear that the lengths of all the tubes are different (it makes no sense to make the same tubes). It is also known that r-l+1 = n.Formally, we can say that Mike's tubular bells are described by a permutation a of length n that contains all numbers from l to r inclusive, with a_i denoting the length of the i-th tube.You are offered an interesting task: to guess what Mike's instrument looks like. Simply, you must guess the permutation.Mike won't tell you l or r. He will only tell you n, and will allow you to ask no more than n + 5000 queries.In each query, you name two positive integers x, y such that 1 \le x, y \le n, x \neq y. In response to this query, the program written by Mike will give you \mathrm{lcm}(a_x, a_y), where \mathrm{lcm}(c,d) denotes the least common multiple of c and d.Solve Mike's problem!InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 20), denoting the number of test cases. Description of the test cases follows.The single line of each test case contains one positive integer n (3 \le n \le 10^5) — number of tubes in Mike's tubular bells. Also 1 \le l \le r \le 2 \cdot 10^5, i.e. the lengths of the tubes do not exceed 2 \cdot 10^5.It is guaranteed that the sum of maximal number of queries (i.e. n + 5000) over all test cases does not exceed 10^5 + 5000. It means that sum of n does not exceed 10^5 + 5000 - t \cdot 5000.InteractionFor each set of input data, read one integer n. You are allowed to make no more than n + 5000 queries.If you want to make a query, output it in the format "? x y", where x and y — the numbers of tubes for which you learn the lcm (least common multiple) of their lengths. Note that 1 \le x, y \le n, x \neq y must be satisfied. The interactor will return a single integer —the answer to your query.If you are ready to print the answer, print it in the format "! a_1 a_2 ... a_n". The output of the answer is not considered a query and is not included in the number of queries.After each query and answer output, don't forget to output the line translation and reset the output buffer. Otherwise you will get the verdict "Idleness limit exceeded". To reset the buffer 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. Note that the interactor is not adaptive. That is, the original permutation is fixed in the beginning and don't depend on your queries.Hacks:Use the following format for hacks:The first line contains a single positive integer t (1 \le t \le 20) — the number of input datasets. A description of the input data sets is given below.The first line of each test case contains one positive integer n (3 \le n \le 10^5) —the number of tubes. It is known that 1 \le l \le r \le 2 \cdot 10^5, i.e. the lengths of the tubes do not exceed 2 \cdot 10^5.The second line of each test case contains an array a of n positive integers — the lengths of the tubes in each input dataset. Remember that l \le a_i \le r and r-l+1 = n, and that all a_i are different.ExampleInput 3 5 8 10 7 6 9 5 24 25 28 27 26 7 1 2 3 4 5 6 7 Output ? 1 2 40 ? 2 5 90 ? 3 1 56 ? 4 5 18 ! 8 10 7 6 9 ? 1 5 312 ? 2 4 675 ! 24 25 28 27 26 ? 1 4 4 ? 2 5 10 ? 3 7 21 ? 6 2 6 ? 2 5 10 ? 1 2 2 ? 1 2 2 ? 1 2 2 ? 1 2 2 ? 1 2 2 ! 1 2 3 4 5 6 7
3 5 8 10 7 6 9 5 24 25 28 27 26 7 1 2 3 4 5 6 7
? 1 2 40 ? 2 5 90 ? 3 1 56 ? 4 5 18 ! 8 10 7 6 9 ? 1 5 312 ? 2 4 675 ! 24 25 28 27 26 ? 1 4 4 ? 2 5 10 ? 3 7 21 ? 6 2 6 ? 2 5 10 ? 1 2 2 ? 1 2 2 ? 1 2 2 ? 1 2 2 ? 1 2 2 ! 1 2 3 4 5 6 7
5 seconds
512 megabytes
['interactive', 'math', 'number theory', 'probabilities', '*2900']
E. Rescue Niwen!time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output Morning desert sun horizonRise above the sands of time...Fates Warning, "Exodus"After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open!Ori was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository.The Gorleks were very fond of the "string expansion" operation. They were also very fond of increasing subsequences.Suppose a string s_1s_2s_3 \ldots s_n is given. Then its "expansion" is defined as the sequence of strings s_1, s_1 s_2, ..., s_1 s_2 \ldots s_n, s_2, s_2 s_3, ..., s_2 s_3 \ldots s_n, s_3, s_3 s_4, ..., s_{n-1} s_n, s_n. For example, the "expansion" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'. To open the ancient repository, Ori must find the size of the largest increasing subsequence of the "expansion" of the string s. Here, strings are compared lexicographically.Help Ori with this task!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 one positive integer t (1 \le t \le 10^3), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer n (1 \le n \le 5000) — length of the string.The second line of each test case contains a non-empty string of length n, which consists of lowercase latin letters.It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputFor every test case print one non-negative integer — the answer to the problem.ExampleInput 7 5 acbac 8 acabacba 12 aaaaaaaaaaaa 10 abacabadac 8 dcbaabcd 3 cba 6 sparky Output 9 17 12 29 14 3 9 NoteIn first test case the "expansion" of the string is: 'a', 'ac', 'acb', 'acba', 'acbac', 'c', 'cb', 'cba', 'cbac', 'b', 'ba', 'bac', 'a', 'ac', 'c'. The answer can be, for example, 'a', 'ac', 'acb', 'acba', 'acbac', 'b', 'ba', 'bac', 'c'.
7 5 acbac 8 acabacba 12 aaaaaaaaaaaa 10 abacabadac 8 dcbaabcd 3 cba 6 sparky
9 17 12 29 14 3 9
2 seconds
512 megabytes
['dp', 'greedy', 'string suffix structures', 'strings', '*2500']
D2. Two Hundred Twenty One (hard version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine.The main element of this machine are n rods arranged along one straight line and numbered from 1 to n inclusive. Each of these rods must carry an electric charge quantitatively equal to either 1 or -1 (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.More formally, the rods can be represented as an array of n numbers characterizing the charge: either 1 or -1. Then the condition must hold: a_1 - a_2 + a_3 - a_4 + \ldots = 0, or \sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0.Sparky charged all n rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has q questions. In the ith question Sparky asks: if the machine consisted only of rods with numbers l_i to r_i inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Also Sparky wants to know the numbers of these rods. Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.Help your friends and answer all of Sparky's questions!InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10^3), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains two positive integers n and q (1 \le n, q \le 3 \cdot 10^5) — the number of rods and the number of questions.The second line of each test case contains a non-empty string s of length n, where the charge of the i-th rod is 1 if s_i is the "+" symbol, or -1 if s_i is the "-" symbol.Each next line from the next q lines contains two positive integers l_i ans r_i (1 \le l_i \le r_i \le n) — numbers, describing Sparky's questions.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5, and the sum of q over all test cases does not exceed 3 \cdot 10^5.It is guaranteed that the sum of the answers (minimal number of rods that can be removed) over all test cases does not exceed 10^6.OutputFor each test case, print the answer in the following format:In the first line print a single integer k — the minimal number of rods that can be removed.In the second line print k numbers separated by a space — the numbers of rods to be removed.If there is more than one correct answer, you can print any.ExampleInput 3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 Output 2 5 8 2 1 11 1 9 0 1 1 2 1 2 1 2 2 1 3 1 2 2 2 3 1 3 1 3 2 3 4 1 4NoteIn the first test case for the first query you can remove the rods numbered 5 and 8, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero.In the second test case: For the first query, we can remove the rods numbered 1 and 11, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. For the second query we can remove the rod numbered 9, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. For the third query we can not remove the rods at all.
3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4
2 5 8 2 1 11 1 9 0 1 1 2 1 2 1 2 2 1 3 1 2 2 2 3 1 3 1 3 2 3 4 1 4
2 seconds
512 megabytes
['data structures', 'math', '*2200']
D1. Two Hundred Twenty One (easy version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine.The main element of this machine are n rods arranged along one straight line and numbered from 1 to n inclusive. Each of these rods must carry an electric charge quantitatively equal to either 1 or -1 (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.More formally, the rods can be represented as an array of n numbers characterizing the charge: either 1 or -1. Then the condition must hold: a_1 - a_2 + a_3 - a_4 + \ldots = 0, or \sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0.Sparky charged all n rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has q questions. In the ith question Sparky asks: if the machine consisted only of rods with numbers l_i to r_i inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.Help your friends and answer all of Sparky's questions!InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10^3), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains two positive integers n and q (1 \le n, q \le 3 \cdot 10^5) — the number of rods and the number of questions.The second line of each test case contains a non-empty string s of length n, where the charge of the i-th rod is 1 if s_i is the "+" symbol, or -1 if s_i is the "-" symbol.Each next line from the next q lines contains two positive integers l_i ans r_i (1 \le l_i \le r_i \le n) — numbers, describing Sparky's questions.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5, and the sum of q over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print a single integer — the minimal number of rods that can be removed.ExampleInput 3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 Output 2 2 1 0 1 2 1 2 1 2 1 1 2 1 NoteIn the first test case for the first query you can remove the rods numbered 5 and 8, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero.In the second test case: For the first query, we can remove the rods numbered 1 and 11, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. For the second query we can remove the rod numbered 9, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. For the third query we can not remove the rods at all.
3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4
2 2 1 0 1 2 1 2 1 2 1 1 2 1
2 seconds
512 megabytes
['data structures', 'dp', 'math', '*1700']
C. Ringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents —there was a pile of different rings: gold and silver..."How am I to tell which is the One?!" the mage howled."Throw them one by one into the Cracks of Doom and watch when Mordor falls!" Somewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found n rings. And the i-th ring was either gold or silver. For convenience Saruman wrote down a binary string s of n characters, where the i-th character was 0 if the i-th ring was gold, and 1 if it was silver.Saruman has a magic function f, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, f(001010) = 10, f(111) = 7, f(11011101) = 221.Saruman, however, thinks that the order of the rings plays some important role. He wants to find 2 pairs of integers (l_1, r_1), (l_2, r_2), such that: 1 \le l_1 \le n, 1 \le r_1 \le n, r_1-l_1+1\ge \lfloor \frac{n}{2} \rfloor 1 \le l_2 \le n, 1 \le r_2 \le n, r_2-l_2+1\ge \lfloor \frac{n}{2} \rfloor Pairs (l_1, r_1) and (l_2, r_2) are distinct. That is, at least one of l_1 \neq l_2 and r_1 \neq r_2 must hold. Let t be the substring s[l_1:r_1] of s, and w be the substring s[l_2:r_2] of s. Then there exists non-negative integer k, such that f(t) = f(w) \cdot k.Here substring s[l:r] denotes s_ls_{l+1}\ldots s_{r-1}s_r, and \lfloor x \rfloor denotes rounding the number down to the nearest integer.Help Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists.InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10^3), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer n (2 \le n \le 2 \cdot 10^4) — length of the string.The second line of each test case contains a non-empty binary string of length n.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor every test case print four integers l_1, r_1, l_2, r_2, which denote the beginning of the first substring, the end of the first substring, the beginning of the second substring, and the end of the second substring, respectively.If there are multiple solutions, print any.ExampleInput 7 6 101111 9 111000111 8 10000000 5 11011 6 001111 3 101 30 100000000000000100000000000000 Output 3 6 1 3 1 9 4 9 5 8 1 4 1 5 3 5 1 6 2 4 1 2 2 3 1 15 16 30NoteIn the first testcase f(t) = f(1111) = 15, f(w) = f(101) = 5.In the second testcase f(t) = f(111000111) = 455, f(w) = f(000111) = 7.In the third testcase f(t) = f(0000) = 0, f(w) = f(1000) = 8.In the fourth testcase f(t) = f(11011) = 27, f(w) = f(011) = 3.In the fifth testcase f(t) = f(001111) = 15, f(w) = f(011) = 3.
7 6 101111 9 111000111 8 10000000 5 11011 6 001111 3 101 30 100000000000000100000000000000
3 6 1 3 1 9 4 9 5 8 1 4 1 5 3 5 1 6 2 4 1 2 2 3 1 15 16 30
1 second
256 megabytes
['constructive algorithms', 'math', '*1500']
B. Scenes From a Memorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the hypnosis session, Nicholas suddenly remembered a positive integer n, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one?For some numbers doing so is impossible: for example, for number 53 it's impossible to delete some of its digits to obtain a not prime integer. However, for all n in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number.Note that you cannot remove all the digits from the number.A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. 1 is neither a prime nor a composite number.InputEach test contains multiple test cases.The first line contains one positive integer t (1 \le t \le 10^3), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer k (1 \le k \le 50) — the number of digits in the number.The second line of each test case contains a positive integer n, which doesn't contain zeros in decimal notation (10^{k-1} \le n < 10^{k}). It is guaranteed that it is always possible to remove less than k digits to make the number not prime.It is guaranteed that the sum of k over all test cases does not exceed 10^4.OutputFor every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions. If there are multiple solutions, print any.ExampleInput 7 3 237 5 44444 3 221 2 35 3 773 1 4 30 626221626221626221626221626221 Output 2 27 1 4 1 1 2 35 2 77 1 4 1 6 NoteIn the first test case, you can't delete 2 digits from the number 237, as all the numbers 2, 3, and 7 are prime. However, you can delete 1 digit, obtaining a number 27 = 3^3.In the second test case, you can delete all digits except one, as 4 = 2^2 is a composite number.
7 3 237 5 44444 3 221 2 35 3 773 1 4 30 626221626221626221626221626221
2 27 1 4 1 1 2 35 2 77 1 4 1 6
1 second
256 megabytes
['brute force', 'constructive algorithms', 'implementation', 'math', 'number theory', '*1000']
A. The Miracle and the Sleepertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers l and r, l\le r. Find the largest possible value of a \bmod b over all pairs (a, b) of integers for which r\ge a \ge b \ge l.As a reminder, a \bmod b is a remainder we get when dividing a by b. For example, 26 \bmod 8 = 2.InputEach test contains multiple test cases.The first line contains one positive integer t (1\le t\le 10^4), denoting the number of test cases. Description of the test cases follows.The only line of each test case contains two integers l, r (1\le l \le r \le 10^9).OutputFor every test case, output the largest possible value of a \bmod b over all pairs (a, b) of integers for which r\ge a \ge b \ge l.ExampleInput 4 1 1 999999999 1000000000 8 26 1 999999999 Output 0 1 12 499999999 NoteIn the first test case, the only allowed pair is (a, b) = (1, 1), for which a \bmod b = 1 \bmod 1 = 0.In the second test case, the optimal choice is pair (a, b) = (1000000000, 999999999), for which a \bmod b = 1.
4 1 1 999999999 1000000000 8 26 1 999999999
0 1 12 499999999
1 second
256 megabytes
['greedy', 'math', '*800']
D1. Up the Strip (simplified version)time limit per test6 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputThis version of the problem differs from the next one only in the constraint on n.Note that the memory limit in this problem is lower than in others.You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom.You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1.Let the token be in cell x > 1 at some moment. One shift of the token can have either of the following kinds: Subtraction: you choose an integer y between 1 and x-1, inclusive, and move the token from cell x to cell x - y. Floored division: you choose an integer z between 2 and x, inclusive, and move the token from cell x to cell \lfloor \frac{x}{z} \rfloor (x divided by z rounded down). Find the number of ways to move the token from cell n to cell 1 using one or more shifts, and print it modulo m. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding).InputThe only line contains two integers n and m (2 \le n \le 2 \cdot 10^5; 10^8 < m < 10^9; m is a prime number) — the length of the strip and the modulo.OutputPrint the number of ways to move the token from cell n to cell 1, modulo m.ExamplesInput 3 998244353 Output 5 Input 5 998244353 Output 25 Input 42 998244353 Output 793019428 NoteIn the first test, there are three ways to move the token from cell 3 to cell 1 in one shift: using subtraction of y = 2, or using division by z = 2 or z = 3.There are also two ways to move the token from cell 3 to cell 1 via cell 2: first subtract y = 1, and then either subtract y = 1 again or divide by z = 2.Therefore, there are five ways in total.
3 998244353
5
6 seconds
128 megabytes
['brute force', 'data structures', 'dp', 'math', 'number theory', '*1700']
C. Deep Down Belowtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing n caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave i, he will have to fight k_i monsters in a row: first a monster with armor a_{i, 1}, then a monster with armor a_{i, 2} and so on, finally, a monster with armor a_{i, k_i}.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by 1.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). 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 caves.The i-th of the next n lines contains an integer k_i (1 \le k_i \le 10^5) — the number of monsters in the i-th cave, followed by k_i integers a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i} (1 \le a_{i, j} \le 10^9) — armor levels of the monsters in cave i in order the hero has to fight them.It is guaranteed that the sum of k_i over all test cases does not exceed 10^5.OutputFor each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.ExampleInput 2 1 1 42 2 3 10 15 8 2 12 11 Output 43 13 NoteIn the first test case, the hero has to beat a single monster with armor 42, it's enough to have power 43 to achieve that.In the second test case, the hero can pass the level with initial power 13 as follows: enter cave 2: beat a monster with armor 12, power increases to 14; beat a monster with armor 11, power increases to 15; enter cave 1: beat a monster with armor 10, power increases to 16; beat a monster with armor 15, power increases to 17; beat a monster with armor 8, power increases to 18.
2 1 1 42 2 3 10 15 8 2 12 11
43 13
2 seconds
512 megabytes
['binary search', 'greedy', 'sortings', '*1300']
A. Simply Strange Sorttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a permutation: an array a = [a_1, a_2, \ldots, a_n] of distinct integers from 1 to n. The length of the permutation n is odd.Consider the following algorithm of sorting the permutation in increasing order.A helper procedure of the algorithm, f(i), takes a single argument i (1 \le i \le n-1) and does the following. If a_i > a_{i+1}, the values of a_i and a_{i+1} are exchanged. Otherwise, the permutation doesn't change.The algorithm consists of iterations, numbered with consecutive integers starting with 1. On the i-th iteration, the algorithm does the following: if i is odd, call f(1), f(3), \ldots, f(n - 2); if i is even, call f(2), f(4), \ldots, f(n - 1). It can be proven that after a finite number of iterations the permutation will be sorted in increasing order.After how many iterations will this happen for the first time?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 999; n is odd) — the length of the permutation.The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the permutation itself. It is guaranteed that the sum of n over all test cases does not exceed 999.OutputFor each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time.If the given permutation is already sorted, print 0.ExampleInput 3 3 3 2 1 7 4 5 7 1 3 2 6 5 1 2 3 4 5 Output 3 5 0 NoteIn the first test case, the permutation will be changing as follows: after the 1-st iteration: [2, 3, 1]; after the 2-nd iteration: [2, 1, 3]; after the 3-rd iteration: [1, 2, 3]. In the second test case, the permutation will be changing as follows: after the 1-st iteration: [4, 5, 1, 7, 2, 3, 6]; after the 2-nd iteration: [4, 1, 5, 2, 7, 3, 6]; after the 3-rd iteration: [1, 4, 2, 5, 3, 7, 6]; after the 4-th iteration: [1, 2, 4, 3, 5, 6, 7]; after the 5-th iteration: [1, 2, 3, 4, 5, 6, 7]. In the third test case, the permutation is already sorted and the answer is 0.
3 3 3 2 1 7 4 5 7 1 3 2 6 5 1 2 3 4 5
3 5 0
2 seconds
512 megabytes
['brute force', 'implementation', 'sortings', '*800']
F2. Nearest Beautiful Number (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is a complicated version of problem F1. The difference between them is the constraints (F1: k \le 2, F2: k \le 10).You are given an integer n. Find the minimum integer x such that x \ge n and the number x is k-beautiful.A number is called k-beautiful if its decimal representation having no leading zeroes contains no more than k different digits. E.g. if k = 2, the numbers 3434443, 55550, 777 and 21 are k-beautiful whereas the numbers 120, 445435 and 998244353 are not.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 consists of one line containing two integers n and k (1 \le n \le 10^9, 1 \le k \le 10).OutputFor each test case output on a separate line x — the minimum k-beautiful integer such that x \ge n.ExampleInput 6 2021 3 177890 2 34512 3 724533 4 998244353 1 12345678 10 Output 2021 181111 34533 724542 999999999 12345678
6 2021 3 177890 2 34512 3 724533 4 998244353 1 12345678 10
2021 181111 34533 724542 999999999 12345678
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dfs and similar', 'dp', 'greedy', '*2100']
F1. Nearest Beautiful Number (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is a simplified version of problem F2. The difference between them is the constraints (F1: k \le 2, F2: k \le 10).You are given an integer n. Find the minimum integer x such that x \ge n and the number x is k-beautiful.A number is called k-beautiful if its decimal representation having no leading zeroes contains no more than k different digits. E.g. if k = 2, the numbers 3434443, 55550, 777 and 21 are k-beautiful whereas the numbers 120, 445435 and 998244353 are not.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 consists of one line containing two integers n and k (1 \le n \le 10^9, 1 \le k \le 2).OutputFor each test case output on a separate line x — the minimum k-beautiful integer such that x \ge n.ExampleInput 4 1 1 221 2 177890 2 998244353 1 Output 1 221 181111 999999999
4 1 1 221 2 177890 2 998244353 1
1 221 181111 999999999
1 second
256 megabytes
['binary search', 'bitmasks', 'brute force', 'constructive algorithms', 'dfs and similar', 'greedy', '*1900']
E. Polycarp and String Transformationtime limit per test3.0 smemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a string s. Polycarp performs the following actions until the string s is empty (t is initially an empty string): he adds to the right to the string t the string s, i.e. he does t = t + s, where t + s is a concatenation of the strings t and s; he selects an arbitrary letter of s and removes from s all its occurrences (the selected letter must occur in the string s at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string s will be empty and the string t will be equal to some value (that is undefined and depends on the order of removing).E.g. consider s="abacaba" so the actions may be performed as follows: t="abacaba", the letter 'b' is selected, then s="aacaa"; t="abacabaaacaa", the letter 'a' is selected, then s="c"; t="abacabaaacaac", the letter 'c' is selected, then s="" (the empty string). You need to restore the initial value of the string s using only the final value of t and find the order of removing letters from s.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 contains one string t consisting of lowercase letters of the Latin alphabet. The length of t doesn't exceed 5 \cdot 10^5. The sum of lengths of all strings t in the test cases doesn't exceed 5 \cdot 10^5.OutputFor each test case output in a separate line: -1, if the answer doesn't exist; two strings separated by spaces. The first one must contain a possible initial value of s. The second one must contain a sequence of letters — it's in what order one needs to remove letters from s to make the string t. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one. ExampleInput 7 abacabaaacaac nowyouknowthat polycarppoycarppoyarppyarppyrpprppp isi everywherevrywhrvryhrvrhrvhv haaha qweqeewew Output abacaba bac -1 polycarp lcoayrp is si everywhere ewyrhv -1 -1 NoteThe first test case is considered in the statement.
7 abacabaaacaac nowyouknowthat polycarppoycarppoyarppyarppyrpprppp isi everywherevrywhrvryhrvrhrvhv haaha qweqeewew
abacaba bac -1 polycarp lcoayrp is si everywhere ewyrhv -1 -1
3.0 s
256 megabytes
['binary search', 'implementation', 'sortings', 'strings', '*1800']
D. Make a Power of Twotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. In 1 move, you can do one of the following actions: erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); add one digit to the right. The actions may be performed in any order any number of times.Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number 301 the digit 3, the result is the number 01 (not 1).You need to perform the minimum number of actions to make the number any power of 2 (i.e. there's an integer k (k \ge 0) such that the resulting number is equal to 2^k). The resulting number must not have leading zeroes.E.g. consider n=1052. The answer is equal to 2. First, let's add to the right one digit 4 (the result will be 10524). Then let's erase the digit 5, so the result will be 1024 which is a power of 2.E.g. consider n=8888. The answer is equal to 3. Let's erase any of the digits 8 three times. The result will be 8 which is a power of 2.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 consists of one line containing one integer n (1 \le n \le 10^9).OutputFor each test case, output in a separate line one integer m — the minimum number of moves to transform the number into any power of 2.ExampleInput 12 1052 8888 6 75 128 1 301 12048 1504 6656 1000000000 687194767 Output 2 3 1 3 0 0 2 1 3 4 9 2 NoteThe answer for the first test case was considered above.The answer for the second test case was considered above.In the third test case, it's enough to add to the right the digit 4 — the number 6 will turn into 64.In the fourth test case, let's add to the right the digit 8 and then erase 7 and 5 — the taken number will turn into 8.The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move.In the seventh test case, you can delete first of all the digit 3 (the result is 01) and then the digit 0 (the result is 1).
12 1052 8888 6 75 128 1 301 12048 1504 6656 1000000000 687194767
2 3 1 3 0 0 2 1 3 4 9 2
1 second
256 megabytes
['greedy', 'math', 'strings', '*1300']
C. Infinity Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has found a table having an infinite number of rows and columns. The rows are numbered from 1, starting from the topmost one. The columns are numbered from 1, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from 1 and so on to the table as follows. The figure shows the placement of the numbers from 1 to 10. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number 1. Then he writes in the table all positive integers beginning from 2 sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number k. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number k.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.Each test case consists of one line containing one integer k (1 \le k \le 10^9) which location must be found.OutputFor each test case, output in a separate line two integers r and c (r, c \ge 1) separated by spaces — the indices of the row and the column containing the cell filled by the number k, respectively.ExampleInput 7 11 14 5 4 1 2 1000000000 Output 2 4 4 3 1 3 2 1 1 1 1 2 31623 14130
7 11 14 5 4 1 2 1000000000
2 4 4 3 1 3 2 1 1 1 1 2 31623 14130
1 second
256 megabytes
['implementation', 'math', '*800']
B. Who's Opposite?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number 1. Each person is looking through the circle's center at the opposite person. A sample of a circle of 6 persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number a is looking at the person with the number b (and vice versa, of course). What is the number associated with a person being looked at by the person with the number c? If, for the specified a, b, and c, no such circle exists, output -1.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 consists of one line containing three distinct integers a, b, c (1 \le a,b,c \le 10^8).OutputFor each test case output in a separate line a single integer d — the number of the person being looked at by the person with the number c in a circle such that the person with the number a is looking at the person with the number b. If there are multiple solutions, print any of them. Output -1 if there's no circle meeting the given conditions.ExampleInput 7 6 2 4 2 3 1 2 4 10 5 3 4 1 3 2 2 5 4 4 3 2 Output 8 -1 -1 -1 4 1 -1 NoteIn the first test case, there's a desired circle of 8 people. The person with the number 6 will look at the person with the number 2 and the person with the number 8 will look at the person with the number 4.In the second test case, there's no circle meeting the conditions. If the person with the number 2 is looking at the person with the number 3, the circle consists of 2 people because these persons are neighbors. But, in this case, they must have the numbers 1 and 2, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers 2 and 4 looking at each other consists of 4 people. Therefore, the person with the number 10 doesn't occur in the circle.
7 6 2 4 2 3 1 2 4 10 5 3 4 1 3 2 2 5 4 4 3 2
8 -1 -1 -1 4 1 -1
1 second
256 megabytes
['math', '*800']
A. Dislike of Threestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp doesn't like integers that are divisible by 3 or end with the digit 3 in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.Polycarp starts to write out the positive (greater than 0) integers which he likes: 1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \dots. Output the k-th element of this sequence (the elements are numbered from 1).InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.Each test case consists of one line containing one integer k (1 \le k \le 1000).OutputFor each test case, output in a separate line one integer x — the k-th element of the sequence that was written out by Polycarp.ExampleInput 10 1 2 3 4 5 6 7 8 9 1000 Output 1 2 4 5 7 8 10 11 14 1666
10 1 2 3 4 5 6 7 8 9 1000
1 2 4 5 7 8 10 11 14 1666
1 second
256 megabytes
['implementation', '*800']
E. Mocha and Starstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMocha wants to be an astrologer. There are n stars which can be seen in Zhijiang, and the brightness of the i-th star is a_i. Mocha considers that these n stars form a constellation, and she uses (a_1,a_2,\ldots,a_n) to show its state. A state is called mathematical if all of the following three conditions are satisfied: For all i (1\le i\le n), a_i is an integer in the range [l_i, r_i]. \sum \limits _{i=1} ^ n a_i \le m. \gcd(a_1,a_2,\ldots,a_n)=1. Here, \gcd(a_1,a_2,\ldots,a_n) denotes the greatest common divisor (GCD) of integers a_1,a_2,\ldots,a_n.Mocha is wondering how many different mathematical states of this constellation exist. Because the answer may be large, you must find it modulo 998\,244\,353.Two states (a_1,a_2,\ldots,a_n) and (b_1,b_2,\ldots,b_n) are considered different if there exists i (1\le i\le n) such that a_i \ne b_i.InputThe first line contains two integers n and m (2 \le n \le 50, 1 \le m \le 10^5) — the number of stars and the upper bound of the sum of the brightness of stars.Each of the next n lines contains two integers l_i and r_i (1 \le l_i \le r_i \le m) — the range of the brightness of the i-th star.OutputPrint a single integer — the number of different mathematical states of this constellation, modulo 998\,244\,353.ExamplesInput 2 4 1 3 1 2 Output 4Input 5 10 1 10 1 10 1 10 1 10 1 10 Output 251Input 5 100 1 94 1 96 1 91 4 96 6 97 Output 47464146NoteIn the first example, there are 4 different mathematical states of this constellation: a_1=1, a_2=1. a_1=1, a_2=2. a_1=2, a_2=1. a_1=3, a_2=1.
2 4 1 3 1 2
4
2 seconds
256 megabytes
['combinatorics', 'dp', 'fft', 'math', 'number theory', '*2200']
D2. Mocha and Diana (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from 1 to n, and they would like to add edges to their forests such that: After adding edges, both of their graphs are still forests. They add the same edges. That is, if an edge (u, v) is added to Mocha's forest, then an edge (u, v) is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.InputThe first line contains three integers n, m_1 and m_2 (1 \le n \le 10^5, 0 \le m_1, m_2 < n) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest.Each of the next m_1 lines contains two integers u and v (1 \le u, v \le n, u \neq v) — the edges in Mocha's forest.Each of the next m_2 lines contains two integers u and v (1 \le u, v \le n, u \neq v) — the edges in Diana's forest.OutputThe first line contains only one integer h, the maximum number of edges Mocha and Diana can add.Each of the next h lines contains two integers u and v (1 \le u, v \le n, u \neq v) — the edge you add each time.If there are multiple correct answers, you can print any one of them.ExamplesInput 3 2 2 1 2 2 3 1 2 1 3 Output 0 Input 5 3 2 5 4 2 1 4 3 4 3 1 4 Output 1 2 4 Input 8 1 2 1 7 2 6 1 5 Output 5 5 2 2 3 3 4 4 7 6 8 NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge (2, 4).
3 2 2 1 2 2 3 1 2 1 3
0
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'trees', 'two pointers', '*2500']
D1. Mocha and Diana (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from 1 to n, and they would like to add edges to their forests such that: After adding edges, both of their graphs are still forests. They add the same edges. That is, if an edge (u, v) is added to Mocha's forest, then an edge (u, v) is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.InputThe first line contains three integers n, m_1 and m_2 (1 \le n \le 1000, 0 \le m_1, m_2 < n) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest.Each of the next m_1 lines contains two integers u and v (1 \le u, v \le n, u \neq v) — the edges in Mocha's forest.Each of the next m_2 lines contains two integers u and v (1 \le u, v \le n, u \neq v) — the edges in Diana's forest.OutputThe first line contains only one integer h, the maximum number of edges Mocha and Diana can add (in each forest).Each of the next h lines contains two integers u and v (1 \le u, v \le n, u \neq v) — the edge you add each time.If there are multiple correct answers, you can print any one of them.ExamplesInput 3 2 2 1 2 2 3 1 2 1 3 Output 0 Input 5 3 2 5 4 2 1 4 3 4 3 1 4 Output 1 2 4 Input 8 1 2 1 7 2 6 1 5 Output 5 5 2 2 3 3 4 4 7 6 8 NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge (2, 4).
3 2 2 1 2 2 3 1 2 1 3
0
1 second
256 megabytes
['brute force', 'constructive algorithms', 'dsu', 'graphs', 'greedy', 'trees', '*1400']
C. Mocha and Hikingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe city where Mocha lives in is called Zhijiang. There are n+1 villages and 2n-1 directed roads in this city. There are two kinds of roads: n-1 roads are from village i to village i+1, for all 1\leq i \leq n-1. n roads can be described by a sequence a_1,\ldots,a_n. If a_i=0, the i-th of these roads goes from village i to village n+1, otherwise it goes from village n+1 to village i, for all 1\leq i\leq n. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan? InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 20) — the number of test cases. Each test case consists of two lines.The first line of each test case contains a single integer n (1 \le n \le 10^4) — indicates that the number of villages is n+1.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 1). If a_i=0, it means that there is a road from village i to village n+1. If a_i=1, it means that there is a road from village n+1 to village i.It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputFor each test case, print a line with n+1 integers, where the i-th number is the i-th village they will go through. If the answer doesn't exist, print -1.If there are multiple correct answers, you can print any one of them.ExampleInput 2 3 0 1 0 3 1 1 0 Output 1 4 2 3 4 1 2 3 NoteIn the first test case, the city looks like the following graph:So all possible answers are (1 \to 4 \to 2 \to 3), (1 \to 2 \to 3 \to 4).In the second test case, the city looks like the following graph:So all possible answers are (4 \to 1 \to 2 \to 3), (1 \to 2 \to 3 \to 4), (3 \to 4 \to 1 \to 2), (2 \to 3 \to 4 \to 1).
2 3 0 1 0 3 1 1 0
1 4 2 3 4 1 2 3
1 second
256 megabytes
['constructive algorithms', 'graphs', '*1200']
B. Mocha and Red and Bluetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs their story unravels, a timeless tale is told once again...Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow.There are n squares arranged in a row, and each of them can be painted either red or blue.Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square.Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color.For example, the imperfectness of "BRRRBBR" is 3, with "BB" occurred once and "RR" occurred twice.Your goal is to minimize the imperfectness and print out the colors of the squares after painting. InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. Each test case consists of two lines.The first line of each test case contains an integer n (1\leq n\leq 100) — the length of the squares row.The second line of each test case contains a string s with length n, containing characters 'B', 'R' and '?'. Here 'B' stands for a blue square, 'R' for a red square, and '?' for a blank square.OutputFor each test case, print a line with a string only containing 'B' and 'R', the colors of the squares after painting, which imperfectness is minimized. If there are multiple solutions, print any of them.ExampleInput 5 7 ?R???BR 7 ???R??? 1 ? 1 B 10 ?R??RB??B? Output BRRBRBR BRBRBRB B B BRRBRBBRBRNoteIn the first test case, if the squares are painted "BRRBRBR", the imperfectness is 1 (since squares 2 and 3 have the same color), which is the minimum possible imperfectness.
5 7 ?R???BR 7 ???R??? 1 ? 1 B 10 ?R??RB??B?
BRRBRBR BRBRBRB B B BRRBRBBRBR
1 second
256 megabytes
['dp', 'greedy', '*900']
A. Mocha and Mathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence a of length n. In each operation, she can select an arbitrary interval [l, r] and for all values i (0\leq i \leq r-l), replace a_{l+i} with a_{l+i} \,\&\, a_{r-i} at the same time, where \& denotes the bitwise AND operation. This operation can be performed any number of times.For example, if n=5, the array is [a_1,a_2,a_3,a_4,a_5], and Mocha selects the interval [2,5], then the new array is [a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2].Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. Each test case consists of two lines.The first line of each test case contains a single integer n (1 \le n \le 100) — the length of the sequence.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9).OutputFor each test case, print one integer — the minimal value of the maximum value in the sequence.ExampleInput 4 2 1 2 3 1 1 3 4 3 11 3 7 5 11 7 15 3 7 Output 0 1 3 3 NoteIn the first test case, Mocha can choose the interval [1,2], then the sequence becomes [ 0, 0], where the first element is 1\,\&\,2, and the second element is 2\,\&\,1.In the second test case, Mocha can choose the interval [1,3], then the sequence becomes [ 1,1,1], where the first element is 1\,\&\,3, the second element is 1\,\&\,1, and the third element is 3\,\&\,1.
4 2 1 2 3 1 1 3 4 3 11 3 7 5 11 7 15 3 7
0 1 3 3
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'math', '*900']
F. Strange Sorttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a permutation: an array a = [a_1, a_2, \ldots, a_n] of distinct integers from 1 to n. The length of the permutation n is odd.Consider the following algorithm of sorting the permutation in increasing order.A helper procedure of the algorithm, f(i), takes a single argument i (1 \le i \le n-1) and does the following. If a_i > a_{i+1}, the values of a_i and a_{i+1} are exchanged. Otherwise, the permutation doesn't change.The algorithm consists of iterations, numbered with consecutive integers starting with 1. On the i-th iteration, the algorithm does the following: if i is odd, call f(1), f(3), \ldots, f(n - 2); if i is even, call f(2), f(4), \ldots, f(n - 1). It can be proven that after a finite number of iterations the permutation will be sorted in increasing order.After how many iterations will this happen for the first time?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 2 \cdot 10^5 - 1; n is odd) — the length of the permutation.The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the permutation itself. It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 - 1.OutputFor each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time.If the given permutation is already sorted, print 0.ExampleInput 3 3 3 2 1 7 4 5 7 1 3 2 6 5 1 2 3 4 5 Output 3 5 0 NoteIn the first test case, the permutation will be changing as follows: after the 1-st iteration: [2, 3, 1]; after the 2-nd iteration: [2, 1, 3]; after the 3-rd iteration: [1, 2, 3]. In the second test case, the permutation will be changing as follows: after the 1-st iteration: [4, 5, 1, 7, 2, 3, 6]; after the 2-nd iteration: [4, 1, 5, 2, 7, 3, 6]; after the 3-rd iteration: [1, 4, 2, 5, 3, 7, 6]; after the 4-th iteration: [1, 2, 4, 3, 5, 6, 7]; after the 5-th iteration: [1, 2, 3, 4, 5, 6, 7]. In the third test case, the permutation is already sorted and the answer is 0.
3 3 3 2 1 7 4 5 7 1 3 2 6 5 1 2 3 4 5
3 5 0
2 seconds
512 megabytes
['data structures', 'sortings', '*3300']
E. Down Belowtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn a certain video game, the player controls a hero characterized by a single integer value: power.On the current level, the hero got into a system of n caves numbered from 1 to n, and m tunnels between them. Each tunnel connects two distinct caves. Any two caves are connected with at most one tunnel. Any cave can be reached from any other cave by moving via tunnels.The hero starts the level in cave 1, and every other cave contains a monster.The hero can move between caves via tunnels. If the hero leaves a cave and enters a tunnel, he must finish his movement and arrive at the opposite end of the tunnel.The hero can use each tunnel to move in both directions. However, the hero can not use the same tunnel twice in a row. Formally, if the hero has just moved from cave i to cave j via a tunnel, he can not head back to cave i immediately after, but he can head to any other cave connected to cave j with a tunnel.It is known that at least two tunnels come out of every cave, thus, the hero will never find himself in a dead end even considering the above requirement.To pass the level, the hero must beat the monsters in all the caves. When the hero enters a cave for the first time, he will have to fight the monster in it. The hero can beat the monster in cave i if and only if the hero's power is strictly greater than a_i. In case of beating the monster, the hero's power increases by b_i. If the hero can't beat the monster he's fighting, the game ends and the player loses.After the hero beats the monster in cave i, all subsequent visits to cave i won't have any consequences: the cave won't have any monsters, and the hero's power won't change either.Find the smallest possible power the hero must start the level with to be able to beat all the monsters and pass the level.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains two integers n and m (3 \le n \le 1000; n \le m \le min(\frac{n(n-1)}{2}, 2000)) — the number of caves and tunnels.The second line contains n-1 integers a_2, a_3, \ldots, a_n (1 \le a_i \le 10^9) — values the hero's power are compared to while fighting monsters in caves 2, 3, \ldots, n.The third line contains n-1 integers b_2, b_3, \ldots, b_n (1 \le b_i \le 10^9) — increases applied to the hero's power for beating monsters in caves 2, 3, \ldots, n.Each of the next m lines contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \ne v_i) — the numbers of caves connected with a tunnel.No two caves are connected with more than one tunnel. Any cave can be reached from any other cave by moving via tunnels. At least two tunnels come out of every cave.It is guaranteed that the sum of n over all test cases does not exceed 1000, and the sum of m over all test cases does not exceed 2000.OutputFor each test case print a single integer — the smallest possible power the hero must start the level with to be able to beat all the monsters and pass the level.ExampleInput 3 4 4 11 22 13 8 7 5 1 2 2 3 3 4 4 1 4 4 11 22 13 5 7 8 1 2 2 3 3 4 4 1 5 7 10 40 20 30 7 2 10 5 1 2 1 5 2 3 2 4 2 5 3 4 4 5 Output 15 15 19 NoteIn the first test case, the hero can pass the level with initial power 15 as follows: move from cave 1 to cave 2: since 15 > 11, the hero beats the monster, and his power increases to 15 + 8 = 23; move from cave 2 to cave 3: since 23 > 22, the hero beats the monster, and his power increases to 23 + 7 = 30; move from cave 3 to cave 4: since 30 > 13, the hero beats the monster, and his power increases to 30 + 5 = 35. In the second test case, the situation is similar except that the power increases for beating monsters in caves 2 and 4 are exchanged. The hero can follow a different route, 1 \rightarrow 4 \rightarrow 3 \rightarrow 2, and pass the level with initial power 15.In the third test case, the hero can pass the level with initial power 19 as follows: move from cave 1 to cave 2: since 19 > 10, the hero beats the monster, and his power increases to 19 + 7 = 26; move from cave 2 to cave 4: since 26 > 20, the hero beats the monster, and his power increases to 26 + 10 = 36; move from cave 4 to cave 5: since 36 > 30, the hero beats the monster, and his power increases to 36 + 5 = 41; move from cave 5 to cave 2: there is no monster in this cave anymore, nothing happens; move from cave 2 to cave 3: since 41 > 40, the hero beats the monster, and his power increases to 41 + 2 = 43.
3 4 4 11 22 13 8 7 5 1 2 2 3 3 4 4 1 4 4 11 22 13 5 7 8 1 2 2 3 3 4 4 1 5 7 10 40 20 30 7 2 10 5 1 2 1 5 2 3 2 4 2 5 3 4 4 5
15 15 19
5 seconds
512 megabytes
['binary search', 'dfs and similar', 'graphs', 'greedy', 'meet-in-the-middle', 'shortest paths', '*3000']
D. Top-Notch Insertionstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider the insertion sort algorithm used to sort an integer sequence [a_1, a_2, \ldots, a_n] of length n in non-decreasing order.For each i in order from 2 to n, do the following. If a_i \ge a_{i-1}, do nothing and move on to the next value of i. Otherwise, find the smallest j such that a_i < a_j, shift the elements on positions from j to i-1 by one position to the right, and write down the initial value of a_i to position j. In this case we'll say that we performed an insertion of an element from position i to position j.It can be noticed that after processing any i, the prefix of the sequence [a_1, a_2, \ldots, a_i] is sorted in non-decreasing order, therefore, the algorithm indeed sorts any sequence.For example, sorting [4, 5, 3, 1, 3] proceeds as follows: i = 2: a_2 \ge a_1, do nothing; i = 3: j = 1, insert from position 3 to position 1: [3, 4, 5, 1, 3]; i = 4: j = 1, insert from position 4 to position 1: [1, 3, 4, 5, 3]; i = 5: j = 3, insert from position 5 to position 3: [1, 3, 3, 4, 5]. You are given an integer n and a list of m integer pairs (x_i, y_i). We are interested in sequences such that if you sort them using the above algorithm, exactly m insertions will be performed: first from position x_1 to position y_1, then from position x_2 to position y_2, ..., finally, from position x_m to position y_m.How many sequences of length n consisting of (not necessarily distinct) integers between 1 and n, inclusive, satisfy the above condition? Print this number modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains two integers n and m (2 \le n \le 2 \cdot 10^5; 0 \le m < n) — the length of the sequence and the number of insertions.The i-th of the following m lines contains two integers x_i and y_i (2 \le x_1 < x_2 < \ldots < x_m \le n; 1 \le y_i < x_i). These lines describe the sequence of insertions in chronological order.It is guaranteed that the sum of m over all test cases does not exceed 2 \cdot 10^5. Note that there is no constraint on the sum of n of the same kind.OutputFor each test case, print the number of sequences of length n consisting of integers from 1 to n such that sorting them with the described algorithm produces the given sequence of insertions, modulo 998\,244\,353.ExampleInput 3 3 0 3 2 2 1 3 1 5 3 3 1 4 1 5 3 Output 10 1 21 NoteIn the first test case, the algorithm performs no insertions — therefore, the initial sequence is already sorted in non-decreasing order. There are 10 such sequences: [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3].In the second test case, the only sequence satisfying the conditions is [3, 2, 1].In the third test case, [4, 5, 3, 1, 3] is one of the sought sequences.
3 3 0 3 2 2 1 3 1 5 3 3 1 4 1 5 3
10 1 21
3 seconds
512 megabytes
['combinatorics', 'data structures', '*2600']
C. Bottom-Tier Reversalstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a permutation: an array a = [a_1, a_2, \ldots, a_n] of distinct integers from 1 to n. The length of the permutation n is odd.You need to sort the permutation in increasing order.In one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if a = [a_1, a_2, \ldots, a_n], you can choose any odd integer p between 1 and n, inclusive, and set a to [a_p, a_{p-1}, \ldots, a_1, a_{p+1}, a_{p+2}, \ldots, a_n].Find a way to sort a using no more than \frac{5n}{2} reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 2021; n is odd) — the length of the permutation.The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the permutation itself. It is guaranteed that the sum of n over all test cases does not exceed 2021.OutputFor each test case, if it's impossible to sort the given permutation in at most \frac{5n}{2} reversals, print a single integer -1.Otherwise, print an integer m (0 \le m \le \frac{5n}{2}), denoting the number of reversals in your sequence of steps, followed by m integers p_i (1 \le p_i \le n; p_i is odd), denoting the lengths of the prefixes of a to be reversed, in chronological order.Note that m doesn't have to be minimized. If there are multiple answers, print any.ExampleInput 3 3 1 2 3 5 3 4 5 2 1 3 2 1 3 Output 4 3 3 3 3 2 3 5 -1 NoteIn the first test case, the permutation is already sorted. Any even number of reversals of the length 3 prefix doesn't change that fact.In the second test case, after reversing the prefix of length 3 the permutation will change to [5, 4, 3, 2, 1], and then after reversing the prefix of length 5 the permutation will change to [1, 2, 3, 4, 5].In the third test case, it's impossible to sort the permutation.
3 3 1 2 3 5 3 4 5 2 1 3 2 1 3
4 3 3 3 3 2 3 5 -1
2 seconds
512 megabytes
['constructive algorithms', 'greedy', '*2000']
B. Up the Striptime limit per test6 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputNote that the memory limit in this problem is lower than in others.You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom.You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1.Let the token be in cell x > 1 at some moment. One shift of the token can have either of the following kinds: Subtraction: you choose an integer y between 1 and x-1, inclusive, and move the token from cell x to cell x - y. Floored division: you choose an integer z between 2 and x, inclusive, and move the token from cell x to cell \lfloor \frac{x}{z} \rfloor (x divided by z rounded down). Find the number of ways to move the token from cell n to cell 1 using one or more shifts, and print it modulo m. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding).InputThe only line contains two integers n and m (2 \le n \le 4 \cdot 10^6; 10^8 < m < 10^9; m is a prime number) — the length of the strip and the modulo.OutputPrint the number of ways to move the token from cell n to cell 1, modulo m.ExamplesInput 3 998244353 Output 5 Input 5 998244353 Output 25 Input 42 998244353 Output 793019428 Input 787788 100000007 Output 94810539 NoteIn the first test, there are three ways to move the token from cell 3 to cell 1 in one shift: using subtraction of y = 2, or using division by z = 2 or z = 3.There are also two ways to move the token from cell 3 to cell 1 via cell 2: first subtract y = 1, and then either subtract y = 1 again or divide by z = 2.Therefore, there are five ways in total.
3 998244353
5
6 seconds
128 megabytes
['brute force', 'dp', 'math', 'number theory', 'two pointers', '*1900']
A. Charmed by the Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Borys are playing tennis.A tennis match consists of games. In each game, one of the players is serving and the other one is receiving.Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa.Each game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve.It is known that Alice won a games and Borys won b games during the match. It is unknown who served first and who won which games.Find all values of k such that exactly k breaks could happen during the match between Alice and Borys in total.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^3). Description of the test cases follows.Each of the next t lines describes one test case and contains two integers a and b (0 \le a, b \le 10^5; a + b > 0) — the number of games won by Alice and Borys, respectively.It is guaranteed that the sum of a + b over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print two lines.In the first line, print a single integer m (1 \le m \le a + b + 1) — the number of values of k such that exactly k breaks could happen during the match.In the second line, print m distinct integers k_1, k_2, \ldots, k_m (0 \le k_1 < k_2 < \ldots < k_m \le a + b) — the sought values of k in increasing order.ExampleInput 3 2 1 1 1 0 5 Output 4 0 1 2 3 2 0 2 2 2 3 NoteIn the first test case, any number of breaks between 0 and 3 could happen during the match: Alice holds serve, Borys holds serve, Alice holds serve: 0 breaks; Borys holds serve, Alice holds serve, Alice breaks serve: 1 break; Borys breaks serve, Alice breaks serve, Alice holds serve: 2 breaks; Alice breaks serve, Borys breaks serve, Alice breaks serve: 3 breaks. In the second test case, the players could either both hold serves (0 breaks) or both break serves (2 breaks).In the third test case, either 2 or 3 breaks could happen: Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve: 2 breaks; Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve: 3 breaks.
3 2 1 1 1 0 5
4 0 1 2 3 2 0 2 2 2 3
2 seconds
512 megabytes
['brute force', 'math', '*1300']
E. Assiut Chesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.ICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king.You compete on an 8\times8 chessboard, the rows are numerated from top to bottom, and the columns are numerated left to right, and the cell in row x and column y is denoted as (x, y).In one turn you can move the queen to any of the squares on the same horizontal line, vertical line, or any of the diagonals. For example, if the queen was on square (4, 5), you can move to (q_1, 5), (4, q_1), (q_1, 9-q_1), or (q_2, q_2+1) where (1 \le q_1 \le 8, q_1 \ne 4, 1 \le q_2 \le 7, q_2 \ne 4). Note that the queen cannot stay on its current cell. In one turn, the king can move "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", or "Up-Right" such that he doesn't get out of the board. The king cannot move into a cell that is on the same row, column or diagonal with the queen (including the position of the queen itself). For example, if the king was on square (4, 5), he can move to (4+k_1, 5+k_2) where (-1 \le k_1,k_2 \le 1, (k_1, k_2) \ne (0, 0)). At the start of the game, you should place the queen at any location on the board, and this is done once per game. After that the king is secretly placed at any cell different from the queen's location. You do not know the position of the king. Then, the king and the queen take turns with the king moving first. The king moves to one of the possible directions ("Right", "Down", "Up-Left", etc.), and you are only given the direction it moves to. After that, you should move your queen by declaring the square to which your queen will move. The game follows like this until you win the game or run out of moves.You win if the king has no valid moves. You lose if after 130 moves of the queen the king still has valid moves.InputThe first line contains a single integer t (1 \le t \le 60) — the number of test cases.InteractionIn each test case, you should print the queen's starting cell immediately. If you placed the queen at the king's cell, you will win immediately.After that, you may make at most 130 moves. Each move is made in the format x y, where x and y are two integers (1 \leq x,y \leq 8) that denote the new row and column of the queen respectively. Your move should be a valid queen move.After the initial queen placement and after each move you will receive a string s that represents the direction of the king's move. It will be one of the following: "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", "Up-Right", or "Done" if you win the game. You should consider "Done" as the end of each test case.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.If at any point you make an invalid query or try to make more than 130 queries for each test case, the game will terminate immediately and you will receive a Wrong Answer verdict.ExampleInput 1 Left Right DoneOutput 7 5 7 6 7 7NoteIn the example, the hidden king was at (8, 8) at the start. The game follows like this:
1 Left Right Done
7 5 7 6 7 7
1 second
256 megabytes
['brute force', 'constructive algorithms', 'interactive', '*2800']
D. Ezzat and Gridtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMoamen was drawing a grid of n rows and 10^9 columns containing only digits 0 and 1. Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful.A grid is beautiful if and only if for every two consecutive rows there is at least one column containing 1 in these two rows.Ezzat will give you the number of rows n, and m segments of the grid that contain digits 1. Every segment is represented with three integers i, l, and r, where i represents the row number, and l and r represent the first and the last column of the segment in that row.For example, if n = 3, m = 6, and the segments are (1,1,1), (1,7,8), (2,7,7), (2,15,15), (3,1,1), (3,15,15), then the grid is: Your task is to tell Ezzat the minimum number of rows that should be removed to make the grid beautiful.InputThe first line contains two integers n and m (1 \le n, m \le 3\cdot10^5).Each of the next m lines contains three integers i, l, and r (1 \le i \le n, 1 \le l \le r \le 10^9). Each of these m lines means that row number i contains digits 1 in columns from l to r, inclusive.Note that the segments may overlap.OutputIn the first line, print a single integer k — the minimum number of rows that should be removed.In the second line print k distinct integers r_1, r_2, \ldots, r_k, representing the rows that should be removed (1 \le r_i \le n), in any order.If there are multiple answers, print any.ExamplesInput 3 6 1 1 1 1 7 8 2 7 7 2 15 15 3 1 1 3 15 15 Output 0 Input 5 4 1 2 3 2 4 6 3 3 5 5 1 1 Output 3 2 4 5NoteIn the first test case, the grid is the one explained in the problem statement. The grid has the following properties: The 1-st row and the 2-nd row have a common 1 in the column 7. The 2-nd row and the 3-rd row have a common 1 in the column 15. As a result, this grid is beautiful and we do not need to remove any row.In the second test case, the given grid is as follows:
3 6 1 1 1 1 7 8 2 7 7 2 15 15 3 1 1 3 15 15
0
2.5 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2200']
C. Moamen and XORtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMoamen and Ezzat are playing a game. They create an array a of n non-negative integers where every element is less than 2^k.Moamen wins if a_1 \,\&\, a_2 \,\&\, a_3 \,\&\, \ldots \,\&\, a_n \ge a_1 \oplus a_2 \oplus a_3 \oplus \ldots \oplus a_n.Here \& denotes the bitwise AND operation, and \oplus denotes the bitwise XOR operation.Please calculate the number of winning for Moamen arrays a.As the result may be very large, print the value modulo 1\,000\,000\,007 (10^9 + 7).InputThe first line contains a single integer t (1 \le t \le 5)— the number of test cases. Each test case consists of one line containing two integers n and k (1 \le n\le 2\cdot 10^5, 0 \le k \le 2\cdot 10^5).OutputFor each test case, print a single value — the number of different arrays that Moamen wins with.Print the result modulo 1\,000\,000\,007 (10^9 + 7).ExampleInput 3 3 1 2 1 4 0 Output 5 2 1 NoteIn the first example, n = 3, k = 1. As a result, all the possible arrays are [0,0,0], [0,0,1], [0,1,0], [1,0,0], [1,1,0], [0,1,1], [1,0,1], and [1,1,1].Moamen wins in only 5 of them: [0,0,0], [1,1,0], [0,1,1], [1,0,1], and [1,1,1].
3 3 1 2 1 4 0
5 2 1
2 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', 'matrices', '*1700']
B. Moamen and k-subarraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMoamen has an array of n distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once: Split the array into exactly k non-empty subarrays such that each element belongs to exactly one subarray. Reorder these subarrays arbitrary. Merge the subarrays in their new order. A sequence a is a subarray of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and k (1 \le k \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). It is guaranteed that all numbers are distinct.It is guaranteed that the sum of n over all test cases does not exceed 3\cdot10^5.OutputFor each test case, you should output a single string.If Moamen can sort the array in non-decreasing order, output "YES" (without quotes). Otherwise, output "NO" (without quotes).You can print each letter of "YES" and "NO" in any case (upper or lower).ExampleInput 3 5 4 6 3 4 2 1 4 2 1 -4 0 -2 5 1 1 2 3 4 5 Output Yes No Yes NoteIn the first test case, a = [6, 3, 4, 2, 1], and k = 4, so we can do the operations as follows: Split a into \{ [6], [3, 4], [2], [1] \}. Reorder them: \{ [1], [2], [3,4], [6] \}. Merge them: [1, 2, 3, 4, 6], so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only 2 subarrays.As an example, if we split it into \{ [1, -4], [0, -2] \}, we can reorder them into \{ [1, -4], [0, -2] \} or \{ [0, -2], [1, -4] \}. However, after merging the subarrays, it is impossible to get a sorted array.
3 5 4 6 3 4 2 1 4 2 1 -4 0 -2 5 1 1 2 3 4 5
Yes No Yes
2 seconds
256 megabytes
['greedy', 'sortings', '*1100']
A. Ezzat and Two Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEzzat has an array of n integers (maybe negative). He wants to split it into two non-empty subsequences a and b, such that every element from the array belongs to exactly one subsequence, and the value of f(a) + f(b) is the maximum possible value, where f(x) is the average of the subsequence x. A sequence x is a subsequence of a sequence y if x can be obtained from y by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of [1,5,6] is (1+5+6)/3 = 12/3 = 4, so f([1,5,6]) = 4.InputThe first line contains a single integer t (1 \le t \le 10^3)— the number of test cases. Each test case consists of two lines.The first line contains a single integer n (2 \le n \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 3\cdot10^5.OutputFor each test case, print a single value — the maximum value that Ezzat can achieve.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 4 3 3 1 2 3 -7 -6 -6 3 2 2 2 4 17 3 5 -3 Output 4.500000000 -12.500000000 4.000000000 18.666666667 NoteIn the first test case, the array is [3, 1, 2]. These are all the possible ways to split this array: a = [3], b = [1,2], so the value of f(a) + f(b) = 3 + 1.5 = 4.5. a = [3,1], b = [2], so the value of f(a) + f(b) = 2 + 2 = 4. a = [3,2], b = [1], so the value of f(a) + f(b) = 2.5 + 1 = 3.5. Therefore, the maximum possible value 4.5.In the second test case, the array is [-7, -6, -6]. These are all the possible ways to split this array: a = [-7], b = [-6,-6], so the value of f(a) + f(b) = (-7) + (-6) = -13. a = [-7,-6], b = [-6], so the value of f(a) + f(b) = (-6.5) + (-6) = -12.5. Therefore, the maximum possible value -12.5.
4 3 3 1 2 3 -7 -6 -6 3 2 2 2 4 17 3 5 -3
4.500000000 -12.500000000 4.000000000 18.666666667
1 second
256 megabytes
['brute force', 'math', 'sortings', '*800']
H. DIY Treetime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William really likes puzzle kits. For one of his birthdays, his friends gifted him a complete undirected edge-weighted graph consisting of n vertices.He wants to build a spanning tree of this graph, such that for the first k vertices the following condition is satisfied: the degree of a vertex with index i does not exceed d_i. Vertices from k + 1 to n may have any degree.William wants you to find the minimum weight of a spanning tree that satisfies all the conditions.A spanning tree is a subset of edges of a graph that forms a tree on all n vertices of the graph. The weight of a spanning tree is defined as the sum of weights of all the edges included in a spanning tree.InputThe first line of input contains two integers n, k (2 \leq n \leq 50, 1 \leq k \leq min(n - 1, 5)).The second line contains k integers d_1, d_2, \ldots, d_k (1 \leq d_i \leq n). The i-th of the next n - 1 lines contains n - i integers w_{i,i+1}, w_{i,i+2}, \ldots, w_{i,n} (1 \leq w_{i,j} \leq 100): weights of edges (i,i+1),(i,i+2),\ldots,(i,n).OutputPrint one integer: the minimum weight of a spanning tree under given degree constraints for the first k vertices. ExampleInput 10 5 5 3 4 2 1 29 49 33 12 55 15 32 62 37 61 26 15 58 15 22 8 58 37 16 9 39 20 14 58 10 15 40 3 19 55 53 13 37 44 52 23 59 58 4 69 80 29 89 28 48 Output 95
10 5 5 3 4 2 1 29 49 33 12 55 15 32 62 37 61 26 15 58 15 22 8 58 37 16 9 39 20 14 58 10 15 40 3 19 55 53 13 37 44 52 23 59 58 4 69 80 29 89 28 48
95
6 seconds
256 megabytes
['graphs', 'greedy', 'math', 'probabilities', '*3300']
G. Gates to Another Worldtime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard output As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from 0 to 2^n - 1. On each planet, there are gates that allow the player to move from planet i to planet j if the binary representations of i and j differ in exactly one bit.William wants to test you and see how you can handle processing the following queries in this game universe: Destroy planets with numbers from l to r inclusively. These planets cannot be moved to anymore. Figure out if it is possible to reach planet b from planet a using some number of planetary gates. It is guaranteed that the planets a and b are not destroyed. InputThe first line contains two integers n, m (1 \leq n \leq 50, 1 \leq m \leq 5 \cdot 10^4), which are the number of bits in binary representation of each planets' designation and the number of queries, respectively.Each of the next m lines contains a query of two types:block l r — query for destruction of planets with numbers from l to r inclusively (0 \le l \le r < 2^n). It's guaranteed that no planet will be destroyed twice.ask a b — query for reachability between planets a and b (0 \le a, b < 2^n). It's guaranteed that planets a and b hasn't been destroyed yet.OutputFor each query of type ask you must output "1" in a new line, if it is possible to reach planet b from planet a and "0" otherwise (without quotation marks).ExamplesInput 3 3 ask 0 7 block 3 6 ask 0 7 Output 1 0 Input 6 10 block 12 26 ask 44 63 block 32 46 ask 1 54 block 27 30 ask 10 31 ask 11 31 ask 49 31 block 31 31 ask 2 51 Output 1 1 0 0 1 0 NoteThe first example test can be visualized in the following way: Response to a query ask 0 7 is positive.Next after query block 3 6 the graph will look the following way (destroyed vertices are highlighted): Response to a query ask 0 7 is negative, since any path from vertex 0 to vertex 7 must go through one of the destroyed vertices.
3 3 ask 0 7 block 3 6 ask 0 7
1 0
4 seconds
1024 megabytes
['bitmasks', 'data structures', 'dsu', 'two pointers', '*3300']
F. Sports Bettingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William is not only interested in trading but also in betting on sports matches. n teams participate in each match. Each team is characterized by strength a_i. Each two teams i < j play with each other exactly once. Team i wins with probability \frac{a_i}{a_i + a_j} and team j wins with probability \frac{a_j}{a_i + a_j}.The team is called a winner if it directly or indirectly defeated all other teams. Team a defeated (directly or indirectly) team b if there is a sequence of teams c_1, c_2, ... c_k such that c_1 = a, c_k = b and team c_i defeated team c_{i + 1} for all i from 1 to k - 1. Note that it is possible that team a defeated team b and in the same time team b defeated team a.William wants you to find the expected value of the number of winners.InputThe first line contains a single integer n (1 \leq n \leq 14), which is the total number of teams participating in a match.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^6)  — the strengths of teams participating in a match.OutputOutput a single integer  — the expected value of the number of winners of the tournament modulo 10^9 + 7.Formally, let M = 10^9+7. It can be demonstrated that the answer can be presented as a irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output a single integer equal to p \cdot q^{-1} \bmod M. In other words, output an integer x such that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput 2 1 2 Output 1 Input 5 1 5 2 11 14 Output 642377629 NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows (a \rightarrow b means that a defeated b): 1 \rightarrow 2 2 \rightarrow 3 3 \rightarrow 1 1 \rightarrow 4 1 \rightarrow 5 2 \rightarrow 4 2 \rightarrow 5 3 \rightarrow 4 3 \rightarrow 5 4 \rightarrow 5 Or more clearly in the picture: In this case every team from the set \{ 1, 2, 3 \} directly or indirectly defeated everyone. I.e.: 1st defeated everyone because they can get to everyone else in the following way 1 \rightarrow 2, 1 \rightarrow 2 \rightarrow 3, 1 \rightarrow 4, 1 \rightarrow 5. 2nd defeated everyone because they can get to everyone else in the following way 2 \rightarrow 3, 2 \rightarrow 3 \rightarrow 1, 2 \rightarrow 4, 2 \rightarrow 5. 3rd defeated everyone because they can get to everyone else in the following way 3 \rightarrow 1, 3 \rightarrow 1 \rightarrow 2, 3 \rightarrow 4, 3 \rightarrow 5. Therefore the total number of winners is 3.
2 1 2
1
4 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'graphs', 'math', 'probabilities', '*2500']
E. Equilibriumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output William has two arrays a and b, each consisting of n items.For some segments l..r of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each i from l to r holds a_i = b_i.To perform a balancing operation an even number of indices must be selected, such that l \le pos_1 < pos_2 < \dots < pos_k \le r. Next the items of array a at positions pos_1, pos_3, pos_5, \dots get incremented by one and the items of array b at positions pos_2, pos_4, pos_6, \dots get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.InputThe first line contains a two integers n and q (2 \le n \le 10^5, 1 \le q \le 10^5), the size of arrays a and b and the number of segments.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).The third line contains n integers b_1, b_2, \dots, b_n (0 \le b_i \le 10^9).Each of the next q lines contains two integers l_i and r_i (1 \le l_i < r_i \le n), the edges of segments.OutputFor each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.ExampleInput 8 5 0 1 2 9 3 2 7 5 2 2 1 9 4 1 5 8 2 6 1 7 2 4 7 8 5 8 Output 1 3 1 -1 -1 NoteFor the first segment from 2 to 6 you can do one operation with pos = [2, 3, 5, 6], after this operation the arrays will be: a = [0, 2, 2, 9, 4, 2, 7, 5], b = [2, 2, 2, 9, 4, 2, 5, 8]. Arrays are equal on a segment from 2 to 6 after this operation.For the second segment from 1 to 7 you can do three following operations: pos = [1, 3, 5, 6] pos = [1, 7] pos = [2, 7] After these operations, the arrays will be: a = [2, 2, 2, 9, 4, 2, 7, 5], b = [2, 2, 2, 9, 4, 2, 7, 8]. Arrays are equal on a segment from 1 to 7 after these operations.For the third segment from 2 to 4 you can do one operation with pos = [2, 3], after the operation arrays will be: a = [0, 2, 2, 9, 3, 2, 7, 5], b = [2, 2, 2, 9, 4, 1, 5, 8]. Arrays are equal on a segment from 2 to 4 after this operation.It is impossible to equalize the fourth and the fifth segment.
8 5 0 1 2 9 3 2 7 5 2 2 1 9 4 1 5 8 2 6 1 7 2 4 7 8 5 8
1 3 1 -1 -1
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2200']
D. Take a Guesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output This is an interactive taskWilliam has a certain sequence of integers a_1, a_2, \dots, a_n in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than 2 \cdot n of the following questions: What is the result of a bitwise AND of two items with indices i and j (i \neq j) What is the result of a bitwise OR of two items with indices i and j (i \neq j) You can ask William these questions and you need to find the k-th smallest number of the sequence.Formally the k-th smallest number is equal to the number at the k-th place in a 1-indexed array sorted in non-decreasing order. For example in array [5, 3, 3, 10, 1] 4th smallest number is equal to 5, and 2nd and 3rd are 3.InputIt is guaranteed that for each element in a sequence the condition 0 \le a_i \le 10^9 is satisfied.InteractionIn the first line you will be given two integers n and k (3 \le n \le 10^4, 1 \le k \le n), which are the number of items in the sequence a and the number k.After that, you can ask no more than 2 \cdot n questions (not including the "finish" operation).Each line of your output may be of one of the following types: "or i j" (1 \le i, j \le n, i \neq j), where i and j are indices of items for which you want to calculate the bitwise OR. "and i j" (1 \le i, j \le n, i \neq j), where i and j are indices of items for which you want to calculate the bitwise AND. "finish res", where res is the kth smallest number in the sequence. After outputting this line the program execution must conclude. In response to the first two types of queries, you will get an integer x, the result of the operation for the numbers you have selected.After outputting a line do not forget to output a new line character and flush the output buffer. Otherwise you will get the "Idleness limit exceeded". To flush the buffer use: fflush(stdout) in C++ System.out.flush() in Java stdout.flush() in Python flush(output) in Pascal for other languages refer to documentation If you perform an incorrect query the response will be -1. After receiving response -1 you must immediately halt your program in order to receive an "Incorrect answer" verdict.Hacking To perform a hack you will need to use the following format:The first line must contain two integers n and k (3 \le n \le 10^4, 1 \le k \le n), which are the number of items in the sequence a and the number k.The second line must contain n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9), the sequence a.ExampleInput 7 6 2 7Output and 2 5 or 5 6 finish 5NoteIn the example, the hidden sequence is [1, 6, 4, 2, 3, 5, 4].Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52a_2=6, a_5=3. Interactor returns bitwise AND of the given numbers.or 5 67a_5=3, a_6=5. Interactor returns bitwise OR of the given numbers.finish 55 is the correct answer. Note that you must find the value and not the index of the kth smallest number.
7 6 2 7
and 2 5 or 5 6 finish 5
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'interactive', 'math', '*1800']
C. Compressed Bracket Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers c_1, c_2, \dots, c_n where c_i is the number of consecutive brackets "(" if i is an odd number or the number of consecutive brackets ")" if i is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is [3, 2, 1, 3].You need to find the total number of continuous subsequences (subsegments) [l, r] (l \le r) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.InputThe first line contains a single integer n (1 \le n \le 1000), the size of the compressed sequence.The second line contains a sequence of integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^9), the compressed sequence.OutputOutput a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences.It can be proved that the answer fits in the signed 64-bit integer data type.ExamplesInput 5 4 1 2 3 1 Output 5 Input 6 1 3 2 1 2 4 Output 6 Input 6 1 1 1 1 2 2 Output 7 NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains 5 subsegments which form regular bracket sequences: Subsequence from the 3rd to 10th character: (()(())) Subsequence from the 4th to 5th character: () Subsequence from the 4th to 9th character: ()(()) Subsequence from the 6th to 9th character: (()) Subsequence from the 7th to 8th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.
5 4 1 2 3 1
5
1 second
256 megabytes
['brute force', 'implementation', '*1800']
B. Take Your Places!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output William has an array of n integers a_1, a_2, \dots, a_n. In one move he can swap two neighboring items. Two items a_i and a_j are considered neighboring if the condition |i - j| = 1 is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 10^5) which is the total number of items in William's array.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) which are William's array.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case output the minimal number of operations needed or -1 if it is impossible to get the array to a state when no neighboring numbers have the same parity.ExampleInput 5 3 6 6 1 1 9 6 1 1 1 2 2 2 2 8 6 6 6 2 3 4 5 1 Output 1 0 3 -1 2 NoteIn the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: [6, 1, 6] In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: [1, 1, 2, 1, 2, 2] swap(2, 3). Array after performing the operation: [1, 2, 1, 1, 2, 2] swap(4, 5). Array after performing the operation: [1, 2, 1, 2, 1, 2] In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: [6, 3, 2, 4, 5, 1] swap(4, 5). Array after performing the operation: [6, 3, 2, 5, 4, 1]
5 3 6 6 1 1 9 6 1 1 1 2 2 2 2 8 6 6 6 2 3 4 5 1
1 0 3 -1 2
1 second
256 megabytes
['implementation', '*1300']
A. A Variety of Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output William has two numbers a and b initially both equal to zero. William mastered performing three different operations with them quickly. Before performing each operation some positive integer k is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a new positive integer k) add number k to both a and b, or add number k to a and subtract k from b, or add number k to b and subtract k from a. Note that after performing operations, numbers a and b may become negative as well.William wants to find out the minimal number of operations he would have to perform to make a equal to his favorite number c and b equal to his second favorite number d.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The only line of each test case contains two integers c and d (0 \le c, d \le 10^9), which are William's favorite numbers and which he wants a and b to be transformed into.OutputFor each test case output a single number, which is the minimal number of operations which William would have to perform to make a equal to c and b equal to d, or -1 if it is impossible to achieve this using the described operations.ExampleInput 6 1 2 3 5 5 3 6 6 8 0 0 0 Output -1 2 2 1 2 0 NoteLet us demonstrate one of the suboptimal ways of getting a pair (3, 5): Using an operation of the first type with k=1, the current pair would be equal to (1, 1). Using an operation of the third type with k=8, the current pair would be equal to (-7, 9). Using an operation of the second type with k=7, the current pair would be equal to (0, 2). Using an operation of the first type with k=3, the current pair would be equal to (3, 5).
6 1 2 3 5 5 3 6 6 8 0 0 0
-1 2 2 1 2 0
1 second
256 megabytes
['math', '*800']
F. Good Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an undirected graph consisting of n vertices with weighted edges.A simple cycle is a cycle of the graph without repeated vertices. Let the weight of the cycle be the XOR of weights of edges it consists of.Let's say the graph is good if all its simple cycles have weight 1. A graph is bad if it's not good.Initially, the graph is empty. Then q queries follow. Each query has the next type: u v x — add edge between vertices u and v of weight x if it doesn't make the graph bad. For each query print, was the edge added or not.InputThe first line contains two integers n and q (3 \le n \le 3 \cdot 10^5; 1 \le q \le 5 \cdot 10^5) — the number of vertices and queries.Next q lines contain queries — one per line. Each query contains three integers u, v and x (1 \le u, v \le n; u \neq v; 0 \le x \le 1) — the vertices of the edge and its weight.It's guaranteed that there are no multiple edges in the input.OutputFor each query, print YES if the edge was added to the graph, or NO otherwise (both case-insensitive).ExampleInput 9 12 6 1 0 1 3 1 3 6 0 6 2 0 6 4 1 3 4 1 2 4 0 2 5 0 4 5 0 7 8 1 8 9 1 9 7 0 Output YES YES YES YES YES NO YES YES NO YES YES NO
9 12 6 1 0 1 3 1 3 6 0 6 2 0 6 4 1 3 4 1 2 4 0 2 5 0 4 5 0 7 8 1 8 9 1 9 7 0
YES YES YES YES YES NO YES YES NO YES YES NO
2 seconds
256 megabytes
['data structures', 'dsu', 'graphs', 'trees', '*2700']
E. Boring Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on a number line, numbered from 1 to n. The i-th segments covers all integer points from l_i to r_i and has a value w_i.You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point m starting from point 1 in arbitrary number of moves.The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset.In every test there exists at least one good subset.InputThe first line contains two integers n and m (1 \le n \le 3 \cdot 10^5; 2 \le m \le 10^6) — the number of segments and the number of integer points.Each of the next n lines contains three integers l_i, r_i and w_i (1 \le l_i < r_i \le m; 1 \le w_i \le 10^6) — the description of the i-th segment.In every test there exists at least one good subset.OutputPrint a single integer — the minimum cost of a good subset.ExamplesInput 5 12 1 5 5 3 4 10 4 10 6 11 12 5 10 12 3 Output 3 Input 1 10 1 10 23 Output 0
5 12 1 5 5 3 4 10 4 10 6 11 12 5 10 12 3
3
3 seconds
256 megabytes
['data structures', 'sortings', 'trees', 'two pointers', '*2100']
D. Say No to Palindromestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call the string beautiful if it does not contain a substring of length at least 2, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first 3 letters of the Latin alphabet (in lowercase).You are given a string s of length n, each character of the string is one of the first 3 letters of the Latin alphabet (in lowercase).You have to answer m queries — calculate the cost of the substring of the string s from l_i-th to r_i-th position, inclusive.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the length of the string s and the number of queries.The second line contains the string s, it consists of n characters, each character one of the first 3 Latin letters.The following m lines contain two integers l_i and r_i (1 \le l_i \le r_i \le n) — parameters of the i-th query.OutputFor each query, print a single integer — the cost of the substring of the string s from l_i-th to r_i-th position, inclusive.ExampleInput 5 4 baacb 1 3 1 5 4 5 2 3 Output 1 2 0 1 NoteConsider the queries of the example test. in the first query, the substring is baa, which can be changed to bac in one operation; in the second query, the substring is baacb, which can be changed to cbacb in two operations; in the third query, the substring is cb, which can be left unchanged; in the fourth query, the substring is aa, which can be changed to ba in one operation.
5 4 baacb 1 3 1 5 4 5 2 3
1 2 0 1
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dp', 'strings', '*1600']
C. Coin Rowstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on a matrix, consisting of 2 rows and m columns. The cell in the i-th row in the j-th column contains a_{i, j} coins in it.Initially, both Alice and Bob are standing in a cell (1, 1). They are going to perform a sequence of moves to reach a cell (2, m).The possible moves are: Move right — from some cell (x, y) to (x, y + 1); Move down — from some cell (x, y) to (x + 1, y). First, Alice makes all her moves until she reaches (2, m). She collects the coins in all cells she visit (including the starting cell).When Alice finishes, Bob starts his journey. He also performs the moves to reach (2, m) and collects the coins in all cells that he visited, but Alice didn't.The score of the game is the total number of coins Bob collects.Alice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.Then the descriptions of t testcases follow.The first line of the testcase contains a single integer m (1 \le m \le 10^5) — the number of columns of the matrix.The i-th of the next 2 lines contain m integers a_{i,1}, a_{i,2}, \dots, a_{i,m} (1 \le a_{i,j} \le 10^4) — the number of coins in the cell in the i-th row in the j-th column of the matrix.The sum of m over all testcases doesn't exceed 10^5.OutputFor each testcase print a single integer — the score of the game if both players play optimally.ExampleInput 3 3 1 3 7 3 5 1 3 1 3 9 3 5 1 1 4 7 Output 7 8 0 NoteThe paths for the testcases are shown on the following pictures. Alice's path is depicted in red and Bob's path is depicted in blue.
3 3 1 3 7 3 5 1 3 1 3 9 3 5 1 1 4 7
7 8 0
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dp', 'implementation', '*1300']
B. Two Tablestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an axis-aligned rectangle room with width W and height H, so the lower left corner is in point (0, 0) and the upper right corner is in (W, H).There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in (x_1, y_1), and the upper right corner in (x_2, y_2).You want to place another rectangular table in this room with width w and height h with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room. Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?InputThe first line contains the single integer t (1 \le t \le 5000) — the number of the test cases.The first line of each test case contains two integers W and H (1 \le W, H \le 10^8) — the width and the height of the room.The second line contains four integers x_1, y_1, x_2 and y_2 (0 \le x_1 < x_2 \le W; 0 \le y_1 < y_2 \le H) — the coordinates of the corners of the first table.The third line contains two integers w and h (1 \le w \le W; 1 \le h \le H) — the width and the height of the second table.OutputFor each test case, print the minimum distance you should move the first table, or -1 if there is no way to free enough space for the second table.Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.ExampleInput 5 8 5 2 1 7 4 4 2 5 4 2 2 5 4 3 3 1 8 0 3 1 6 1 5 8 1 3 0 6 1 5 1 8 10 4 5 7 8 8 5 Output 1.000000000 -1 2.000000000 2.000000000 0.000000000 NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by (0, -1), so the lower left corner will move from (2, 1) to (2, 0). Then you can place the second table at (0, 3)-(4, 5).In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by (0, 2), so the lower left corner will move from (0, 3) to (0, 5).
5 8 5 2 1 7 4 4 2 5 4 2 2 5 4 3 3 1 8 0 3 1 6 1 5 8 1 3 0 6 1 5 1 8 10 4 5 7 8 8 5
1.000000000 -1 2.000000000 2.000000000 0.000000000
2 seconds
256 megabytes
['brute force', '*1300']
A. PizzaForcestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of 6 slices, medium ones consist of 8 slices, and large pizzas consist of 10 slices each. Baking them takes 15, 20 and 25 minutes, respectively.Petya's birthday is today, and n of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least n slices in total. For example: if 12 friends come to Petya's birthday, he has to order pizzas containing at least 12 slices in total. He can order two small pizzas, containing exactly 12 slices, and the time to bake them is 30 minutes; if 15 friends come to Petya's birthday, he has to order pizzas containing at least 15 slices in total. He can order a small pizza and a large pizza, containing 16 slices, and the time to bake them is 40 minutes; if 300 friends come to Petya's birthday, he has to order pizzas containing at least 300 slices in total. He can order 15 small pizzas, 10 medium pizzas and 13 large pizzas, in total they contain 15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300 slices, and the total time to bake them is 15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750 minutes; if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is 15 minutes. InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.Each testcase consists of a single line that contains a single integer n (1 \le n \le 10^{16}) — the number of Petya's friends.OutputFor each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least n slices in total.ExampleInput 6 12 15 300 1 9999999999999999 3 Output 30 40 750 15 25000000000000000 15
6 12 15 300 1 9999999999999999 3
30 40 750 15 25000000000000000 15
2 seconds
256 megabytes
['brute force', 'math', '*900']
E. Youtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n nodes. As a reminder, a tree is a connected undirected graph without cycles.Let a_1, a_2, \ldots, a_n be a sequence of integers. Perform the following operation exactly n times: Select an unerased node u. Assign a_u := number of unerased nodes adjacent to u. Then, erase the node u along with all edges that have it as an endpoint. For each integer k from 1 to n, find the number, modulo 998\,244\,353, of different sequences a_1, a_2, \ldots, a_n that satisfy the following conditions: it is possible to obtain a by performing the aforementioned operations exactly n times in some order. \operatorname{gcd}(a_1, a_2, \ldots, a_n) = k. Here, \operatorname{gcd} means the greatest common divisor of the elements in a. InputThe first line contains a single integer t (1 \le t \le 10\,000)  — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^5).Each of the next n - 1 lines contains two integers u and v (1 \le u, v \le n) indicating there is an edge between vertices u and v. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print n integers in a single line, where for each k from 1 to n, the k-th integer denotes the answer when \operatorname{gcd} equals to k.ExampleInput 2 3 2 1 1 3 2 1 2 Output 3 1 0 2 0 NoteIn the first test case, If we delete the nodes in order 1 \rightarrow 2 \rightarrow 3 or 1 \rightarrow 3 \rightarrow 2, then the obtained sequence will be a = [2, 0, 0] which has \operatorname{gcd} equals to 2. If we delete the nodes in order 2 \rightarrow 1 \rightarrow 3, then the obtained sequence will be a = [1, 1, 0] which has \operatorname{gcd} equals to 1. If we delete the nodes in order 3 \rightarrow 1 \rightarrow 2, then the obtained sequence will be a = [1, 0, 1] which has \operatorname{gcd} equals to 1. If we delete the nodes in order 2 \rightarrow 3 \rightarrow 1 or 3 \rightarrow 2 \rightarrow 1, then the obtained sequence will be a = [0, 1, 1] which has \operatorname{gcd} equals to 1. Note that here we are counting the number of different sequences, not the number of different orders of deleting nodes.
2 3 2 1 1 3 2 1 2
3 1 0 2 0
5 seconds
256 megabytes
['dfs and similar', 'dp', 'math', 'number theory', '*2600']
D. Dianetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. Find any string s of length n consisting only of English lowercase letters such that each non-empty substring of s occurs in s an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5).It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print a single line containing the string s. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.ExampleInput 4 3 5 9 19 Output abc diane bbcaabbba youarethecutestuwuu NoteIn the first test case, each substring of "abc" occurs exactly once.In the third test case, each substring of "bbcaabbba" occurs an odd number of times. In particular, "b" occurs 5 times, "a" and "bb" occur 3 times each, and each of the remaining substrings occurs exactly once.
4 3 5 9 19
abc diane bbcaabbba youarethecutestuwuu
1 second
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1800']
C. Mikasatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and m. Find the \operatorname{MEX} of the sequence n \oplus 0, n \oplus 1, \ldots, n \oplus m. Here, \oplus is the bitwise XOR operator.\operatorname{MEX} of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For example, \operatorname{MEX}(0, 1, 2, 4) = 3, and \operatorname{MEX}(1, 2021) = 0. InputThe first line contains a single integer t (1 \le t \le 30\,000)  — the number of test cases.The first and only line of each test case contains two integers n and m (0 \le n, m \le 10^9).OutputFor each test case, print a single integer  — the answer to the problem.ExampleInput 5 3 5 4 6 3 2 69 696 123456 654321 Output 4 3 0 640 530866 NoteIn the first test case, the sequence is 3 \oplus 0, 3 \oplus 1, 3 \oplus 2, 3 \oplus 3, 3 \oplus 4, 3 \oplus 5, or 3, 2, 1, 0, 7, 6. The smallest non-negative integer which isn't present in the sequence i. e. the \operatorname{MEX} of the sequence is 4.In the second test case, the sequence is 4 \oplus 0, 4 \oplus 1, 4 \oplus 2, 4 \oplus 3, 4 \oplus 4, 4 \oplus 5, 4 \oplus 6, or 4, 5, 6, 7, 0, 1, 2. The smallest non-negative integer which isn't present in the sequence i. e. the \operatorname{MEX} of the sequence is 3.In the third test case, the sequence is 3 \oplus 0, 3 \oplus 1, 3 \oplus 2, or 3, 2, 1. The smallest non-negative integer which isn't present in the sequence i. e. the \operatorname{MEX} of the sequence is 0.
5 3 5 4 6 3 2 69 696 123456 654321
4 3 0 640 530866
1 second
256 megabytes
['binary search', 'bitmasks', 'greedy', 'implementation', '*1800']
B. Cobbtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \ldots, a_n and an integer k. Find the maximum value of i \cdot j - k \cdot (a_i | a_j) over all pairs (i, j) of integers with 1 \le i < j \le n. Here, | is the bitwise OR operator.InputThe first line contains a single integer t (1 \le t \le 10\,000)  — the number of test cases.The first line of each test case contains two integers n (2 \le n \le 10^5) and k (1 \le k \le \min(n, 100)).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n).It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print a single integer  — the maximum possible value of i \cdot j - k \cdot (a_i | a_j).ExampleInput 4 3 3 1 1 3 2 2 1 2 4 3 0 1 2 3 6 6 3 2 0 0 5 6 Output -1 -4 3 12 NoteLet f(i, j) = i \cdot j - k \cdot (a_i | a_j).In the first test case, f(1, 2) = 1 \cdot 2 - k \cdot (a_1 | a_2) = 2 - 3 \cdot (1 | 1) = -1. f(1, 3) = 1 \cdot 3 - k \cdot (a_1 | a_3) = 3 - 3 \cdot (1 | 3) = -6. f(2, 3) = 2 \cdot 3 - k \cdot (a_2 | a_3) = 6 - 3 \cdot (1 | 3) = -3. So the maximum is f(1, 2) = -1.In the fourth test case, the maximum is f(3, 4) = 12.
4 3 3 1 1 3 2 2 1 2 4 3 0 1 2 3 6 6 3 2 0 0 5 6
-1 -4 3 12
1 second
256 megabytes
['bitmasks', 'brute force', 'greedy', 'math', '*1700']
A. Cherrytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \ldots, a_n. Find the maximum value of max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r) over all pairs (l, r) of integers for which 1 \le l < r \le n.InputThe first line contains a single integer t (1 \le t \le 10\,000)  — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6).It is guaranteed that the sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print a single integer  — the maximum possible value of the product from the statement.ExampleInput 4 3 2 4 3 4 3 2 3 1 2 69 69 6 719313 273225 402638 473783 804745 323328 Output 12 6 4761 381274500335 NoteLet f(l, r) = max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r).In the first test case, f(1, 2) = max(a_1, a_2) \cdot min(a_1, a_2) = max(2, 4) \cdot min(2, 4) = 4 \cdot 2 = 8. f(1, 3) = max(a_1, a_2, a_3) \cdot min(a_1, a_2, a_3) = max(2, 4, 3) \cdot min(2, 4, 3) = 4 \cdot 2 = 8. f(2, 3) = max(a_2, a_3) \cdot min(a_2, a_3) = max(4, 3) \cdot min(4, 3) = 4 \cdot 3 = 12. So the maximum is f(2, 3) = 12.In the second test case, the maximum is f(1, 2) = f(1, 3) = f(2, 3) = 6.
4 3 2 4 3 4 3 2 3 1 2 69 69 6 719313 273225 402638 473783 804745 323328
12 6 4761 381274500335
1 second
256 megabytes
['greedy', '*800']
I. Stairstime limit per test10 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFor a permutation p of numbers 1 through n, we define a stair array a as follows: a_i is length of the longest segment of permutation which contains position i and is made of consecutive values in sorted order: [x, x+1, \ldots, y-1, y] or [y, y-1, \ldots, x+1, x] for some x \leq y. For example, for permutation p = [4, 1, 2, 3, 7, 6, 5] we have a = [1, 3, 3, 3, 3, 3, 3]. You are given the stair array a. Your task is to calculate the number of permutations which have stair array equal to a. Since the number can be big, compute it modulo 998\,244\,353. Note that this number can be equal to zero.InputThe first line of input contains integer n (1 \le n \le 10^5)  — the length of a stair array a.The second line of input contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n).OutputPrint the number of permutations which have stair array equal to a. Since the number can be big, compute it modulo 998\,244\,353.ExamplesInput 6 3 3 3 1 1 1 Output 6 Input 7 4 4 4 4 3 3 3 Output 6 Input 1 1 Output 1 Input 8 2 2 2 2 2 2 1 1 Output 370 Input 4 3 2 3 1 Output 0
6 3 3 3 1 1 1
6
10 seconds
1024 megabytes
['combinatorics', 'divide and conquer', 'dp', 'fft', 'math', '*3400']
H. XOR and Distancetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n distinct elements and an integer k. Each element in the array is a non-negative integer not exceeding 2^k-1.Let's define the XOR distance for a number x as the value of f(x) = \min\limits_{i = 1}^{n} \min\limits_{j = i + 1}^{n} |(a_i \oplus x) - (a_j \oplus x)|,where \oplus denotes the bitwise XOR operation.For every integer x from 0 to 2^k-1, you have to calculate f(x).InputThe first line contains two integers n and k (1 \le k \le 19; 2 \le n \le 2^k).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2^k-1). All these integers are distinct.OutputPrint 2^k integers. The i-th of them should be equal to f(i-1).ExamplesInput 3 3 6 0 3 Output 3 1 1 2 2 1 1 3 Input 3 4 13 4 2 Output 2 2 6 6 3 1 2 2 2 2 1 3 6 6 2 2 NoteConsider the first example: for x = 0, if we apply bitwise XOR to the elements of the array with x, we get the array [6, 0, 3], and the minimum absolute difference of two elements is 3; for x = 1, if we apply bitwise XOR to the elements of the array with x, we get the array [7, 1, 2], and the minimum absolute difference of two elements is 1; for x = 2, if we apply bitwise XOR to the elements of the array with x, we get the array [4, 2, 1], and the minimum absolute difference of two elements is 1; for x = 3, if we apply bitwise XOR to the elements of the array with x, we get the array [5, 3, 0], and the minimum absolute difference of two elements is 2; for x = 4, if we apply bitwise XOR to the elements of the array with x, we get the array [2, 4, 7], and the minimum absolute difference of two elements is 2; for x = 5, if we apply bitwise XOR to the elements of the array with x, we get the array [3, 5, 6], and the minimum absolute difference of two elements is 1; for x = 6, if we apply bitwise XOR to the elements of the array with x, we get the array [0, 6, 5], and the minimum absolute difference of two elements is 1; for x = 7, if we apply bitwise XOR to the elements of the array with x, we get the array [1, 7, 4], and the minimum absolute difference of two elements is 3.
3 3 6 0 3
3 1 1 2 2 1 1 3
3 seconds
512 megabytes
['bitmasks', 'divide and conquer', 'trees', '*2900']
G. Common Divisor Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a sequence of distinct integers a_1, \ldots, a_n, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than 1.There are q queries, in each query, you want to get from one given node a_s to another a_t. In order to achieve that, you can choose an existing value a_i and create new value a_{n+1} = a_i \cdot (1 + a_i), with edges to all values that are not coprime with a_{n+1}. Also, n gets increased by 1. You can repeat that operation multiple times, possibly making the sequence much longer and getting huge or repeated values. What's the minimum possible number of newly created nodes so that a_t is reachable from a_s?Queries are independent. In each query, you start with the initial sequence a given in the input.InputThe first line contains two integers n and q (2 \leq n \leq 150\,000, 1 \leq q \leq 300\,000) — the size of the sequence and the number of queries.The second line contains n distinct integers a_1, a_2, \ldots, a_n (2 \leq a_i \leq 10^6, a_i \neq a_j if i \ne j).The j-th of the following q lines contains two distinct integers s_j and t_j (1 \leq s_j, t_j \leq n, s_j \neq t_j) — indices of nodes for j-th query.OutputPrint q lines. The j-th line should contain one integer: the minimum number of new nodes you create in order to move from a_{s_j} to a_{t_j}.ExamplesInput 3 3 2 10 3 1 2 1 3 2 3 Output 0 1 1 Input 5 12 3 8 7 6 25 1 2 1 3 1 4 1 5 2 1 2 3 2 4 2 5 3 1 3 2 3 4 3 5 Output 0 1 0 1 0 1 0 1 1 1 1 2 NoteIn the first example, you can first create new value 2 \cdot 3 = 6 or 10 \cdot 11 = 110 or 3 \cdot 4 = 12. None of that is needed in the first query because you can already get from a_1 = 2 to a_2 = 10.In the second query, it's optimal to first create 6 or 12. For example, creating 6 makes it possible to get from a_1 = 2 to a_3 = 3 with a path (2, 6, 3). In the last query of the second example, we want to get from a_3 = 7 to a_5 = 25. One way to achieve that is to first create 6 \cdot 7 = 42 and then create 25 \cdot 26 = 650. The final graph has seven nodes and it contains a path from a_3 = 7 to a_5 = 25.
3 3 2 10 3 1 2 1 3 2 3
0 1 1
4 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dsu', 'graphs', 'hashing', 'math', 'number theory', '*2700']
F. Pairwise Modulotime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a consisting of n distinct positive integers, numbered from 1 to n. Define p_k as p_k = \sum_{1 \le i, j \le k} a_i \bmod a_j, where x \bmod y denotes the remainder when x is divided by y. You have to find and print p_1, p_2, \ldots, p_n. InputThe first line contains n — the length of the array (2 \le n \le 2 \cdot 10^5).The second line contains n space-separated distinct integers a_1, \ldots, a_n (1 \le a_i \le 3 \cdot 10^5, a_i \neq a_j if i \neq j). OutputPrint n integers p_1, p_2, \ldots, p_n. ExamplesInput 4 6 2 7 3 Output 0 2 12 22 Input 3 3 2 1 Output 0 3 5
4 6 2 7 3
0 2 12 22
4 seconds
256 megabytes
['data structures', 'math', '*2300']
E. Permutation Shifttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn identity permutation of length n is an array [1, 2, 3, \dots, n].We performed the following operations to an identity permutation of length n: firstly, we cyclically shifted it to the right by k positions, where k is unknown to you (the only thing you know is that 0 \le k \le n - 1). When an array is cyclically shifted to the right by k positions, the resulting array is formed by taking k last elements of the original array (without changing their relative order), and then appending n - k first elements to the right of them (without changing relative order of the first n - k elements as well). For example, if we cyclically shift the identity permutation of length 6 by 2 positions, we get the array [5, 6, 1, 2, 3, 4]; secondly, we performed the following operation at most m times: pick any two elements of the array and swap them. You are given the values of n and m, and the resulting array. Your task is to find all possible values of k in the cyclic shift operation.InputThe first line contains one integer t (1 \le t \le 10^5) — the number of test cases.Each test case consists of two lines. The first line contains two integers n and m (3 \le n \le 3 \cdot 10^5; 0 \le m \le \frac{n}{3}).The second line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, each integer from 1 to n appears in this sequence exactly once) — the resulting array.The sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print the answer in the following way: firstly, print one integer r (0 \le r \le n) — the number of possible values of k for the cyclic shift operation; secondly, print r integers k_1, k_2, \dots, k_r (0 \le k_i \le n - 1) — all possible values of k in increasing order. ExampleInput 4 4 1 2 3 1 4 3 1 1 2 3 3 1 3 2 1 6 0 1 2 3 4 6 5 Output 1 3 1 0 3 0 1 2 0 NoteConsider the example: in the first test case, the only possible value for the cyclic shift is 3. If we shift [1, 2, 3, 4] by 3 positions, we get [2, 3, 4, 1]. Then we can swap the 3-rd and the 4-th elements to get the array [2, 3, 1, 4]; in the second test case, the only possible value for the cyclic shift is 0. If we shift [1, 2, 3] by 0 positions, we get [1, 2, 3]. Then we don't change the array at all (we stated that we made at most 1 swap), so the resulting array stays [1, 2, 3]; in the third test case, all values from 0 to 2 are possible for the cyclic shift: if we shift [1, 2, 3] by 0 positions, we get [1, 2, 3]. Then we can swap the 1-st and the 3-rd elements to get [3, 2, 1]; if we shift [1, 2, 3] by 1 position, we get [3, 1, 2]. Then we can swap the 2-nd and the 3-rd elements to get [3, 2, 1]; if we shift [1, 2, 3] by 2 positions, we get [2, 3, 1]. Then we can swap the 1-st and the 2-nd elements to get [3, 2, 1]; in the fourth test case, we stated that we didn't do any swaps after the cyclic shift, but no value of cyclic shift could produce the array [1, 2, 3, 4, 6, 5].
4 4 1 2 3 1 4 3 1 1 2 3 3 1 3 2 1 6 0 1 2 3 4 6 5
1 3 1 0 3 0 1 2 0
3 seconds
256 megabytes
['brute force', 'combinatorics', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'math', '*2100']
D. Backspacetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t, both consisting of lowercase English letters. You are going to type the string s character by character, from the first character to the last one.When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the last character you have typed among those that aren't deleted yet (or does nothing if there are no characters in the current string). For example, if s is "abcbd" and you press Backspace instead of typing the first and the fourth characters, you will get the string "bd" (the first press of Backspace deletes no character, and the second press deletes the character 'c'). Another example, if s is "abcaa" and you press Backspace instead of the last two letters, then the resulting text is "a".Your task is to determine whether you can obtain the string t, if you type the string s and press "Backspace" instead of typing several (maybe zero) characters of s.InputThe first line contains a single integer q (1 \le q \le 10^5) — the number of test cases.The first line of each test case contains the string s (1 \le |s| \le 10^5). Each character of s is a lowercase English letter.The second line of each test case contains the string t (1 \le |t| \le 10^5). Each character of t is a lowercase English letter.It is guaranteed that the total number of characters in the strings over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print "YES" if you can obtain the string t by typing the string s and replacing some characters with presses of "Backspace" button, or "NO" if you cannot.You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput 4 ababa ba ababa bb aaa aaaa aababa ababa Output YES NO NO YES NoteConsider the example test from the statement.In order to obtain "ba" from "ababa", you may press Backspace instead of typing the first and the fourth characters.There's no way to obtain "bb" while typing "ababa".There's no way to obtain "aaaa" while typing "aaa".In order to obtain "ababa" while typing "aababa", you have to press Backspace instead of typing the first character, then type all the remaining characters.
4 ababa ba ababa bb aaa aaaa aababa ababa
YES NO NO YES
2 seconds
256 megabytes
['dp', 'greedy', 'strings', 'two pointers', '*1500']
C. Penaltytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a simplified penalty phase at the end of a football match.A penalty phase consists of at most 10 kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the 7-th kick the first team has scored 1 goal, and the second team has scored 3 goals, the penalty phase ends — the first team cannot reach 3 goals.You know which player will be taking each kick, so you have your predictions for each of the 10 kicks. These predictions are represented by a string s consisting of 10 characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way: if s_i is 1, then the i-th kick will definitely score a goal; if s_i is 0, then the i-th kick definitely won't score a goal; if s_i is ?, then the i-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase — you may know that some kick will/won't be scored, but the referee doesn't.InputThe first line contains one integer t (1 \le t \le 1\,000) — the number of test cases.Each test case is represented by one line containing the string s, consisting of exactly 10 characters. Each character is either 1, 0, or ?.OutputFor each test case, print one integer — the minimum possible number of kicks in the penalty phase.ExampleInput 4 1?0???1001 1111111111 ?????????? 0100000000 Output 7 10 6 9 NoteConsider the example test:In the first test case, consider the situation when the 1-st, 5-th and 7-th kicks score goals, and kicks 2, 3, 4 and 6 are unsuccessful. Then the current number of goals for the first team is 3, for the second team is 0, and the referee sees that the second team can score at most 2 goals in the remaining kicks. So the penalty phase can be stopped after the 7-th kick.In the second test case, the penalty phase won't be stopped until all 10 kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the 6-th kick, the first team has scored 0 goals and the second team has scored 3 goals, and the referee sees that the first team can score at most 2 goals in the remaining kicks. So, the penalty phase can be stopped after the 6-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the 9-th kick.
4 1?0???1001 1111111111 ?????????? 0100000000
7 10 6 9
3 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'greedy', '*1200']
B. Reverse Stringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is i, you move it to the position i + 1. Of course, moving the chip to the right is impossible if it is already in the last position.After moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is i, you move it to the position i - 1. Of course, moving the chip to the left is impossible if it is already in the first position.When you place a chip or move it, you write down the character where the chip ends up after your action. For example, if s is abcdef, you place the chip onto the 3-rd character, move it to the right 2 times and then move it to the left 3 times, you write down the string cdedcb.You are given two strings s and t. Your task is to determine whether it's possible to perform the described operations with s so that you write down the string t as a result.InputThe first line contains one integer q (1 \le q \le 500) — the number of test cases.Each test case consists of two lines. The first line contains the string s (1 \le |s| \le 500), the second line contains the string t (1 \le |t| \le 2 \cdot |s| - 1). Both strings consist of lowercase English characters.It is guaranteed that the sum of |s| over all test cases does not exceed 500.OutputFor each test case, print "YES" if you can obtain the string t by performing the process mentioned in the statement with the string s, or "NO" if you cannot.You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput 6 abcdef cdedcb aaa aaaaa aab baaa ab b abcdef abcdef ba baa Output YES YES NO YES YES NO NoteConsider the examples.The first test case is described in the statement.In the second test case, you can place the chip on the 1-st position, move it twice to the right, and then move it twice to the left.In the fourth test case, you can place the chip on the 2-nd position, and then don't move it at all.In the fifth test case, you can place the chip on the 1-st position, move it 5 times to the right, and then finish the process.
6 abcdef cdedcb aaa aaaaa aab baaa ab b abcdef abcdef ba baa
YES YES NO YES YES NO
3 seconds
256 megabytes
['brute force', 'dp', 'hashing', 'implementation', 'strings', '*1300']
A. Digits Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define S(x) to be the sum of digits of number x written in decimal system. For example, S(5) = 5, S(10) = 1, S(322) = 7.We will call an integer x interesting if S(x + 1) < S(x). In each test you will be given one integer n. Your task is to calculate the number of integers x such that 1 \le x \le n and x is interesting.InputThe first line contains one integer t (1 \le t \le 1000)  — number of test cases.Then t lines follow, the i-th line contains one integer n (1 \le n \le 10^9) for the i-th test case.OutputPrint t integers, the i-th should be the answer for the i-th test case.ExampleInput 5 1 9 10 34 880055535 Output 0 1 1 3 88005553 NoteThe first interesting number is equal to 9.
5 1 9 10 34 880055535
0 1 1 3 88005553
1 second
256 megabytes
['math', 'number theory', '*800']
I. Organizing a Music Festivaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are the organizer of the famous "Zurich Music Festival". There will be n singers who will perform at the festival, identified by the integers 1, 2, \dots, n. You must choose in which order they are going to perform on stage. You have m friends and each of them has a set of favourite singers. More precisely, for each 1\le i\le m, the i-th friend likes singers s_{i,1}, \, s_{i, 2}, \, \dots, \,s_{i, q_i}.A friend of yours is happy if the singers he likes perform consecutively (in an arbitrary order). An ordering of the singers is valid if it makes all your friends happy.Compute the number of valid orderings modulo 998\,244\,353.InputThe first line contains two integers n and m (1\le n,\,m\le 100) — the number of singers and the number of friends correspondingly.The i-th of the next m lines contains the integer q_i (1\le q_i\le n) — the number of favorite singers of the i-th friend – followed by the q_i integers s_{i,1}, \, s_{i, 2}, \, \dots, \,s_{i, q_i} (1\le s_{i,1}<s_{i,2}<\cdots<s_{i,q_i}\le n) — the indexes of his favorite singers.OutputPrint the number of valid orderings of the singers modulo 998\,244\,353.ExamplesInput 3 1 2 1 3 Output 4 Input 5 5 2 1 2 2 2 3 2 3 4 2 4 5 2 1 5 Output 0 Input 100 1 1 50 Output 35305197 Input 5 1 5 1 2 3 4 5 Output 120 Input 2 5 1 2 1 2 1 2 1 1 1 1 Output 2 Input 11 4 5 4 5 7 9 11 2 2 10 2 9 11 7 1 2 3 5 8 10 11 Output 384 NoteExplanation of the first sample: There are 3 singers and only 1 friend. The friend likes the two singers 1 and 3. Thus, the 4 valid orderings are: 1 3 2 2 1 3 2 3 1 3 1 2 Explanation of the second sample: There are 5 singers and 5 friends. One can show that no ordering is valid.Explanation of the third sample: There are 100 singers and only 1 friend. The friend likes only singer 50, hence all the 100! possible orderings are valid.Explanation of the fourth sample: There are 5 singers and only 1 friend. The friend likes all the singers, hence all the 5!=120 possible orderings are valid.
3 1 2 1 3
4
1 second
256 megabytes
['dfs and similar', 'math', '*3400']
H. Guess the Perimetertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us call a point of the plane admissible if its coordinates are positive integers less than or equal to 200.There is an invisible rectangle such that: its vertices are all admissible; its sides are parallel to the coordinate axes; its area is strictly positive. Your task is to guess the perimeter of this rectangle.In order to guess it, you may ask at most 4 queries. In each query, you choose a nonempty subset of the admissible points and you are told how many of the chosen points are inside or on the boundary of the invisible rectangle.InteractionTo ask a query (of the kind described in the statement), you shall print two lines: In the first line print "? k" (without the quotes) where k (k\ge 1) is the number of chosen points. In the second line print 2k integers x_1,\, y_1,\, x_2,\, y_2,\, \dots,\, x_k,\, y_k (1\le x_i,y_i\le 200 for i=1,2,\dots,k) where (x_1, y_1),\,(x_2, y_2),\,(x_3, y_3),\, \dots,\,(x_k, y_k) are the k distinct admissible chosen points (the order of the points is not important). After this, you should read an integer — the number of chosen points that are inside or on the boundary of the invisible rectangle.When you have identified the perimeter p of the invisible rectangle, you must print "! p" (without quotes) and terminate your program.If you ask more than 4 queries or if one of the queries is malformed, the interactor terminates immediately and your program receives verdict Wrong Answer.The interactor may be adaptive (i.e., the hidden rectangle may not be chosen before the beginning of the interaction).After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. HacksTo hack a solution, use the following format.The input has only one line, containing the 4 integers x_0, y_0, x_1, y_1 (1\le x_0<x_1\le 200, 1\le y_0 < y_1 \le 200) — (x_0,y_0) is the bottom-left vertex of the hidden rectangle and (x_1, y_1) is the top-right vertex of the hidden rectangle.Note that for hacks the interaction won't be adaptive.ExamplesInput 13 5 123 80 Output Input 2 2 4 4 Output Input 1 1 200 200 Output NoteThe following is an example of interaction for the first sample intended to show the format of the queries. \begin{array}{l|l|l} \text{Query (contestant program)} & \text{Answer (interactor)} & \text{Explanation} \\ \hline \mathtt{?\ 4} & & \text{We choose the $4$ vertices of} \\ \mathtt{13\ 5\ 13\ 80\ 123\ 5\ 123\ 80} & \mathtt{4} &\text{the hidden rectangle.}\\ \hline \mathtt{?\ 5} & & \text{We choose $4$ points just outside the hidden}\\ \mathtt{100\ 4\ 100\ 81\ 12\ 40\ 124\ 40\ 50\ 50} & \mathtt{1}& \text{rectangle and also the point $(50,50)$.}\\ \hline \mathtt{?\ 2} & & \text{We choose the points $(1, 1)$} \\ \mathtt{200\ 200\ 1\ 1} & \mathtt{0} & \text{and $(200,200)$.}\\ \hline \mathtt{!\ 370} & & \text{This is the correct perimeter.} \end{array} For the second sample, a possible interaction is the following. \begin{array}{l|l|l} \text{Query (contestant program)} & \text{Answer (interactor)} & \text{Explanation} \\ \hline \mathtt{?\ 4} & & \text{We choose the points $(3, 2)$, $(4, 1)$,} \\ \mathtt{3\ 2\ 4\ 1\ 5\ 2\ 4\ 3} & 2 & \text{$(5, 2)$ and $(4, 3)$.} \\ \hline \mathtt{?\ 7} & & \text{We choose the points $(1, 4)$, $(2, 4)$,} \\ \mathtt{1\ 4\ 2\ 4\ 1\ 5\ 2\ 5\ 5\ 5\ 5\ 6\ 6\ 5} & 1 & \text{$(1, 5)$, $(2, 5)$, $(5, 5)$, $(5, 6)$ and $(6, 5)$.} \\ \hline \mathtt{!\ 8} & & \text{This is the correct perimeter.} \end{array} The situation is shown in the following picture: The green points are the ones belonging to the first query, while the orange points are the ones belonging to the second query. One can see that there are exactly two rectangles consistent with the interactor's answers: the rectangle of vertices (2, 2) and (4, 4), shown in red; the rectangle of vertices (4, 2) and (5, 5), shown in blue. Since both of these rectangles have perimeter 8, this is the final answer.
13 5 123 80
null
1 second
256 megabytes
['binary search', 'interactive', 'number theory', '*3300']
G. A Serious Refereetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputAndrea has come up with what he believes to be a novel sorting algorithm for arrays of length n. The algorithm works as follows.Initially there is an array of n integers a_1,\, a_2,\, \dots,\, a_n. Then, k steps are executed.For each 1\le i\le k, during the i-th step the subsequence of the array a with indexes j_{i,1}< j_{i,2}< \dots< j_{i, q_i} is sorted, without changing the values with the remaining indexes. So, the subsequence a_{j_{i,1}},\, a_{j_{i,2}},\, \dots,\, a_{j_{i,q_i}} is sorted and all other elements of a are left untouched.Andrea, being eager to share his discovery with the academic community, sent a short paper describing his algorithm to the journal "Annals of Sorting Algorithms" and you are the referee of the paper (that is, the person who must judge the correctness of the paper). You must decide whether Andrea's algorithm is correct, that is, if it sorts any array a of n integers.InputThe first line contains two integers n and k (1\le n\le 40, 0\le k\le 10) — the length of the arrays handled by Andrea's algorithm and the number of steps of Andrea's algorithm.Then k lines follow, each describing the subsequence considered in a step of Andrea's algorithm.The i-th of these lines contains the integer q_i (1\le q_i\le n) followed by q_i integers j_{i,1},\,j_{i,2},\,\dots,\, j_{i,q_i} (1\le j_{i,1}<j_{i,2}<\cdots<j_{i,q_i}\le n) — the length of the subsequence considered in the i-th step and the indexes of the subsequence.OutputIf Andrea's algorithm is correct print ACCEPTED, otherwise print REJECTED.ExamplesInput 4 3 3 1 2 3 3 2 3 4 2 1 2 Output ACCEPTED Input 4 3 3 1 2 3 3 2 3 4 3 1 3 4 Output REJECTED Input 3 4 1 1 1 2 1 3 2 1 3 Output REJECTED Input 5 2 3 2 3 4 5 1 2 3 4 5 Output ACCEPTED NoteExplanation of the first sample: The algorithm consists of 3 steps. The first one sorts the subsequence [a_1, a_2, a_3], the second one sorts the subsequence [a_2, a_3, a_4], the third one sorts the subsequence [a_1,a_2]. For example, if initially a=[6, 5, 6, 3], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) [{\color{red}6},{\color{red}5},{\color{red}6},3] \rightarrow [5, {\color{red}6}, {\color{red}6}, {\color{red}3}] \rightarrow [{\color{red}5}, {\color{red}3}, 6, 6] \rightarrow [3, 5, 6, 6] \,. One can prove that, for any initial array a, at the end of the algorithm the array a will be sorted.Explanation of the second sample: The algorithm consists of 3 steps. The first one sorts the subsequence [a_1, a_2, a_3], the second one sorts the subsequence [a_2, a_3, a_4], the third one sorts the subsequence [a_1,a_3,a_4]. For example, if initially a=[6, 5, 6, 3], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) [{\color{red}6},{\color{red}5},{\color{red}6},3] \rightarrow [5, {\color{red}6}, {\color{red}6}, {\color{red}3}] \rightarrow [{\color{red}5}, 3, {\color{red}6}, {\color{red}6}] \rightarrow [5, 3, 6, 6] \,. Notice that a=[6,5,6,3] is an example of an array that is not sorted by the algorithm.Explanation of the third sample: The algorithm consists of 4 steps. The first 3 steps do nothing because they sort subsequences of length 1, whereas the fourth step sorts the subsequence [a_1,a_3]. For example, if initially a=[5,6,4], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) [{\color{red}5},6,4] \rightarrow [5,{\color{red}6},4] \rightarrow [5,{\color{red}6},4] \rightarrow [{\color{red}5},6,{\color{red}4}]\rightarrow [4,6,5] \,. Notice that a=[5,6,4] is an example of an array that is not sorted by the algorithm.Explanation of the fourth sample: The algorithm consists of 2 steps. The first step sorts the subsequences [a_2,a_3,a_4], the second step sorts the whole array [a_1,a_2,a_3,a_4,a_5]. For example, if initially a=[9,8,1,1,1], the algorithm transforms the array as follows (the subsequence that gets sorted is highlighted in red) [9,{\color{red}8},{\color{red}1},{\color{red}1},1] \rightarrow [{\color{red}9},{\color{red}1},{\color{red}1},{\color{red}8},{\color{red}1}] \rightarrow [1,1,1,8,9] \,. Since in the last step the whole array is sorted, it is clear that, for any initial array a, at the end of the algorithm the array a will be sorted.
4 3 3 1 2 3 3 2 3 4 2 1 2
ACCEPTED
1 second
512 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'sortings', '*3000']
F. Telepantingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn ant moves on the real line with constant speed of 1 unit per second. It starts at 0 and always moves to the right (so its position increases by 1 each second).There are n portals, the i-th of which is located at position x_i and teleports to position y_i < x_i. Each portal can be either active or inactive. The initial state of the i-th portal is determined by s_i: if s_i=0 then the i-th portal is initially inactive, if s_i=1 then the i-th portal is initially active. When the ant travels through a portal (i.e., when its position coincides with the position of a portal): if the portal is inactive, it becomes active (in this case the path of the ant is not affected); if the portal is active, it becomes inactive and the ant is instantly teleported to the position y_i, where it keeps on moving as normal. How long (from the instant it starts moving) does it take for the ant to reach the position x_n + 1? It can be shown that this happens in a finite amount of time. Since the answer may be very large, compute it modulo 998\,244\,353.InputThe first line contains the integer n (1\le n\le 2\cdot 10^5) — the number of portals.The i-th of the next n lines contains three integers x_i, y_i and s_i (1\le y_i < x_i\le 10^9, s_i\in\{0,1\}) — the position of the i-th portal, the position where the ant is teleported when it travels through the i-th portal (if it is active), and the initial state of the i-th portal.The positions of the portals are strictly increasing, that is x_1<x_2<\cdots<x_n. It is guaranteed that the 2n integers x_1, \, x_2, \, \dots, \, x_n, \, y_1, \, y_2, \, \dots, \, y_n are all distinct.OutputOutput the amount of time elapsed, in seconds, from the instant the ant starts moving to the instant it reaches the position x_n+1. Since the answer may be very large, output it modulo 998\,244\,353.ExamplesInput 4 3 2 0 6 5 1 7 4 0 8 1 1 Output 23 Input 1 454971987 406874902 1 Output 503069073 Input 5 243385510 42245605 0 644426565 574769163 0 708622105 208990040 0 786625660 616437691 0 899754846 382774619 0 Output 899754847 Input 5 200000000 100000000 1 600000000 400000000 0 800000000 300000000 0 900000000 700000000 1 1000000000 500000000 0 Output 3511295 NoteExplanation of the first sample: The ant moves as follows (a curvy arrow denotes a teleporting, a straight arrow denotes normal movement with speed 1 and the time spent during the movement is written above the arrow). 0 \stackrel{6}{\longrightarrow} 6 \leadsto 5 \stackrel{3}{\longrightarrow} 8 \leadsto 1 \stackrel{2}{\longrightarrow} 3 \leadsto 2 \stackrel{4}{\longrightarrow} 6 \leadsto 5 \stackrel{2}{\longrightarrow} 7 \leadsto 4 \stackrel{2}{\longrightarrow} 6 \leadsto 5 \stackrel{4}{\longrightarrow} 9 Notice that the total time is 6+3+2+4+2+2+4=23.Explanation of the second sample: The ant moves as follows (a curvy arrow denotes a teleporting, a straight arrow denotes normal movement with speed 1 and the time spent during the movement is written above the arrow). 0 \stackrel{454971987}{\longrightarrow} 454971987 \leadsto 406874902 \stackrel{48097086}{\longrightarrow} 454971988 Notice that the total time is 454971987+48097086=503069073.Explanation of the third sample: Since all portals are initially off, the ant will not be teleported and will go straight from 0 to x_n+1=899754846+1=899754847.
4 3 2 0 6 5 1 7 4 0 8 1 1
23
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'sortings', '*2200']
E. Colors and Intervalstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe numbers 1, \, 2, \, \dots, \, n \cdot k are colored with n colors. These colors are indexed by 1, \, 2, \, \dots, \, n. For each 1 \le i \le n, there are exactly k numbers colored with color i.Let [a, \, b] denote the interval of integers between a and b inclusive, that is, the set \{a, \, a + 1, \, \dots, \, b\}. You must choose n intervals [a_1, \, b_1], \, [a_2, \, b_2], \, \dots, [a_n, \, b_n] such that: for each 1 \le i \le n, it holds 1 \le a_i < b_i \le n \cdot k; for each 1 \le i \le n, the numbers a_i and b_i are colored with color i; each number 1 \le x \le n \cdot k belongs to at most \left\lceil \frac{n}{k - 1} \right\rceil intervals. One can show that such a family of intervals always exists under the given constraints.InputThe first line contains two integers n and k (1 \le n \le 100, 2 \le k \le 100) — the number of colors and the number of occurrences of each color.The second line contains n \cdot k integers c_1, \, c_2, \, \dots, \, c_{nk} (1 \le c_j \le n), where c_j is the color of number j. It is guaranteed that, for each 1 \le i \le n, it holds c_j = i for exactly k distinct indices j.OutputOutput n lines. The i-th line should contain the two integers a_i and b_i.If there are multiple valid choices of the intervals, output any.ExamplesInput 4 3 2 4 3 1 1 4 2 3 2 1 3 4 Output 4 5 1 7 8 11 6 12Input 1 2 1 1 Output 1 2 Input 3 3 3 1 2 3 2 1 2 1 3 Output 6 8 3 7 1 4Input 2 3 2 1 1 1 2 2 Output 2 3 5 6 NoteIn the first sample, each number can be contained in at most \left\lceil \frac{4}{3 - 1} \right\rceil = 2 intervals. The output is described by the following picture: In the second sample, the only interval to be chosen is forced to be [1, \, 2], and each number is indeed contained in at most \left\lceil \frac{1}{2 - 1} \right\rceil = 1 interval.In the third sample, each number can be contained in at most \left\lceil \frac{3}{3 - 1} \right\rceil = 2 intervals. The output is described by the following picture:
4 3 2 4 3 1 1 4 2 3 2 1 3 4
4 5 1 7 8 11 6 12
1 second
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'sortings', '*2300']
D. Array Differentiationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n integers a_1, \, a_2, \, \dots, \, a_n.Does there exist a sequence of n integers b_1, \, b_2, \, \dots, \, b_n such that the following property holds? For each 1 \le i \le n, there exist two (not necessarily distinct) indices j and k (1 \le j, \, k \le n) such that a_i = b_j - b_k. InputThe first line contains a single integer t (1 \le t \le 20) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 10).The second line of each test case contains the n integers a_1, \, \dots, \, a_n (-10^5 \le a_i \le 10^5).OutputFor each test case, output a line containing YES if a sequence b_1, \, \dots, \, b_n satisfying the required property exists, and NO otherwise.ExampleInput 5 5 4 -7 -1 5 10 1 0 3 1 10 100 4 -3 2 10 2 9 25 -171 250 174 152 242 100 -205 -258 Output YES YES NO YES YES NoteIn the first test case, the sequence b = [-9, \, 2, \, 1, \, 3, \, -2] satisfies the property. Indeed, the following holds: a_1 = 4 = 2 - (-2) = b_2 - b_5; a_2 = -7 = -9 - (-2) = b_1 - b_5; a_3 = -1 = 1 - 2 = b_3 - b_2; a_4 = 5 = 3 - (-2) = b_4 - b_5; a_5 = 10 = 1 - (-9) = b_3 - b_1. In the second test case, it is sufficient to choose b = [0], since a_1 = 0 = 0 - 0 = b_1 - b_1.In the third test case, it is possible to show that no sequence b of length 3 satisfies the property.
5 5 4 -7 -1 5 10 1 0 3 1 10 100 4 -3 2 10 2 9 25 -171 250 174 152 242 100 -205 -258
YES YES NO YES YES
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dfs and similar', 'dp', 'graphs', 'math', '*1800']
C. Maximize the Intersectionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a circle lie 2n distinct points, with the following property: however you choose 3 chords that connect 3 disjoint pairs of points, no point strictly inside the circle belongs to all 3 chords. The points are numbered 1, \, 2, \, \dots, \, 2n in clockwise order.Initially, k chords connect k pairs of points, in such a way that all the 2k endpoints of these chords are distinct.You want to draw n - k additional chords that connect the remaining 2(n - k) points (each point must be an endpoint of exactly one chord).In the end, let x be the total number of intersections among all n chords. Compute the maximum value that x can attain if you choose the n - k chords optimally.Note that the exact position of the 2n points is not relevant, as long as the property stated in the first paragraph holds.InputThe first line contains a single 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 k (1 \le n \le 100, 0 \le k \le n) — half the number of points and the number of chords initially drawn.Then k lines follow. The i-th of them contains two integers x_i and y_i (1 \le x_i, \, y_i \le 2n, x_i \ne y_i) — the endpoints of the i-th chord. It is guaranteed that the 2k numbers x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k are all distinct.OutputFor each test case, output the maximum number of intersections that can be obtained by drawing n - k additional chords.ExampleInput 4 4 2 8 2 1 5 1 1 2 1 2 0 10 6 14 6 2 20 9 10 13 18 15 12 11 7 Output 4 0 1 14 NoteIn the first test case, there are three ways to draw the 2 additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones): We see that the third way gives the maximum number of intersections, namely 4.In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.In the third test case, we can make at most one intersection by drawing chords 1-3 and 2-4, as shown below:
4 4 2 8 2 1 5 1 1 2 1 2 0 10 6 14 6 2 20 9 10 13 18 15 12 11 7
4 0 1 14
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'geometry', 'greedy', 'sortings', '*1800']
B. Running for Goldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Olympic Games have just started and Federico is eager to watch the marathon race.There will be n athletes, numbered from 1 to n, competing in the marathon, and all of them have taken part in 5 important marathons, numbered from 1 to 5, in the past. For each 1\le i\le n and 1\le j\le 5, Federico remembers that athlete i ranked r_{i,j}-th in marathon j (e.g., r_{2,4}=3 means that athlete 2 was third in marathon 4).Federico considers athlete x superior to athlete y if athlete x ranked better than athlete y in at least 3 past marathons, i.e., r_{x,j}<r_{y,j} for at least 3 distinct values of j.Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of each test case contains a single integer n (1\le n\le 50\,000) — the number of athletes.Then n lines follow, each describing the ranking positions of one athlete.The i-th of these lines contains the 5 integers r_{i,1},\,r_{i,2},\,r_{i,3},\,r_{i,4},\, r_{i,5} (1\le r_{i,j}\le 50\,000) — the ranking positions of athlete i in the past 5 marathons. It is guaranteed that, in each of the 5 past marathons, the n athletes have distinct ranking positions, i.e., for each 1\le j\le 5, the n values r_{1,j},\, r_{2, j},\, \dots,\, r_{n, j} are distinct.It is guaranteed that the sum of n over all test cases does not exceed 50\,000.OutputFor each test case, print a single integer — the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print -1. If there is more than such one athlete, print any of them.ExampleInput 4 1 50000 1 50000 50000 50000 3 10 10 20 30 30 20 20 30 10 10 30 30 10 20 20 3 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 6 9 5 3 7 1 7 4 1 6 8 5 6 7 3 2 6 7 8 8 6 4 2 2 4 5 8 3 6 9 4 Output 1 -1 1 5 NoteExplanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal.Explanation of the second test case: There are n=3 athletes. Athlete 1 is superior to athlete 2. Indeed athlete 1 ranks better than athlete 2 in the marathons 1, 2 and 3. Athlete 2 is superior to athlete 3. Indeed athlete 2 ranks better than athlete 3 in the marathons 1, 2, 4 and 5. Athlete 3 is superior to athlete 1. Indeed athlete 3 ranks better than athlete 1 in the marathons 3, 4 and 5. Explanation of the third test case: There are n=3 athletes. Athlete 1 is superior to athletes 2 and 3. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete 2 is superior to athlete 3. Athlete 3 is not superior to any other athlete. Explanation of the fourth test case: There are n=6 athletes. Athlete 1 is superior to athletes 3, 4, 6. Athlete 2 is superior to athletes 1, 4, 6. Athlete 3 is superior to athletes 2, 4, 6. Athlete 4 is not superior to any other athlete. Athlete 5 is superior to athletes 1, 2, 3, 4, 6. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete 6 is only superior to athlete 4.
4 1 50000 1 50000 50000 50000 3 10 10 20 30 30 20 20 30 10 10 30 30 10 20 20 3 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 6 9 5 3 7 1 7 4 1 6 8 5 6 7 3 2 6 7 8 8 6 4 2 2 4 5 8 3 6 9 4
1 -1 1 5
1 second
256 megabytes
['combinatorics', 'graphs', 'greedy', 'sortings', '*1500']
A. Subsequence Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string s of length n, consisting of lowercase letters of the English alphabet, is given.You must choose some number k between 0 and n. Then, you select k characters of s and permute them however you want. In this process, the positions of the other n-k characters remain unchanged. You have to perform this operation exactly once.For example, if s=\texttt{"andrea"}, you can choose the k=4 characters \texttt{"a_d_ea"} and permute them into \texttt{"d_e_aa"} so that after the operation the string becomes \texttt{"dneraa"}.Determine the minimum k so that it is possible to sort s alphabetically (that is, after the operation its characters appear in alphabetical order).InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then t test cases follow.The first line of each test case contains one integer n (1 \le n \le 40) — the length of the string.The second line of each test case contains the string s. It is guaranteed that s contains only lowercase letters of the English alphabet.OutputFor each test case, output the minimum k that allows you to obtain a string sorted alphabetically, through the operation described above.ExampleInput 4 3 lol 10 codeforces 5 aaaaa 4 dcba Output 2 6 0 4 NoteIn the first test case, we can choose the k=2 characters \texttt{"_ol"} and rearrange them as \texttt{"_lo"} (so the resulting string is \texttt{"llo"}). It is not possible to sort the string choosing strictly less than 2 characters.In the second test case, one possible way to sort s is to consider the k=6 characters \texttt{"_o__force_"} and rearrange them as \texttt{"_c__efoor_"} (so the resulting string is \texttt{"ccdeefoors"}). One can show that it is not possible to sort the string choosing strictly less than 6 characters.In the third test case, string s is already sorted (so we can choose k=0 characters).In the fourth test case, we can choose all k=4 characters \texttt{"dcba"} and reverse the whole string (so the resulting string is \texttt{"abcd"}).
4 3 lol 10 codeforces 5 aaaaa 4 dcba
2 6 0 4
1 second
256 megabytes
['sortings', 'strings', '*800']
F. Equidistant Verticestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is an undirected connected graph without cycles.You are given a tree of n vertices. Find the number of ways to choose exactly k vertices in this tree (i. e. a k-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer c such that for all u, v (u \ne v, u, v are in selected vertices) d_{u,v}=c, where d_{u,v} is the distance from u to v).Since the answer may be very large, you need to output it modulo 10^9 + 7.InputThe first line contains one integer t (1 \le t \le 10) — the number of test cases. Then t test cases follow.Each test case is preceded by an empty line.Each test case consists of several lines. The first line of the test case contains two integers n and k (2 \le k \le n \le 100) — the number of vertices in the tree and the number of vertices to be selected, respectively. Then n - 1 lines follow, each of them contains two integers u and v (1 \le u, v \le n, u \neq v) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges.OutputFor each test case output in a separate line a single integer — the number of ways to select exactly k vertices so that for all pairs of selected vertices the distances between the vertices in the pairs are equal, modulo 10^9 + 7 (in other words, print the remainder when divided by 1000000007).ExampleInput 3 4 2 1 2 2 3 2 4 3 3 1 2 2 3 5 3 1 2 2 3 2 4 4 5 Output 6 0 1
3 4 2 1 2 2 3 2 4 3 3 1 2 2 3 5 3 1 2 2 3 2 4 4 5
6 0 1
1 second
256 megabytes
['brute force', 'combinatorics', 'dfs and similar', 'dp', 'trees', '*2200']