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
|
---|---|---|---|---|---|
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number n. Find three distinct integers a, b, c such that 2 \le a, b, c and a \cdot b \cdot c = n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases.The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 \le n \le 10^9).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent n as a \cdot b \cdot c for some distinct integers a, b, c such that 2 \le a, b, c.Otherwise, print "YES" and any possible such representation.ExampleInput
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
| 5
64
32
97
2
12345
| YES 2 4 8 NO NO NO YES 3 5 823 | 2 seconds | 256 megabytes | ['greedy', 'math', 'number theory', '*1300'] |
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0, 0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x, y) to the point (x + 1, y) or to the point (x, y + 1).As we say above, the robot wants to collect all n packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string s of length n is lexicographically less than the string t of length n if there is some index 1 \le j \le n that for all i from 1 to j-1 s_i = t_i and s_j < t_j. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer t (1 \le t \le 100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer n (1 \le n \le 1000) — the number of packages.The next n lines contain descriptions of packages. The i-th package is given as two integers x_i and y_i (0 \le x_i, y_i \le 1000) — the x-coordinate of the package and the y-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0, 0) doesn't contain a package.The sum of all values n over test cases in the test doesn't exceed 1000.OutputPrint the answer for each test case.If it is impossible to collect all n packages in some order starting from (0,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInput
3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
Output
YES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | 3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
| YES RUUURRRRUU NO YES RRRRUUU | 1 second | 256 megabytes | ['implementation', 'sortings', '*1200'] |
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.He wants to distribute all these n coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives A coins to Alice, B coins to Barbara and C coins to Cerene (A+B+C=n), then a + A = b + B = c + C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all n coins between sisters in a way described above.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.The next t lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a, b, c and n (1 \le a, b, c, n \le 10^8) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all n coins between his sisters and "NO" otherwise.ExampleInput
5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
Output
YES
YES
NO
NO
YES
| 5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
| YES YES NO NO YES | 2 seconds | 256 megabytes | ['math', '*800'] |
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are s (s > 0) opponents remaining and t (0 \le t \le s) of them make a mistake on it, JOE receives \displaystyle\frac{t}{s} dollars, and consequently there will be s - t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer n (1 \le n \le 10^5), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10^{-4}. In other words, if your answer is a and the jury answer is b, then it must hold that \frac{|a - b|}{max(1, b)} \le 10^{-4}.ExamplesInput
1
Output
1.000000000000
Input
2
Output
1.500000000000
NoteIn the second example, the best scenario would be: one contestant fails at the first question, the other fails at the next one. The total reward will be \displaystyle \frac{1}{2} + \frac{1}{1} = 1.5 dollars. | 1
| 1.000000000000 | 1 second | 256 megabytes | ['combinatorics', 'greedy', 'math', '*1000'] |
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor s of the building. On each floor (including floor s, of course), there is a restaurant offering meals. However, due to renovations being in progress, k of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases in the test. Then the descriptions of t test cases follow.The first line of a test case contains three integers n, s and k (2 \le n \le 10^9, 1 \le s \le n, 1 \le k \le \min(n-1, 1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains k distinct integers a_1, a_2, \ldots, a_k (1 \le a_i \le n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of k over all test cases does not exceed 1000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor s to a floor with an open restaurant.ExampleInput
5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
Output
2
0
4
0
2
NoteIn the first example test case, the nearest floor with an open restaurant would be the floor 4.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 6-th floor. | 5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
| 2 0 4 0 2 | 1 second | 256 megabytes | ['binary search', 'brute force', 'implementation', '*1100'] |
F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora n boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all n boxes with n distinct integers a_1, a_2, \ldots, a_n and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices i, j and k, such that a_i \mid a_j and a_i \mid a_k. In other words, a_i divides both a_j and a_k, that is a_j \bmod a_i = 0, a_k \bmod a_i = 0. After choosing, Nora will give the k-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box k becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 10^9 + 7.InputThe first line contains an integer n (3 \le n \le 60), denoting the number of boxes.The second line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le 60), where a_i is the label of the i-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 10^9 + 7.ExamplesInput
3
2 6 8
Output
2
Input
5
2 3 4 9 12
Output
4
Input
4
5 7 2 9
Output
1
NoteLet's illustrate the box pile as a sequence b, with the pile's bottommost box being at the leftmost position.In the first example, there are 2 distinct piles possible: b = [6] ([2, \mathbf{6}, 8] \xrightarrow{(1, 3, 2)} [2, 8]) b = [8] ([2, 6, \mathbf{8}] \xrightarrow{(1, 2, 3)} [2, 6]) In the second example, there are 4 distinct piles possible: b = [9, 12] ([2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, \mathbf{12}] \xrightarrow{(1, 3, 4)} [2, 3, 4]) b = [4, 12] ([2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, \mathbf{12}] \xrightarrow{(2, 3, 4)} [2, 3, 9]) b = [4, 9] ([2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, \mathbf{9}, 12] \xrightarrow{(2, 4, 3)} [2, 3, 12]) b = [9, 4] ([2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, \mathbf{4}, 12] \xrightarrow{(1, 4, 3)} [2, 3, 12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 1 valid pile, and that pile is empty. | 3
2 6 8
| 2 | 1 second | 256 megabytes | ['bitmasks', 'combinatorics', 'dp', '*3500'] |
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string p. From the unencrypted papers included, Rin already knows the length n of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string s of an arbitrary length into the artifact's terminal, and it will return every starting position of s as a substring of p.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains \frac{7}{5} units of energy. For each time Rin inputs a string s of length t, the artifact consumes \frac{1}{t^2} units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer t (1 \le t \le 500), the number of test cases. The interaction for each testcase is described below:First, read an integer n (4 \le n \le 50), the length of the string p.Then you can make queries of type "? s" (1 \le |s| \le n) to find the occurrences of s as a substring of p.After the query, you need to read its result as a series of integers in a line: The first integer k denotes the number of occurrences of s as a substring of p (-1 \le k \le n). If k = -1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following k integers a_1, a_2, \ldots, a_k (1 \le a_1 < a_2 < \ldots < a_k \le n) denote the starting positions of the substrings that match the string s.When you find out the string p, print "! p" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 1 or 0. If the interactor returns 1, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 0, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string p is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer t (t = 1).The second line should contain an integer n (4 \le n \le 50) — the string's size.The third line should contain a string of size n, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInput
1
4
2 1 2
1 2
0
1Output
? C
? CH
? CCHO
! CCHH
Input
2
5
0
2 2 3
1
8
1 5
1 5
1 3
2 1 2
1Output
? O
? HHH
! CHHHH
? COO
? COOH
? HCCOO
? HH
! HHHCCOOH
NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well. | 1
4
2 1 2
1 2
0
1 | ? C ? CH ? CCHO ! CCHH | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'interactive', 'math', '*3500'] |
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1, 2, 3, \ldots). The node with a number x (x > 1), is directly connected with a node with number \frac{x}{f(x)}, with f(x) being the lowest prime divisor of x.Vanessa's mind is divided into n fragments. Due to more than 500 years of coma, the fragments have been scattered: the i-th fragment is now located at the node with a number k_i! (a factorial of k_i).To maximize the chance of successful awakening, Ivy decides to place the samples in a node P, so that the total length of paths from each fragment to P is smallest possible. If there are multiple fragments located at the same node, the path from that node to P needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node P.InputThe first line contains an integer n (1 \le n \le 10^6) — number of fragments of Vanessa's mind.The second line contains n integers: k_1, k_2, \ldots, k_n (0 \le k_i \le 5000), denoting the nodes where fragments of Vanessa's mind are located: the i-th fragment is at the node with a number k_i!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node P).As a reminder, if there are multiple fragments at the same node, the distance from that node to P needs to be counted multiple times as well.ExamplesInput
3
2 1 4
Output
5
Input
4
3 1 4 4
Output
6
Input
4
3 1 4 1
Output
6
Input
5
3 1 4 1 5
Output
11
NoteConsidering the first 24 nodes of the system, the node network will look as follows (the nodes 1!, 2!, 3!, 4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 1. From here: The distance from Vanessa's first fragment to the node 1 is 1. The distance from Vanessa's second fragment to the node 1 is 0. The distance from Vanessa's third fragment to the node 1 is 4. The total length is 5.For the second example, the assembly node will be 6. From here: The distance from Vanessa's first fragment to the node 6 is 0. The distance from Vanessa's second fragment to the node 6 is 2. The distance from Vanessa's third fragment to the node 6 is 2. The distance from Vanessa's fourth fragment to the node 6 is again 2. The total path length is 6. | 3
2 1 4
| 5 | 2 seconds | 512 megabytes | ['dp', 'graphs', 'greedy', 'math', 'number theory', 'trees', '*2700'] |
C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of n small gangs. This network contains exactly n - 1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 0 to n - 2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass S password layers, with S being defined by the following formula:S = \sum_{1 \leq u < v \leq n} mex(u, v)Here, mex(u, v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang u to gang v.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of S, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible S before he returns?InputThe first line contains an integer n (2 \leq n \leq 3000), the number of gangs in the network.Each of the next n - 1 lines contains integers u_i and v_i (1 \leq u_i, v_i \leq n; u_i \neq v_i), indicating there's a direct link between gangs u_i and v_i.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of S — the number of password layers in the gangs' network.ExamplesInput
3
1 2
2 3
Output
3
Input
5
1 2
1 3
1 4
3 5
Output
10
NoteIn the first example, one can achieve the maximum S with the following assignment: With this assignment, mex(1, 2) = 0, mex(1, 3) = 2 and mex(2, 3) = 1. Therefore, S = 0 + 2 + 1 = 3.In the second example, one can achieve the maximum S with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1, 3) = 1 mex(1, 5) = 2 mex(2, 3) = 1 mex(2, 5) = 2 mex(3, 4) = 1 mex(4, 5) = 3 Therefore, S = 1 + 2 + 1 + 2 + 1 + 3 = 10. | 3
1 2
2 3
| 3 | 3 seconds | 512 megabytes | ['combinatorics', 'dfs and similar', 'dp', 'greedy', 'trees', '*2300'] |
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows: The coordinates of the 0-th node is (x_0, y_0) For i > 0, the coordinates of i-th node is (a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y) Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.While within the OS space, Aroma can do the following actions: From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?InputThe first line contains integers x_0, y_0, a_x, a_y, b_x, b_y (1 \leq x_0, y_0 \leq 10^{16}, 2 \leq a_x, a_y \leq 100, 0 \leq b_x, b_y \leq 10^{16}), which define the coordinates of the data nodes.The second line contains integers x_s, y_s, t (1 \leq x_s, y_s, t \leq 10^{16}) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within t seconds.ExamplesInput
1 1 2 3 1 0
2 4 20
Output
3Input
1 1 2 3 1 0
15 27 26
Output
2Input
1 1 2 3 1 0
2 2 1
Output
0NoteIn all three examples, the coordinates of the first 5 data nodes are (1, 1), (3, 3), (7, 9), (15, 27) and (31, 81) (remember that nodes are numbered from 0).In the first example, the optimal route to collect 3 nodes is as follows: Go to the coordinates (3, 3) and collect the 1-st node. This takes |3 - 2| + |3 - 4| = 2 seconds. Go to the coordinates (1, 1) and collect the 0-th node. This takes |1 - 3| + |1 - 3| = 4 seconds. Go to the coordinates (7, 9) and collect the 2-nd node. This takes |7 - 1| + |9 - 1| = 14 seconds. In the second example, the optimal route to collect 2 nodes is as follows: Collect the 3-rd node. This requires no seconds. Go to the coordinates (7, 9) and collect the 2-th node. This takes |15 - 7| + |27 - 9| = 26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | 1 1 2 3 1 0
2 4 20
| 3 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'geometry', 'greedy', 'implementation', '*1700'] |
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze, in the forms of a 2 \times n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1, 1) to the gate at (2, n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only q such moments: the i-th moment toggles the state of cell (r_i, c_i) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the q moments, whether it is still possible to move from cell (1, 1) to cell (2, n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers n, q (2 \le n \le 10^5, 1 \le q \le 10^5).The i-th of q following lines contains two integers r_i, c_i (1 \le r_i \le 2, 1 \le c_i \le n), denoting the coordinates of the cell to be flipped at the i-th moment.It is guaranteed that cells (1, 1) and (2, n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1, 1) to cell (2, n), print "Yes", otherwise print "No". There should be exactly q answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInput
5 5
2 3
1 4
2 4
2 3
1 4
Output
Yes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query, the girl still able to reach the goal. One of the shortest path ways should be: (1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1, 3). After the fourth query, the (2, 3) is not blocked, but now all the 4-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | 5 5
2 3
1 4
2 4
2 3
1 4
| Yes No No No Yes | 1.5 seconds | 256 megabytes | ['data structures', 'dsu', 'implementation', '*1400'] |
F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city, where one of your friends already lives. There are n cafés in this city, where n is a power of two. The i-th café produces a single variety of coffee a_i. As you're a coffee-lover, before deciding to move or not, you want to know the number d of distinct varieties of coffees produced in this city.You don't know the values a_1, \ldots, a_n. Fortunately, your friend has a memory of size k, where k is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café c, and he will tell you if he tasted a similar coffee during the last k days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30\ 000 times.More formally, the memory of your friend is a queue S. Doing a query on café c will: Tell you if a_c is in S; Add a_c at the back of S; If |S| > k, pop the front element of S. Doing a reset request will pop all elements out of S.Your friend can taste at most \dfrac{2n^2}{k} cups of coffee in total. Find the diversity d (number of distinct values in the array a).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array a may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array a consistent with all the answers given so far.InputThe first line contains two integers n and k (1 \le k \le n \le 1024, k and n are powers of two).It is guaranteed that \dfrac{2n^2}{k} \le 20\ 000.InteractionYou begin the interaction by reading n and k. To ask your friend to taste a cup of coffee produced by the café c, in a separate line output? cWhere c must satisfy 1 \le c \le n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety a_c is one of the last k varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30\ 000 times. When you determine the number d of different coffee varieties, output! dIn case your query is invalid, you asked more than \frac{2n^2}{k} queries of type ? or you asked more than 30\ 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers n and k, separated by space (1 \le k \le n \le 1024, k and n are powers of two).It must hold that \dfrac{2n^2}{k} \le 20\ 000.The third line should contain n integers a_1, a_2, \ldots, a_n, separated by spaces (1 \le a_i \le n).ExamplesInput
4 2
N
N
Y
N
N
N
N
Output
? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
Input
8 8
N
N
N
N
Y
Y
Output
? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example, the array is a = [1, 4, 1, 3]. The city produces 3 different varieties of coffee (1, 3 and 4).The successive varieties of coffee tasted by your friend are 1, 4, \textbf{1}, 3, 3, 1, 4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a = [1, 2, 3, 4, 5, 6, 6, 6]. The city produces 6 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2, 6, 4, 5, \textbf{2}, \textbf{5}. | 4 2
N
N
Y
N
N
N
N
| ? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 | 1 second | 256 megabytes | ['graphs', 'interactive', '*2800'] |
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a_1, \ldots, a_n of n non-negative integers.Let's call it sharpened if and only if there exists an integer 1 \le k \le n such that a_1 < a_2 < \ldots < a_k and a_k > a_{k+1} > \ldots > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4], [0, 1], [12, 10, 8] and [3, 11, 15, 9, 7, 4] are sharpened; The arrays [2, 8, 2, 8, 6, 5], [0, 1, 1, 0] and [2, 5, 6, 9, 8, 8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any i (1 \le i \le n) such that a_i>0 and assign a_i := a_i - 1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 15\ 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 3 \cdot 10^5).The second line of each test case contains a sequence of n non-negative integers a_1, \ldots, a_n (0 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInput
10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
Output
Yes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test, the given array is already sharpened.In the third test case of the first test, we can transform the array into [3, 11, 15, 9, 7, 4] (decrease the first element 97 times and decrease the last element 4 times). It is sharpened because 3 < 11 < 15 and 15 > 9 > 7 > 4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | 10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
| Yes Yes Yes No No Yes Yes Yes Yes No | 1 second | 256 megabytes | ['greedy', 'implementation', '*1300'] |
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \rightarrow 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number s, consisting of n digits.It is guaranteed that s does not contain leading zeros and the sum of n over all test cases does not exceed 3000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInput
4
4
1227
1
0
6
177013
24
222373204424185217171912
Output
1227
-1
17703
2237344218521717191
NoteIn the first test case of the example, 1227 is already an ebne number (as 1 + 2 + 2 + 7 = 12, 12 is divisible by 2, while in the same time, 1227 is not divisible by 2) so we don't need to delete any digits. Answers such as 127 and 17 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 1 digit such as 17703, 77013 or 17013. Answers such as 1701 or 770 will not be accepted as they are not ebne numbers. Answer 013 will not be accepted as it contains leading zeroes.Explanation: 1 + 7 + 7 + 0 + 3 = 18. As 18 is divisible by 2 while 17703 is not divisible by 2, we can see that 17703 is an ebne number. Same with 77013 and 17013; 1 + 7 + 0 + 1 = 9. Because 9 is not divisible by 2, 1701 is not an ebne number; 7 + 7 + 0 = 14. This time, 14 is divisible by 2 but 770 is also divisible by 2, therefore, 770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 \rightarrow 22237320442418521717191 (delete the last digit). | 4
4
1227
1
0
6
177013
24
222373204424185217171912
| 1227 -1 17703 2237344218521717191 | 1 second | 256 megabytes | ['greedy', 'math', 'strings', '*900'] |
F. Making Shapestime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given n pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: Start at the origin (0, 0). Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x, y) and you choose the vector (u, v), draw a segment from your current point to the point at (x + u, y + v) and set your current point to (x + u, y + v). Repeat step 2 until you reach the origin again.You can reuse a vector as many times as you want.Count the number of different, non-degenerate (with an area greater than 0) and convex shapes made from applying the steps, such that the shape can be contained within a m \times m square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo 998244353.Two shapes are considered the same if there exists some parallel translation of the first shape to another.A shape can be contained within a m \times m square if there exists some parallel translation of this shape so that every point (u, v) inside or on the border of the shape satisfies 0 \leq u, v \leq m.InputThe first line contains two integers n and m — the number of vectors and the size of the square (1 \leq n \leq 5, 1 \leq m \leq 10^9).Each of the next n lines contains two integers x_i and y_i — the x-coordinate and y-coordinate of the i-th vector (|x_i|, |y_i| \leq 4, (x_i, y_i) \neq (0, 0)).It is guaranteed, that no two vectors are parallel, so for any two indices i and j such that 1 \leq i < j \leq n, there is no real value k such that x_i \cdot k = x_j and y_i \cdot k = y_j.OutputOutput a single integer — the number of satisfiable shapes by modulo 998244353.ExamplesInput
3 3
-1 0
1 1
0 -1
Output
3
Input
3 3
-1 0
2 2
0 -1
Output
1
Input
3 1776966
-1 0
3 3
0 -2
Output
296161
Input
4 15
-4 -4
-1 1
-1 -4
4 3
Output
1
Input
5 10
3 -4
4 -3
1 -3
2 -3
-3 -4
Output
0
Input
5 1000000000
-2 4
2 -3
0 -4
2 4
-1 -3
Output
9248783
NoteThe shapes for the first sample are: The only shape for the second sample is: The only shape for the fourth sample is: | 3 3
-1 0
1 1
0 -1
| 3 | 5 seconds | 768 megabytes | ['dp', '*3500'] |
E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today, Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be x; Remove element on the position x from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position x which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4, 2, 7, 3, 5, 6, 1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence a.In the i-th round, he inserts an element with value i somewhere in a. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence a?Node v is in the node u subtree if and only if v = u or v is in the subtree of one of the vertex u children. The size of the subtree of node u is the number of nodes v such that v is in the subtree of u.Ildar will do n rounds in total. The homework is the sequence of answers to the n questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence a from William. However, he has no idea how to find the answers to the n questions. Help Harris!InputThe first line contains a single integer n (1 \le n \le 150000).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n). It is guarenteed that each integer from 1 to n appears in the sequence exactly once.OutputPrint n lines, i-th line should contain a single integer — the answer to the i-th question.ExamplesInput
5
2 4 1 5 3
Output
1
3
6
8
11
Input
6
1 2 4 5 6 3
Output
1
3
6
8
12
17
NoteAfter the first round, the sequence is 1. The tree is The answer is 1.After the second round, the sequence is 2, 1. The tree is The answer is 2+1=3.After the third round, the sequence is 2, 1, 3. The tree is The answer is 2+1+3=6.After the fourth round, the sequence is 2, 4, 1, 3. The tree is The answer is 1+4+1+2=8.After the fifth round, the sequence is 2, 4, 1, 5, 3. The tree is The answer is 1+3+1+5+1=11. | 5
2 4 1 5 3
| 1 3 6 8 11 | 5 seconds | 256 megabytes | ['data structures', '*3300'] |
D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city, where one of your friends already lives. There are n cafés in this city, where n is a power of two. The i-th café produces a single variety of coffee a_i. As you're a coffee-lover, before deciding to move or not, you want to know the number d of distinct varieties of coffees produced in this city.You don't know the values a_1, \ldots, a_n. Fortunately, your friend has a memory of size k, where k is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café c, and he will tell you if he tasted a similar coffee during the last k days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30\ 000 times.More formally, the memory of your friend is a queue S. Doing a query on café c will: Tell you if a_c is in S; Add a_c at the back of S; If |S| > k, pop the front element of S. Doing a reset request will pop all elements out of S.Your friend can taste at most \dfrac{3n^2}{2k} cups of coffee in total. Find the diversity d (number of distinct values in the array a).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array a may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array a consistent with all the answers given so far.InputThe first line contains two integers n and k (1 \le k \le n \le 1024, k and n are powers of two).It is guaranteed that \dfrac{3n^2}{2k} \le 15\ 000.InteractionYou begin the interaction by reading n and k. To ask your friend to taste a cup of coffee produced by the café c, in a separate line output? cWhere c must satisfy 1 \le c \le n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety a_c is one of the last k varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30\ 000 times. When you determine the number d of different coffee varieties, output! dIn case your query is invalid, you asked more than \frac{3n^2}{2k} queries of type ? or you asked more than 30\ 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers n and k, separated by space (1 \le k \le n \le 1024, k and n are powers of two).It must hold that \dfrac{3n^2}{2k} \le 15\ 000.The third line should contain n integers a_1, a_2, \ldots, a_n, separated by spaces (1 \le a_i \le n).ExamplesInput
4 2
N
N
Y
N
N
N
N
Output
? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
Input
8 8
N
N
N
N
Y
Y
Output
? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example, the array is a = [1, 4, 1, 3]. The city produces 3 different varieties of coffee (1, 3 and 4).The successive varieties of coffee tasted by your friend are 1, 4, \textbf{1}, 3, 3, 1, 4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a = [1, 2, 3, 4, 5, 6, 6, 6]. The city produces 6 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2, 6, 4, 5, \textbf{2}, \textbf{5}. | 4 2
N
N
Y
N
N
N
N
| ? 1 ? 2 ? 3 ? 4 R ? 4 ? 1 ? 2 ! 3 | 1 second | 256 megabytes | ['constructive algorithms', 'graphs', 'interactive', '*3000'] |
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1).You're given k subsets A_1, \ldots, A_k of \{1, 2, \dots, n\}, such that the intersection of any three subsets is empty. In other words, for all 1 \le i_1 < i_2 < i_3 \le k, A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing.In one operation, you can choose one of these k subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let m_i be the minimum number of operations you have to do in order to make the i first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1 and n), they can be either off or on.You have to compute m_i for all 1 \le i \le n.InputThe first line contains two integers n and k (1 \le n, k \le 3 \cdot 10^5).The second line contains a binary string of length n, representing the initial state of each lamp (the lamp i is off if s_i = 0, on if s_i = 1).The description of each one of the k subsets follows, in the following format:The first line of the description contains a single integer c (1 \le c \le n) — the number of elements in the subset.The second line of the description contains c distinct integers x_1, \ldots, x_c (1 \le x_i \le n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output n lines. The i-th line should contain a single integer m_i — the minimum number of operations required to make the lamps 1 to i be simultaneously on.ExamplesInput
7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
Output
1
2
3
3
3
3
3
Input
8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
Output
1
1
1
1
1
1
4
4
Input
5 3
00011
3
1 2 3
1
4
3
3 4 5
Output
1
1
1
1
1
Input
19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
Output
0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i = 1, we can just apply one operation on A_1, the final states will be 1010110; For i = 2, we can apply operations on A_1 and A_3, the final states will be 1100110; For i \ge 3, we can apply operations on A_1, A_2 and A_3, the final states will be 1111111. In the second example: For i \le 6, we can just apply one operation on A_2, the final states will be 11111101; For i \ge 7, we can apply operations on A_1, A_3, A_4, A_6, the final states will be 11111111. | 7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
| 1 2 3 3 3 3 3 | 3 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*2400'] |
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k \ge 2 and 2k non-empty strings s_1, t_1, s_2, t_2, \dots, s_k, t_k that satisfy the following conditions: If we write the strings s_1, s_2, \dots, s_k in order, the resulting string will be equal to s; If we write the strings t_1, t_2, \dots, t_k in order, the resulting string will be equal to t; For all integers i between 1 and k inclusive, s_i and t_i are anagrams of each other. If such strings don't exist, then t is said to be an irreducible anagram of s. Note that these notions are only defined when s and t are anagrams of each other.For example, consider the string s = "gamegame". Then the string t = "megamage" is a reducible anagram of s, we may choose for example s_1 = "game", s_2 = "gam", s_3 = "e" and t_1 = "mega", t_2 = "mag", t_3 = "e": On the other hand, we can prove that t = "memegaga" is an irreducible anagram of s.You will be given a string s and q queries, represented by two integers 1 \le l \le r \le |s| (where |s| is equal to the length of the string s). For each query, you should find if the substring of s formed by characters from the l-th to the r-th has at least one irreducible anagram.InputThe first line contains a string s, consisting of lowercase English characters (1 \le |s| \le 2 \cdot 10^5).The second line contains a single integer q (1 \le q \le 10^5) — the number of queries.Each of the following q lines contain two integers l and r (1 \le l \le r \le |s|), representing a query for the substring of s formed by characters from the l-th to the r-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInput
aaaaa
3
1 1
2 4
5 5
Output
Yes
No
Yes
Input
aabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
Output
No
Yes
Yes
Yes
No
No
NoteIn the first sample, in the first and third queries, the substring is "a", which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand, in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s_1 = "a", s_2 = "aa", t_1 = "a", t_2 = "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | aaaaa
3
1 1
2 4
5 5
| Yes No Yes | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'strings', 'two pointers', '*1800'] |
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n - 1 friends have found an array of integers a_1, a_2, \dots, a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the m-th position in the line. Before the process starts, you may choose up to k different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer x such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to x?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers n, m and k (1 \le m \le n \le 3500, 0 \le k \le n - 1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains n positive integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 3500.OutputFor each test case, print the largest integer x such that you can guarantee to obtain at least x.ExampleInput
4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
Output
8
4
1
1
NoteIn the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (5) because he or she was forced by you to take the last element. After this turn the remaining array will be [2, 9, 2, 3, 8]; the second person will take the first element (2) because he or she was forced by you to take the first element. After this turn the remaining array will be [9, 2, 3, 8]; if the third person will choose to take the first element (9), at your turn the remaining array will be [2, 3, 8] and you will take 8 (the last element); if the third person will choose to take the last element (8), at your turn the remaining array will be [9, 2, 3] and you will take 9 (the first element). Thus, this strategy guarantees to end up with at least 8. We can prove that there is no strategy that guarantees to end up with at least 9. Hence, the answer is 8.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 4. | 4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
| 8 4 1 1 | 1 second | 256 megabytes | ['brute force', 'data structures', 'implementation', '*1600'] |
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n_1 vertices, the second part contains n_2 vertices, and there are m edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs r coins) or paint it blue (it costs b coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n_1, n_2, m, r and b (1 \le n_1, n_2, m, r, b \le 200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n_1 characters. Each character is either U, R or B. If the i-th character is U, then the i-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n_2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then m lines follow, the i-th line contains two integers u_i and v_i (1 \le u_i \le n_1, 1 \le v_i \le n_2) denoting an edge connecting the vertex u_i from the first part and the vertex v_i from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer -1.Otherwise, print an integer c denoting the total cost of coloring, and a string consisting of m characters. The i-th character should be U if the i-th edge should be left uncolored, R if the i-th edge should be painted red, or B if the i-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInput
3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
Output
35
BUURRU
Input
3 1 3 4 5
RRR
B
2 1
1 1
3 1
Output
-1
Input
3 1 3 4 5
URU
B
2 1
1 1
3 1
Output
14
RBB
| 3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
| 35 BUURRU | 1 second | 512 megabytes | ['constructive algorithms', 'flows', '*2900'] |
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.Initially, Polycarp's recent chat list p looks like 1, 2, \dots, n (in other words, it is an identity permutation).After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.For example, let the recent chat list be p = [4, 1, 5, 3, 2]: if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2]; if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2]; if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers n and m (1 \le n, m \le 3 \cdot 10^5) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains m integers a_1, a_2, \dots, a_m (1 \le a_i \le n) — the descriptions of the received messages.OutputPrint n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInput
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
NoteIn the first example, Polycarp's recent chat list looks like this: [1, 2, 3, 4, 5] [3, 1, 2, 4, 5] [5, 3, 1, 2, 4] [1, 5, 3, 2, 4] [4, 1, 5, 3, 2] So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).In the second example, Polycarp's recent chat list looks like this: [1, 2, 3, 4] [1, 2, 3, 4] [2, 1, 3, 4] [4, 2, 1, 3] | 5 4
3 5 1 4
| 1 3 2 5 1 4 1 5 1 5 | 3 seconds | 256 megabytes | ['data structures', '*2000'] |
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.You have to choose two arrays a_i and a_j (1 \le i, j \le n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k \in [1, m] b_k = \max(a_{i, k}, a_{j, k}).Your goal is to choose i and j so that the value of \min \limits_{k = 1}^{m} b_k is maximum possible.InputThe first line contains two integers n and m (1 \le n \le 3 \cdot 10^5, 1 \le m \le 8) — the number of arrays and the number of elements in each array, respectively.Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 \le a_{x, y} \le 10^9).OutputPrint two integers i and j (1 \le i, j \le n, it is possible that i = j) — the indices of the two arrays you have to choose so that the value of \min \limits_{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.ExampleInput
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
| 6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
| 1 5 | 5 seconds | 512 megabytes | ['binary search', 'bitmasks', 'dp', '*2000'] |
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and m. Calculate the number of pairs of arrays (a, b) such that: the length of both arrays is equal to m; each element of each array is an integer between 1 and n (inclusive); a_i \le b_i for any index i from 1 to m; array a is sorted in non-descending order; array b is sorted in non-ascending order. As the result can be very large, you should print it modulo 10^9+7.InputThe only line contains two integers n and m (1 \le n \le 1000, 1 \le m \le 10).OutputPrint one integer – the number of arrays a and b satisfying the conditions described above modulo 10^9+7.ExamplesInput
2 2
Output
5
Input
10 1
Output
55
Input
723 9
Output
157557417
NoteIn the first test there are 5 suitable arrays: a = [1, 1], b = [2, 2]; a = [1, 2], b = [2, 2]; a = [2, 2], b = [2, 2]; a = [1, 1], b = [2, 1]; a = [1, 1], b = [1, 1]. | 2 2
| 5 | 1 second | 256 megabytes | ['combinatorics', 'dp', '*1600'] |
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers A and B, calculate the number of pairs (a, b) such that 1 \le a \le A, 1 \le b \le B, and the equation a \cdot b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11) = 10011). a and b should not contain leading zeroes.InputThe first line contains t (1 \le t \le 100) — the number of test cases.Each test case contains two integers A and B (1 \le A, B \le 10^9).OutputPrint one integer — the number of pairs (a, b) such that 1 \le a \le A, 1 \le b \le B, and the equation a \cdot b + a + b = conc(a, b) is true.ExampleInput
31 114 2191 31415926Output
1
0
1337
NoteThere is only one suitable pair in the first test case: a = 1, b = 9 (1 + 9 + 1 \cdot 9 = 19). | 31 114 2191 31415926 | 1 0 1337 | 1 second | 256 megabytes | ['math', '*1100'] |
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days optimizing the program, he will make the program run in \left\lceil \frac{d}{x + 1} \right\rceil days (\left\lceil a \right\rceil is the ceiling function: \left\lceil 2.4 \right\rceil = 3, \left\lceil 2 \right\rceil = 2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x + \left\lceil \frac{d}{x + 1} \right\rceil.Will Adilbek be able to provide the generated results in no more than n days?InputThe first line contains a single integer T (1 \le T \le 50) — the number of test cases.The next T lines contain test cases – one per line. Each line contains two integers n and d (1 \le n \le 10^9, 1 \le d \le 10^9) — the number of days before the deadline and the number of days the program runs.OutputPrint T answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in n days or NO (case insensitive) otherwise.ExampleInput
3
1 1
4 5
5 11
Output
YES
YES
NO
NoteIn the first test case, Adilbek decides not to optimize the program at all, since d \le n.In the second test case, Adilbek can spend 1 day optimizing the program and it will run \left\lceil \frac{5}{2} \right\rceil = 3 days. In total, he will spend 4 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 2 days, it'll still work \left\lceil \frac{11}{2+1} \right\rceil = 4 days. | 3
1 1
4 5
5 11
| YES YES NO | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'math', 'ternary search', '*1100'] |
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are n cards with k features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k = 4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers n and k (1 \le n \le 1500, 1 \le k \le 30) — number of cards and number of features.Each of the following n lines contains a card description: a string consisting of k letters "S", "E", "T". The i-th character of this string decribes the i-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInput
3 3
SET
ETS
TSE
Output
1Input
3 4
SETE
ETSE
TSES
Output
0Input
5 4
SETT
TEST
EEET
ESTE
STES
Output
2NoteIn the third example test, these two triples of cards are sets: "SETT", "TEST", "EEET" "TEST", "ESTE", "STES" | 3 3
SET
ETS
TSE
| 1 | 3 seconds | 256 megabytes | ['brute force', 'data structures', 'implementation', '*1500'] |
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index i in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer t — the number of groups of students (1 \le t \le 100). The following 2t lines contain descriptions of groups of students.The description of the group starts with an integer k_i (1 \le k_i \le 100) — the number of students in the group, followed by a string s_i, consisting of k_i letters "A" and "P", which describes the i-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInput
1
4
PPAP
Output
1
Input
3
12
APPAPPPAPPPP
3
AAP
3
PPA
Output
4
1
0
NoteIn the first test, after 1 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 1 minute — AAPAAPPAAPPP after 2 minutes — AAAAAAPAAAPP after 3 minutes — AAAAAAAAAAAP after 4 minutes all 12 students are angry In the second group after 1 minute, all students are angry. | 1
4
PPAP
| 1 | 1 second | 256 megabytes | ['greedy', 'implementation', '*800'] |
F. Harry The Pottertime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTo defeat Lord Voldemort, Harry needs to destroy all horcruxes first. The last horcrux is an array a of n integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index i (1 \le i \le n), an integer x, and subtract x from a_i. choose two indices i and j (1 \le i, j \le n; i \ne j), an integer x, and subtract x from a_i and x + 1 from a_j. Note that x does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.InputThe first line contains a single integer n — the size of the array a (1 \le n \le 20). The following line contains n integers a_1, a_2, \ldots, a_n — array elements (-10^{15} \le a_i \le 10^{15}).OutputOutput a single integer — the minimum number of operations required to destroy the array a.ExamplesInput
3
1 10 100
Output
3
Input
3
5 3 -2
Output
2
Input
1
0
Output
0
NoteIn the first example one can just apply the operation of the first kind three times.In the second example, one can apply the operation of the second kind two times: first, choose i = 2, j = 1, x = 4, it transforms the array into (0, -1, -2), and then choose i = 3, j = 2, x = -2 to destroy the array.In the third example, there is nothing to be done, since the array is already destroyed. | 3
1 10 100
| 3 | 9 seconds | 1024 megabytes | ['brute force', 'constructive algorithms', 'dp', 'fft', 'implementation', 'math', '*3100'] |
E. Fedya the Potter Strikes Backtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya has a string S, initially empty, and an array W, also initially empty.There are n queries to process, one at a time. Query i consists of a lowercase English letter c_i and a nonnegative integer w_i. First, c_i must be appended to S, and w_i must be appended to W. The answer to the query is the sum of suspiciousnesses for all subsegments of W [L, \ R], (1 \leq L \leq R \leq i).We define the suspiciousness of a subsegment as follows: if the substring of S corresponding to this subsegment (that is, a string of consecutive characters from L-th to R-th, inclusive) matches the prefix of S of the same length (that is, a substring corresponding to the subsegment [1, \ R - L + 1]), then its suspiciousness is equal to the minimum in the array W on the [L, \ R] subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is 0.Help Fedya answer all the queries before the orderlies come for him!InputThe first line contains an integer n (1 \leq n \leq 600\,000) — the number of queries.The i-th of the following n lines contains the query i: a lowercase letter of the Latin alphabet c_i and an integer w_i (0 \leq w_i \leq 2^{30} - 1).All queries are given in an encrypted form. Let ans be the answer to the previous query (for the first query we set this value equal to 0). Then, in order to get the real query, you need to do the following: perform a cyclic shift of c_i in the alphabet forward by ans, and set w_i equal to w_i \oplus (ans \ \& \ MASK), where \oplus is the bitwise exclusive "or", \& is the bitwise "and", and MASK = 2^{30} - 1.OutputPrint n lines, i-th line should contain a single integer — the answer to the i-th query.ExamplesInput
7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
Output
1
2
4
5
7
9
12
Input
4
a 2
y 2
z 0
y 2
Output
2
2
2
2
Input
5
a 7
u 5
t 3
s 10
s 11
Output
7
9
11
12
13
NoteFor convenience, we will call "suspicious" those subsegments for which the corresponding lines are prefixes of S, that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string S is equal to "abacaba", and all w_i = 1, that is, the suspiciousness of all suspicious sub-segments is simply equal to 1. Let's see how the answer is obtained after each request:1. S = "a", the array W has a single subsegment — [1, \ 1], and the corresponding substring is "a", that is, the entire string S, thus it is a prefix of S, and the suspiciousness of the subsegment is 1.2. S = "ab", suspicious subsegments: [1, \ 1] and [1, \ 2], total 2.3. S = "aba", suspicious subsegments: [1, \ 1], [1, \ 2], [1, \ 3] and [3, \ 3], total 4.4. S = "abac", suspicious subsegments: [1, \ 1], [1, \ 2], [1, \ 3], [1, \ 4] and [3, \ 3], total 5.5. S = "abaca", suspicious subsegments: [1, \ 1], [1, \ 2], [1, \ 3], [1, \ 4] , [1, \ 5], [3, \ 3] and [5, \ 5], total 7.6. S = "abacab", suspicious subsegments: [1, \ 1], [1, \ 2], [1, \ 3], [1, \ 4] , [1, \ 5], [1, \ 6], [3, \ 3], [5, \ 5] and [5, \ 6], total 9.7. S = "abacaba", suspicious subsegments: [1, \ 1], [1, \ 2], [1, \ 3], [1, \ 4] , [1, \ 5], [1, \ 6], [1, \ 7], [3, \ 3], [5, \ 5], [5, \ 6], [5, \ 7] and [7, \ 7], total 12.In the second example, after all requests S = "aaba", W = [2, 0, 2, 0].1. S = "a", suspicious subsegments: [1, \ 1] (suspiciousness 2), totaling 2.2. S = "aa", suspicious subsegments: [1, \ 1] (2), [1, \ 2] (0), [2, \ 2] ( 0), totaling 2.3. S = "aab", suspicious subsegments: [1, \ 1] (2), [1, \ 2] (0), [1, \ 3] ( 0), [2, \ 2] (0), totaling 2.4. S = "aaba", suspicious subsegments: [1, \ 1] (2), [1, \ 2] (0), [1, \ 3] ( 0), [1, \ 4] (0), [2, \ 2] (0), [4, \ 4] (0), totaling 2.In the third example, from the condition after all requests S = "abcde", W = [7, 2, 10, 1, 7].1. S = "a", suspicious subsegments: [1, \ 1] (7), totaling 7.2. S = "ab", suspicious subsegments: [1, \ 1] (7), [1, \ 2] (2), totaling 9.3. S = "abc", suspicious subsegments: [1, \ 1] (7), [1, \ 2] (2), [1, \ 3] ( 2), totaling 11.4. S = "abcd", suspicious subsegments: [1, \ 1] (7), [1, \ 2] (2), [1, \ 3] ( 2), [1, \ 4] (1), totaling 12.5. S = "abcde", suspicious subsegments: [1, \ 1] (7), [1, \ 2] (2), [1, \ 3] ( 2), [1, \ 4] (1), [1, \ 5] (1), totaling 13. | 7
a 1
a 0
y 3
y 5
v 4
u 6
r 8
| 1 2 4 5 7 9 12 | 4 seconds | 256 megabytes | ['data structures', 'strings', '*3200'] |
D. LCCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn infinitely long Line Chillland Collider (LCC) was built in Chillland. There are n pipes with coordinates x_i that are connected to LCC. When the experiment starts at time 0, i-th proton flies from the i-th pipe with speed v_i. It flies to the right with probability p_i and flies to the left with probability (1 - p_i). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first exampleInputThe first line of input contains one integer n — the number of pipes (1 \le n \le 10^5). Each of the following n lines contains three integers x_i, v_i, p_i — the coordinate of the i-th pipe, the speed of the i-th proton and the probability that the i-th proton flies to the right in percentage points (-10^9 \le x_i \le 10^9, 1 \le v \le 10^6, 0 \le p_i \le 100). It is guaranteed that all x_i are distinct and sorted in increasing order.OutputIt's possible to prove that the answer can always be represented as a fraction P/Q, where P is an integer and Q is a natural number not divisible by 998\,244\,353. In this case, print P \cdot Q^{-1} modulo 998\,244\,353.ExamplesInput
2
1 1 100
3 1 0
Output
1
Input
3
7 10 0
9 4 86
14 5 100
Output
0
Input
4
6 4 50
11 25 50
13 16 50
15 8 50
Output
150902884
| 2
1 1 100
3 1 0
| 1 | 2 seconds | 256 megabytes | ['data structures', 'math', 'matrices', 'probabilities', '*3100'] |
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 3 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed \left\lceil 0.777(n+1)^2 \right\rceil (\lceil x \rceil is x rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number n (1 \le n \le 100) — the length of the picked string.InteractionYou start the interaction by reading the number n.To ask a query about a substring from l to r inclusively (1 \le l \le r \le n), you should output? l ron a separate line. After this, all substrings of s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 3 queries of the first type or there will be more than \left\lceil 0.777(n+1)^2 \right\rceil substrings returned in total, you will receive verdict Wrong answer.To guess the string s, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can 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 you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer n (1 \le n \le 100) — the length of the string, and the following line should contain the string s.ExampleInput
4
a
aa
a
cb
b
c
cOutput
? 1 2
? 3 4
? 4 4
! aabc | 4
a
aa
a
cb
b
c
c | ? 1 2 ? 3 4 ? 4 4 ! aabc | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'hashing', 'interactive', 'math', '*2800'] |
C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 3 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)^2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number n (1 \le n \le 100) — the length of the picked string.InteractionYou start the interaction by reading the number n.To ask a query about a substring from l to r inclusively (1 \le l \le r \le n), you should output? l ron a separate line. After this, all substrings of s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 3 queries of the first type or there will be more than (n+1)^2 substrings returned in total, you will receive verdict Wrong answer.To guess the string s, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can 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 you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer n (1 \le n \le 100) — the length of the string, and the following line should contain the string s.ExampleInput
4
a
aa
a
cb
b
c
cOutput
? 1 2
? 3 4
? 4 4
! aabc | 4
a
aa
a
cb
b
c
c | ? 1 2 ? 3 4 ? 4 4 ! aabc | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'interactive', 'math', '*2400'] |
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. Illustration for the second example, the first integer is a_i and the integer in parentheses is c_iAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer n (1 \leq n \leq 2000) — the number of vertices in the tree.The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 \leq p_i \leq n; 0 \leq c_i \leq n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.It is guaranteed that the values of p_i describe a rooted tree with n vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 \leq a_i \leq {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.If there are no solutions, print "NO".ExamplesInput
3
2 0
0 2
2 0
Output
YES
1 2 1 Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
| 3
2 0
0 2
2 0
| YES 1 2 1 | 1 second | 256 megabytes | ['constructive algorithms', 'data structures', 'dfs and similar', 'graphs', 'greedy', 'trees', '*1800'] |
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 2). For example, the complexity of 1 4 2 3 5 is 2 and the complexity of 1 3 5 7 6 4 2 is 1.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer n (1 \le n \le 100) — the number of light bulbs on the garland.The second line contains n integers p_1,\ p_2,\ \ldots,\ p_n (0 \le p_i \le n) — the number on the i-th bulb, or 0 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInput
5
0 5 0 2 3
Output
2
Input
7
1 0 0 5 0 0 2
Output
1
NoteIn the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only (5, 4) and (2, 3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | 5
0 5 0 2 3
| 2 | 1 second | 256 megabytes | ['dp', 'greedy', 'sortings', '*1800'] |
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a, consisting of n integers, find:\max\limits_{1 \le i < j \le n} LCM(a_i,a_j),where LCM(x, y) is the smallest positive integer that is divisible by both x and y. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.InputThe first line contains an integer n (2 \le n \le 10^5) — the number of elements in the array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5) — the elements of the array a.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array a.ExamplesInput
3
13 35 77
Output
1001Input
6
1 2 4 8 16 32
Output
32 | 3
13 35 77
| 1001 | 1 second | 256 megabytes | ['binary search', 'combinatorics', 'number theory', '*2900'] |
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l \le x \le r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2.Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.The first of each test case contains a single integer n (2 \le n \le 2\cdot10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 \le l_i \le r_i \le 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputPrint t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.ExampleInput
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
| 3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
| 2 1 5 | 4 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'data structures', 'dp', 'graphs', 'sortings', 'trees', 'two pointers', '*2300'] |
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, \dots, a_n and challenged him to choose an integer X such that the value \underset{1 \leq i \leq n}{\max} (a_i \oplus X) is minimum possible, where \oplus denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of \underset{1 \leq i \leq n}{\max} (a_i \oplus X).InputThe first line contains integer n (1\le n \le 10^5).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2^{30}-1).OutputPrint one integer — the minimum possible value of \underset{1 \leq i \leq n}{\max} (a_i \oplus X).ExamplesInput
3
1 2 3
Output
2
Input
2
1 5
Output
4
NoteIn the first sample, we can choose X = 3.In the second sample, we can choose X = 5. | 3
1 2 3
| 2 | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'dfs and similar', 'divide and conquer', 'dp', 'greedy', 'strings', 'trees', '*1900'] |
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer X (1 \le X \le 10^{12}).OutputPrint two positive integers, a and b, such that the value of max(a, b) is minimum possible and LCM(a, b) equals X. If there are several possible such pairs, you can print any.ExamplesInput
2
Output
1 2
Input
6
Output
2 3
Input
4
Output
1 4
Input
1
Output
1 1
| 2
| 1 2 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', '*1400'] |
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l, r] (1 \le l \le r \le n) that does not include all of cupcakes (he can't choose [l, r] = [1, n]) and buy exactly one cupcake of each of types l, l + 1, \dots, r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7, 4, -1]. Yasser will buy all of them, the total tastiness will be 7 + 4 - 1 = 10. Adel can choose segments [7], [4], [-1], [7, 4] or [4, -1], their total tastinesses are 7, 4, -1, 11 and 3, respectively. Adel can choose segment with tastiness 11, and as 10 is not strictly greater than 11, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains n (2 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9), where a_i represents the tastiness of the i-th type of cupcake.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInput
3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
Output
YES
NO
NO
NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment [1, 2] with total tastiness 11, which is not less than the total tastiness of all cupcakes, which is 10.In the third example, Adel can choose the segment [3, 3] with total tastiness of 5. Note that Yasser's cupcakes' total tastiness is also 5, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | 3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
| YES NO NO | 1 second | 256 megabytes | ['dp', 'greedy', 'implementation', '*1300'] |
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: 'L' (Left) sets the position x: =x - 1; 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position x doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 0; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 0 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position -2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains n (1 \le n \le 10^5) — the number of commands Mezo sends.The second line contains a string s of n commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInput
4
LRLR
Output
5
NoteIn the example, Zoma may end up anywhere between -2 and 2. | 4
LRLR
| 5 | 1 second | 256 megabytes | ['math', '*800'] |
G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year), and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n \times m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1, 1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells a and b, then the two cells a and b are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells a and b is a sequence of free cells in which the first cell is a, the last cell is b, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1, 1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1, 1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases t. (1 \le t \le 100). Afterward, t test cases with the described format will be given.The first line of a test contains two integers n, m (2 \le n, m \le 20), the size of the grid.In the next n line of a test contains a string of length m, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1, 1)) is free, and every free cell is reachable from (1, 1). If t \geq 2 is satisfied, then the size of the grid will satisfy n \le 10, m \le 10. In other words, if any grid with size n > 10 or m > 10 is given as an input, then it will be the only input on the test case (t = 1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n-1) \times (2m-1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1 \le i \le n, 1 \le j \le m, if the cell (i, j) is free cell, print 'O' in the cell (2i-1, 2j-1). Otherwise, print 'X' in the cell (2i-1, 2j-1). For all 1 \le i \le n, 1 \le j \le m-1, if the neighboring cell (i, j), (i, j+1) have wall blocking it, print ' ' in the cell (2i-1, 2j). Otherwise, print any printable character except spaces in the cell (2i-1, 2j). A printable character has an ASCII code in range [32, 126]: This includes spaces and alphanumeric characters. For all 1 \le i \le n-1, 1 \le j \le m, if the neighboring cell (i, j), (i+1, j) have wall blocking it, print ' ' in the cell (2i, 2j-1). Otherwise, print any printable character except spaces in the cell (2i, 2j-1) For all 1 \le i \le n-1, 1 \le j \le m-1, print any printable character in the cell (2i, 2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m-1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInput
4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
Output
YES
OOO
O
OOO
NO
YES
OOOOO X
O O
X O O X
O
OOO X O
O O O
O OOOOO
YES
OOOOOOOOOOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
O O O
OOO OOO OOO
| 4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
| YES OOO O OOO NO YES OOOOO X O O X O O X O OOO X O O O O O OOOOO YES OOOOOOOOOOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO O O O OOO OOO OOO | 3 seconds | 1024 megabytes | ['graphs', '*3300'] |
F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains n users numbered 1, 2, \ldots, n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1.To prevent a possible server breakdown, Donghyun created a backup network T_2, which also connects the same n users via a tree graph. If a system breaks down, exactly one edge e \in T_1 becomes unusable. In this case, Donghyun will protect the edge e by picking another edge f \in T_2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f \in T_2 for as many edges e \in T_1 as possible. However, since the backup network T_2 is fragile, f \in T_2 can be assigned as the replacement edge for at most one edge in T_1. With this restriction, Donghyun wants to protect as many edges in T_1 as possible.Formally, let E(T) be an edge set of the tree T. We consider a bipartite graph with two parts E(T_1) and E(T_2). For e \in E(T_1), f \in E(T_2), there is an edge connecting \{e, f\} if and only if graph T_1 - \{e\} + \{f\} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer n (2 \le n \le 250\,000), the number of users. In the next n-1 lines, two integers a_i, b_i (1 \le a_i, b_i \le n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_1.In the next n-1 lines, two integers c_i, d_i (1 \le c_i, d_i \le n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_2. It is guaranteed that both edge sets form a tree of size n.OutputIn the first line, print the number m (0 \leq m < n), the maximum number of edges that can be protected.In the next m lines, print four integers a_i, b_i, c_i, d_i. Those four numbers denote that the edge (a_i, b_i) in T_1 is will be replaced with an edge (c_i, d_i) in T_2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (a_i, b_i) from T_1 and adds edge (c_i, d_i) from T_2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInput
4
1 2
2 3
4 3
1 3
2 4
1 4
Output
3
3 2 4 2
2 1 1 3
4 3 1 4
Input
5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
Output
4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
Input
9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
Output
8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
| 4
1 2
2 3
4 3
1 3
2 4
1 4
| 3 3 2 4 2 2 1 1 3 4 3 1 4 | 4 seconds | 1024 megabytes | ['data structures', 'graph matchings', 'graphs', 'math', 'trees', '*3200'] |
E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle, which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s = \{(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)\} consisting of n distinct points. In the set s, no three distinct points lie on a single line. For a point p \in s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 4 vertices) that strictly encloses the point p (i.e. the point p is strictly inside a quadrilateral). Kiwon is interested in the number of 4-point subsets of s that can be used to build a castle protecting p. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p) be the number of 4-point subsets that can enclose the point p. Please compute the sum of f(p) for all points p \in s.InputThe first line contains a single integer n (5 \le n \le 2\,500).In the next n lines, two integers x_i and y_i (-10^9 \le x_i, y_i \le 10^9) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p) for all points p \in s.ExamplesInput
5
-1 0
1 0
-10 -1
10 -1
0 3
Output
2Input
8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
Output
40Input
10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
Output
213 | 5
-1 0
1 0
-10 -1
10 -1
0 3
| 2 | 3 seconds | 1024 megabytes | ['combinatorics', 'geometry', 'math', 'sortings', '*2500'] |
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism, Hyunuk will host a conference about how great this new year will be!The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i \le ea_i) and [sb_i, eb_i] (sb_i \le eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if \max(x, u) \le \min(y, v).We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer n (1 \le n \le 100\,000), the number of lectures held in the conference.Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 \le sa_i, ea_i, sb_i, eb_i \le 10^9, sa_i \le ea_i, sb_i \le eb_i).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInput
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
NoteIn second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.In first and third example, venue-sensitive set does not exist. | 2
1 2 3 6
3 4 7 8
| YES | 2 seconds | 1024 megabytes | ['binary search', 'data structures', 'hashing', 'sortings', '*2100'] |
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).A sequence a is a subsegment 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. We will denote the subsegments as [l, r], where l, r are two integers with 1 \le l \le r \le n. This indicates the subsegment where l-1 elements from the beginning and n-r elements from the end are deleted from the sequence.For a permutation p_1, p_2, \ldots, p_n, we define a framed segment as a subsegment [l,r] where \max\{p_l, p_{l+1}, \dots, p_r\} - \min\{p_l, p_{l+1}, \dots, p_r\} = r - l. For example, for the permutation (6, 7, 1, 8, 5, 3, 2, 4) some of its framed segments are: [1, 2], [5, 8], [6, 7], [3, 3], [8, 8]. In particular, a subsegment [i,i] is always a framed segments for any i between 1 and n, inclusive.We define the happiness of a permutation p as the number of pairs (l, r) such that 1 \le l \le r \le n, and [l, r] is a framed segment. For example, the permutation [3, 1, 2] has happiness 5: all segments except [1, 2] are framed segments.Given integers n and m, Jongwon wants to compute the sum of happiness for all permutations of length n, modulo the prime number m. Note that there exist n! (factorial of n) different permutations of length n.InputThe only line contains two integers n and m (1 \le n \le 250\,000, 10^8 \le m \le 10^9, m is prime).OutputPrint r (0 \le r < m), the sum of happiness for all permutations of length n, modulo a prime number m.ExamplesInput
1 993244853
Output
1
Input
2 993244853
Output
6
Input
3 993244853
Output
32
Input
2019 993244853
Output
923958830
Input
2020 437122297
Output
265955509
NoteFor sample input n=3, let's consider all permutations of length 3: [1, 2, 3], all subsegments are framed segment. Happiness is 6. [1, 3, 2], all subsegments except [1, 2] are framed segment. Happiness is 5. [2, 1, 3], all subsegments except [2, 3] are framed segment. Happiness is 5. [2, 3, 1], all subsegments except [2, 3] are framed segment. Happiness is 5. [3, 1, 2], all subsegments except [1, 2] are framed segment. Happiness is 5. [3, 2, 1], all subsegments are framed segment. Happiness is 6. Thus, the sum of happiness is 6+5+5+5+5+6 = 32. | 1 993244853
| 1 | 1 second | 1024 megabytes | ['combinatorics', 'math', '*1600'] |
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a = [a_1, a_2, \ldots, a_l] of length l has an ascent if there exists a pair of indices (i, j) such that 1 \le i < j \le l and a_i < a_j. For example, the sequence [0, 2, 0, 2, 0] has an ascent because of the pair (1, 4), but the sequence [4, 3, 3, 3, 1] doesn't have an ascent.Let's call a concatenation of sequences p and q the sequence that is obtained by writing down sequences p and q one right after another without changing the order. For example, the concatenation of the [0, 2, 0, 2, 0] and [4, 3, 3, 3, 1] is the sequence [0, 2, 0, 2, 0, 4, 3, 3, 3, 1]. The concatenation of sequences p and q is denoted as p+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has n sequences s_1, s_2, \ldots, s_n which may have different lengths. Gyeonggeun will consider all n^2 pairs of sequences s_x and s_y (1 \le x, y \le n), and will check if its concatenation s_x + s_y has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x, y) of sequences s_1, s_2, \ldots, s_n whose concatenation s_x + s_y contains an ascent.InputThe first line contains the number n (1 \le n \le 100\,000) denoting the number of sequences.The next n lines contain the number l_i (1 \le l_i) denoting the length of s_i, followed by l_i integers s_{i, 1}, s_{i, 2}, \ldots, s_{i, l_i} (0 \le s_{i, j} \le 10^6) denoting the sequence s_i. It is guaranteed that the sum of all l_i does not exceed 100\,000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInput
5
1 1
1 1
1 2
1 4
1 3
Output
9
Input
3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
Output
7
Input
10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
Output
72
NoteFor the first example, the following 9 arrays have an ascent: [1, 2], [1, 2], [1, 3], [1, 3], [1, 4], [1, 4], [2, 3], [2, 4], [3, 4]. Arrays with the same contents are counted as their occurences. | 5
1 1
1 1
1 2
1 4
1 3
| 9 | 2 seconds | 1024 megabytes | ['binary search', 'combinatorics', 'data structures', 'dp', 'implementation', 'sortings', '*1400'] |
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of n strings s_1, s_2, s_3, \ldots, s_{n} and m strings t_1, t_2, t_3, \ldots, t_{m}. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings x and y as the string that is obtained by writing down strings x and y one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s_1 and t_1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n = 3, m = 4, s = {"a", "b", "c"}, t = {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size n and m and also q queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n, m (1 \le n, m \le 20).The next line contains n strings s_1, s_2, \ldots, s_{n}. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 1 and at most 10.The next line contains m strings t_1, t_2, \ldots, t_{m}. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 1 and at most 10.Among the given n + m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer q (1 \le q \le 2\,020).In the next q lines, an integer y (1 \le y \le 10^9) is given, denoting the year we want to know the name for.OutputPrint q lines. For each line, print the name of the year as per the rule described above.ExampleInput
10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
Output
sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | 10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
| sinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja | 1 second | 1024 megabytes | ['implementation', 'strings', '*800'] |
F. DIY Garlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of n lamps and n - 1 wires. Exactly one lamp will be connected to power grid, and power will be transmitted from it to other lamps by the wires. Each wire connectes exactly two lamps; one lamp is called the main lamp for this wire (the one that gets power from some other wire and transmits it to this wire), the other one is called the auxiliary lamp (the one that gets power from this wire). Obviously, each lamp has at most one wire that brings power to it (and this lamp is the auxiliary lamp for this wire, and the main lamp for all other wires connected directly to it).Each lamp has a brightness value associated with it, the i-th lamp has brightness 2^i. We define the importance of the wire as the sum of brightness values over all lamps that become disconnected from the grid if the wire is cut (and all other wires are still working).Polycarp has drawn the scheme of the garland he wants to make (the scheme depicts all n lamp and n - 1 wires, and the lamp that will be connected directly to the grid is marked; the wires are placed in such a way that the power can be transmitted to each lamp). After that, Polycarp calculated the importance of each wire, enumerated them from 1 to n - 1 in descending order of their importance, and then wrote the index of the main lamp for each wire (in the order from the first wire to the last one).The following day Polycarp bought all required components of the garland and decided to solder it — but he could not find the scheme. Fortunately, Polycarp found the list of indices of main lamps for all wires. Can you help him restore the original scheme?InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of lamps.The second line contains n - 1 integers a_1, a_2, ..., a_{n - 1} (1 \le a_i \le n), where a_i is the index of the main lamp for the i-th wire (wires are numbered in descending order of importance).OutputIf it is impossible to restore the original scheme, print one integer -1.Otherwise print the scheme as follows. In the first line, print one integer k (1 \le k \le n) — the index of the lamp that is connected to the power grid. Then print n - 1 lines, each containing two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) — the indices of the lamps connected by some wire. The descriptions of the wires (and the lamps connected by a wire) can be printed in any order. The printed description must correspond to a scheme of a garland such that Polycarp could have written the list a_1, a_2, ..., a_{n - 1} from it. If there are multiple such schemes, output any of them.ExampleInput
6
3 6 3 1 5
Output
3
6 3
6 5
1 3
1 4
5 2
NoteThe scheme for the first example (R denotes the lamp connected to the grid, the numbers on wires are their importance values): | 6
3 6 3 1 5
| 3 6 3 6 5 1 3 1 4 5 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'trees', '*2200'] |
E. New Year Partiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.For all friends 1 \le x_i \le n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of friends.The second line contains n integers x_1, x_2, \dots, x_n (1 \le x_i \le n) — the coordinates of the houses of the friends.OutputPrint two integers — the minimum and the maximum possible number of occupied houses after all moves are performed.ExamplesInput
4
1 2 4 4
Output
2 4
Input
9
1 1 8 8 8 4 4 4 4
Output
3 8
Input
7
4 3 7 1 4 3 3
Output
3 6
NoteIn the first example friends can go to [2, 2, 3, 3]. So friend 1 goes to x_1+1, friend 2 stays at his house x_2, friend 3 goes to x_3-1 and friend 4 goes to x_4-1. [1, 1, 3, 3], [2, 2, 3, 3] or [2, 2, 4, 4] are also all valid options to obtain 2 occupied houses.For the maximum number of occupied houses friends can go to [1, 2, 3, 4] or to [0, 2, 4, 5], for example. | 4
1 2 4 4
| 2 4 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*1800'] |
D. Christmas Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n Christmas trees on an infinite number line. The i-th tree grows at the position x_i. All x_i are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are m people who want to celebrate Christmas. Let y_1, y_2, \dots, y_m be the positions of people (note that all values x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m should be distinct and all y_j should be integer). You want to find such an arrangement of people that the value \sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j| is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let d_j be the distance from the j-th human to the nearest Christmas tree (d_j = \min\limits_{i=1}^{n} |y_j - x_i|). Then you need to choose such positions y_1, y_2, \dots, y_m that \sum\limits_{j=1}^{m} d_j is the minimum possible.InputThe first line of the input contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the number of Christmas trees and the number of people.The second line of the input contains n integers x_1, x_2, \dots, x_n (-10^9 \le x_i \le 10^9), where x_i is the position of the i-th Christmas tree. It is guaranteed that all x_i are distinct.OutputIn the first line print one integer res — the minimum possible value of \sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j| (in other words, the sum of distances to the nearest Christmas tree for all people).In the second line print m integers y_1, y_2, \dots, y_m (-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9), where y_j is the position of the j-th human. All y_j should be distinct and all values x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m should be distinct.If there are multiple answers, print any of them.ExamplesInput
2 6
1 5
Output
8
-1 2 6 4 0 3
Input
3 5
0 3 1
Output
7
5 -2 4 -1 2
| 2 6
1 5
| 8 -1 2 6 4 0 3 | 2 seconds | 256 megabytes | ['graphs', 'greedy', 'shortest paths', '*1800'] |
C. Friends and Giftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or 1 \le f_i \le n if the i-th friend wants to give the gift to the friend f_i.You want to fill in the unknown values (f_i = 0) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of friends.The second line of the input contains n integers f_1, f_2, \dots, f_n (0 \le f_i \le n, f_i \ne i, all f_i \ne 0 are distinct), where f_i is the either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or 1 \le f_i \le n if the i-th friend wants to give the gift to the friend f_i. It is also guaranteed that there is at least two values f_i = 0.OutputPrint n integers nf_1, nf_2, \dots, nf_n, where nf_i should be equal to f_i if f_i \ne 0 or the number of friend whom the i-th friend wants to give the gift to. All values nf_i should be distinct, nf_i cannot be equal to i. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself.If there are several answers, you can print any.ExamplesInput
5
5 0 0 2 4
Output
5 3 1 2 4
Input
7
7 0 0 1 4 0 6
Output
7 3 2 1 4 5 6
Input
7
7 4 0 3 0 5 1
Output
7 4 2 3 6 5 1
Input
5
2 1 0 0 0
Output
2 1 4 5 3
| 5
5 0 0 2 4
| 5 3 1 2 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'math', '*1500'] |
B. Candies Divisiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time: b - a \le 1 (it means b = a or b = a + 1); the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed \lfloor\frac{k}{2}\rfloor (less than or equal to \lfloor\frac{k}{2}\rfloor). \lfloor\frac{k}{2}\rfloor is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then \lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 5 \cdot 10^4) — the number of test cases.The next t lines describe test cases. The i-th test case contains two integers n and k (1 \le n, k \le 10^9) — the number of candies and the number of kids.OutputFor each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.ExampleInput
5
5 2
19 4
12 7
6 2
100000 50010
Output
5
18
10
6
75015
NoteIn the first test case, Santa can give 3 and 2 candies to kids. There a=2, b=3,a+1=3.In the second test case, Santa can give 5, 5, 4 and 4 candies. There a=4,b=5,a+1=5. The answer cannot be greater because then the number of kids with 5 candies will be 3.In the third test case, Santa can distribute candies in the following way: [1, 2, 2, 1, 1, 2, 1]. There a=1,b=2,a+1=2. He cannot distribute two remaining candies in a way to be satisfied.In the fourth test case, Santa can distribute candies in the following way: [3, 3]. There a=3, b=3, a+1=4. Santa distributed all 6 candies. | 5
5 2
19 4
12 7
6 2
100000 50010
| 5 18 10 6 75015 | 2 seconds | 256 megabytes | ['math', '*900'] |
A. Minutes Before the New Yeartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 \le hh < 24 and 0 \le mm < 60. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows 0 hours and 0 minutes.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 1439) — the number of test cases.The following t lines describe test cases. The i-th line contains the time as two integers h and m (0 \le h < 24, 0 \le m < 60). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: h=0 and m=0. It is guaranteed that both h and m are given without leading zeros.OutputFor each test case, print the answer on it — the number of minutes before the New Year.ExampleInput
5
23 55
23 0
0 1
4 20
23 59
Output
5
60
1439
1180
1
| 5
23 55
23 0
0 1
4 20
23 59
| 5 60 1439 1180 1 | 1 second | 256 megabytes | ['math', '*800'] |
E. The Cake Is a Lietime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake.Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought about how the cake was cut.It is known that the cake was originally a regular n-sided polygon, each vertex of which had a unique number from 1 to n. The vertices were numbered in random order.Each piece of the cake is a triangle. The cake was cut into n - 2 pieces as follows: each time one cut was made with a knife (from one vertex to another) such that exactly one triangular piece was separated from the current cake, and the rest continued to be a convex polygon. In other words, each time three consecutive vertices of the polygon were selected and the corresponding triangle was cut off.A possible process of cutting the cake is presented in the picture below. Example of 6-sided cake slicing. You are given a set of n-2 triangular pieces in random order. The vertices of each piece are given in random order — clockwise or counterclockwise. Each piece is defined by three numbers — the numbers of the corresponding n-sided cake vertices.For example, for the situation in the picture above, you could be given a set of pieces: [3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1].You are interested in two questions. What was the enumeration of the n-sided cake vertices? In what order were the pieces cut? Formally, you have to find two permutations p_1, p_2, \dots, p_n (1 \le p_i \le n) and q_1, q_2, \dots, q_{n - 2} (1 \le q_i \le n - 2) such that if the cake vertices are numbered with the numbers p_1, p_2, \dots, p_n in order clockwise or counterclockwise, then when cutting pieces of the cake in the order q_1, q_2, \dots, q_{n - 2} always cuts off a triangular piece so that the remaining part forms one convex polygon.For example, in the picture above the answer permutations could be: p=[2, 4, 6, 1, 3, 5] (or any of its cyclic shifts, or its reversal and after that any cyclic shift) and q=[2, 4, 1, 3].Write a program that, based on the given triangular pieces, finds any suitable permutations p and q.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then there are t independent sets of input data.The first line of each set consists of a single integer n (3 \le n \le 10^5) — the number of vertices in the cake.The following n - 2 lines describe the numbers of the pieces vertices: each line consists of three different integers a, b, c (1 \le a, b, c \le n) — the numbers of the pieces vertices of cake given in random order. The pieces are given in random order.It is guaranteed that the answer to each of the tests exists. It is also guaranteed that the sum of n for all test cases does not exceed 10^5.OutputPrint 2t lines — answers to given t test cases in the order in which they are written in the input. Each answer should consist of 2 lines.In the first line of an answer on a test case print n distinct numbers p_1, p_2, \dots, p_n(1 \le p_i \le n) — the numbers of the cake vertices in clockwise or counterclockwise order.In the second line of an answer on a test case print n - 2 distinct numbers q_1, q_2, \dots, q_{n - 2}(1 \le q_i \le n - 2) — the order of cutting pieces of the cake. The number of a piece of the cake corresponds to its number in the input.If there are several answers, print any. It is guaranteed that the answer to each of the tests exists.ExampleInput
3
6
3 6 5
5 2 4
5 4 6
6 3 1
6
2 5 6
2 5 1
4 1 2
1 3 5
3
1 2 3
Output
1 6 4 2 5 3
4 2 3 1
1 4 2 6 5 3
3 4 2 1
1 3 2
1
| 3
6
3 6 5
5 2 4
5 4 6
6 3 1
6
2 5 6
2 5 1
4 1 2
1 3 5
3
1 2 3
| 1 6 4 2 5 3 4 2 3 1 1 4 2 6 5 3 3 4 2 1 1 3 2 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dfs and similar', 'graphs', '*2400'] |
D. Enchanted Artifacttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After completing the last level of the enchanted temple, you received a powerful artifact of the 255th level. Do not rush to celebrate, because this artifact has a powerful rune that can be destroyed with a single spell s, which you are going to find. We define the spell as some non-empty string consisting only of the letters a and b.At any time, you can cast an arbitrary non-empty spell t, and the rune on the artifact will begin to resist. Resistance of the rune is the edit distance between the strings that specify the casted spell t and the rune-destroying spell s.Edit distance of two strings s and t is a value equal to the minimum number of one-character operations of replacing, inserting and deleting characters in s to get t. For example, the distance between ababa and aaa is 2, the distance between aaa and aba is 1, the distance between bbaba and abb is 3. The edit distance is 0 if and only if the strings are equal.It is also worth considering that the artifact has a resistance limit — if you cast more than n + 2 spells, where n is the length of spell s, the rune will be blocked.Thus, it takes n + 2 or fewer spells to destroy the rune that is on your artifact. Keep in mind that the required destructive spell s must also be counted among these n + 2 spells.Note that the length n of the rune-destroying spell s is not known to you in advance. It is only known that its length n does not exceed 300.InteractionInteraction is happening through queries.Each request consists of a single non-empty string t — the spell you want to cast. The length of string t should not exceed 300. Each string should consist only of the letters a and b.In response to the query, you will get resistance runes — the edit distance between the strings that specify the casted spell t and the secret rune-destroying spell s. Remember that s contains only the letters a and b.After breaking the rune, your program should end immediately. A rune is destroyed when you get a response with resistance 0. After receiving the value 0, your program should terminate normally.In this problem interactor is not adaptive. This means that during any test the rune-destroying spell s does not change. If your query is invalid, -1 will be returned. After receiving this your program should immediately terminate normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.If the number of spells exceeds limit (n + 2, where n is the length of the spell s, which is unknown to you), you will get the Wrong Answer verdict.Your solution may receive the verdict Idleness Limit Exceeded if you don't output anything or forget to flush the output buffer.To flush the output buffer, you need to do the following immediately after printing the query and the line end: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; for other languages see documentation. HacksFor hacks, use the following format:In a single line print the string s (1 \le |s| \le 300) of letters a and b, which defines the rune-destroying spell.The hacked solution will not have direct access to the unknown spell.ExampleInput
2
2
1
2
3
0Output
aaa
aaab
abba
bba
abaaa
aabba |
2
2
1
2
3
0 | aaa aaab abba bba abaaa aabba | 1 second | 256 megabytes | ['constructive algorithms', 'interactive', 'strings', '*2300'] |
C. Petya and Examtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0 to T, inclusive.All problems are divided into two types: easy problems — Petya takes exactly a minutes to solve any easy problem; hard problems — Petya takes exactly b minutes (b > a) to solve any hard problem. Thus, if Petya starts solving an easy problem at time x, then it will be solved at time x+a. Similarly, if at a time x Petya starts to solve a hard problem, then it will be solved at time x+b.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time t_i (0 \le t_i \le T) at which it will become mandatory (required). If Petya leaves the exam at time s and there is such a problem i that t_i \le s and he didn't solve it, then he will receive 0 points for the whole exam. Otherwise (i.e if he has solved all such problems for which t_i \le s) he will receive a number of points equal to the number of solved problems. Note that leaving at time s Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if n=2, T=5, a=2, b=3, the first problem is hard and t_1=3 and the second problem is easy and t_2=2. Then: if he leaves at time s=0, then he will receive 0 points since he will not have time to solve any problems; if he leaves at time s=1, he will receive 0 points since he will not have time to solve any problems; if he leaves at time s=2, then he can get a 1 point by solving the problem with the number 2 (it must be solved in the range from 0 to 2); if he leaves at time s=3, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time s=4, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time s=5, then he can get 2 points by solving all problems. Thus, the answer to this test is 2.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.InputThe first line contains the integer m (1 \le m \le 10^4) — the number of test cases in the test.The next lines contain a description of m test cases. The first line of each test case contains four integers n, T, a, b (2 \le n \le 2\cdot10^5, 1 \le T \le 10^9, 1 \le a < b \le 10^9) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively.The second line of each test case contains n numbers 0 or 1, separated by single space: the i-th number means the type of the i-th problem. A value of 0 means that the problem is easy, and a value of 1 that the problem is hard.The third line of each test case contains n integers t_i (0 \le t_i \le T), where the i-th number means the time at which the i-th problem will become mandatory.It is guaranteed that the sum of n for all test cases does not exceed 2\cdot10^5.OutputPrint the answers to m test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam.ExampleInput
10
3 5 1 3
0 0 1
2 1 4
2 5 2 3
1 0
3 2
1 20 2 4
0
16
6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6
4 16 3 6
1 0 1 1
8 3 5 6
6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17
7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10
6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12
5 17 2 5
1 1 1 1 0
17 11 10 6 4
1 1 1 2
0
1
Output
3
2
1
0
1
4
0
1
2
1
| 10
3 5 1 3
0 0 1
2 1 4
2 5 2 3
1 0
3 2
1 20 2 4
0
16
6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6
4 16 3 6
1 0 1 1
8 3 5 6
6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17
7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10
6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12
5 17 2 5
1 1 1 1 0
17 11 10 6 4
1 1 1 2
0
1
| 3 2 1 0 1 4 0 1 2 1 | 2 seconds | 256 megabytes | ['greedy', 'sortings', 'two pointers', '*1800'] |
B2. K for the Price of One (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: 2 \le k \le n.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store.Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by a_i — the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index i if he currently has enough coins (i.e p \ge a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i). Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p \ge a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i). Please note that each good can be bought no more than once.For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases in the test.The next lines contain a description of t test cases. The first line of each test case contains three integers n, p, k (2 \le n \le 2 \cdot 10^5, 1 \le p \le 2\cdot10^9, 2 \le k \le n) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.The second line of each test case contains n integers a_i (1 \le a_i \le 10^4) — the prices of goods.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case in a separate line print one integer m — the maximum number of goods that Vasya can buy.ExampleInput
8
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
3 2 3
4 2 6
5 2 3
10 1 3 9 2
2 10000 2
10000 10000
2 9999 2
10000 10000
4 6 4
3 2 3 2
5 5 3
1 2 2 1 2
Output
3
4
1
1
2
0
4
5
| 8
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
3 2 3
4 2 6
5 2 3
10 1 3 9 2
2 10000 2
10000 10000
2 9999 2
10000 10000
4 6 4
3 2 3 2
5 5 3
1 2 2 1 2
| 3 4 1 1 2 0 4 5 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'sortings', '*1600'] |
B1. K for the Price of One (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store. Remember, that in this problem k=2.Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by a_i — the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index i if he currently has enough coins (i.e p \ge a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i). Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p \ge a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i). Please note that each good can be bought no more than once.For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases in the test.The next lines contain a description of t test cases. The first line of each test case contains three integers n, p, k (2 \le n \le 2 \cdot 10^5, 1 \le p \le 2\cdot10^9, k=2) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.The second line of each test case contains n integers a_i (1 \le a_i \le 10^4) — the prices of goods.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5. It is guaranteed that in this version of the problem k=2 for all test cases.OutputFor each test case in a separate line print one integer m — the maximum number of goods that Vasya can buy.ExampleInput
6
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
2 10000 2
10000 10000
2 9999 2
10000 10000
5 13 2
8 2 8 2 5
3 18 2
1 2 3
Output
3
4
2
0
4
3
| 6
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
2 10000 2
10000 10000
2 9999 2
10000 10000
5 13 2
8 2 8 2 5
3 18 2
1 2 3
| 3 4 2 0 4 3 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'sortings', '*1400'] |
A. Temporarily unavailabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a distance less than or equal to r from the point x=c, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from x=a to x=b. His speed — one unit of distance per minute.InputThe first line contains a positive integer t (1 \le t \le 1000) — the number of test cases. In the following lines are written t test cases.The description of each test case is one line, which contains four integers a, b, c and r (-10^8 \le a,b,c \le 10^8, 0 \le r \le 10^8) — the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively.Any of the numbers a, b and c can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.OutputPrint t numbers — answers to given test cases in the order they are written in the test. Each answer is an integer — the number of minutes during which Polycarp will be unavailable during his movement.ExampleInput
9
1 10 7 1
3 3 3 0
8 2 10 4
8 2 10 100
-10 20 -17 2
-3 2 2 0
-3 1 2 0
2 3 2 3
-1 3 -2 2
Output
7
0
4
0
30
5
4
0
3
NoteThe following picture illustrates the first test case. Polycarp goes from 1 to 10. The yellow area shows the coverage area of the station with a radius of coverage of 1, which is located at the point of 7. The green area shows a part of the path when Polycarp is out of coverage area. | 9
1 10 7 1
3 3 3 0
8 2 10 4
8 2 10 100
-10 20 -17 2
-3 2 2 0
-3 1 2 0
2 3 2 3
-1 3 -2 2
| 7 0 4 0 30 5 4 0 3 | 1 second | 256 megabytes | ['implementation', 'math', '*900'] |
B. Azamon Web Servicestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string s representing Jeff's product name and the string c representing his competitor's product name, find a way to swap at most one pair of characters in s (that is, find two distinct indices i and j and swap s_i and s_j) such that the resulting new name becomes strictly lexicographically smaller than c, or determine that it is impossible.Note: String a is strictly lexicographically smaller than string b if and only if one of the following holds: a is a proper prefix of b, that is, a is a prefix of b such that a \neq b; There exists an integer 1 \le i \le \min{(|a|, |b|)} such that a_i < b_i and a_j = b_j for 1 \le j < i. InputThe first line of input contains a single integer t (1 \le t \le 1500) denoting the number of test cases. The next lines contain descriptions of the test cases.Each test case consists of a single line containing two space-separated strings s and c (2 \le |s| \le 5000, 1 \le |c| \le 5000). The strings s and c consists of uppercase English letters.It is guaranteed that the sum of |s| in the input is at most 5000 and the sum of the |c| in the input is at most 5000.OutputFor each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than c. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible. ExampleInput
3
AZAMON APPLE
AZAMON AAAAAAAAAAALIBABA
APPLE BANANA
Output
AMAZON
---
APPLE
NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL". | 3
AZAMON APPLE
AZAMON AAAAAAAAAAALIBABA
APPLE BANANA
| AMAZON --- APPLE | 2 seconds | 256 megabytes | ['greedy', '*1600'] |
A. Suffix Threetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe just discovered a new data structure in our research group: a suffix three!It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.Let us tell you how it works. If a sentence ends with "po" the language is Filipino. If a sentence ends with "desu" or "masu" the language is Japanese. If a sentence ends with "mnida" the language is Korean. Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.Oh, did I say three suffixes? I meant four.InputThe first line of input contains a single integer t (1 \leq t \leq 30) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing a single string denoting the sentence. Spaces are represented as underscores (the symbol "_") for ease of reading. The sentence has at least 1 and at most 1000 characters, and consists only of lowercase English letters and underscores. The sentence has no leading or trailing underscores and no two consecutive underscores. It is guaranteed that the sentence ends with one of the four suffixes mentioned above.OutputFor each test case, print a single line containing either "FILIPINO", "JAPANESE", or "KOREAN" (all in uppercase, without quotes), depending on the detected language.ExampleInput
8
kamusta_po
genki_desu
ohayou_gozaimasu
annyeong_hashimnida
hajime_no_ippo
bensamu_no_sentou_houhou_ga_okama_kenpo
ang_halaman_doon_ay_sarisari_singkamasu
si_roy_mustang_ay_namamasu
Output
FILIPINO
JAPANESE
JAPANESE
KOREAN
FILIPINO
FILIPINO
JAPANESE
JAPANESE
NoteThe first sentence ends with "po", so it is written in Filipino.The second and third sentences end with "desu" and "masu", so they are written in Japanese.The fourth sentence ends with "mnida", so it is written in Korean. | 8
kamusta_po
genki_desu
ohayou_gozaimasu
annyeong_hashimnida
hajime_no_ippo
bensamu_no_sentou_houhou_ga_okama_kenpo
ang_halaman_doon_ay_sarisari_singkamasu
si_roy_mustang_ay_namamasu
| FILIPINO JAPANESE JAPANESE KOREAN FILIPINO FILIPINO JAPANESE JAPANESE | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Intergalactic Sliding Puzzletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 \times (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1.In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so.InputThe first line of input contains a single integer t (1 \le t \le 4) denoting the number of test cases. The next lines contain descriptions of the test cases.Each test case consists of three lines. The first line contains a single integer k (1 \le k \le 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E.OutputFor each test case, first, print a single line containing either: SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc.You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: The total length of all strings in your output for a single case is at most 10^4; There must be no cycles involving the shortcuts that are reachable from the main sequence; The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: TurTlER lddrrurTlER lddrrurlddrrlER lddrrurlddrrlTruTR lddrrurlddrrllddrrruTR lddrrurlddrrllddrrrulddrrR lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts.Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted.ExampleInput
2
3
1 2 3 5 6 E 7
8 9 10 4 11 12 13
11
34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1
E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3
Output
SURGERY COMPLETE
IR
R SrS
S rr
I lldll
DONE
SURGERY FAILED
NoteThere are three shortcuts defined in the first sample output: R = SrS S = rr I = lldll The sequence of moves is IR and it expands to: IR lldllR lldllSrS lldllrrrS lldllrrrrr | 2
3
1 2 3 5 6 E 7
8 9 10 4 11 12 13
11
34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1
E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3
| SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED | 1 second | 256 megabytes | ['combinatorics', 'constructive algorithms', 'math', '*3400'] |
E. Kirchhoff's Current Losstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend Kirchhoff is shocked with the current state of electronics design."Ohmygosh! Watt is wrong with the field? All these circuits are inefficient! There's so much capacity for improvement. The electrical engineers must not conduct their classes very well. It's absolutely revolting" he said.The negativity just keeps flowing out of him, but even after complaining so many times he still hasn't lepton the chance to directly change anything."These circuits have too much total resistance. Wire they designed this way? It's just causing a massive loss of resistors! Their entire field could conserve so much money if they just maximized the potential of their designs. Why can't they just try alternative ideas?"The frequency of his protests about the electrical engineering department hertz your soul, so you have decided to take charge and help them yourself. You plan to create a program that will optimize the circuits while keeping the same circuit layout and maintaining the same effective resistance.A circuit has two endpoints, and is associated with a certain constant, R, called its effective resistance. The circuits we'll consider will be formed from individual resistors joined together in series or in parallel, forming more complex circuits. The following image illustrates combining circuits in series or parallel. According to your friend Kirchhoff, the effective resistance can be calculated quite easily when joining circuits this way: When joining k circuits in series with effective resistances R_1, R_2, \ldots, R_k, the effective resistance R of the resulting circuit is the sum R = R_1 + R_2 + \ldots + R_k. When joining k circuits in parallel with effective resistances R_1, R_2, \ldots, R_k, the effective resistance R of the resulting circuit is found by solving for R in \frac{1}{R} = \frac{1}{R_1} + \frac{1}{R_2} + \ldots + \frac{1}{R_k}, assuming all R_i > 0; if at least one R_i = 0, then the effective resistance of the whole circuit is simply R = 0. Circuits will be represented by strings. Individual resistors are represented by an asterisk, "*". For more complex circuits, suppose s_1, s_2, \ldots, s_k represent k \ge 2 circuits. Then: "(s_1 S s_2 S \ldots S s_k)" represents their series circuit; "(s_1 P s_2 P \ldots P s_k)" represents their parallel circuit. For example, "(* P (* S *) P *)" represents the following circuit: Given a circuit, your task is to assign the resistances of the individual resistors such that they satisfy the following requirements: Each individual resistor has a nonnegative integer resistance value; The effective resistance of the whole circuit is r; The sum of the resistances of the individual resistors is minimized. If there are n individual resistors, then you need to output the list r_1, r_2, \ldots, r_n (0 \le r_i, and r_i is an integer), where r_i is the resistance assigned to the i-th individual resistor that appears in the input (from left to right). If it is impossible to accomplish the task, you must say so as well.If it is possible, then it is guaranteed that the minimum sum of resistances is at most 10^{18}. InputThe first line of input contains a single integer t (1 \le t \le 32000), denoting the number of test cases. The next lines contain descriptions of the test cases.Each test case consists of a single line containing the integer r (1 \le r \le 10^6), space, and then the string representing the circuit. It is guaranteed that the string is valid and follows the description above. The number of individual resistors (symbols "*") is at least 1 and at most 80000.It is guaranteed that the total number of individual resistors across all test cases is at most 320000.OutputFor each test case, print a single line: If it's possible to achieve an effective resistance of r, print "REVOLTING" (without quotes) and then n integers r_1, r_2, \ldots, r_n — the resistances assigned to the individual resistors. Here, n denotes the number of the individual resistors in the circuit. There may be multiple possible such assignments with a minimal sum of resistances of the individual resistors, you can output any of them; If it's impossible, print the string: "LOSS" (without quotes). ExampleInput
3
5 *
1 (* S *)
1 (* P (* S *))
Output
REVOLTING 5
REVOLTING 1 0
REVOLTING 2 1 1
NoteThe following illustrates the third sample case: Here, the sum of the resistances of the individual resistors is 2 + 1 + 1 = 4, which can be shown to be the minimum. Note that there may be other assignments that achieve this minimum. | 3
5 *
1 (* S *)
1 (* P (* S *))
| REVOLTING 5 REVOLTING 1 0 REVOLTING 2 1 1 | 2 seconds | 256 megabytes | ['math', '*2900'] |
D. Miss Punyversetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Oak has n nesting places, numbered with integers from 1 to n. Nesting place i is home to b_i bees and w_i wasps.Some nesting places are connected by branches. We call two nesting places adjacent if there exists a branch between them. A simple path from nesting place x to y is given by a sequence s_0, \ldots, s_p of distinct nesting places, where p is a non-negative integer, s_0 = x, s_p = y, and s_{i-1} and s_{i} are adjacent for each i = 1, \ldots, p. The branches of The Oak are set up in such a way that for any two pairs of nesting places x and y, there exists a unique simple path from x to y. Because of this, biologists and computer scientists agree that The Oak is in fact, a tree.A village is a nonempty set V of nesting places such that for any two x and y in V, there exists a simple path from x to y whose intermediate nesting places all lie in V. A set of villages \cal P is called a partition if each of the n nesting places is contained in exactly one of the villages in \cal P. In other words, no two villages in \cal P share any common nesting place, and altogether, they contain all n nesting places.The Oak holds its annual Miss Punyverse beauty pageant. The two contestants this year are Ugly Wasp and Pretty Bee. The winner of the beauty pageant is determined by voting, which we will now explain. Suppose \mathcal{P} is a partition of the nesting places into m villages V_1, \ldots, V_m. There is a local election in each village. Each of the insects in this village vote for their favorite contestant. If there are strictly more votes for Ugly Wasp than Pretty Bee, then Ugly Wasp is said to win in that village. Otherwise, Pretty Bee wins. Whoever wins in the most number of villages wins.As it always goes with these pageants, bees always vote for the bee (which is Pretty Bee this year) and wasps always vote for the wasp (which is Ugly Wasp this year). Unlike their general elections, no one abstains from voting for Miss Punyverse as everyone takes it very seriously.Mayor Waspacito, and his assistant Alexwasp, wants Ugly Wasp to win. He has the power to choose how to partition The Oak into exactly m villages. If he chooses the partition optimally, determine the maximum number of villages in which Ugly Wasp wins.InputThe first line of input contains a single integer t (1 \le t \le 100) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains two space-separated integers n and m (1 \le m \le n \le 3000). The second line contains n space-separated integers b_1, b_2, \ldots, b_n (0 \le b_i \le 10^9). The third line contains n space-separated integers w_1, w_2, \ldots, w_n (0 \le w_i \le 10^9). The next n - 1 lines describe the pairs of adjacent nesting places. In particular, the i-th of them contains two space-separated integers x_i and y_i (1 \le x_i, y_i \le n, x_i \neq y_i) denoting the numbers of two adjacent nesting places. It is guaranteed that these pairs form a tree.It is guaranteed that the sum of n in a single file is at most 10^5.OutputFor each test case, output a single line containing a single integer denoting the maximum number of villages in which Ugly Wasp wins, among all partitions of The Oak into m villages.ExampleInput
2
4 3
10 160 70 50
70 111 111 0
1 2
2 3
3 4
2 1
143 420
214 349
2 1
Output
2
0
NoteIn the first test case, we need to partition the n = 4 nesting places into m = 3 villages. We can make Ugly Wasp win in 2 villages via the following partition: \{\{1, 2\}, \{3\}, \{4\}\}. In this partition, Ugly Wasp wins in village \{1, 2\}, garnering 181 votes as opposed to Pretty Bee's 170; Ugly Wasp also wins in village \{3\}, garnering 111 votes as opposed to Pretty Bee's 70; Ugly Wasp loses in the village \{4\}, garnering 0 votes as opposed to Pretty Bee's 50. Thus, Ugly Wasp wins in 2 villages, and it can be shown that this is the maximum possible number.In the second test case, we need to partition the n = 2 nesting places into m = 1 village. There is only one way to do this: \{\{1, 2\}\}. In this partition's sole village, Ugly Wasp gets 563 votes, and Pretty Bee also gets 563 votes. Ugly Wasp needs strictly more votes in order to win. Therefore, Ugly Wasp doesn't win in any village. | 2
4 3
10 160 70 50
70 111 111 0
1 2
2 3
3 4
2 1
143 420
214 349
2 1
| 2 0 | 4 seconds | 512 megabytes | ['dp', 'greedy', 'trees', '*2500'] |
C. Jeremy Bearimytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWelcome! Everything is fine.You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B?InputThe first line of input contains a single integer t (1 \le t \le 500) denoting the number of test cases. The next lines contain descriptions of the test cases.The first line of each test case contains a single integer k denoting the number of pairs of people (1 \le k \le 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 \le a_i, b_i \le 2k, a_i \neq b_i, 1 \le t_i \le 10^6). It is guaranteed that the given roads define a tree structure.It is guaranteed that the sum of the k in a single file is at most 3 \cdot 10^5.OutputFor each test case, output a single line containing two space-separated integers G and B. ExampleInput
2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
Output
15 33
6 6
NoteFor the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33. | 2
3
1 2 3
3 2 4
2 4 3
4 5 6
5 6 5
2
1 2 1
1 3 2
1 4 3
| 15 33 6 6 | 3 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'greedy', 'trees', '*2000'] |
B. Beingawesomeismtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r \times c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.In particular, a single use of your power is this: You choose a horizontal 1 \times x subgrid or a vertical x \times 1 subgrid. That value of x is up to you; You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number s of steps; You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 \times 4 subgrid, the direction NORTH, and s = 2 steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.InputThe first line of input contains a single integer t (1 \le t \le 2\cdot 10^4) denoting the number of test cases.The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 \le r, c \le 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r \cdot c in a single file is at most 3 \cdot 10^6.OutputFor each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. ExampleInput
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". | 4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
| 2 1 MORTAL 4 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1800'] |
A. Cut and Pastetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location \ell is denoted by an integer in \{0, \ldots, |s|\}, with the following meaning: If \ell = 0, then the cursor is located before the first character of s. If \ell = |s|, then the cursor is located right after the last character of s. If 0 < \ell < |s|, then the cursor is located between s_\ell and s_{\ell+1}. We denote by s_\text{left} the string to the left of the cursor and s_\text{right} the string to the right of the cursor. We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions: The Move action. Move the cursor one step to the right. This increments \ell once. The Cut action. Set c \leftarrow s_\text{right}, then set s \leftarrow s_\text{left}. The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c. The cursor initially starts at \ell = 0. Then, we perform the following procedure: Perform the Move action once. Perform the Cut action once. Perform the Paste action s_\ell times. If \ell = x, stop. Otherwise, return to step 1. You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7. It is guaranteed that \ell \le |s| at any time.InputThe first line of input contains a single integer t (1 \le t \le 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.The first line of each test case contains a single integer x (1 \le x \le 10^6). The second line of each test case consists of the initial string s (1 \le |s| \le 500). It is guaranteed, that s consists of the characters "1", "2", "3".It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that \ell \le |s| at any time.OutputFor each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7. ExampleInput
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
NoteLet's illustrate what happens with the first test case. Initially, we have s = 231. Initially, \ell = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above: Step 1, Move once: we get \ell = 1. Step 2, Cut once: we get s = 2 and c = 31. Step 3, Paste s_\ell = 2 times: we get s = 23131. Step 4: \ell = 1 \not= x = 5, so we return to step 1. Step 1, Move once: we get \ell = 2. Step 2, Cut once: we get s = 23 and c = 131. Step 3, Paste s_\ell = 3 times: we get s = 23131131131. Step 4: \ell = 2 \not= x = 5, so we return to step 1. Step 1, Move once: we get \ell = 3. Step 2, Cut once: we get s = 231 and c = 31131131. Step 3, Paste s_\ell = 1 time: we get s = 23131131131. Step 4: \ell = 3 \not= x = 5, so we return to step 1. Step 1, Move once: we get \ell = 4. Step 2, Cut once: we get s = 2313 and c = 1131131. Step 3, Paste s_\ell = 3 times: we get s = 2313113113111311311131131. Step 4: \ell = 4 \not= x = 5, so we return to step 1. Step 1, Move once: we get \ell = 5. Step 2, Cut once: we get s = 23131 and c = 13113111311311131131. Step 3, Paste s_\ell = 1 times: we get s = 2313113113111311311131131. Step 4: \ell = 5 = x, so we stop. At the end of the procedure, s has length 25. | 4
5
231
7
2323
6
333
24
133321333
| 25 1438 1101 686531475 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1700'] |
F. New Year and Handle Changetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is getting near. So it's time to change handles on codeforces. Mishka wants to change his handle but in such a way that people would not forget who he is.To make it work, he only allowed to change letters case. More formally, during one handle change he can choose any segment of his handle [i; i + l - 1] and apply tolower or toupper to all letters of his handle on this segment (more fomally, replace all uppercase letters with corresponding lowercase or vice versa). The length l is fixed for all changes.Because it is not allowed to change codeforces handle too often, Mishka can perform at most k such operations. What is the minimum value of min(lower, upper) (where lower is the number of lowercase letters, and upper is the number of uppercase letters) can be obtained after optimal sequence of changes?InputThe first line of the input contains three integers n, k and l (1 \le n, k, l \le 10^6, l \le n) — the length of Mishka's handle, the number of changes and the length of the segment.The second line of the input contains one string s, consisting of n lowercase and uppercase Latin letters — Mishka's handle.OutputPrint one integer — the minimum value of min(lower, upper) after that Mishka change his handle at most k times in a way described in the problem statement.ExamplesInput
7 1 4
PikMike
Output
0
Input
15 2 2
AaAaAAaaAAAAaaA
Output
2
Input
14 2 6
aBcdEFGHIJklMn
Output
0
Input
9 2 2
aAaAAAaaA
Output
1
| 7 1 4
PikMike
| 0 | 3 seconds | 256 megabytes | ['binary search', 'dp', '*2800'] |
E. New Year Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYeah, we failed to make up a New Year legend for this problem.A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition.For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; p = [\textbf{5}, 4, 2, 3, \textbf{1}, 7, 8, 6], l = [[5, 1]]; the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; p = [\textbf{5}, \textbf{4}, \textbf{2}, \textbf{3}, \textbf{1}, \textbf{7}, \textbf{8}, \textbf{6}], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7].Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 \le n \le 50, 1 \le k \le 10^{18}).OutputFor each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order).ExampleInput
5
3 3
5 15
4 13
6 8
4 2
Output
2 1 3
3 1 2 5 4
-1
1 2 6 3 4 5
1 2 4 3
| 5
3 3
5 15
4 13
6 8
4 2
| 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 | 1 second | 256 megabytes | ['combinatorics', 'dp', '*2700'] |
D. Santa's Bottime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following: choose one kid x equiprobably among all n kids; choose some item y equiprobably among all k_x items kid x wants; choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot. If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?InputThe first line contains one integer n (1 \le n \le 10^6) — the number of kids who wrote their letters to Santa.Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 \le k_i, a_{i, j} \le 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.It is guaranteed that \sum \limits_{i = 1}^{n} k_i \le 10^6.OutputPrint the probatility that the Bot produces a valid decision as follows:Let this probability be represented as an irreducible fraction \frac{x}{y}. You have to print x \cdot y^{-1} \mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y \cdot y^{-1} has remainder 1 modulo 998244353). ExamplesInput
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
| 2
2 2 1
1 1
| 124780545 | 5 seconds | 256 megabytes | ['combinatorics', 'math', 'probabilities', '*1700'] |
C. Stack of Presentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSanta has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct.Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are k presents above the present Santa wants to send, it takes him 2k + 1 seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer t different test cases.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Then the test cases follow, each represented by three lines.The first line contains two integers n and m (1 \le m \le n \le 10^5) — the number of presents in the stack and the number of presents Santa wants to send, respectively.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le n, all a_i are unique) — the order of presents in the stack.The third line contains m integers b_1, b_2, ..., b_m (1 \le b_i \le n, all b_i are unique) — the ordered list of presents Santa has to send.The sum of n over all test cases does not exceed 10^5.OutputFor each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.ExampleInput
2
3 3
3 1 2
3 2 1
7 2
2 1 7 3 4 5 6
3 1
Output
5
8
| 2
3 3
3 1 2
3 2 1
7 2
2 1 7 3 4 5 6
3 1
| 5 8 | 1 second | 256 megabytes | ['data structures', 'implementation', '*1400'] |
B. Verse For Santatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly — the part which takes a_2 seconds, and so on. After reciting the verse, Vasya will get the number of presents equal to the number of parts he fully recited.Vasya can skip at most one part of the verse while reciting it (if he skips more than one part, then Santa will definitely notice it).Santa will listen to Vasya's verse for no more than s seconds. For example, if s = 10, a = [100, 9, 1, 1], and Vasya skips the first part of verse, then he gets two presents.Note that it is possible to recite the whole verse (if there is enough time). Determine which part Vasya needs to skip to obtain the maximum possible number of gifts. If Vasya shouldn't skip anything, print 0. If there are multiple answers, print any of them.You have to process t test cases.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains two integers n and s (1 \le n \le 10^5, 1 \le s \le 10^9) — the number of parts in the verse and the maximum number of seconds Santa will listen to Vasya, respectively.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the time it takes to recite each part of the verse.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print one integer — the number of the part that Vasya needs to skip to obtain the maximum number of gifts. If Vasya shouldn't skip any parts, print 0.ExampleInput
3
7 11
2 9 1 3 18 1 4
4 35
11 9 10 7
1 8
5
Output
2
1
0
NoteIn the first test case if Vasya skips the second part then he gets three gifts.In the second test case no matter what part of the verse Vasya skips.In the third test case Vasya can recite the whole verse. | 3
7 11
2 9 1 3 18 1 4
4 35
11 9 10 7
1 8
5
| 2 1 0 | 1 second | 256 megabytes | ['binary search', 'brute force', 'implementation', '*1300'] |
A. New Year Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.InputThe first line contains a single integer t (1 \le t \le 100) — the number of sets of lamps Polycarp has bought.Each of the next t lines contains three integers r, g and b (1 \le r, g, b \le 10^9) — the number of red, green and blue lamps in the set, respectively.OutputPrint t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.ExampleInput
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example. | 3
3 3 3
1 10 2
2 1 1
| Yes No Yes | 1 second | 256 megabytes | ['math', '*900'] |
F. Cardstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the following experiment. You have a deck of m cards, and exactly one card is a joker. n times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.Let x be the number of times you have taken the joker out of the deck during this experiment. Assuming that every time you shuffle the deck, all m! possible permutations of cards are equiprobable, what is the expected value of x^k? Print the answer modulo 998244353.InputThe only line contains three integers n, m and k (1 \le n, m < 998244353, 1 \le k \le 5000).OutputPrint one integer — the expected value of x^k, taken modulo 998244353 (the answer can always be represented as an irreducible fraction \frac{a}{b}, where b \mod 998244353 \ne 0; you have to print a \cdot b^{-1} \mod 998244353).ExamplesInput
1 1 1
Output
1
Input
1 1 5000
Output
1
Input
2 2 2
Output
499122178
Input
998244352 1337 5000
Output
326459680
| 1 1 1
| 1 | 4 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', 'number theory', 'probabilities', '*2600'] |
E. Tests for problem Dtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of n vertices, find a set of segments such that: both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair (i, j) such that i \ne j, i \in [1, n] and j \in [1, n], the vertices i and j are connected with an edge if and only if the segments i and j intersect, but neither segment i is fully contained in segment j, nor segment j is fully contained in segment i. Can you solve this problem too?InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5) — the number of vertices in the tree.Then n - 1 lines follow, each containing two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) denoting the endpoints of the i-th edge.It is guaranteed that the given graph is a tree.OutputPrint n pairs of integers, the i-th pair should contain two integers l_i and r_i (1 \le l_i < r_i \le 2n) — the endpoints of the i-th segment. All 2n integers you print should be unique.It is guaranteed that the answer always exists.ExamplesInput
6
1 2
1 3
3 4
3 5
2 6
Output
9 12
7 10
3 11
1 5
2 4
6 8
Input
1
Output
1 2
| 6
1 2
1 3
3 4
3 5
2 6
| 9 12 7 10 3 11 1 5 2 4 6 8 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'divide and conquer', 'trees', '*2200'] |
D. Segment Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs the name of the task implies, you are asked to do some work with segments and trees.Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.You are given n segments [l_1, r_1], [l_2, r_2], \dots, [l_n, r_n], l_i < r_i for every i. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.Let's generate a graph with n vertices from these segments. Vertices v and u are connected by an edge if and only if segments [l_v, r_v] and [l_u, r_u] intersect and neither of it lies fully inside the other one.For example, pairs ([1, 3], [2, 4]) and ([5, 10], [3, 7]) will induce the edges but pairs ([1, 2], [3, 4]) and ([5, 7], [3, 10]) will not.Determine if the resulting graph is a tree or not.InputThe first line contains a single integer n (1 \le n \le 5 \cdot 10^5) — the number of segments.The i-th of the next n lines contain the description of the i-th segment — two integers l_i and r_i (1 \le l_i < r_i \le 2n).It is guaranteed that all segments borders are pairwise distinct. OutputPrint "YES" if the resulting graph is a tree and "NO" otherwise.ExamplesInput
6
9 12
2 11
1 3
6 10
5 7
4 8
Output
YES
Input
5
1 3
2 4
5 9
6 8
7 10
Output
NO
Input
5
5 8
3 6
2 9
7 10
1 4
Output
NO
NoteThe graph corresponding to the first example:The graph corresponding to the second example:The graph corresponding to the third example: | 6
9 12
2 11
1 3
6 10
5 7
4 8
| YES | 2 seconds | 256 megabytes | ['data structures', 'dsu', 'graphs', 'trees', '*2100'] |
C. Berry Jamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKarlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were 2n jars of strawberry and blueberry jam.All the 2n jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly n jars to his left and n jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten 1 jar to his left and then 5 jars to his right. There remained exactly 3 full jars of both strawberry and blueberry jam. Jars are numbered from 1 to 2n from left to right, so Karlsson initially stands between jars n and n+1.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer t independent test cases.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains 2n integers a_1, a_2, \dots, a_{2n} (1 \le a_i \le 2) — a_i=1 means that the i-th jar from the left is a strawberry jam jar and a_i=2 means that it is a blueberry jam jar.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.ExampleInput
4
6
1 1 1 2 2 1 2 1 2 1 1 2
2
1 2 1 2
3
1 1 1 1 1 1
2
2 1 1 1
Output
6
0
6
2
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all 6 jars so that there remain 0 jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave 1 jar of both jams. | 4
6
1 1 1 2 2 1 2 1 2 1 1 2
2
1 2 1 2
3
1 1 1 1 1 1
2
2 1 1 1
| 6 0 6 2 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'implementation', '*1700'] |
B. A and Btime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by 1; during the second operation you choose one of these numbers and increase it by 2, and so on. You choose the number of these operations yourself.For example, if a = 1 and b = 3, you can perform the following sequence of three operations: add 1 to a, then a = 2 and b = 3; add 2 to b, then a = 2 and b = 5; add 3 to a, then a = 5 and b = 5. Calculate the minimum number of operations required to make a and b equal. InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The only line of each test case contains two integers a and b (1 \le a, b \le 10^9).OutputFor each test case print one integer — the minimum numbers of operations required to make a and b equal. ExampleInput
3
1 3
11 11
30 20
Output
3
0
4
NoteFirst test case considered in the statement.In the second test case integers a and b are already equal, so you don't need to perform any operations.In the third test case you have to apply the first, the second, the third and the fourth operation to b (b turns into 20 + 1 + 2 + 3 + 4 = 30). | 3
1 3
11 11
30 20
| 3 0 4 | 1 second | 256 megabytes | ['greedy', 'math', '*1500'] |
A. Shuffle Hashingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm: take the password p, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain p' (p' can still be equal to p); generate two random strings, consisting of lowercase Latin letters, s_1 and s_2 (any of these strings can be empty); the resulting hash h = s_1 + p' + s_2, where addition is string concatenation. For example, let the password p = "abacaba". Then p' can be equal to "aabcaab". Random strings s1 = "zyx" and s2 = "kjh". Then h = "zyxaabcaabkjh".Note that no letters could be deleted or added to p to obtain p', only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password p and the hash h, check that h can be the hash for the password p.Your program should answer t independent test cases.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains a non-empty string p, consisting of lowercase Latin letters. The length of p does not exceed 100.The second line of each test case contains a non-empty string h, consisting of lowercase Latin letters. The length of h does not exceed 100.OutputFor each test case print the answer to it — "YES" if the given hash h could be obtained from the given password p or "NO" otherwise.ExampleInput
5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten
Output
YES
YES
NO
YES
NO
NoteThe first test case is explained in the statement.In the second test case both s_1 and s_2 are empty and p'= "threetwoone" is p shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case s_1= "n", s_2 is empty and p'= "one" is p shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password. | 5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten
| YES YES NO YES NO | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'strings', '*1000'] |
D. Let's Play the Words?time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that: the final set of n words still contains different words (i.e. all words are unique); there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.The first line of a test case contains one integer n (1 \le n \le 2\cdot10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4\cdot10^6. All words are different.Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2\cdot10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4\cdot10^6.OutputPrint answer for all of t test cases in the order they appear.If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 \le k \le n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.ExampleInput
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
| 4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
| 1 3 -1 0 2 1 2 | 3 seconds | 256 megabytes | ['data structures', 'hashing', 'implementation', 'math', '*1900'] |
B. Make Them Oddtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n positive integers a_1, a_2, \dots, a_n. For the one move you can choose any even value c and divide by two all elements that equal c.For example, if a=[6,8,12,6,3,12] and you choose c=6, and a is transformed into a=[3,8,12,3,3,12] after the move.You need to find the minimal number of moves for transforming a to an array of only odd integers (each element shouldn't be divisible by 2).InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.The first line of a test case contains n (1 \le n \le 2\cdot10^5) — the number of integers in the sequence a. The second line contains positive integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).The sum of n for all test cases in the input doesn't exceed 2\cdot10^5.OutputFor t test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by 2).ExampleInput
4
6
40 6 40 3 20 1
1
1024
4
2 4 8 16
3
3 1 7
Output
4
10
4
0
NoteIn the first test case of the example, the optimal sequence of moves can be as follows: before making moves a=[40, 6, 40, 3, 20, 1]; choose c=6; now a=[40, 3, 40, 3, 20, 1]; choose c=40; now a=[20, 3, 20, 3, 20, 1]; choose c=20; now a=[10, 3, 10, 3, 10, 1]; choose c=10; now a=[5, 3, 5, 3, 5, 1] — all numbers are odd. Thus, all numbers became odd after 4 moves. In 3 or fewer moves, you cannot make them all odd. | 4
6
40 6 40 3 20 1
1
1024
4
2 4 8 16
3
3 1 7
| 4 10 4 0 | 3 seconds | 256 megabytes | ['greedy', 'number theory', '*1200'] |
A. Happy Birthday, Polycarp!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHooray! Polycarp turned n years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his n birthdays: from the 1-th to the n-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: 1, 77, 777, 44 and 999999. The following numbers are not beautiful: 12, 11110, 6969 and 987654321.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from 1 to n (inclusive) that are beautiful.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Then t test cases follow.Each test case consists of one line, which contains a positive integer n (1 \le n \le 10^9) — how many years Polycarp has turned.OutputPrint t integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between 1 and n, inclusive.ExampleInput
6
18
1
9
100500
33
1000000000
Output
10
1
9
45
12
81
NoteIn the first test case of the example beautiful years are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 11. | 6
18
1
9
100500
33
1000000000
| 10 1 9 45 12 81 | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. Asterisk Substringstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a string s of n lowercase English letters. Let t_i be the string obtained by replacing the i-th character of s with an asterisk character *. For example, when s = \mathtt{abc}, we have t_1 = \tt{*bc}, t_2 = \tt{a*c}, and t_3 = \tt{ab*}.Given a string s, count the number of distinct strings of lowercase English letters and asterisks that occur as a substring of at least one string in the set \{s, t_1, \ldots, t_n \}. The empty string should be counted.Note that *'s are just characters and do not play any special role as in, for example, regex matching.InputThe only line contains a string s of n lowercase English letters (1 \leq n \leq 10^5).OutputPrint a single integer — the number of distinct strings of s, t_1, \ldots, t_n.ExampleInput
abc
Output
15
NoteFor the sample case, the distinct substrings are (empty string), a, b, c, *, ab, a*, bc, b*, *b, *c, abc, ab*, a*c, *bc. | abc
| 15 | 5 seconds | 512 megabytes | ['string suffix structures', '*3400'] |
E. Four Stonestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each position (that is, if a coordinate x appears k times among numbers b_1, \ldots, b_4, there should be exactly k stones at x in the end).We are allowed to move stones with the following operation: choose two stones at distinct positions x and y with at least one stone each, and move one stone from x to 2y - x. In other words, the operation moves a stone to a symmetric position relative to some other stone. At any moment it is allowed to have any number of stones at the same position.Find any sequence of operations that achieves the goal, or determine that it is impossible. The sequence does not have to be shortest, but it may contain at most 1000 operations.InputThe first line contains four integers a_1, \ldots, a_4 (-10^9 \leq a_i \leq 10^9) — initial coordinates of the stones. There may be multiple stones sharing the same coordinate.The second line contains four integers b_1, \ldots, b_4 (-10^9 \leq b_i \leq 10^9) — target coordinates of the stones. There may be multiple targets sharing the same coordinate.OutputIf there is no sequence of operations that achieves the goal, print a single integer -1. Otherwise, on the first line print a single integer k (0 \leq k \leq 1000) — the number of operations in your sequence. On the next k lines, describe the operations. The i-th of these lines should contain two integers x_i and y_i (x_i \neq y_i) — coordinates of the moved stone and the center of symmetry stone for the i-th operation.For each operation i, there should at least one stone in each of the coordinates x_i and y_i, and the resulting coordinate 2y_i - x_i must not exceed 10^{18} by absolute value.If there are multiple suitable sequences, print any of them. It is guaranteed that if there is a suitable sequence of operations, then there is also a suitable sequence that satisfies all the additional requirement.ExamplesInput
0 1 2 3
3 5 6 8
Output
3
1 3
2 5
0 3
Input
0 0 0 0
1 1 1 1
Output
-1
Input
0 0 0 1
0 1 0 1
Output
-1
| 0 1 2 3
3 5 6 8
| 3 1 3 2 5 0 3 | 1 second | 512 megabytes | ['constructive algorithms', '*3500'] |
D. Tree Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya has a tree with n vertices numbered from 1 to n, and n - 1 edges numbered from 1 to n - 1. Initially each vertex contains a token with the number of the vertex written on it.Vasya plays a game. He considers all edges of the tree by increasing of their indices. For every edge he acts as follows: If both endpoints of the edge contain a token, remove a token from one of the endpoints and write down its number. Otherwise, do nothing.The result of the game is the sequence of numbers Vasya has written down. Note that there may be many possible resulting sequences depending on the choice of endpoints when tokens are removed.Vasya has played for such a long time that he thinks he exhausted all possible resulting sequences he can obtain. He wants you to verify him by computing the number of distinct sequences modulo 998\,244\,353.InputThe first line contains a single integer n (2 \leq n \leq 2 \cdot 10^5) — the number of vertices of the tree.The next n - 1 lines describe edges of the tree. The i-th of these lines contains two integers u_i, v_i (1 \leq u_i, v_i \leq n) — endpoints of the edge with index i. It is guaranteed that the given graph is indeed a tree.OutputPrint a single integer — the number of distinct sequences modulo 998\,244\,353.ExamplesInput
5
1 2
1 3
1 4
1 5
Output
5
Input
7
7 2
7 6
1 2
7 5
4 7
3 5
Output
10
NoteIn the first sample case the distinct sequences are (1), (2, 1), (2, 3, 1), (2, 3, 4, 1), (2, 3, 4, 5).Int the second sample case the distinct sequences are (2, 6, 5, 3), (2, 6, 5, 7), (2, 6, 7, 2), (2, 6, 7, 5), (2, 7, 3), (2, 7, 5), (7, 1, 3), (7, 1, 5), (7, 2, 3), (7, 2, 5). | 5
1 2
1 3
1 4
1 5
| 5 | 2 seconds | 512 megabytes | ['dp', 'trees', '*2900'] |
C. Beautiful Rectangletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen.A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.InputThe first line contains n (1 \le n \le 4\cdot10^5). The second line contains n integers (1 \le a_i \le 10^9).OutputIn the first line print x (1 \le x \le n) — the total number of cells of the required maximum beautiful rectangle. In the second line print p and q (p \cdot q=x): its sizes. In the next p lines print the required rectangle itself. If there are several answers, print any.ExamplesInput
12
3 1 4 1 5 9 2 6 5 3 5 8
Output
12
3 4
1 2 3 5
3 1 5 4
5 6 8 9
Input
5
1 1 1 1 1
Output
1
1 1
1
| 12
3 1 4 1 5 9 2 6 5 3 5 8
| 12 3 4 1 2 3 5 3 1 5 4 5 6 8 9 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'constructive algorithms', 'data structures', 'greedy', 'math', '*2300'] |
B. Two Fairstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 \le a, b \le n; a \ne b).Find the number of pairs of cities x and y (x \ne a, x \ne b, y \ne a, y \ne b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.InputThe first line of the input contains an integer t (1 \le t \le 4\cdot10^4) — the number of test cases in the input. Next, t test cases are specified.The first line of each test case contains four integers n, m, a and b (4 \le n \le 2\cdot10^5, n - 1 \le m \le 5\cdot10^5, 1 \le a,b \le n, a \ne b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — numbers of cities connected by the road.Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.The sum of the values of n for all sets of input data in the test does not exceed 2\cdot10^5. The sum of the values of m for all sets of input data in the test does not exceed 5\cdot10^5.OutputPrint t integers — the answers to the given test cases in the order they are written in the input.ExampleInput
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
| 3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
| 4 0 1 | 3 seconds | 256 megabytes | ['combinatorics', 'dfs and similar', 'dsu', 'graphs', '*1900'] |
A. As Simple as One and Twotime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a non-empty string s=s_1s_2\dots s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j (1 \le j \le n-2), that s_{j}s_{j+1}s_{j+2}="one" or s_{j}s_{j+1}s_{j+2}="two".For example: Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"), Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like s="onetwone", then if Polycarp selects two indices 3 and 6, then "onetwone" will be selected and the result is "ontwne".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the input. Next, the test cases are given.Each test case consists of one non-empty string s. Its length does not exceed 1.5\cdot10^5. The string s consists only of lowercase Latin letters.It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed 1.5\cdot10^6.OutputPrint an answer for each test case in the input in order of their appearance.The first line of each answer should contain r (0 \le r \le |s|) — the required minimum number of positions to be removed, where |s| is the length of the given line. The second line of each answer should contain r different integers — the indices themselves for removal in any order. Indices are numbered from left to right from 1 to the length of the string. If r=0, then the second line can be skipped (or you can print empty). If there are several answers, print any of them.ExamplesInput
4
onetwone
testme
oneoneone
twotwo
Output
2
6 3
0
3
4 1 7
2
1 4
Input
10
onetwonetwooneooonetwooo
two
one
twooooo
ttttwo
ttwwoo
ooone
onnne
oneeeee
oneeeeeeetwooooo
Output
6
18 11 12 1 6 21
1
1
1
3
1
2
1
6
0
1
4
0
1
1
2
1 11
NoteIn the first example, answers are: "onetwone", "testme" — Polycarp likes it, there is nothing to remove, "oneoneone", "twotwo". In the second example, answers are: "onetwonetwooneooonetwooo", "two", "one", "twooooo", "ttttwo", "ttwwoo" — Polycarp likes it, there is nothing to remove, "ooone", "onnne" — Polycarp likes it, there is nothing to remove, "oneeeee", "oneeeeeeetwooooo". | 4
onetwone
testme
oneoneone
twotwo
| 2 6 3 0 3 4 1 7 2 1 4 | 3 seconds | 256 megabytes | ['dp', 'greedy', '*1400'] |
F. Шардирование постовограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводЭто интерактивная задача.Когда данных становится слишком много и они не помещаются на один сервер, их приходится шардировать. Рассмотрим систему хранения постов пользователей, которая расположена на S серверах, нумеруемых с единицы. Каждый раз когда пользователь пишет пост, ему выдается уникальный идентификатор в пределах от 1 до 10^{18} и сохраняется на случайный сервер. Чем позже был создан пост, тем больше его id. Иногда посты удаляются, поэтому на серверах может лежать существенно разное количество постов.Рассмотрим все неудаленные id постов пользователя и отсортируем их по возрастанию. Вам хочется узнать k-й из них. Для этого вы можете послать не более 100 дополнительных запросов. Каждый запрос имеет формат «? i j». В ответ вы получите идентификатор j-го по возрастанию поста пользователя среди хранящихся на i-м сервере. Когда вы считаете, что знаете k-й по возрастанию идентификатор, вместо запроса необходимо вывести ответ в формате «! id». Протокол взаимодействияВ первой строке записано два числа n и S (1 \le n \le 100, 1 \le S \le 5) — количество пользователей для которых необходимо независимо решить задачу, а также количество серверов, на которых хранятся посты.Далее необходимо n раз решить задачу. Вначале необходимо считать S чисел a_1, a_2, ... a_S (0 \le a_i; \sum a_i \le 10^5) — количество постов пользователя на каждом сервере. В следующей строке будет задано число k (1 \le k \le \sum a_i ) — идентификатор какого по возрастанию поста необходимо узнать.Далее необходимо совершить не более 100 запросов в формате, который описан в условии.Заметим, что ограничение на количество запросов действует на каждого пользователя отдельно, поэтому при переходе к следующему тесту счетчик вопросов сбрасывается.ПримерВходные данные
1 2
3 2
3
3
5
10Выходные данные
? 1 2
? 2 1
? 1 3
! 5
ПримечаниеВ примере на первом сервере хранятся посты с id 1, 3 и 10. А на втором 5 и 7. Необходимо найти третье по возрастанию число, это 5. | Входные данные
1 2
3 2
3
3
5
10 | Выходные данные ? 1 2 ? 2 1 ? 1 3 ! 5 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem', 'binary search', 'interactive'] |
E3. Контрольная суммаограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводДанные пользователей ВКонтакте хранятся на десятках тысяч серверов. Для того, чтобы можно было определять ошибки при записи данных на диск, на диск регулярно записываются текущие контрольные суммы CRC32 (Wiki, IEEE 802-3). Благодаря этому, при чтении данных можно заново вычислить контрольную сумму и проверить, что данные и контрольная сумма записаны корректно. Разумеется, проверки на совпадение контрольной суммы встроены в большинство сервисов ВКонтакте. Но как-то раз оказалось, что в одном сегменте данных нужно изменить значение четырех последовательных байт на новое — нужно заменить значения последовательности a_i, a_{i+1}, a_{i+2}, a_{i+3} на x_0, x_1, x_2, x_3. При этом, нужно чтобы значение контрольной суммы CRC32 осталось прежним. Конечно, при изменении последовательности ее контрольная сумма изменится, поэтому кроме изменения этих четырех байт на новое значение, были выбраны четыре байта a_{j}, a_{j+1}, a_{j+2}, a_{j+3}, которым можно назначить любое значение. Ваша задача выбрать им новые значения так, чтобы CRC32 данной последовательности не изменился, или определить, что это невозможно. Поскольку изменение данных — операция серьезная, перед самим изменением нужно определить, как изменится последовательность для q независимых тестовых случаев.Входные данныеВ первой строке дано два целых числа n и q — количество байт в файле и количество запросов, для которых нужно решить задачу (8 \le n \le 2 \cdot 10^5; 1 \le q \le 10^5).Во второй строке дано n чисел a_0, a_1, \ldots, a_{n-1} — содержимое файла в байтах (0 \le a_i \le 255).В следующих q строках дано по шесть чисел i, j, x_0, x_1, x_2, x_3 — позиция i, начиная с которой нужно заменить четыре байта на x_0, x_1, x_2, x_3, и позиция j, начиная с которой можно менять четыре байта как угодно (0 \le i, j \le n-4; 0 \le x_0, x_1, x_2, x_3 \le 255). Гарантируется, что отрезки [i; i+3] и [j; j+3] не пересекаются.Выходные данныеДля каждого запроса выведите четыре целых числа z_0, z_1, z_2, z_3, на которые нужно заменить четыре байта с номерами j, j+1, j+2, j+3, чтобы crc32 не изменился. Обратите внимание, что все запросы независимы, и на самом деле последовательность не изменяется.Если существует несколько решений, выведите любое, а если для данного запроса валидного решения нет, выведите No solution.ПримерыВходные данные
8 1
1 2 3 4 5 6 7 8
0 4 0 0 0 0
Выходные данные
212 34 127 159
Входные данные
16 3
4 5 6 7 0 0 0 0 0 0 0 85 200 47 47 0
11 0 0 0 0 0
3 12 7 0 0 0
0 11 0 0 0 0
Выходные данные
0 0 0 0
200 47 47 0
0 0 0 0
ПримечаниеCRC32 байтовой последовательности из первого примера (1 2 3 4 5 6 7 8) равен 3fca88c5, CRC32 измененной последовательности (0 0 0 0 212 34 127 159) так же равен 3fca88c5. Стандартная утилита crc32 из большинства дистрибутивов линукса должна посчитать от них данную контрольную сумму.CRC32 последовательности из второго примера равен ecbb4b55. | Входные данные
8 1
1 2 3 4 5 6 7 8
0 4 0 0 0 0
| Выходные данные 212 34 127 159 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
E2. Контрольная суммаограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводДанные пользователей ВКонтакте хранятся на десятках тысяч серверов. Для того, чтобы можно было определять ошибки при записи данных на диск, на диск регулярно записываются текущие контрольные суммы CRC32 (Wiki, IEEE 802-3). Благодаря этому, при чтении данных можно заново вычислить контрольную сумму и проверить, что данные и контрольная сумма записаны корректно. Разумеется, проверки на совпадение контрольной суммы встроены в большинство сервисов ВКонтакте. Но как-то раз оказалось, что в одном сегменте данных нужно изменить значение четырех последовательных байт на новое — нужно заменить значения последовательности a_i, a_{i+1}, a_{i+2}, a_{i+3} на x_0, x_1, x_2, x_3. При этом, нужно чтобы значение контрольной суммы CRC32 осталось прежним. Конечно, при изменении последовательности ее контрольная сумма изменится, поэтому кроме изменения этих четырех байт на новое значение, были выбраны четыре байта a_{j}, a_{j+1}, a_{j+2}, a_{j+3}, которым можно назначить любое значение. Ваша задача выбрать им новые значения так, чтобы CRC32 данной последовательности не изменился, или определить, что это невозможно. Поскольку изменение данных — операция серьезная, перед самим изменением нужно определить, как изменится последовательность для q независимых тестовых случаев.Обратите внимание, что в этой версии задачи есть всего один тест с n=50\,000, q=8, который вы можете скачать по этой ссылке. Ваше решение не обязано проходить тесты из условия, и не будет на них протестировано. Если вы хотите проверить ваше решение на тестах из условия, отправляйте его в задачу E3, где первые два теста соответствуют примерам из условия.Входные данныеВ первой строке дано два целых числа n и q — количество байт в файле и количество запросов, для которых нужно решить задачу (8 \le n \le 2 \cdot 10^5; 1 \le q \le 10^5).Во второй строке дано n чисел a_0, a_1, \ldots, a_{n-1} — содержимое файла в байтах (0 \le a_i \le 255).В следующих q строках дано по шесть чисел i, j, x_0, x_1, x_2, x_3 — позиция i, начиная с которой нужно заменить четыре байта на x_0, x_1, x_2, x_3, и позиция j, начиная с которой можно менять четыре байта как угодно (0 \le i, j \le n-4; 0 \le x_0, x_1, x_2, x_3 \le 255). Гарантируется, что отрезки [i; i+3] и [j; j+3] не пересекаются.Выходные данныеДля каждого запроса выведите четыре целых числа z_0, z_1, z_2, z_3, на которые нужно заменить четыре байта с номерами j, j+1, j+2, j+3, чтобы crc32 не изменился. Обратите внимание, что все запросы независимы, и на самом деле последовательность не изменяется.Если существует несколько решений, выведите любое, а если для данного запроса валидного решения нет, выведите No solution.ПримерыВходные данные
8 1
1 2 3 4 5 6 7 8
0 4 0 0 0 0
Выходные данные
212 34 127 159
Входные данные
16 3
4 5 6 7 0 0 0 0 0 0 0 85 200 47 47 0
11 0 0 0 0 0
3 12 7 0 0 0
0 11 0 0 0 0
Выходные данные
0 0 0 0
200 47 47 0
0 0 0 0
ПримечаниеCRC32 байтовой последовательности из первого примера (1 2 3 4 5 6 7 8) равен 3fca88c5, CRC32 измененной последовательности (0 0 0 0 212 34 127 159) так же равен 3fca88c5. Стандартная утилита crc32 из большинства дистрибутивов линукса должна посчитать от них данную контрольную сумму.CRC32 последовательности из второго примера равен ecbb4b55. | Входные данные
8 1
1 2 3 4 5 6 7 8
0 4 0 0 0 0
| Выходные данные 212 34 127 159 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
E1. Контрольная суммаограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводДанные пользователей ВКонтакте хранятся на десятках тысяч серверов. Для того, чтобы можно было определять ошибки при записи данных на диск, на диск регулярно записываются текущие контрольные суммы CRC32 (Wiki, IEEE 802-3). Благодаря этому, при чтении данных можно заново вычислить контрольную сумму и проверить, что данные и контрольная сумма записаны корректно. Разумеется, проверки на совпадение контрольной суммы встроены в большинство сервисов ВКонтакте. Но как-то раз оказалось, что в одном сегменте данных нужно изменить значение четырех последовательных байт на новое — нужно заменить значения последовательности a_i, a_{i+1}, a_{i+2}, a_{i+3} на x_0, x_1, x_2, x_3. При этом, нужно чтобы значение контрольной суммы CRC32 осталось прежним. Конечно, при изменении последовательности ее контрольная сумма изменится, поэтому кроме изменения этих четырех байт на новое значение, были выбраны четыре байта a_{j}, a_{j+1}, a_{j+2}, a_{j+3}, которым можно назначить любое значение. Ваша задача выбрать им новые значения так, чтобы CRC32 данной последовательности не изменился, или определить, что это невозможно. Поскольку изменение данных — операция серьезная, перед самим изменением нужно определить, как изменится последовательность для q независимых тестовых случаев.Обратите внимание, что в этой версии задачи есть всего один тест с n=16, q=8, который вы можете скачать по этой ссылке. Ваше решение не обязано проходить тесты из условия, и не будет на них протестировано. Если вы хотите проверить ваше решение на тестах из условия, отправляйте его в задачу E3, где первые два теста соответствуют примерам из условия.Входные данныеВ первой строке дано два целых числа n и q — количество байт в файле и количество запросов, для которых нужно решить задачу (8 \le n \le 2 \cdot 10^5; 1 \le q \le 10^5).Во второй строке дано n чисел a_0, a_1, \ldots, a_{n-1} — содержимое файла в байтах (0 \le a_i \le 255).В следующих q строках дано по шесть чисел i, j, x_0, x_1, x_2, x_3 — позиция i, начиная с которой нужно заменить четыре байта на x_0, x_1, x_2, x_3, и позиция j, начиная с которой можно менять четыре байта как угодно (0 \le i, j \le n-4; 0 \le x_0, x_1, x_2, x_3 \le 255). Гарантируется, что отрезки [i; i+3] и [j; j+3] не пересекаются.Выходные данныеДля каждого запроса выведите четыре целых числа z_0, z_1, z_2, z_3, на которые нужно заменить четыре байта с номерами j, j+1, j+2, j+3, чтобы crc32 не изменился. Обратите внимание, что все запросы независимы, и на самом деле последовательность не изменяется.Если существует несколько решений, выведите любое, а если для данного запроса валидного решения нет, выведите No solution.ПримерыВходные данные
8 1
1 2 3 4 5 6 7 8
0 4 0 0 0 0
Выходные данные
212 34 127 159
Входные данные
16 3
4 5 6 7 0 0 0 0 0 0 0 85 200 47 47 0
11 0 0 0 0 0
3 12 7 0 0 0
0 11 0 0 0 0
Выходные данные
0 0 0 0
200 47 47 0
0 0 0 0
ПримечаниеCRC32 байтовой последовательности из первого примера (1 2 3 4 5 6 7 8) равен 3fca88c5, CRC32 измененной последовательности (0 0 0 0 212 34 127 159) так же равен 3fca88c5. Стандартная утилита crc32 из большинства дистрибутивов линукса должна посчитать от них данную контрольную сумму.CRC32 последовательности из второго примера равен ecbb4b55. | Входные данные
8 1
1 2 3 4 5 6 7 8
0 4 0 0 0 0
| Выходные данные 212 34 127 159 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
D. Storage2ограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводДля надежного, но компактного хранения картинок во ВКонтакте используются избыточные коды. Все картинки разбиваются на группы по 15, и для каждой группы картинок вычисляются 13 избыточных кодов. Избыточные коды необходимы, чтобы суметь восстановить некоторые картинки, если они будут утеряны вследствие поломки жесткого диска.Перед вычислением избыточных кодов 15 картинок из одной группы записываются в матрицу из 3 строк и 5 столбцов. Далее к получившейся матрице справа добавляются два столбца с 6 избыточными кодами (каждая пара кодов вычисляется на основе картинок в той же строке), а затем снизу добавляется еще одна строка из 7 избыточных кодов (каждый из них считается на основе картинок или избыточных кодов в том же столбце).Будем называть картинки и избыточные коды блоками. Таким образом, из 15 картинок мы получили 28 блоков, расставленных в виде матрицы 4 на 7. В данной задаче вам не будут даны формулы вычисления избыточных кодов, но даны их свойства: а именно по 3 любым блокам из одного столбца можно однозначно восстановить утерянный четвертый блок в том же столбце, а также по 5 любым блокам из одной строки можно однозначно восстановить оставшиеся два из той же строки, если они были утеряны. Естественно, операцию восстановления можно применять несколько раз к разным строкам и столбцам в любом порядке, а также в следующих операциях использовать блоки, восстановленные ранее.Пусть у вас есть 28 блоков (15 картинок и 13 избыточных кодов), и вы потеряли случайные k из них (равновероятно среди всех вариантов). Ваша задача посчитать вероятность, что хотя бы одну из 15 картинок будет невозможно восстановить, а также матожидание количества потерянных картинок.Входные данныеВ единственной строке входных данных записано целое число k (0 \le k \le 28) — количество потерянных блоков.Выходные данныеВыведите два числа — вероятность, что хотя бы одну картинку невозможно восстановить из оставшихся блоков, и матожидание количества картинок, которые невозможно восстановить из оставшихся блоков.Ответы будут считаться корректными, если их абсолютная или относительная погрешность не превосходит 10^{-9}.ПримерыВходные данные
28
Выходные данные
1.00000000000000000000 15.00000000000000000000
Входные данные
6
Выходные данные
0.00055741360089186175 0.00179168657429526999
ПримечаниеВ первом примере утеряны все 28 блоков, очевидно, с 100% вероятностью потеряны все 15 картинок.Во втором примере только в 210 случаев из 376740 будет невозможно восстановить хотя бы одну картинку, поэтому вероятность 210/376740. В зависимости от расположения утерянных блоков будет невозможно восстановить от 1 до 6 картинок, матожидание равно 15/8372.Приведены два возможных способа потерять 6 блоков.На первом случае утеряны 3 картинки и 3 избыточных кода (отмечены крестиками). Вначале мы можем восстановить один утерянный блок в первой строке (используя 5 других из этой же строки) и восстановить два утерянных блока в четвертой строке (используя 5 других из той же строки). Затем мы можем восстановить три оставшихся блока (используя 3 других блока из соответствующих столбцов). Заметим, что при восстановлении по столбцу мы использовали в том числе и восстановленные на первом шаге блоки. Таким образом, нам удалось восстановить все блоки и не было потеряно ни одной картинки.На втором случае утеряны 4 картинки и 2 избыточных кода. Во второй и третьей строках по три утерянных блока, а значит мы не можем однозначно восстановить ни один из блоков в них. Аналогично, в третьем, пятом и седьмом столбцах по два утерянных блока, а значит мы не можем однозначно восстановить ни один из блоков в них. В остальных строках и столбцах все блоки остались целыми, восстанавливать нечего. Таким образом, нам не удастся восстановить ни один из шести утерянных блоков, но только из четыре из них были картинками. | Входные данные
28
| Выходные данные 1.00000000000000000000 15.00000000000000000000 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
C. #define Задача B ...ограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводКомпания «ВКонтакте» активно использует языки C/C++ для разработки движков. Старший разработчик Вася — большой любитель языка C, ведь только в нем можно полностью раскрыть потенциал Define-Oriented Programming. В языке C директива #define позволяет сделать прямую подстановку куска кода в любое место программы. Например, при исполнении следующего кода значение переменной v будет равно 11 (в переменную v запишется результат выражения 3 + 4 \cdot 2).#define add(x) + x#define mul(y) * yint v = 3 add(4) mul(2);Недавно Вася написал небольшую программу, которая заполняет массив большой длины. Программа выглядит следующим образом:#define A0(x) x,#define A1(x) A0(x) A0(x + 1) A0(x + 3) A0(x + 4)#define A2(x) A1(x) A1(x + 1) A1(x + 3) A1(x + 4)#define A3(x) A2(x) A2(x + 1) A2(x + 3) A2(x + 4)#define A4(x) A3(x) A3(x + 1) A3(x + 3) A3(x + 4)...#define A24(x) A23(x) A23(x + 1) A23(x + 3) A23(x + 4)#define A25(x) A24(x) A24(x + 1) A24(x + 3) A24(x + 4)const long long values[1125899906842624] = { A25(0) };К сожалению, его программа не компилируется в силу несовершенства его компьютера, но ему очень интересно знать, какие значения лежали бы в массиве values, если бы ему удалось скомпилировать и запустить программу. Помогите ему это узнать.Входные данныеВ первой строке дано одно целое число n (1 \le n \le 1\,000) — количество элементов массива, значения которых интересуют Васю.Следующие n строк содержат n целых чисел pos_i (0 \le pos_i \le 1\,125\,899\,906\,842\,623) — позиции, для которых нужно узнать значение в массиве.Выходные данныеВыведите n строк. В i-й строке должно содержаться значение элемента массива на позиции pos_i.ПримерВходные данные
5
0
1
3
5
8
Выходные данные
0
1
4
2
3
ПримечаниеНачало этого массива выглядит следующим образом:const long long values[1125899906842624] = { 0, 1, 3, 4, 1, 2, 4, ... }; | Входные данные
5
0
1
3
5
8
| Выходные данные 0 1 4 2 3 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
B. Code Reviewограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводУ команды разработки движков ВКонтакте есть общий чат. После каждого сложного коммита в репозиторий, автор этого коммита присылает в чат сообщение с предложением провести ревью. Для одобрения или отклонения коммита достаточно, чтобы его проверил один разработчик, не принимавший участие в его написании.Перед тем, как оставить новую заявку на ревью, каждый разработчик проводит ревью последней из оставленных заявок, которые еще никем не проверены (если может — если он не является автором этой заявки) и только после этого оставляет новую заявку.Вам дан лог заявок на ревью с момента появления чата в хронологическом порядке. Найдите коммиты, которые никто не проверил.Входные данныеВ первой строке записано одно целое число n (1 ≤ n ≤ 50 000) — количество просьб о code review в чате.В следующих n строках записаны внутренний целочисленный идентификатор разработчика i и хеш коммита h (1 ≤ i ≤ 50 000; h состоит из строчных букв латинского алфавита от a до f и цифр). Все хеши коммитов уникальны и имеют длины от 1 до 20 символов, включительно.Выходные данныеВыведите все хеши коммитов, которые не попали на ревью, в том же порядке, в котором они были даны во входных данных.ПримерВходные данные
7
1 0e813c50
1 00e9422b
1 520cb7b4
2 052dd9ad
3 9dd5f347
3 e35f067b
1 bb4d4a99
Выходные данные
0e813c50
00e9422b
9dd5f347
bb4d4a99
| Входные данные
7
1 0e813c50
1 00e9422b
1 520cb7b4
2 052dd9ad
3 9dd5f347
3 e35f067b
1 bb4d4a99
| Выходные данные 0e813c50 00e9422b 9dd5f347 bb4d4a99 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
A. Скрытый другограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВам дан граф друзей VK. Недавно у пользователей появилась возможность скрывать друзей из социального графа. Для заданного графа друзей найдите скрытые дружеские связи, то есть такие ситуации, когда пользователь u находится в друзьях у пользователя v, но пользователь v не находится в друзьях у пользователя u.Входные данныеВ первой строке задано одно целое число n (2 \le n \le 100) — количество человек в графе друзей ВКонтакте. Пользователи пронумерованы целыми числами от 1 до n.В следующих n строках дан граф друзей каждого из этих людей: в i-й из этих строк сначала дано количество друзей у i-го человека и список номеров его друзей, разделенные пробелами. Номера друзей в каждой из n этих строк не повторяются.Выходные данныеВ первой строке выведите одно число k — количество скрытых дружеских связей.В следующих k строках выведите пары чисел u, v, означающие, что пользователь u скрыл пользователя v из друзей. Пары выводите в любом порядке.ПримерыВходные данные
5
3 2 3 4
4 1 3 4 5
0
2 1 2
3 4 3 1
Выходные данные
6
3 5
4 5
5 2
3 1
1 5
3 2
Входные данные
2
0
1 1
Выходные данные
1
1 2
| Входные данные
5
3 2 3 4
4 1 3 4 5
0
2 1 2
3 4 3 1
| Выходные данные 6 3 5 4 5 5 2 3 1 1 5 3 2 | ограничение по времени на тест2 секунды | ограничение по памяти на тест512 мегабайт | ['*special problem'] |
F. Two Bracket Sequencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two bracket sequences (not necessarily regular) s and t consisting only of characters '(' and ')'. You want to construct the shortest regular bracket sequence that contains both given bracket sequences as subsequences (not necessarily contiguous).Recall what is the regular bracket sequence: () is the regular bracket sequence; if S is the regular bracket sequence, then (S) is a regular bracket sequence; if S and T regular bracket sequences, then ST (concatenation of S and T) is a regular bracket sequence. Recall that the subsequence of the string s is such string t that can be obtained from s by removing some (possibly, zero) amount of characters. For example, "coder", "force", "cf" and "cores" are subsequences of "codeforces", but "fed" and "z" are not.InputThe first line of the input contains one bracket sequence s consisting of no more than 200 characters '(' and ')'.The second line of the input contains one bracket sequence t consisting of no more than 200 characters '(' and ')'.OutputPrint one line — the shortest regular bracket sequence that contains both given bracket sequences as subsequences (not necessarily contiguous). If there are several answers, you can print any.ExamplesInput
(())(()
()))()
Output
(())()()
Input
)
((
Output
(())
Input
)
)))
Output
((()))
Input
())
(()(()(()(
Output
(()()()(()()))
| (())(()
()))()
| (())()() | 2 seconds | 512 megabytes | ['dp', 'strings', 'two pointers', '*2200'] |
E. Nearest Opposite Paritytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 \le i - a_i) or to the position i + a_i (if i + a_i \le n).For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa).InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the i-th element of a.OutputPrint n integers d_1, d_2, \dots, d_n, where d_i is the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa) or -1 if it is impossible to reach such a position.ExampleInput
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
| 10
4 5 7 6 7 5 4 4 6 4
| 1 1 1 2 -1 1 1 3 1 1 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'shortest paths', '*1900'] |
D. Remove One Elementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray a with indices from l to r is a[l \dots r] = a_l, a_{l + 1}, \dots, a_r. The subarray a[l \dots r] is called strictly increasing if a_l < a_{l+1} < \dots < a_r.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the i-th element of a.OutputPrint one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.ExamplesInput
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
NoteIn the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | 5
1 2 5 3 4
| 4 | 2 seconds | 256 megabytes | ['brute force', 'dp', '*1500'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.