contest_id
int32
1
2.13k
index
stringclasses
62 values
problem_id
stringlengths
2
6
title
stringlengths
0
67
rating
int32
0
3.5k
tags
stringlengths
0
139
statement
stringlengths
0
6.96k
input_spec
stringlengths
0
2.32k
output_spec
stringlengths
0
1.52k
note
stringlengths
0
5.06k
sample_tests
stringlengths
0
1.02k
difficulty_category
stringclasses
6 values
tag_count
int8
0
11
statement_length
int32
0
6.96k
input_spec_length
int16
0
2.32k
output_spec_length
int16
0
1.52k
contest_year
int16
0
21
1,933
B
1933B
B. Turtle Math: Fast Three Task
800
implementation; math; number theory
You are given an array \(a_1, a_2, \ldots, a_n\).In one move, you can perform either of the following two operations: Choose an element from the array and remove it from the array. As a result, the length of the array decreases by \(1\); Choose an element from the array and increase its value by \(1\). You can perform any number of moves. If the current array becomes empty, then no more moves can be made.Your task is to find the minimum number of moves required to make the sum of the elements of the array \(a\) divisible by \(3\). It is possible that you may need \(0\) moves.Note that the sum of the elements of an empty array (an array of length \(0\)) is equal to \(0\).
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” 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 \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^4\)).The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single integer: the minimum number of moves.
In the first test case, initially the array \(a = [2, 2, 5, 4]\). One of the optimal ways to make moves is: remove the current \(4\)th element and get \(a = [2, 2, 5]\); As a result, the sum of the elements of the array \(a\) will be divisible by \(3\) (indeed, \(a_1 + a_2 + a_3 = 2 + 2 + 5 = 9\)).In the second test case, initially, the sum of the array is \(1+3+2 = 6\), which is divisible by \(3\). Therefore, no moves are required. Hence, the answer is \(0\).In the fourth test case, initially, the sum of the array is \(1\), which is not divisible by \(3\). By removing its only element, you will get an empty array, so its sum is \(0\). Hence, the answer is \(1\).
Input: 842 2 5 431 3 243 7 6 81142 2 4 225 572 4 8 1 9 3 424 10 | Output: 1 0 0 1 1 2 1 1
Beginner
3
679
377
73
19
1,902
D
1902D
D. Robot Queries
1,900
binary search; data structures; dp; implementation
There is an infinite \(2\)-dimensional grid. Initially, a robot stands in the point \((0, 0)\). The robot can execute four commands: U β€” move from point \((x, y)\) to \((x, y + 1)\); D β€” move from point \((x, y)\) to \((x, y - 1)\); L β€” move from point \((x, y)\) to \((x - 1, y)\); R β€” move from point \((x, y)\) to \((x + 1, y)\). You are given a sequence of commands \(s\) of length \(n\). Your task is to answer \(q\) independent queries: given four integers \(x\), \(y\), \(l\) and \(r\); determine whether the robot visits the point \((x, y)\), while executing a sequence \(s\), but the substring from \(l\) to \(r\) is reversed (i. e. the robot performs commands in order \(s_1 s_2 s_3 \dots s_{l-1} s_r s_{r-1} s_{r-2} \dots s_l s_{r+1} s_{r+2} \dots s_n\)).
The first line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 2 \cdot 10^5\)) β€” the length of the command sequence and the number of queries, respectively.The second line contains a string \(s\) of length \(n\), consisting of characters U, D, L and/or R.Then \(q\) lines follow, the \(i\)-th of them contains four integers \(x_i\), \(y_i\), \(l_i\) and \(r_i\) (\(-n \le x_i, y_i \le n\); \(1 \le l \le r \le n\)) describing the \(i\)-th query.
For each query, print YES if the robot visits the point \((x, y)\), while executing a sequence \(s\), but the substring from \(l\) to \(r\) is reversed; otherwise print NO.
In the first query of the first sample, the path of the robot looks as follows: In the second query of the first sample, the path of the robot looks as follows: In the third query of the first sample, the path of the robot looks as follows:
Input: 8 3RDLLUURU-1 2 1 70 0 3 40 1 7 8 | Output: YES YES NO
Hard
4
766
453
172
19
1,284
C
1284C
C. New Year and Permutation
1,600
combinatorics; math
Recall 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\).
The only line contains two integers \(n\) and \(m\) (\(1 \le n \le 250\,000\), \(10^8 \le m \le 10^9\), \(m\) is prime).
Print \(r\) (\(0 \le r < m\)), the sum of happiness for all permutations of length \(n\), modulo a prime number \(m\).
For 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\).
Input: 1 993244853 | Output: 1
Medium
2
1,730
120
118
12
825
G
825G
G. Tree Queries
2,500
dfs and similar; graphs; trees
You are given a tree consisting of n vertices (numbered from 1 to n). Initially all vertices are white. You have to process q queries of two different types: 1 x β€” change the color of vertex x to black. It is guaranteed that the first query will be of this type. 2 x β€” for the vertex x, find the minimum index y such that the vertex with index y belongs to the simple path from x to some black vertex (a simple path never visits any vertex more than once). For each query of type 2 print the answer to it.Note that the queries are given in modified way.
The first line contains two numbers n and q (3 ≀ n, q ≀ 106).Then n - 1 lines follow, each line containing two numbers xi and yi (1 ≀ xi < yi ≀ n) and representing the edge between vertices xi and yi.It is guaranteed that these edges form a tree.Then q lines follow. Each line contains two integers ti and zi, where ti is the type of ith query, and zi can be used to restore xi for this query in this way: you have to keep track of the answer to the last query of type 2 (let's call this answer last, and initially last = 0); then xi = (zi + last) mod n + 1.It is guaranteed that the first query is of type 1, and there is at least one query of type 2.
For each query of type 2 output the answer to it.
Input: 4 61 22 33 41 21 22 21 32 22 2 | Output: 321
Expert
3
553
652
49
8
1,673
E
1673E
E. Power or XOR?
2,500
bitmasks; combinatorics; math; number theory
The symbol \(\wedge\) is quite ambiguous, especially when used without context. Sometimes it is used to denote a power (\(a\wedge b = a^b\)) and sometimes it is used to denote the XOR operation (\(a\wedge b=a\oplus b\)). You have an ambiguous expression \(E=A_1\wedge A_2\wedge A_3\wedge\ldots\wedge A_n\). You can replace each \(\wedge\) symbol with either a \(\texttt{Power}\) operation or a \(\texttt{XOR}\) operation to get an unambiguous expression \(E'\).The value of this expression \(E'\) is determined according to the following rules: All \(\texttt{Power}\) operations are performed before any \(\texttt{XOR}\) operation. In other words, the \(\texttt{Power}\) operation takes precedence over \(\texttt{XOR}\) operation. For example, \(4\;\texttt{XOR}\;6\;\texttt{Power}\;2=4\oplus (6^2)=4\oplus 36=32\). Consecutive powers are calculated from left to right. For example, \(2\;\texttt{Power}\;3 \;\texttt{Power}\;4 = (2^3)^4 = 8^4 = 4096\). You are given an array \(B\) of length \(n\) and an integer \(k\). The array \(A\) is given by \(A_i=2^{B_i}\) and the expression \(E\) is given by \(E=A_1\wedge A_2\wedge A_3\wedge\ldots\wedge A_n\). You need to find the XOR of the values of all possible unambiguous expressions \(E'\) which can be obtained from \(E\) and has at least \(k\) \(\wedge\) symbols used as \(\texttt{XOR}\) operation. Since the answer can be very large, you need to find it modulo \(2^{2^{20}}\). Since this number can also be very large, you need to print its binary representation without leading zeroes. If the answer is equal to \(0\), print \(0\).
The first line of input contains two integers \(n\) and \(k\) \((1\leq n\leq 2^{20}, 0\leq k < n)\).The second line of input contains \(n\) integers \(B_1,B_2,\ldots,B_n\) \((1\leq B_i < 2^{20})\).
Print a single line containing a binary string without leading zeroes denoting the answer to the problem. If the answer is equal to \(0\), print \(0\).
For each of the testcases \(1\) to \(3\), \(A = \{2^3,2^1,2^2\} = \{8,2,4\}\) and \(E=8\wedge 2\wedge 4\).For the first testcase, there is only one possible valid unambiguous expression \(E' = 8\oplus 2\oplus 4 = 14 = (1110)_2\).For the second testcase, there are three possible valid unambiguous expressions \(E'\): \(8\oplus 2\oplus 4 = 14\) \(8^2\oplus 4 = 64\oplus 4= 68\) \(8\oplus 2^4 = 8\oplus 16= 24\) XOR of the values of all of these is \(14\oplus 68\oplus 24 = 82 = (1010010)_2\).For the third testcase, there are four possible valid unambiguous expressions \(E'\): \(8\oplus 2\oplus 4 = 14\) \(8^2\oplus 4 = 64\oplus 4= 68\) \(8\oplus 2^4 = 8\oplus 16= 24\) \((8^2)^4 = 64^4 = 2^{24} = 16777216\) XOR of the values of all of these is \(14\oplus 68\oplus 24\oplus 16777216 = 16777298 = (1000000000000000001010010)_2\).For the fourth testcase, \(A=\{2,2\}\) and \(E=2\wedge 2\). The only possible valid unambiguous expression \(E' = 2\oplus 2 = 0 = (0)_2\).
Input: 3 2 3 1 2 | Output: 1110
Expert
4
1,583
197
151
16
1,665
D
1665D
D. GCD Guess
2,000
bitmasks; chinese remainder theorem; constructive algorithms; games; interactive; math; number theory
This is an interactive problem.There is a positive integer \(1 \le x \le 10^9\) that you have to guess.In one query you can choose two positive integers \(a \neq b\). As an answer to this query you will get \(\gcd(x + a, x + b)\), where \(\gcd(n, m)\) is the greatest common divisor of the numbers \(n\) and \(m\).To guess one hidden number \(x\) you are allowed to make no more than \(30\) queries.
The first line of input contains a single integer \(t\) (\(1 \le t \le 1000\)) denoting the number of test cases.The integer \(x\) that you have to guess satisfies the constraints: (\(1 \le x \le 10^9\)).
The first hidden number is \(4\), that's why the answers for the queries are:""? 1 2"" β€” \(\gcd(4 + 1, 4 + 2) = \gcd(5, 6) = 1\).""? 12 4"" β€” \(\gcd(4 + 12, 4 + 4) = \gcd(16, 8) = 8\).The second hidden number is \(10^9\), that's why the answer for the query is:""? 2000000000 1999999999"" β€” \(\gcd(3 \cdot 10^9, 3 \cdot 10^9 - 1) = 1\).These queries are made only for understanding the interaction and are not enough for finding the true \(x\).
Input: 2 1 8 1 | Output: ? 1 2 ? 12 4 ! 4 ? 2000000000 1999999999 ! 1000000000
Hard
7
399
204
0
16
1,216
B
1216B
B. Shooting
900
greedy; implementation; sortings
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed \(n\) cans in a row on a table. Cans are numbered from left to right from \(1\) to \(n\). Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the \(i\)-th can is \(a_i\). It means that if Vasya has already knocked \(x\) cans down and is now about to start shooting the \(i\)-th one, he will need \((a_i \cdot x + 1)\) shots to knock it down. You can assume that if Vasya starts shooting the \(i\)-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the \(n\) given cans down exactly once is minimum possible.
The first line of the input contains one integer \(n\) \((2 \le n \le 1\,000)\) β€” the number of cans.The second line of the input contains the sequence \(a_1, a_2, \dots, a_n\) \((1 \le a_i \le 1\,000)\), where \(a_i\) is the durability of the \(i\)-th can.
In the first line print the minimum number of shots required to knock each of the \(n\) given cans down exactly once.In the second line print the sequence consisting of \(n\) distinct integers from \(1\) to \(n\) β€” the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.
In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots \(20 \cdot 1 + 1 = 21\) times. After that only second can remains. To knock it down Vasya shoots \(10 \cdot 2 + 1 = 21\) times. So the total number of shots is \(1 + 21 + 21 = 43\).In the second example the order of shooting does not matter because all cans have the same durability.
Input: 3 20 10 20 | Output: 43 1 3 2
Beginner
3
862
257
345
12
1,858
A
1858A
A. Buttons
800
games; greedy; math
Anna and Katie ended up in a secret laboratory.There are \(a+b+c\) buttons in the laboratory. It turned out that \(a\) buttons can only be pressed by Anna, \(b\) buttons can only be pressed by Katie, and \(c\) buttons can be pressed by either of them. Anna and Katie decided to play a game, taking turns pressing these buttons. Anna makes the first turn. Each button can be pressed at most once, so at some point, one of the girls will not be able to make her turn.The girl who cannot press a button loses. Determine who will win if both girls play optimally.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.Each test case consists of three integers \(a\), \(b\), and \(c\) (\(1 \le a, b, c \le 10^9\)) β€” the number of buttons that can only be pressed by Anna, the number of buttons that can only be pressed by Katie, and the number of buttons that can be pressed by either of them, respectively.
For each test case, output First if Anna wins, or Second if Katie wins.
For the simplicity of the explanation, we will numerate the buttons by the numbers from \(1\) to \(a+b+c\): the first \(a\) buttons can only be pressed by Anna, the next \(b\) buttons can only be pressed by Katie, and the last \(c\) buttons can be pressed by either of them.In the first test case, Anna can press the \(3\)-rd button on the first turn. Then Katie will press the \(2\)-nd button (since it is the only possible turn for her). Then Anna will press the \(1\)-st button. Katie won't have a button to press, so Anna will win.In the second test case, Anna can press the first nine buttons in some order on her turns. No matter what buttons Katie will press, all the buttons from the \(10\)-th to the \(15\)-th will be pressed after \(12\) turns. On the \(13\)-th turn, Anna will press one of the first nine buttons and Katie will not have a button to press on her turn. Thus, Anna will win.In the third test case, the game can proceed as follows: On the \(1\)-st turn Anna presses the \(5\)-th button. On the \(2\)-st turn Katie presses the \(4\)-th button. On the \(3\)-st turn Anna presses the \(6\)-th button. On the \(4\)-st turn Katie presses the \(3\)-th button. On the \(5\)-st turn Anna presses the \(1\)-th button. On the \(6\)-st turn Katie presses the \(2\)-th button. Anna cannot make the turn, so Katie wins. It can be shown that Katie can win no matter what moves Anna takes.
Input: 51 1 19 3 31 2 36 6 92 2 8 | Output: First First Second First Second
Beginner
3
559
385
71
18
803
E
803E
E. Roma and Poker
2,000
dp; graphs
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.Last evening Roma started to play poker. He decided to spend no more than k virtual bourles β€” he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k.Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost.The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: In the end the absolute difference between the number of wins and loses is equal to k; There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence.
The first line contains two numbers n (the length of Roma's sequence) and k (1 ≀ n, k ≀ 1000).The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence.
If there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO.Otherwise print this sequence. If there are multiple answers, print any of them.
Input: 3 2L?? | Output: LDL
Hard
2
1,353
222
191
8
592
C
592C
C. The Big Race
1,800
math
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L.Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today?
The first line of the input contains three integers t, w and b (1 ≀ t, w, b ≀ 5Β·1018) β€” the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively.
Print the answer to the problem as an irreducible fraction . Follow the format of the samples output.The fraction (p and q are integers, and both p β‰₯ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d.
In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
Input: 10 3 2 | Output: 3/10
Medium
1
1,345
208
264
5
1,585
E
1585E
E. Frequency Queries
2,400
data structures; dfs and similar; trees
Petya has a rooted tree with an integer written on each vertex. The vertex \(1\) is the root. You are to answer some questions about the tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node \(v\) is the next vertex on the shortest path from \(v\) to the root.Each question is defined by three integers \(v\), \(l\), and \(k\). To get the answer to the question, you need to perform the following steps: First, write down the sequence of all integers written on the shortest path from the vertex \(v\) to the root (including those written in the \(v\) and the root). Count the number of times each integer occurs. Remove all integers with less than \(l\) occurrences. Replace the sequence, removing all duplicates and ordering the elements by the number of occurrences in the original list in increasing order. In case of a tie, you can choose the order of these elements arbitrary. The answer to the question is the \(k\)-th number in the remaining sequence. Note that the answer is not always uniquely determined, because there could be several orderings. Also, it is possible that the length of the sequence on this step is less than \(k\), in this case the answer is \(-1\). For example, if the sequence of integers on the path from \(v\) to the root is \([2, 2, 1, 7, 1, 1, 4, 4, 4, 4]\), \(l = 2\) and \(k = 2\), then the answer is \(1\).Please answer all questions about the tree.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 10^6\)). Description of the test cases follows.The first line of each test case contains two integers \(n\), \(q\) (\(1 \leq n, q \leq 10^6\)) β€” the number of vertices in the tree and the number of questions.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq n\)), where \(a_i\) is the number written on the \(i\)-th vertex.The third line contains \(n-1\) integers \(p_2, p_3, \ldots, p_n\) (\(1 \leq p_i \leq n\)), where \(p_i\) is the parent of node \(i\). It's guaranteed that the values \(p\) define a correct tree.Each of the next \(q\) lines contains three integers \(v\), \(l\), \(k\) (\(1 \leq v, l, k \leq n\)) β€” descriptions of questions.It is guaranteed that the sum of \(n\) and the sum of \(q\) over all test cases do not exceed \(10^6\).
For each question of each test case print the answer to the question. In case of multiple answers, print any.
Input: 2 3 3 1 1 1 1 2 3 1 1 3 1 2 3 2 1 5 5 1 2 1 1 2 1 1 2 2 3 1 1 2 1 2 4 1 1 4 2 1 4 2 2 | Output: 1 -1 1 1 1 2 1 -1
Expert
3
1,455
897
109
15
1,209
E1
1209E1
E1. Rotate Columns (easy version)
2,000
bitmasks; brute force; dp; greedy; sortings
This is an easier version of the next problem. The difference is only in constraints.You are given a rectangular \(n \times m\) matrix \(a\). In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for \(i\)-th row it is equal \(r_i\). What is the maximal possible value of \(r_1+r_2+\ldots+r_n\)?
The first line contains an integer \(t\) (\(1 \le t \le 40\)), the number of test cases in the input.The first line of each test case contains integers \(n\) and \(m\) (\(1 \le n \le 4\), \(1 \le m \le 100\)) β€” the number of rows and the number of columns in the given matrix \(a\). Each of the following \(n\) lines contains \(m\) integers, the elements of \(a\) (\(1 \le a_{i, j} \le 10^5\)).
Print \(t\) integers: answers for all test cases in the order they are given in the input.
In the first test case, you can shift the third column down by one, this way there will be \(r_1 = 5\) and \(r_2 = 7\).In the second case you can don't rotate anything at all, this way there will be \(r_1 = r_2 = 10\) and \(r_3 = 9\).
Input: 2 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 | Output: 12 29
Hard
5
562
394
90
12
1,906
C
1906C
C. Cursed Game
3,000
interactive
You found an antique box in your warehouse and decided to open it. The moment you open the box, it traps you into a cursed game where you are playing against a demon. The game consists of \(333\) rounds and you have to win all rounds in order to escape. The demon also gives you \(999\) coins that you can use throughout all rounds.Note that in this problem, denote cell \((r, c)\) of a grid as the cell in row \(r\) and column \(c\) of the grid.Before the start of each round, the demon will prepare a secret paper, which can be represented as a grid with \(3\) rows and \(3\) columns, both numbered from \(1\) to \(3\). The demon will secretly put a hole in one or more cells, and you are not aware which cells have a hole in it. Then, the round starts with the demon giving you an odd integer \(N\) (\(3 \leq N \leq 33\)).Within each round, you can ask the demon several queries, each costing you one coin. For each query, you are allowed to give the demon your paper, which can be represented as a grid with \(N\) rows and \(N\) columns, both numbered from \(1\) to \(N\). Each cell is coloured either black or white by you.For each of your query, the demon will calculate a binary result grid with \(N - 2\) rows and \(N - 2\) columns, both numbered from \(1\) to \(N - 2\). The value on cell \((r, c)\) of the result grid is filled as follows. The demon will put the secret paper on top of your paper such that the cell \((r + i - 1, c + j - 1)\) of your paper aligns with the cell \((i, j)\) of the secret paper, for \(1 \leq i, j \leq 3\). The demon can only see the colour of the cell in your paper if the corresponding cell in the secret paper has a hole in it. The value on cell \((r, c)\) of the result grid is \(1\) if there is an odd number of black cells that it can see through the holes, or \(0\) otherwise. You win the round if the result grid consists of only the values \(1\). Otherwise, the demon will give you the result grid as a feedback, and the round continues.If you have spent all the coins and still did not win all the rounds, then you will be trapped forever. Escape the cursed game!
Sample Interaction #1The following interaction only shows \(2\) rounds. The actual interaction stays until you win all \(333\) rounds or you run out of coins. Explanation for the sample interaction #1For the first round, the following illustration shows how the demon finds the value in cell \((1, 1)\) of the result grid for the first and second queries. The grey-colored square represents the secret paper, and the circles represent the holes. In the first query, there are \(4\) black cells that can be seen through the holes, therefore the value in cell \((1, 1)\) of the result grid is \(0\). In the second query, there are \(5\) black cells that can be seen through the holes, therefore the value in cell \((1, 1)\) of the result grid is \(1\). As the result grid consists of only 1, the first round ends. For the second round, the following illustration shows how the demon find the value in cell \((2, 1)\) of the result grid for the first query. Since there are \(2\) black cells that can be seen through the holes, the value in cell \((2, 1)\) is \(0\).
Master
1
2,114
0
0
19
681
E
681E
E. Runaway to a Shadow
2,500
geometry; sortings
Dima is living in a dormitory, as well as some cockroaches.At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly T seconds for aiming, and after that he will precisely strike the cockroach and finish it.To survive the cockroach has to run into a shadow, cast by round plates standing on the table, in T seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed v. If at some moment t ≀ T it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.Determine the probability of that the cockroach will stay alive.
In the first line of the input the four integers x0, y0, v, T (|x0|, |y0| ≀ 109, 0 ≀ v, T ≀ 109) are given β€” the cockroach initial position on the table in the Cartesian system at the moment 0, the cockroach's constant speed and the time in seconds Dima needs for aiming respectively.In the next line the only number n (1 ≀ n ≀ 100 000) is given β€” the number of shadow circles casted by plates.In the next n lines shadow circle description is given: the ith of them consists of three integers xi, yi, ri (|xi|, |yi| ≀ 109, 0 ≀ r ≀ 109) β€” the ith shadow circle on-table position in the Cartesian system and its radius respectively.Consider that the table is big enough for the cockroach not to run to the table edges and avoid Dima's precise strike.
Print the only real number p β€” the probability of that the cockroach will stay alive.Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.
The picture for the first sample is given below. Red color stands for points which being chosen as the cockroach's running direction will cause him being killed, green color for those standing for survival directions. Please note that despite containing a circle centered in ( - 2, 2) a part of zone is colored red because the cockroach is not able to reach it in one second.
Input: 0 0 1 131 1 1-1 -1 1-2 2 1 | Output: 0.50000000000
Expert
2
921
748
181
6
936
C
936C
C. Lock Puzzle
2,300
constructive algorithms; implementation; strings
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.The string on the screen can be changed using the operation Β«shift xΒ». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = Ξ±Ξ² changes to Ξ²RΞ±, where the length of Ξ² is x, and the length of Ξ± is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation Β«shift 4Β» the string Β«abcacbΒ» will be changed with string Β«bcacab Β», since Ξ± = ab, Ξ² = cacb, Ξ²R = bcac.Explorers are afraid that if they apply too many operations Β«shiftΒ», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
The first line contains an integer n, the length of the strings s and t (1 ≀ n ≀ 2 000).After that, there are two strings s and t, consisting of n lowercase Latin letters each.
If it is impossible to get string t from string s using no more than 6100 operations Β«shiftΒ», print a single number - 1.Otherwise, in the first line output the number of operations k (0 ≀ k ≀ 6100). In the next line output k numbers xi corresponding to the operations Β«shift xiΒ» (0 ≀ xi ≀ n) in the order in which they should be applied.
Input: 6abacbbbabcba | Output: 46 3 2 3
Expert
3
1,241
176
337
9
793
D
793D
D. Presents in Bankopolis
2,100
dp; graphs; shortest paths
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
The first line contains two integers n and k (1 ≀ n, k ≀ 80) β€” the number of crossroads (and offices) and the number of offices Oleg wants to visit.The second line contains single integer m (0 ≀ m ≀ 2000) β€” the number of bicycle lanes in Bankopolis.The next m lines contain information about the lanes.The i-th of these lines contains three integers ui, vi and ci (1 ≀ ui, vi ≀ n, 1 ≀ ci ≀ 1000), denoting the crossroads connected by the i-th road and its difficulty.
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
In the first example Oleg visiting banks by path 1 β†’ 6 β†’ 2 β†’ 4.Path 1 β†’ 6 β†’ 2 β†’ 7 with smaller difficulity is incorrect because crossroad 2 β†’ 7 passes near already visited office on the crossroad 6.In the second example Oleg can visit banks by path 4 β†’ 1 β†’ 3.
Input: 7 441 6 26 2 22 4 22 7 1 | Output: 6
Hard
3
1,175
467
125
7
1,082
E
1082E
E. Increasing Frequency
2,000
binary search; dp; greedy
You are given array \(a\) of length \(n\). You can choose one segment \([l, r]\) (\(1 \le l \le r \le n\)) and integer value \(k\) (positive, negative or even zero) and change \(a_l, a_{l + 1}, \dots, a_r\) by \(k\) each (i.e. \(a_i := a_i + k\) for each \(l \le i \le r\)).What is the maximum possible number of elements with value \(c\) that can be obtained after one such operation?
The first line contains two integers \(n\) and \(c\) (\(1 \le n \le 5 \cdot 10^5\), \(1 \le c \le 5 \cdot 10^5\)) β€” the length of array and the value \(c\) to obtain.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 5 \cdot 10^5\)) β€” array \(a\).
Print one integer β€” the maximum possible number of elements with value \(c\) which can be obtained after performing operation described above.
In the first example we can choose any segment and \(k = 0\). The array will stay same.In the second example we can choose segment \([1, 3]\) and \(k = -4\). The array will become \([2, -2, 2]\).
Input: 6 9 9 9 9 9 9 9 | Output: 6
Hard
3
385
278
142
10
45
H
45H
H. Road Problem
2,100
graphs
The Berland capital (as you very well know) contains n junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions. The city administration noticed that in the cities of all the developed countries between any two roads one can drive along at least two paths so that the paths don't share any roads (but they may share the same junction). The administration decided to add the minimal number of roads so that this rules was fulfilled in the Berland capital as well. In the city road network should exist no more than one road between every pair of junctions before or after the reform.
The first input line contains a pair of integers n, m (2 ≀ n ≀ 900, 1 ≀ m ≀ 100000), where n is the number of junctions and m is the number of roads. Each of the following m lines contains a description of a road that is given by the numbers of the connected junctions ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). The junctions are numbered from 1 to n. It is possible to reach any junction of the city from any other one moving along roads.
On the first line print t β€” the number of added roads. Then on t lines print the descriptions of the added roads in the format of the input data. You can use any order of printing the roads themselves as well as the junctions linked by every road. If there are several solutions to that problem, print any of them.If the capital doesn't need the reform, print the single number 0.If there's no solution, print the single number -1.
Input: 4 31 22 33 4 | Output: 11 4
Hard
1
767
430
431
0
32
B
32B
B. Borze
800
expression parsing; implementation
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes).
Output the decoded ternary number. It can have leading zeroes.
Input: .-.-- | Output: 012
Beginner
2
283
227
62
0
1,056
G
1056G
G. Take Metro
2,900
brute force; data structures; graphs
Having problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city.Unfortunately for Arkady, the line is circular. It means that the stations are enumerated from \(1\) to \(n\) and there is a tunnel between any pair of consecutive stations as well as between the station \(1\) and the station \(n\). Trains that go in clockwise direction visit the stations in order \(1 \to 2 \to 3 \to \ldots \to n \to 1\) while the trains that go in the counter-clockwise direction visit the stations in the reverse order.The stations that have numbers from \(1\) to \(m\) have interior mostly in red colors while the stations that have numbers from \(m + 1\) to \(n\) have blue interior. Arkady entered the metro at station \(s\) and decided to use the following algorithm to choose his way home. Initially he has a positive integer \(t\) in his mind. If the current station has red interior, he takes a clockwise-directed train, otherwise he takes a counter-clockwise-directed train. He rides exactly \(t\) stations on the train and leaves the train. He decreases \(t\) by one. If \(t\) is still positive, he returns to step \(2\). Otherwise he exits the metro. You have already realized that this algorithm most probably won't bring Arkady home. Find the station he will exit the metro at so that you can continue helping him.
The first line contains two integers \(n\) and \(m\) (\(3 \le n \le 10^5\), \(1 \le m < n\)) β€” the total number of stations and the number of stations that have red interior.The second line contains two integers \(s\) and \(t\) (\(1 \le s \le n\), \(1 \le t \le 10^{12}\)) β€” the starting station and the initial value of \(t\).
Output the only integer β€” the station where Arkady will exit the metro.
Consider the first example. There are \(10\) stations and the first \(4\) of them are red. Arkady starts at station \(3\) with value \(t = 1\), so just rides \(1\) station in clockwise direction and ends up on the station \(4\).In the second example the metro is same as in the first example, but Arkady starts at station \(3\) with value \(t = 5\). It is a red station so he rides \(5\) stations in clockwise direction and leaves the train at station \(8\). It is a blue station, so he rides \(4\) stations in counter-clockwise direction and leaves at station \(4\). It is a red station, so he rides \(3\) stations in clockwise direction and leaves at station \(7\). It is a blue station, so he rides \(2\) stations in counter-clockwise direction and leaves at station \(5\). It is a blue station, so he rides \(1\) station in counter-clockwise direction and leaves at station \(4\). Now \(t = 0\), so Arkady exits metro at the station \(4\).
Input: 10 4 3 1 | Output: 4
Master
3
1,401
327
71
10
161
A
161A
A. Dress'em in Vests!
1,300
binary search; brute force; greedy; two pointers
The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai - x to ai + y, inclusive (numbers x, y β‰₯ 0 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai - x ≀ bj ≀ ai + y.
The first input line contains four integers n, m, x and y (1 ≀ n, m ≀ 105, 0 ≀ x, y ≀ 109) β€” the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) in non-decreasing order, separated by single spaces β€” the desired sizes of vests. The third line contains m integers b1, b2, ..., bm (1 ≀ bj ≀ 109) in non-decreasing order, separated by single spaces β€” the sizes of the available vests.
In the first line print a single integer k β€” the maximum number of soldiers equipped with bulletproof vests. In the next k lines print k pairs, one pair per line, as ""ui vi"" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order.If there are multiple optimal answers, you are allowed to print any of them.
In the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped.
Input: 5 3 0 01 2 3 3 41 3 5 | Output: 21 13 2
Easy
4
897
517
621
1
1,968
E
1968E
E. Cells Arrangement
1,600
constructive algorithms
You are given an integer \(n\). You choose \(n\) cells \((x_1,y_1), (x_2,y_2),\dots,(x_n,y_n)\) in the grid \(n\times n\) where \(1\le x_i\le n\) and \(1\le y_i\le n\).Let \(\mathcal{H}\) be the set of distinct Manhattan distances between any pair of cells. Your task is to maximize the size of \(\mathcal{H}\). Examples of sets and their construction are given in the notes.If there exists more than one solution, you are allowed to output any.Manhattan distance between cells \((x_1,y_1)\) and \((x_2,y_2)\) equals \(|x_1-x_2|+|y_1-y_2|\).
The first line contains a single integer \(t\) (\(1\le t\le 50\)) β€” the number of test cases.Each of the following \(t\) lines contains a single integer \(n\) (\(2\le n\le 10^3\)).
For each test case, output \(n\) points which maximize the size of \(\mathcal{H}\). It is not necessary to output an empty line at the end of the answer for each test case.
In the first testcase we have \(n=2\). One of the possible arrangements is: The arrangement with cells located in \((1,1)\) and \((1,2)\). In this case \(\mathcal{H}=\{|1-1|+|1-1|,|1-1|+|2-2|,|1-1|+|1-2|\}=\{0,0,1\}=\{0,1\}\). Hence, the size of \(\mathcal{H}\) is \(2\). It can be shown that it is the greatest possible answer.In the second testcase we have \(n=3\). The optimal arrangement is: The arrangement with cells located in \((2,1)\), \((2,3)\) and \((3,1)\). \(\mathcal{H}\)=\(\{|2-2|+|1-1|,|2-2|+|3-3|,|3-3|+|1-1|,|2-2|+|1-3|,|2-3|+|1-1|,|2-3|+|3-1|\}\)=\(\{0,0,0,2,1,3\}\)=\(\{0,1,2,3\}\).For \(n=4\) a possible arrangement is: For \(n=5\) a possible arrangement is: For \(n=6\) a possible arrangement is:
Input: 523456 | Output: 1 1 1 2 2 1 2 3 3 1 1 1 1 3 4 3 4 4 1 1 1 3 1 4 2 1 5 5 1 4 1 5 1 6 5 2 5 5 6 1
Medium
1
541
180
172
19
1,315
A
1315A
A. Dead Pixel
800
implementation
Screen resolution of Polycarp's monitor is \(a \times b\) pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates \((x, y)\) (\(0 \le x < a, 0 \le y < b\)). You can consider columns of pixels to be numbered from \(0\) to \(a-1\), and rows β€” from \(0\) to \(b-1\).Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.
In the first line you are given an integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases in the test. In the next lines you are given descriptions of \(t\) test cases.Each test case contains a single line which consists of \(4\) integers \(a, b, x\) and \(y\) (\(1 \le a, b \le 10^4\); \(0 \le x < a\); \(0 \le y < b\)) β€” the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that \(a+b>2\) (e.g. \(a=b=1\) is impossible).
Print \(t\) integers β€” the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.
In the first test case, the screen resolution is \(8 \times 8\), and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
Input: 6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 | Output: 56 6 442 1 45 80
Beginner
1
559
461
201
13
1,710
A
1710A
A. Color the Picture
1,500
constructive algorithms; greedy; math
A picture can be represented as an \(n\times m\) grid (\(n\) rows and \(m\) columns) so that each of the \(n \cdot m\) cells is colored with one color. You have \(k\) pigments of different colors. You have a limited amount of each pigment, more precisely you can color at most \(a_i\) cells with the \(i\)-th pigment.A picture is considered beautiful if each cell has at least \(3\) toroidal neighbors with the same color as itself.Two cells are considered toroidal neighbors if they toroidally share an edge. In other words, for some integers \(1 \leq x_1,x_2 \leq n\) and \(1 \leq y_1,y_2 \leq m\), the cell in the \(x_1\)-th row and \(y_1\)-th column is a toroidal neighbor of the cell in the \(x_2\)-th row and \(y_2\)-th column if one of following two conditions holds: \(x_1-x_2 \equiv \pm1 \pmod{n}\) and \(y_1=y_2\), or \(y_1-y_2 \equiv \pm1 \pmod{m}\) and \(x_1=x_2\). Notice that each cell has exactly \(4\) toroidal neighbors. For example, if \(n=3\) and \(m=4\), the toroidal neighbors of the cell \((1, 2)\) (the cell on the first row and second column) are: \((3, 2)\), \((2, 2)\), \((1, 3)\), \((1, 1)\). They are shown in gray on the image below: The gray cells show toroidal neighbors of \((1, 2)\). Is it possible to color all cells with the pigments provided and create a beautiful picture?
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 10^4\)). The description of the test cases follows.The first line of each test case contains three integers \(n\), \(m\), and \(k\) (\(3 \leq n,m \leq 10^9\), \(1 \leq k \leq 10^5\)) β€” the number of rows and columns of the picture and the number of pigments.The next line contains \(k\) integers \(a_1,a_2,\dots, a_k\) (\(1 \leq a_i \leq 10^9\)) β€” \(a_i\) is the maximum number of cells that can be colored with the \(i\)-th pigment.It is guaranteed that the sum of \(k\) over all test cases does not exceed \(10^5\).
For each test case, print ""Yes"" (without quotes) if it is possible to color a beautiful picture. Otherwise, print ""No"" (without quotes).
In the first test case, one possible solution is as follows: In the third test case, we can color all cells with pigment \(1\).
Input: 64 6 312 9 83 3 28 83 3 29 54 5 210 115 4 29 1110 10 311 45 14 | Output: Yes No Yes Yes No No
Medium
3
1,309
629
140
17
1,208
E
1208E
E. Let Them Slide
2,200
data structures; implementation
You are given \(n\) arrays that can have different sizes. You also have a table with \(w\) columns and \(n\) rows. The \(i\)-th array is placed horizontally in the \(i\)-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.You need to find the maximum sum of the integers in the \(j\)-th column for each \(j\) from \(1\) to \(w\) independently. Optimal placements for columns \(1\), \(2\) and \(3\) are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.
The first line contains two integers \(n\) (\(1 \le n \le 10^{6}\)) and \(w\) (\(1 \le w \le 10^{6}\)) β€” the number of arrays and the width of the table.Each of the next \(n\) lines consists of an integer \(l_{i}\) (\(1 \le l_{i} \le w\)), the length of the \(i\)-th array, followed by \(l_{i}\) integers \(a_{i1}, a_{i2}, \ldots, a_{il_i}\) (\(-10^{9} \le a_{ij} \le 10^{9}\)) β€” the elements of the array.The total length of the arrays does no exceed \(10^{6}\).
Print \(w\) integers, the \(i\)-th of them should be the maximum sum for column \(i\).
Illustration for the first example is in the statement.
Input: 3 3 3 2 4 8 2 2 5 2 6 3 | Output: 10 15 16
Hard
2
661
463
86
12
1,278
A
1278A
A. Shuffle Hashing
1,000
brute force; implementation; strings
Polycarp 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.
The 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\).
For 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.
The 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.
Input: 5 abacaba zyxaabcaabkjh onetwothree threetwoone one zzonneyy one none twenty ten | Output: YES YES NO YES NO
Beginner
3
1,115
394
144
12
1,474
F
1474F
F. 1 2 3 4 ...
3,000
dp; math; matrices
Igor had a sequence \(d_1, d_2, \dots, d_n\) of integers. When Igor entered the classroom there was an integer \(x\) written on the blackboard.Igor generated sequence \(p\) using the following algorithm: initially, \(p = [x]\); for each \(1 \leq i \leq n\) he did the following operation \(|d_i|\) times: if \(d_i \geq 0\), then he looked at the last element of \(p\) (let it be \(y\)) and appended \(y + 1\) to the end of \(p\); if \(d_i < 0\), then he looked at the last element of \(p\) (let it be \(y\)) and appended \(y - 1\) to the end of \(p\). For example, if \(x = 3\), and \(d = [1, -1, 2]\), \(p\) will be equal \([3, 4, 3, 4, 5]\).Igor decided to calculate the length of the longest increasing subsequence of \(p\) and the number of them.A sequence \(a\) is a subsequence of a sequence \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) elements.A sequence \(a\) is an increasing sequence if each element of \(a\) (except the first one) is strictly greater than the previous element.For \(p = [3, 4, 3, 4, 5]\), the length of longest increasing subsequence is \(3\) and there are \(3\) of them: \([\underline{3}, \underline{4}, 3, 4, \underline{5}]\), \([\underline{3}, 4, 3, \underline{4}, \underline{5}]\), \([3, 4, \underline{3}, \underline{4}, \underline{5}]\).
The first line contains a single integer \(n\) (\(1 \leq n \leq 50\)) β€” the length of the sequence \(d\).The second line contains a single integer \(x\) (\(-10^9 \leq x \leq 10^9\)) β€” the integer on the blackboard.The third line contains \(n\) integers \(d_1, d_2, \ldots, d_n\) (\(-10^9 \leq d_i \leq 10^9\)).
Print two integers: the first integer should be equal to the length of the longest increasing subsequence of \(p\); the second should be equal to the number of them modulo \(998244353\). You should print only the second number modulo \(998244353\).
The first test case was explained in the statement.In the second test case \(p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108]\).In the third test case \(p = [1, 2, \ldots, 2000000000]\).
Input: 3 3 1 -1 2 | Output: 3 3
Master
3
1,315
310
248
14
1,176
B
1176B
B. Merge it!
1,100
math
You are given an array \(a\) consisting of \(n\) integers \(a_1, a_2, \dots , a_n\).In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array \([2, 1, 4]\) you can obtain the following arrays: \([3, 4]\), \([1, 6]\) and \([2, 5]\).Your task is to find the maximum possible number of elements divisible by \(3\) that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer \(t\) independent queries.
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) β€” the number of queries.The first line of each query contains one integer \(n\) (\(1 \le n \le 100\)).The second line of each query contains \(n\) integers \(a_1, a_2, \dots , a_n\) (\(1 \le a_i \le 10^9\)).
For each query print one integer in a single line β€” the maximum possible number of elements divisible by \(3\) that are in the array after performing described operation an arbitrary (possibly, zero) number of times.
In the first query of the example you can apply the following sequence of operations to obtain \(3\) elements divisible by \(3\): \([3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]\).In the second query you can obtain \(3\) elements divisible by \(3\) with the following sequence of operations: \([1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]\).
Input: 2 5 3 1 2 3 1 7 1 1 1 1 1 2 2 | Output: 3 3
Easy
1
592
272
216
11
792
D
792D
D. Paths in a Complete Binary Tree
1,900
bitmasks; trees
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2.In the picture you can see a complete binary tree with n = 15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1 ≀ ui ≀ n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui = 4 and si = Β«UURLΒ», then the answer is 10.
The first line contains two integer numbers n and q (1 ≀ n ≀ 1018, q β‰₯ 1). n is such that n + 1 is a power of 2.The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1 ≀ ui ≀ n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'.It is guaranteed that the sum of lengths of si (for each i such that 1 ≀ i ≀ q) doesn't exceed 105.
Print q numbers, i-th number must be the answer to the i-th query.
Input: 15 24UURL8LRLLLLLLLL | Output: 105
Hard
2
1,693
452
66
7
1,628
D1
1628D1
D1. Game on Sum (Easy Version)
2,100
combinatorics; dp; games; math
This is the easy version of the problem. The difference is the constraints on \(n\), \(m\) and \(t\). You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers \(n\), \(m\) and \(k\), and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially \(0\). The game consists of \(n\) turns. Each turn, Alice picks a real number from \(0\) to \(k\) (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least \(m\) out of the \(n\) turns.Bob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).If Alice and Bob play optimally, what will the final score of the game be?
The first line of the input contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases. The description of test cases follows.Each test case consists of a single line containing the three integers, \(n\), \(m\), and \(k\) (\(1 \le m \le n \le 2000, 0 \le k < 10^9 + 7\)) β€” the number of turns, how many of those turns Bob has to add, and the biggest number Alice can choose, respectively.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\).
For each test case output a single integer number β€” the score of the optimal game modulo \(10^9 + 7\).Formally, let \(M = 10^9 + 7\). It can be shown that the answer can be expressed as an irreducible fraction \(\frac{p}{q}\), where \(p\) and \(q\) are integers and \(q \not \equiv 0 \pmod{M}\). Output the integer equal to \(p \cdot q^{-1} \bmod M\). In other words, output such an integer \(x\) that \(0 \le x < M\) and \(x \cdot q \equiv p \pmod{M}\).
In the first test case, the entire game has \(3\) turns, and since \(m = 3\), Bob has to add in each of them. Therefore Alice should pick the biggest number she can, which is \(k = 2\), every turn.In the third test case, Alice has a strategy to guarantee a score of \(\frac{75}{8} \equiv 375000012 \pmod{10^9 + 7}\).In the fourth test case, Alice has a strategy to guarantee a score of \(\frac{45}{2} \equiv 500000026 \pmod{10^9 + 7}\).
Input: 73 3 22 1 106 3 106 4 10100 1 14 4 069 4 20 | Output: 6 5 375000012 500000026 958557139 0 49735962
Hard
4
1,002
495
454
16
418
D
418D
D. Big Problems for Organizers
2,800
data structures; graphs; trees
The Finals of the ""Russian Code Cup"" 2214 will be held in n hotels. Two hotels (let's assume that they are the main hotels), will host all sorts of events, and the remaining hotels will accommodate the participants. The hotels are connected by n - 1 roads, you can get from any hotel to any other one.The organizers wonder what is the minimum time all the participants need to get to the main hotels, if each participant goes to the main hotel that is nearest to him and moving between two hotels connected by a road takes one unit of time.The hosts consider various options for the location of the main hotels. For each option help the organizers to find minimal time.
The first line contains an integer n (2 ≀ n ≀ 100000) β€” the number of hotels. The next n - 1 lines contain two integers each β€” the numbers of the hotels that have a road between them. Consider hotels are numbered from 1 to n.The next line contains an integer m (1 ≀ m ≀ 100000) β€” the number of queries. The following m lines contains two distinct integers each β€” the numbers of the hotels we assume to be the main.
For each request of the organizers print a single integer β€” the time that all participants need to reach the main hotels.
Input: 32 33 132 12 33 1 | Output: 111
Master
3
671
414
121
4
1,805
D
1805D
D. A Wide, Wide Graph
1,800
dfs and similar; dp; graphs; greedy; trees
You are given a tree (a connected graph without cycles) with \(n\) vertices. Consider a fixed integer \(k\). Then, the graph \(G_k\) is an undirected graph with \(n\) vertices, where an edge between vertices \(u\) and \(v\) exists if and only if the distance between vertices \(u\) and \(v\) in the given tree is at least \(k\).For each \(k\) from \(1\) to \(n\), print the number of connected components in the graph \(G_k\).
The first line contains the integer \(n\) (\(2 \le n \le 10^5\)) β€” the number of vertices in the graph.Each of the next \(n-1\) lines contains two integers \(u\) and \(v\) (\(1 \le u, v \le n\)), denoting an edge between vertices \(u\) and \(v\) in the tree. It is guaranteed that these edges form a valid tree.
Output \(n\) integers: the number of connected components in the graph \(G_k\) for each \(k\) from \(1\) to \(n\).
In the first example: If \(k=1\), the graph has an edge between each pair of vertices, so it has one component. If \(k=4\), the graph has only edges \(4 \leftrightarrow 6\) and \(5 \leftrightarrow 6\), so the graph has \(4\) components.In the second example: when \(k=1\) or \(k=2\) the graph has one component. When \(k=3\) the graph \(G_k\) splits into \(3\) components: one component has vertices \(1\), \(4\) and \(5\), and two more components contain one vertex each. When \(k=4\) or \(k=5\) each vertex is a separate component.
Input: 6 1 2 1 3 2 4 2 5 3 6 | Output: 1 1 2 4 6 6
Medium
5
426
311
114
18
446
A
446A
A. DZY Loves Sequences
1,600
dp; implementation; two pointers
DZY has a sequence a, consisting of n integers.We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.
The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109).
In a single line print the answer to the problem β€” the maximum length of the required subsegment.
You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
Input: 67 2 3 1 5 6 | Output: 5
Medium
3
469
114
97
4
64
B
64B
B. Expression
1,500
*special; expression parsing
You are given a line Β«n#mΒ», where Β«nΒ» and Β«mΒ» are digits, and Β«#Β» is a sign Β«+Β» or Β«-Β». Print the value of the given expression.
The only given line has a string in form Β«n#mΒ», where Β«nΒ» and Β«mΒ» are digits (from 0 to 9), and Β«#Β» is a sign Β«+Β» or Β«-Β».
Print the value of the given expression.
Input: 1-5 | Output: -4
Medium
2
128
121
40
0
1,913
B
1913B
B. Swap and Delete
1,000
strings
You are given a binary string \(s\) (a string consisting only of 0-s and 1-s).You can perform two types of operations on \(s\): delete one character from \(s\). This operation costs \(1\) coin; swap any pair of characters in \(s\). This operation is free (costs \(0\) coins). You can perform these operations any number of times and in any order.Let's name a string you've got after performing operations above as \(t\). The string \(t\) is good if for each \(i\) from \(1\) to \(|t|\) \(t_i \neq s_i\) (\(|t|\) is the length of the string \(t\)). The empty string is always good. Note that you are comparing the resulting string \(t\) with the initial string \(s\).What is the minimum total cost to make the string \(t\) good?
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.The only line of each test case contains a binary string \(s\) (\(1 \le |s| \le 2 \cdot 10^5\); \(s_i \in \{\)0, 1\(\}\)) β€” the initial string, consisting of characters 0 and/or 1.Additional constraint on the input: the total length of all strings \(s\) doesn't exceed \(2 \cdot 10^5\).
For each test case, print one integer β€” the minimum total cost to make string \(t\) good.
In the first test case, you have to delete a character from \(s\) to get the empty string \(t\). Only then \(t\) becomes good. One deletion costs \(1\) coin.In the second test case, you can, for example, delete the second character from \(s\) to get the string 01, and then swap the first and second characters to get the string \(t\) \(=\) 10. String \(t\) is good, since \(t_1 \neq s_1\) and \(t_2 \neq s_2\). The total cost is \(1\) coin.In the third test case, you can, for example, swap \(s_1\) with \(s_2\), swap \(s_3\) with \(s_4\), swap \(s_5\) with \(s_7\), \(s_6\) with \(s_8\) and \(s_9\) with \(s_{10}\). You'll get \(t\) \(=\) 1010001110. All swap operations are free, so the total cost is \(0\).
Input: 400110101110001111100 | Output: 1 1 0 4
Beginner
1
727
413
89
19
2,050
D
2050D
D. Digital string maximization
1,300
brute force; greedy; math; strings
You are given a string \(s\), consisting of digits from \(0\) to \(9\). In one operation, you can pick any digit in this string, except for \(0\) or the leftmost digit, decrease it by \(1\), and then swap it with the digit left to the picked.For example, in one operation from the string \(1023\), you can get \(1103\) or \(1022\).Find the lexicographically maximum string you can obtain after any number of operations.
The first line of the input consists of an integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.Each test case consists of a single line consisting of a digital string \(s\) (\(1 \le |s| \le 2\cdot 10^5\)), where \(|s|\) denotes the length of \(s\). The string does not contain leading zeroes.It is guaranteed that the sum of \(|s|\) of all test cases doesn't exceed \(2\cdot 10^5\).
For each test case, print the answer on a separate line.
In the first example, the following sequence of operations is suitable: \(19 \rightarrow 81\).In the second example, the following sequence of operations is suitable: \(1709 \rightarrow 1780 \rightarrow 6180 \rightarrow 6710\).In the fourth example, the following sequence of operations is suitable: \(51476 \rightarrow 53176 \rightarrow 53616 \rightarrow 53651 \rightarrow 55351 \rightarrow 55431\).
Input: 6191709115555147698765432105891917899 | Output: 81 6710 33311 55431 9876543210 7875567711
Easy
4
419
394
56
20
1,357
E1
1357E1
E1. Power of quantum Fourier transform
0
*special
Implement an operation that is equivalent to the operation QFT\(^P\), where QFT is the quantum Fourier transform.Your operation should take the following inputs: an integer \(P\) (\(2 \le P \le 2.1\cdot 10^6\)). a register of type LittleEndian - a wrapper type for an array of qubits that encodes an unsigned integer in little-endian format, with the least significant bit written first (corresponding to the array element with index 0). (If you need to, you can convert it to an array type using unwrap operator: let qubitArray = inputRegister!;) The ""output"" of your solution is the state in which it left the input qubits.Your code should have the following signature (note that your operation should have Adjoint and Controlled variants defined for it; is Adj+Ctl in the operation signature will generate them automatically based on your code):namespace Solution { open Microsoft.Quantum.Arithmetic; open Microsoft.Quantum.Intrinsic; operation Solve (p : Int, inputRegister : LittleEndian) : Unit is Adj+Ctl { // your code here }}You can learn more about QFT in this kata. You are allowed to take advantage of library operations, including QFTLE which implements the necessary transform in the first power.
Beginner
1
1,212
0
0
13
2,039
E
2039E
E. Shohag Loves Inversions
2,200
combinatorics; dp; implementation; math
Shohag has an array \(a\) of integers. Initially \(a = [0, 1]\). He can repeatedly perform the following operation any number of times: Let \(k\) be the number of inversions\(^{\text{βˆ—}}\) in the current array \(a\). Insert \(k\) at any position in \(a\), including the beginning or the end. For example, if \(a = [4, 6, 2, 4]\), then the number of inversions is \(k = 3\). So Shohag can obtain the following arrays after the operation: \([\textbf{3}, 4, 6, 2, 4]\), \([4, \textbf{3}, 6, 2, 4]\), \([4, 6, \textbf{3}, 2, 4]\), \([4, 6, 2, \textbf{3}, 4]\), and \([4, 6, 2, 4, \textbf{3}]\).Given an integer \(n\), help Shohag count, modulo \(998\,244\,353\), the number of distinct arrays of length \(n\) that can be obtained after performing the operations.\(^{\text{βˆ—}}\)The number of inversions in an array \(a\) is the number of pairs of indices (\(i\), \(j\)) such that \(i < j\) and \(a_i > a_j\).
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first and only line of each test case contains an integer \(n\) (\(2 \le n \le 10^6\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, output an integer β€” the number of possible arrays modulo \(998\,244\,353\).
In the first test case, the following \(5\) arrays can be obtained (the inserted inversion count is shown in bold): \([0, 1] \rightarrow [0, \textbf{0}, 1] \rightarrow [0, 0, 1, \textbf{0}]\), \([0, 1] \rightarrow [0, \textbf{0}, 1] \rightarrow [0, 0, \textbf{0}, 1]\), \([0, 1] \rightarrow [0, 1, \textbf{0}] \rightarrow [0, 1, 0, \textbf{1}]\), \([0, 1] \rightarrow [0, 1, \textbf{0}] \rightarrow [0, 1, \textbf{1}, 0]\), \([0, 1] \rightarrow [0, 1, \textbf{0}] \rightarrow [\textbf{1}, 0, 1, 0]\).
Input: 442769 | Output: 5 1 682 325188814
Hard
4
903
272
95
20
358
B
358B
B. Dima and Text Messages
1,500
brute force; strings
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the ""less"" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs ""more"" and ""less"" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.
In a single line, print ""yes"" (without the quotes), if Dima decoded the text message correctly, and ""no"" (without the quotes) otherwise.
Please note that Dima got a good old kick in the pants for the second sample from the statement.
Input: 3iloveyou<3i<3love<23you<3 | Output: yes
Medium
2
1,088
461
140
3
1,743
A
1743A
A. Password
800
brute force; combinatorics; implementation; math
Monocarp has forgotten the password to his mobile phone. The password consists of \(4\) digits from \(0\) to \(9\) (note that it can start with the digit \(0\)).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of \(4\) digits that could be the password for Monocarp's mobile phone (i. e. these sequences should meet all constraints on Monocarp's password).
The first line contains a single integer \(t\) (\(1 \le t \le 200\)) β€” the number of testcases.The first line of each testcase contains a single integer \(n\) (\(1 \le n \le 8\)) β€” the number of digits for which Monocarp remembers that they were not used in the password.The second line contains \(n\) different integers \(a_1, a_2, \dots a_n\) (\(0 \le a_i \le 9\)) representing the digits that were not used in the password. Note that the digits \(a_1, a_2, \dots, a_n\) are given in ascending order.
For each testcase, print one integer β€” the number of different \(4\)-digit sequences that meet the constraints.
In the first example, all possible passwords are: ""3377"", ""3737"", ""3773"", ""7337"", ""7373"", ""7733"".
Input: 280 1 2 4 5 6 8 918 | Output: 6 216
Beginner
4
586
502
111
17
72
G
72G
G. Fibonacci army
1,000
*special; dp
King Cambyses loves Fibonacci numbers. He has several armies. Today he wants to make a new army for himself and he wants the number of men in this army to be the n-th Fibonacci number.Given n you should find n-th Fibonacci number. The set of Fibonacci numbers start with f0 = f1 = 1 and for each i β‰₯ 2, fi = fi - 1 + fi - 2.
Input contains a single integer n (1 ≀ n ≀ 20).
Write a single integer. The n-th Fibonacci number.
Input: 2 | Output: 2
Beginner
2
324
47
50
0
1,330
B
1330B
B. Dreamoon Likes Permutations
1,400
implementation; math
The sequence of \(m\) integers is called the permutation if it contains all integers from \(1\) to \(m\) exactly once. The number \(m\) is called the length of the permutation.Dreamoon has two permutations \(p_1\) and \(p_2\) of non-zero lengths \(l_1\) and \(l_2\).Now Dreamoon concatenates these two permutations into another sequence \(a\) of length \(l_1 + l_2\). First \(l_1\) elements of \(a\) is the permutation \(p_1\) and next \(l_2\) elements of \(a\) is the permutation \(p_2\). You are given the sequence \(a\), and you need to find two permutations \(p_1\) and \(p_2\). If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)
The first line contains an integer \(t\) (\(1 \le t \le 10\,000\)) denoting the number of test cases in the input.Each test case contains two lines. The first line contains one integer \(n\) (\(2 \leq n \leq 200\,000\)): the length of \(a\). The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq n-1\)).The total sum of \(n\) is less than \(200\,000\).
For each test case, the first line of output should contain one integer \(k\): the number of ways to divide \(a\) into permutations \(p_1\) and \(p_2\).Each of the next \(k\) lines should contain two integers \(l_1\) and \(l_2\) (\(1 \leq l_1, l_2 \leq n, l_1 + l_2 = n\)), denoting, that it is possible to divide \(a\) into two permutations of length \(l_1\) and \(l_2\) (\(p_1\) is the first \(l_1\) elements of \(a\), and \(p_2\) is the last \(l_2\) elements of \(a\)). You can print solutions in any order.
In the first example, two possible ways to divide \(a\) into permutations are \(\{1\} + \{4, 3, 2, 1\}\) and \(\{1,4,3,2\} + \{1\}\).In the second example, the only way to divide \(a\) into permutations is \(\{2,4,1,3\} + \{2,1\}\).In the third example, there are no possible ways.
Input: 6 5 1 4 3 2 1 6 2 4 1 3 2 1 4 2 1 1 3 4 1 3 3 1 12 2 1 3 4 5 6 7 8 9 1 10 2 3 1 1 1 | Output: 2 1 4 4 1 1 4 2 0 0 1 2 10 0
Easy
2
723
383
510
13
822
D
822D
D. My pretty girl Noora
1,800
brute force; dp; greedy; math; number theory
In Pavlopolis University where Noora studies it was decided to hold beauty contest ""Miss Pavlopolis University"". Let's describe the process of choosing the most beautiful girl in the university in more detail.The contest is held in several stages. Suppose that exactly n girls participate in the competition initially. All the participants are divided into equal groups, x participants in each group. Furthermore the number x is chosen arbitrarily, i. e. on every stage number x can be different. Within each group the jury of the contest compares beauty of the girls in the format ""each with each"". In this way, if group consists of x girls, then comparisons occur. Then, from each group, the most beautiful participant is selected. Selected girls enter the next stage of the competition. Thus if n girls were divided into groups, x participants in each group, then exactly participants will enter the next stage. The contest continues until there is exactly one girl left who will be ""Miss Pavlopolis University""But for the jury this contest is a very tedious task. They would like to divide the girls into groups in each stage so that the total number of pairwise comparisons of the girls is as few as possible. Let f(n) be the minimal total number of comparisons that should be made to select the most beautiful participant, if we admit n girls to the first stage.The organizers of the competition are insane. They give Noora three integers t, l and r and ask the poor girl to calculate the value of the following expression: t0Β·f(l) + t1Β·f(l + 1) + ... + tr - lΒ·f(r). However, since the value of this expression can be quite large the organizers ask her to calculate it modulo 109 + 7. If Noora can calculate the value of this expression the organizers promise her to help during the beauty contest. But the poor girl is not strong in mathematics, so she turned for help to Leha and he turned to you.
The first and single line contains three integers t, l and r (1 ≀ t < 109 + 7, 2 ≀ l ≀ r ≀ 5Β·106).
In the first line print single integer β€” the value of the expression modulo 109 + 7.
Consider the sample.It is necessary to find the value of .f(2) = 1. From two girls you can form only one group of two people, in which there will be one comparison.f(3) = 3. From three girls you can form only one group of three people, in which there will be three comparisons.f(4) = 3. From four girls you can form two groups of two girls each. Then at the first stage there will be two comparisons, one in each of the two groups. In the second stage there will be two girls and there will be one comparison between them. Total 2 + 1 = 3 comparisons. You can also leave all girls in same group in the first stage. Then comparisons will occur. Obviously, it's better to split girls into groups in the first way.Then the value of the expression is .
Input: 2 2 4 | Output: 19
Medium
5
1,911
98
84
8
526
C
526C
C. Om Nom and Candies
2,000
brute force; greedy; math
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs Wr grams and each blue candy weighs Wb grams. Eating a single red candy gives Om Nom Hr joy units and eating a single blue candy gives Om Nom Hb joy units.Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.
The single line contains five integers C, Hr, Hb, Wr, Wb (1 ≀ C, Hr, Hb, Wr, Wb ≀ 109).
Print a single integer β€” the maximum number of joy units that Om Nom can get.
In the sample test Om Nom can eat two candies of each type and thus get 16 joy units.
Input: 10 3 5 2 3 | Output: 16
Hard
3
1,142
87
77
5
1,693
E
1693E
E. Outermost Maximums
3,400
data structures; greedy
Yeri has an array of \(n + 2\) non-negative integers : \(a_0, a_1, ..., a_n, a_{n + 1}\).We know that \(a_0 = a_{n + 1} = 0\).She wants to make all the elements of \(a\) equal to zero in the minimum number of operations.In one operation she can do one of the following: Choose the leftmost maximum element and change it to the maximum of the elements on its left. Choose the rightmost maximum element and change it to the maximum of the elements on its right.Help her find the minimum number of operations needed to make all elements of \(a\) equal to zero.
The first line contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le n\)).
Print a single integer β€” the minimum number of operations needed to make all elements of \(a\) equal to zero.
In the first sample, you get \(\langle 1, \underline{1}, 2, 4, 0, 2 \rangle\) by performing the first operation and \(\langle 1, 4, 2, \underline{2}, 0, 2 \rangle\) by performing the second operation.One way to achieve our goal is shown below. (The underlines show the last change.) \(\langle 1, 4, 2, 4, 0, 2 \rangle \to \langle 1, 4, 2, \underline{2}, 0, 2 \rangle \to \langle 1, \underline{1}, 2, 2, 0, 2 \rangle \to \langle 1, 1, 2, 2, 0, \underline{0} \rangle \to \langle 1, 1, 2, \underline{0}, 0, 0 \rangle \to \langle 1, 1, \underline{0}, 0, 0, 0 \rangle \to \langle \underline{0}, 1, 0, 0, 0, 0 \rangle \to \langle 0, \underline{0}, 0, 0, 0, 0 \rangle \)In the third sample each element is already equal to zero so no operations are needed.
Input: 6 1 4 2 4 0 2 | Output: 7
Master
2
557
166
109
16
650
A
650A
A. Watchmen
1,400
data structures; geometry; math
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≀ i < j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
The first line of the input contains the single integer n (1 ≀ n ≀ 200 000) β€” the number of watchmen.Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109).Some positions may coincide.
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
Input: 31 17 51 5 | Output: 2
Easy
3
743
210
151
6
1,657
B
1657B
B. XY Sequence
800
greedy
You are given four integers \(n\), \(B\), \(x\) and \(y\). You should build a sequence \(a_0, a_1, a_2, \dots, a_n\) where \(a_0 = 0\) and for each \(i \ge 1\) you can choose: either \(a_i = a_{i - 1} + x\) or \(a_i = a_{i - 1} - y\). Your goal is to build such a sequence \(a\) that \(a_i \le B\) for all \(i\) and \(\sum\limits_{i=0}^{n}{a_i}\) is maximum possible.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Next \(t\) cases follow.The first and only line of each test case contains four integers \(n\), \(B\), \(x\) and \(y\) (\(1 \le n \le 2 \cdot 10^5\); \(1 \le B, x, y \le 10^9\)).It's guaranteed that the total sum of \(n\) doesn't exceed \(2 \cdot 10^5\).
For each test case, print one integer β€” the maximum possible \(\sum\limits_{i=0}^{n}{a_i}\).
In the first test case, the optimal sequence \(a\) is \([0, 1, 2, 3, 4, 5]\).In the second test case, the optimal sequence \(a\) is \([0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]\).In the third test case, the optimal sequence \(a\) is \([0, -3, -6, 1, -2]\).
Input: 35 100 1 307 1000000000 1000000000 10000000004 1 7 3 | Output: 15 4000000000 -10
Beginner
1
367
352
92
16
1,781
D
1781D
D. Many Perfect Squares
1,800
brute force; math; number theory
You are given a set \(a_1, a_2, \ldots, a_n\) of distinct positive integers.We define the squareness of an integer \(x\) as the number of perfect squares among the numbers \(a_1 + x, a_2 + x, \ldots, a_n + x\).Find the maximum squareness among all integers \(x\) between \(0\) and \(10^{18}\), inclusive.Perfect squares are integers of the form \(t^2\), where \(t\) is a non-negative integer. The smallest perfect squares are \(0, 1, 4, 9, 16, \ldots\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 50\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 50\)) β€” the size of the set.The second line contains \(n\) distinct integers \(a_1, a_2, \ldots, a_n\) in increasing order (\(1 \le a_1 < a_2 < \ldots < a_n \le 10^9\)) β€” the set itself.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(50\).
For each test case, print a single integer β€” the largest possible number of perfect squares among \(a_1 + x, a_2 + x, \ldots, a_n + x\), for some \(0 \le x \le 10^{18}\).
In the first test case, for \(x = 0\) the set contains two perfect squares: \(1\) and \(4\). It is impossible to obtain more than two perfect squares.In the second test case, for \(x = 3\) the set looks like \(4, 9, 16, 25, 100\), that is, all its elements are perfect squares.
Input: 451 2 3 4 551 6 13 22 97110052 5 10 17 26 | Output: 2 5 1 2
Medium
3
453
507
170
17
1,340
A
1340A
A. Nastya and Strange Generator
1,500
brute force; data structures; greedy; implementation
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of \(n\) steps. At the \(i\)-th step, a place is chosen for the number \(i\) \((1 \leq i \leq n)\). The position for the number \(i\) is defined as follows: For all \(j\) from \(1\) to \(n\), we calculate \(r_j\) β€” the minimum index such that \(j \leq r_j \leq n\), and the position \(r_j\) is not yet occupied in the permutation. If there are no such positions, then we assume that the value of \(r_j\) is not defined. For all \(t\) from \(1\) to \(n\), we calculate \(count_t\) β€” the number of positions \(1 \leq j \leq n\) such that \(r_j\) is defined and \(r_j = t\). Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the \(count\) array is maximum. The generator selects one of these positions for the number \(i\). The generator can choose any position. Let's have a look at the operation of the algorithm in the following example: Let \(n = 5\) and the algorithm has already arranged the numbers \(1, 2, 3\) in the permutation. Consider how the generator will choose a position for the number \(4\): The values of \(r\) will be \(r = [3, 3, 3, 4, \times]\), where \(\times\) means an indefinite value. Then the \(count\) values will be \(count = [0, 0, 3, 1, 0]\). There are only two unoccupied positions in the permutation: \(3\) and \(4\). The value in the \(count\) array for position \(3\) is \(3\), for position \(4\) it is \(1\). The maximum value is reached only for position \(3\), so the algorithm will uniquely select this position for number \(4\). Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind \(p_1, p_2, \ldots, p_n\) and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.
The first line contains a single integer \(t\) \((1 \leq t \leq 10^5)\) β€” the number of test cases. Then the descriptions of the test cases follow.The first line of the test case contains a single integer \(n\) \((1 \leq n \leq 10^5)\) β€” the size of the permutation.The second line of the test case contains \(n\) different integers \(p_1, p_2, \ldots, p_n\) (\(1 \leq p_i \leq n\)) β€” the permutation written by Denis.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(10^5\).
Print ""Yes"" if this permutation could be obtained as a result of the generator. Otherwise, print ""No"".All letters can be displayed in any case.
Let's simulate the operation of the generator in the first test.At the \(1\) step, \(r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]\). The maximum value is reached in any free position, so the generator can choose a random position from \(1\) to \(5\). In our example, it chose \(5\).At the \(2\) step, \(r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]\). The maximum value is reached in positions from \(1\) to \(4\), so the generator can choose a random position among them. In our example, it chose \(1\).At the \(3\) step, \(r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]\). The maximum value is \(2\) and is reached only at the \(2\) position, so the generator will choose this position.At the \(4\) step, \(r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]\). The maximum value is \(3\) and is reached only at the \(3\) position, so the generator will choose this position.At the \(5\) step, \(r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]\). The maximum value is \(4\) and is reached only at the \(4\) position, so the generator will choose this position.In total, we got a permutation of \(2, 3, 4, 5, 1\), that is, a generator could generate it.
Input: 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 | Output: Yes Yes No Yes No
Medium
4
2,614
501
147
13
555
D
555D
D. Case of a Top Secret
2,500
binary search; implementation; math
Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure.However, he needs help conducting one of the investigative experiment. There are n pegs put on a plane, they are numbered from 1 to n, the coordinates of the i-th of them are (xi, 0). Then, we tie to the bottom of one of the pegs a weight on a tight rope of length l (thus, its coordinates will be equal to (xi, - l), where i is the number of the used peg). Then the weight is pushed to the right, so that it starts to rotate counterclockwise. At the same time, if the weight during rotation touches some of the other pegs, it then begins to rotate around that peg. Suppose that each peg itself is very thin and does not affect the rope length while weight is rotating around it. More formally, if at some moment the segment of the rope contains one or more pegs in addition to the peg around which the weight is rotating, the weight will then rotate around the farthermost one of them on a shorter segment of a rope. In particular, if the segment of the rope touches some peg by its endpoint, it is considered that the weight starts to rotate around that peg on a segment of the rope of length 0.At some moment the weight will begin to rotate around some peg, without affecting the rest of the pegs. Andrewid interested in determining the number of this peg.Andrewid prepared m queries containing initial conditions for pushing the weight, help him to determine for each of them, around what peg the weight will eventually rotate.
The first line contains integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of pegs and queries.The next line contains n integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the pegs. It is guaranteed that the coordinates of all the pegs are distinct integers.Next m lines contain the descriptions of the queries of pushing the weight, each consists of two integers ai (1 ≀ ai ≀ n) and li (1 ≀ li ≀ 109) β€” the number of the starting peg and the length of the rope.
Print m lines, the i-th line should contain the number of the peg around which the weight will eventually rotate after the i-th push.
Picture to the first sample test: Picture to the second sample test:Note that in the last query weight starts to rotate around the peg 1 attached to a rope segment of length 0.
Input: 3 20 3 52 31 8 | Output: 32
Expert
3
1,572
474
133
5
8
B
8B
B. Obsession with Robots
1,400
constructive algorithms; graphs; implementation
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug β€” the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest.The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest.In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in.
The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100.
In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist).
Input: LLUUUR | Output: OK
Easy
3
1,573
280
117
0
1,657
F
1657F
F. Words on Tree
2,600
2-sat; dfs and similar; dsu; graphs; trees
You are given a tree consisting of \(n\) vertices, and \(q\) triples \((x_i, y_i, s_i)\), where \(x_i\) and \(y_i\) are integers from \(1\) to \(n\), and \(s_i\) is a string with length equal to the number of vertices on the simple path from \(x_i\) to \(y_i\).You want to write a lowercase Latin letter on each vertex in such a way that, for each of \(q\) given triples, at least one of the following conditions holds: if you write out the letters on the vertices on the simple path from \(x_i\) to \(y_i\) in the order they appear on this path, you get the string \(s_i\); if you write out the letters on the vertices on the simple path from \(y_i\) to \(x_i\) in the order they appear on this path, you get the string \(s_i\). Find any possible way to write a letter on each vertex to meet these constraints, or report that it is impossible.
The first line contains two integers \(n\) and \(q\) (\(2 \le n \le 4 \cdot 10^5\); \(1 \le q \le 4 \cdot 10^5\)) β€” the number of vertices in the tree and the number of triples, respectively.Then \(n - 1\) lines follow; the \(i\)-th of them contains two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n\); \(u_i \ne v_i\)) β€” the endpoints of the \(i\)-th edge. These edges form a tree.Then \(q\) lines follow; the \(j\)-th of them contains two integers \(x_j\) and \(y_j\), and a string \(s_j\) consisting of lowercase Latin letters. The length of \(s_j\) is equal to the number of vertices on the simple path between \(x_j\) and \(y_j\).Additional constraint on the input: \(\sum \limits_{j=1}^{q} |s_j| \le 4 \cdot 10^5\).
If there is no way to meet the conditions on all triples, print NO. Otherwise, print YES in the first line, and a string of \(n\) lowercase Latin letters in the second line; the \(i\)-th character of the string should be the letter you write on the \(i\)-th vertex. If there are multiple answers, print any of them.
Input: 3 2 2 3 2 1 2 1 ab 2 3 bc | Output: YES abc
Expert
5
844
728
315
16
1,866
J
1866J
J. Jackets and Packets
2,800
dp
Pak Chanek has \(N\) jackets that are stored in a wardrobe. Pak Chanek's wardrobe has enough room for two stacks of jackets, namely the left stack and the right stack. Initially, all \(N\) jackets are in the left stack, while the right stack is empty. Initially, the \(i\)-th jacket from the top of the left stack has colour \(C_i\).Pak Chanek wants to pack all of those jackets into some packets, such that the jackets in the same packet has the same colour. However, it is possible for two jackets with the same colour to be in different packets.Pak Chanek can do two kinds of operations: Pak Chanek can pick any number of jackets from the top from one stack as long as the colour is the same, then take those jackets out of the stack and pack them into a packet. This packing operation takes \(X\) minutes, no matter how many jackets are packed. Pak Chanek can move one topmost jacket from one stack to the top of the other stack (possibly right to left or left to right). This moving operation takes \(Y\) minutes. Determine the minimum time to pack all jackets!
The first line contains three integers \(N\), \(X\), and \(Y\) (\(1 \leq N \leq 400\); \(1\leq X,Y\leq10^9\)) β€” the number of jackets, the time to do a packing operation, and the time to do a movement operation.The second line contains \(N\) integers \(C_1, C_2, C_3, \ldots, C_N\) (\(1 \leq C_i \leq N\)) β€” the colour of each jacket.
An integer representing the minimum time to pack all jackets.
Let's denote the contents of the two stacks using arrays that represent the colours of the jackets in the stack from top to bottom. Initially, the two stacks form \([4, 4, 2, 4, 1, 2, 2, 1]\) and \([]\).Pak Chanek can do the following sequence of operations: Movement from left to right. The two stacks become \([4, 2, 4, 1, 2, 2, 1]\) and \([4]\). Movement from left to right. The two stacks become \([2, 4, 1, 2, 2, 1]\) and \([4, 4]\). Packing for \(1\) jacket from the top of the left stack. The two stacks become \([4, 1, 2, 2, 1]\) and \([4, 4]\). Movement from left to right. The two stacks become \([1, 2, 2, 1]\) and \([4, 4, 4]\). Movement from left to right. The two stacks become \([2, 2, 1]\) and \([1, 4, 4, 4]\). Packing for \(2\) jackets from the top of the left stack. The two stacks become \([1]\) and \([1, 4, 4, 4]\). Movement from right to left. The two stacks become \([1, 1]\) and \([4, 4, 4]\). Packing for \(3\) jackets from the top of the right stack. The two stacks become \([1, 1]\) and \([]\). Packing for \(2\) jackets from the top of the left stack. The two stacks become \([]\) and \([]\). In total, it requires a time of \(2+2+7+2+2+7+2+7+7=38\) minutes to pack all jackets. It can be proven that there are no other ways that are faster.
Input: 8 7 2 4 4 2 4 1 2 2 1 | Output: 38
Master
1
1,066
334
61
18
1,536
F
1536F
F. Omkar and Akmar
2,600
chinese remainder theorem; combinatorics; constructive algorithms; fft; games; geometry; math; meet-in-the-middle; string suffix structures
Omkar and Akmar are playing a game on a circular board with \(n\) (\(2 \leq n \leq 10^6\)) cells. The cells are numbered from \(1\) to \(n\) so that for each \(i\) (\(1 \leq i \leq n-1\)) cell \(i\) is adjacent to cell \(i+1\) and cell \(1\) is adjacent to cell \(n\). Initially, each cell is empty.Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves.Output the number of possible distinct games where both players play optimally modulo \(10^9+7\). Note that we only consider games where some player has lost and there are no more valid moves.Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.
The only line will contain an integer \(n\) (\(2 \leq n \leq 10^6\)) β€” the number of cells on the board.
Output a single integer β€” the number of possible distinct games where both players play optimally modulo \(10^9+7\).
For the first sample case, the first player has \(4\) possible moves. No matter what the first player plays, the second player only has \(1\) possible move, so there are \(4\) possible games.
Input: 2 | Output: 4
Expert
9
1,264
104
116
15
1,671
D
1671D
D. Insert a Progression
1,600
brute force; constructive algorithms; greedy
You are given a sequence of \(n\) integers \(a_1, a_2, \dots, a_n\). You are also given \(x\) integers \(1, 2, \dots, x\).You are asked to insert each of the extra integers into the sequence \(a\). Each integer can be inserted at the beginning of the sequence, at the end of the sequence, or between any elements of the sequence.The score of the resulting sequence \(a'\) is the sum of absolute differences of adjacent elements in it \(\left(\sum \limits_{i=1}^{n+x-1} |a'_i - a'_{i+1}|\right)\).What is the smallest possible score of the resulting sequence \(a'\)?
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of testcases.The first line of each testcase contains two integers \(n\) and \(x\) (\(1 \le n, x \le 2 \cdot 10^5\)) β€” the length of the sequence and the number of extra integers.The second line of each testcase contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 2 \cdot 10^5\)).The sum of \(n\) over all testcases doesn't exceed \(2 \cdot 10^5\).
For each testcase, print a single integer β€” the smallest sum of absolute differences of adjacent elements of the sequence after you insert the extra integers into it.
Here are the sequences with the smallest scores for the example. The underlined elements are the extra integers. Note that there exist other sequences with this smallest score. \(\underline{1}, \underline{2}, \underline{3}, \underline{4}, \underline{5}, 10\) \(\underline{7}, 7, \underline{6}, \underline{4}, 2, \underline{2}, \underline{1}, \underline{3}, \underline{5}, \underline{8}, 10\) \(6, \underline{1}, 1, \underline{2}, 5, 7, 3, 3, 9, 10, 10, 1\) \(1, 3, \underline{1}, 1, 2, \underline{2}, \underline{3}, \underline{4}, \underline{5}, \underline{6}, \underline{7}, \underline{8}, \underline{9}, \underline{10}\)
Input: 41 5103 87 2 1010 26 1 5 7 3 3 9 10 10 14 101 3 1 2 | Output: 9 15 31 13
Medium
3
565
445
166
16
1,285
A
1285A
A. Mezo Playing Zoma
800
math
Today, 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.
The 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).
Print one integer β€” the number of different positions Zoma may end up at.
In the example, Zoma may end up anywhere between \(-2\) and \(2\).
Input: 4 LRLR | Output: 5
Beginner
1
1,080
186
73
12
327
B
327B
B. Hungry Sequence
1,200
math
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: Its elements are in increasing order. That is an inequality ai < aj holds for any two indices i, j (i < j). For any two indices i and j (i < j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.
The input contains a single integer: n (1 ≀ n ≀ 105).
Output a line that contains n space-separated integers a1 a2, ..., an (1 ≀ ai ≀ 107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1.If there are multiple solutions you can output any one.
Input: 3 | Output: 2 9 15
Easy
1
542
53
257
3
1,312
A
1312A
A. Two Regular Polygons
800
geometry; greedy; math; number theory
You are given two integers \(n\) and \(m\) (\(m < n\)). Consider a convex regular polygon of \(n\) vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with \(m\) vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The next \(t\) lines describe test cases. Each test case is given as two space-separated integers \(n\) and \(m\) (\(3 \le m < n \le 100\)) β€” the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.
For each test case, print the answer β€” ""YES"" (without quotes), if it is possible to build another convex regular polygon with \(m\) vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and ""NO"" otherwise.
The first test case of the example It can be shown that the answer for the second test case of the example is ""NO"".
Input: 2 6 3 7 3 | Output: YES NO
Beginner
4
571
353
297
13
1,616
E
1616E
E. Lexicographically Small Enough
2,200
brute force; data structures; greedy; strings
You are given two strings \(s\) and \(t\) of equal length \(n\). In one move, you can swap any two adjacent characters of the string \(s\).You need to find the minimal number of operations you need to make string \(s\) lexicographically smaller than string \(t\).A string \(a\) is lexicographically smaller than a string \(b\) if and only if one of the following holds: \(a\) is a prefix of \(b\), but \(a \ne b\); in the first position where \(a\) and \(b\) differ, the string \(a\) has a letter that appears earlier in the alphabet than the corresponding letter in \(b\).
The first line of input contains one integer \(q\) (\(1 \le q \le 10\,000\)): 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 the string \(s\) consisting of \(n\) lowercase English letters.The third line of each test case contains the string \(t\) consisting of \(n\) lowercase English letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print in a separate line the minimal number of operations you need to make string \(s\) lexicographically smaller than string \(t\), or \(-1\), if it's impossible.
Input: 4 1 a a 3 rll rrr 3 caa aca 5 ababa aabba | Output: -1 0 2 2
Hard
4
573
494
183
16
1,808
C
1808C
C. Unlucky Numbers
1,900
brute force; dp; greedy; implementation
In this problem, unlike problem A, you need to look for unluckiest number, not the luckiest one.Note that the constraints of this problem differ from such in problem A.Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively.Each starship has a number β€”some positive integer \(x\). Let's define the luckiness of a number \(x\) as the difference between the largest and smallest digits of that number. For example, \(142857\) has \(8\) as its largest digit and \(1\) as its smallest digit, so its luckiness is \(8-1=7\). And the number \(111\) has all digits equal to \(1\), so its luckiness is zero.Hateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from \(l\) to \(r\) inclusively. While in the store, Hateehc wanted to find a starship with the unluckiest number.Since there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question.
The first line contains an integer \(t\) (\(1 \le t \le 600\)) β€”the number of test cases.Each of the following \(t\) lines contains a description of the test case. The description consists of two integers \(l\), \(r\) (\(1 \le l \le r \le 10^{18}\)) β€” the largest and smallest numbers of the starships in the store.
Print \(t\) lines, one line for each test case, containing the unluckiest starship number in the store.If there are several ways to choose the unluckiest number, output any of them.
Let's look at two test examples: the luckiness of the number \(59\) is \(9 - 5 = 4\); the luckiness of \(60\) equals \(6 - 0 = 6\); the luckiness of \(61\) equals \(6 - 1 = 5\); the luckiness of \(62\) equals \(6 - 2 = 4\); the luckiness of \(63\) is \(6 - 3 = 3\). So the unluckiest number is \(63\).In the fifth test case, the unluckiest numbers are \(1\), \(2\), \(3\), \(4\), \(5\), \(6\), \(7\), \(8\), \(9\), \(11\), \(22\), \(33\), \(44\), \(55\), \(66\), \(77\), \(88\), \(99\), so you are allowed to choose any of them.
Input: 559 6342 4948 5390 901 100 | Output: 63 44 53 90 1
Hard
4
1,180
315
181
18
1,209
C
1209C
C. Paint the Digits
1,500
constructive algorithms; greedy; implementation
You are given a sequence of \(n\) digits \(d_1d_2 \dots d_{n}\). You need to paint all the digits in two colors so that: each digit is painted either in the color \(1\) or in the color \(2\); if you write in a row from left to right all the digits painted in the color \(1\), and then after them all the digits painted in the color \(2\), then the resulting sequence of \(n\) digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence \(d=914\) the only valid coloring is \(211\) (paint in the color \(1\) two last digits, paint in the color \(2\) the first digit). But \(122\) is not a valid coloring (\(9\) concatenated with \(14\) is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.
The first line contains a single integer \(t\) (\(1 \le t \le 10000\)) β€” the number of test cases in the input.The first line of each test case contains an integer \(n\) (\(1 \le n \le 2\cdot10^5\)) β€” the length of a given sequence of digits.The next line contains a sequence of \(n\) digits \(d_1d_2 \dots d_{n}\) (\(0 \le d_i \le 9\)). The digits are written in a row without spaces or any other separators. The sequence can start with 0.It is guaranteed that the sum of the values ​​of \(n\) for all test cases in the input does not exceed \(2\cdot10^5\).
Print \(t\) lines β€” the answers to each of the test cases in the input.If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of \(n\) digits \(t_1t_2 \dots t_n\) (\(1 \le t_i \le 2\)), where \(t_i\) is the color the \(i\)-th digit is painted in. If there are several feasible solutions, print any of them.If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign).
In the first test case, \(d=040425524644\). The output \(t=121212211211\) is correct because \(0022444\) (painted in \(1\)) concatenated with \(44556\) (painted in \(2\)) is \(002244444556\) which is a sorted sequence of \(n\) given digits.
Input: 5 12 040425524644 1 0 9 123456789 2 98 3 987 | Output: 121212211211 1 222222222 21 -
Medium
3
999
558
498
12
1,873
E
1873E
E. Building an Aquarium
1,100
binary search; sortings
You love fish, that's why you have decided to build an aquarium. You have a piece of coral made of \(n\) columns, the \(i\)-th of which is \(a_i\) units tall. Afterwards, you will build a tank around the coral as follows: Pick an integer \(h \geq 1\) β€” the height of the tank. Build walls of height \(h\) on either side of the tank. Then, fill the tank up with water so that the height of each column is \(h\), unless the coral is taller than \(h\); then no water should be added to this column. For example, with \(a=[3,1,2,4,6,2,5]\) and a height of \(h=4\), you will end up using a total of \(w=8\) units of water, as shown. You can use at most \(x\) units of water to fill up the tank, but you want to build the biggest tank possible. What is the largest value of \(h\) you can select?
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases.The first line of each test case contains two positive integers \(n\) and \(x\) (\(1 \leq n \leq 2 \cdot 10^5\); \(1 \leq x \leq 10^9\)) β€” the number of columns of the coral and the maximum amount of water you can use.The second line of each test case contains \(n\) space-separated integers \(a_i\) (\(1 \leq a_i \leq 10^9\)) β€” the heights of the coral.The sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, output a single positive integer \(h\) (\(h \geq 1\)) β€” the maximum height the tank can have, so you need at most \(x\) units of water to fill up the tank.We have a proof that under these constraints, such a value of \(h\) always exists.
The first test case is pictured in the statement. With \(h=4\) we need \(8\) units of water, but if \(h\) is increased to \(5\) we need \(13\) units of water, which is more than \(x=9\). So \(h=4\) is optimal.In the second test case, we can pick \(h=4\) and add \(3\) units to each column, using a total of \(9\) units of water. It can be shown that this is optimal.In the third test case, we can pick \(h=2\) and use all of our water, so it is optimal.
Input: 57 93 1 2 4 6 2 53 101 1 14 11 4 3 46 19842 6 5 9 1 81 10000000001 | Output: 4 4 2 335 1000000001
Easy
2
789
522
257
18
1,840
F
1840F
F. Railguns
2,200
brute force; dfs and similar; dp; graphs
Tema is playing a very interesting computer game.During the next mission, Tema's character found himself on an unfamiliar planet. Unlike Earth, this planet is flat and can be represented as an \(n \times m\) rectangle.Tema's character is located at the point with coordinates \((0, 0)\). In order to successfully complete the mission, he needs to reach the point with coordinates \((n, m)\) alive.Let the character of the computer game be located at the coordinate \((i, j)\). Every second, starting from the first, Tema can: either use vertical hyperjump technology, after which his character will end up at coordinate \((i + 1, j)\) at the end of the second; or use horizontal hyperjump technology, after which his character will end up at coordinate \((i, j + 1)\) at the end of the second; or Tema can choose not to make a hyperjump, in which case his character will not move during this second; The aliens that inhabit this planet are very dangerous and hostile. Therefore, they will shoot from their railguns \(r\) times.Each shot completely penetrates one coordinate vertically or horizontally. If the character is in the line of its impact at the time of the shot (at the end of the second), he dies.Since Tema looked at the game's source code, he knows complete information about each shot β€” the time, the penetrated coordinate, and the direction of the shot.What is the minimum time for the character to reach the desired point? If he is doomed to die and cannot reach the point with coordinates \((n, m)\), output \(-1\).
The first line of the input contains a single integer \(T\) (\(1 \le T \le 10^4\)) β€” the number of test cases.Then follow the descriptions of the test cases.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \cdot m \le 10^4\)) β€” the size of the planet, its height and width.The second line of each test case contains a single integer \(r\) (\(1 \le r \le 100\)) β€” the number of shots.Then follow \(r\) lines, each describing one shot.A shot is described by three integers \(t\), \(d\), \(coord\). Where \(t\) is the second at which the shot will be fired (\(1 \le t \le 10^9\)). \(d\) is the direction of the shot (\(d = 1\) denotes a horizontal shot, \(d = 2\) denotes a vertical shot). \(coord\) is the size of the penetrated coordinate (\(0 \le coord \le n\) for \(d = 1\), \(0 \le coord \le m\) for \(d = 2\)).The sum of the products \(n \cdot m\) over all test cases does not exceed \(10^4\).
For each test case, output a single number β€” the minimum time for the character to reach the coordinate \((n, m)\), or \(-1\) if he is doomed to die.
In the first test case, the character can move as follows: \((0, 0) \rightarrow (0, 1) \rightarrow (0, 2) \rightarrow (0, 3) \rightarrow (0, 3) \rightarrow (1, 3)\).In the second test case, the character will not be able to leave the rectangle that will be completely penetrated by shots at the second \(2\).
Input: 51 341 2 02 2 13 2 24 1 13 362 1 02 1 12 1 22 2 02 2 12 2 22 137 1 22 1 17 2 12 259 1 23 2 05 1 24 2 27 1 04 676 1 212 1 34 1 017 2 31 2 616 2 63 2 4 | Output: 5 -1 3 6 10
Hard
4
1,532
929
149
18
89
D
89D
D. Space mines
2,500
geometry
Once upon a time in the galaxy of far, far away...Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon β€” space mines. Let's describe a space mine's build.Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius r with the center in the point O. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point P, such that (transporting long-spiked mines is problematic), where |OP| is the length of the segment connecting O and P. It is convenient to describe the point P by a vector p such that P = O + p.The Death Star is shaped like a ball with the radius of R (R exceeds any mine's radius). It moves at a constant speed along the v vector at the speed equal to |v|. At the moment the rebels noticed the Star of Death, it was located in the point A.The rebels located n space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed).
The first input data line contains 7 integers Ax, Ay, Az, vx, vy, vz, R. They are the Death Star's initial position, the direction of its movement, and its radius ( - 10 ≀ vx, vy, vz ≀ 10, |v| > 0, 0 < R ≀ 100).The second line contains an integer n, which is the number of mines (1 ≀ n ≀ 100). Then follow n data blocks, the i-th of them describes the i-th mine.The first line of each block contains 5 integers Oix, Oiy, Oiz, ri, mi, which are the coordinates of the mine centre, the radius of its body and the number of spikes (0 < ri < 100, 0 ≀ mi ≀ 10). Then follow mi lines, describing the spikes of the i-th mine, where the j-th of them describes the i-th spike and contains 3 integers pijx, pijy, pijz β€” the coordinates of the vector where the given spike is directed ().The coordinates of the mines' centers and the center of the Death Star are integers, their absolute value does not exceed 10000. It is guaranteed that R > ri for any 1 ≀ i ≀ n. For any mines i β‰  j the following inequality if fulfilled: . Initially the Death Star and the mines do not have common points.
If the rebels will succeed in stopping the Death Star using space mines, print the time from the moment the Death Star was noticed to the blast.If the Death Star will not touch a mine, print ""-1"" (without quotes).For the answer the absolute or relative error of 10 - 6 is acceptable.
Input: 0 0 0 1 0 0 5210 8 0 2 20 -3 02 2 020 0 0 4 32 4 0-4 3 01 -5 0 | Output: 10.0000000000
Expert
1
1,896
1,080
285
0
1,921
B
1921B
B. Arranging Cats
800
greedy; implementation
In order to test the hypothesis about the cats, the scientists must arrange the cats in the boxes in a specific way. Of course, they would like to test the hypothesis and publish a sensational article as quickly as possible, because they are too engrossed in the next hypothesis about the phone's battery charge.Scientists have \(n\) boxes in which cats may or may not sit. Let the current state of the boxes be denoted by the sequence \(b_1, \dots, b_n\): \(b_i = 1\) if there is a cat in box number \(i\), and \(b_i = 0\) otherwise. Fortunately, the unlimited production of cats has already been established, so in one day, the scientists can perform one of the following operations: Take a new cat and place it in a box (for some \(i\) such that \(b_i = 0\), assign \(b_i = 1\)). Remove a cat from a box and send it into retirement (for some \(i\) such that \(b_i = 1\), assign \(b_i = 0\)). Move a cat from one box to another (for some \(i, j\) such that \(b_i = 1, b_j = 0\), assign \(b_i = 0, b_j = 1\)). It has also been found that some boxes were immediately filled with cats. Therefore, the scientists know the initial position of the cats in the boxes \(s_1, \dots, s_n\) and the desired position \(f_1, \dots, f_n\).Due to the large amount of paperwork, the scientists do not have time to solve this problem. Help them for the sake of science and indicate the minimum number of days required to test the hypothesis.
Each test consists of several test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. This is followed by descriptions of the test cases.Each test case consists of three lines.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) β€” the number of boxes.The second line of each test case contains a string \(s\) of \(n\) characters, where the \(i\)-th character is '1' if there is a cat in the \(i\)-th box and '0' otherwise.The third line of each test case contains a string \(f\) of \(n\) characters, where the \(i\)-th character is '1' if there should be a cat in the \(i\)-th box and '0' otherwise.It is guaranteed that in a test the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output a single integer on a separate line β€” the minimum number of operations required to obtain the desired position from the initial position. It can be shown that a solution always exists.
In the first test case, you can first move the cat from the first box to the fifth, and then remove the cat from the fourth box.In the second test case, there is nothing to do β€” the only cat is already sitting in the correct box.In the third test case of input data, it takes three days to place a cat in each box.
Input: 6510010000011113000111401011010310010181001100111111110 | Output: 2 0 3 2 1 4
Beginner
2
1,426
782
211
19
1,461
A
1461A
A. String Generation
800
constructive algorithms; greedy
One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length \(n\) to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules: the string may only contain characters 'a', 'b', or 'c'; the maximum length of a substring of this string that is a palindrome does not exceed \(k\). A string \(a\) is a substring of a string \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. For example, strings ""a"", ""bc"", ""abc"" are substrings of a string ""abc"", while strings ""ac"", ""ba"", ""cba"" are not.A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, strings ""abccba"", ""abbba"", ""aba"", ""abacaba"", ""a"", and ""bacab"" are palindromes, while strings ""abcbba"", ""abb"", and ""ab"" are not.Now Joe wants to find any correct string. Help him! It can be proven that the answer always exists under the given constraints.
Each test contains one or more test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10\)).The only line of each test case contains two integers \(n\) and \(k\) (\(1 \le k \le n \le 1\,000\)) β€” the required string length and the maximum length of a palindrome substring, respectively.
For each test case, print any string that satisfies the conditions from the problem statement. If there are multiple correct answers, you can print any one of them. It can be proven that the answer always exists under the given constraints.
In the first test case of the example, the palindrome substring with the maximum length is ""aa"". Its length does not exceed \(2\), so it fits.In the second test case all palindrome substrings have the length one.
Input: 2 3 2 4 1 | Output: aab acba
Beginner
2
1,153
312
240
14
690
D3
690D3
D3. The Wall (hard)
2,100
dp
So many wall designs to choose from! Even modulo 106 + 3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow them down.Heidi is quick to come up with criteria for a useful wall: In a useful wall, at least one segment is wider than W bricks. This should give the zombies something to hit their heads against. Or, in a useful wall, at least one column is higher than H bricks. This provides a lookout from which zombies can be spotted at a distance. This should rule out a fair amount of possibilities, right? Help Heidi compute the number of useless walls that do not confirm to either of these criteria. In other words, a wall is useless if every segment has width at most W and height at most H.Parameter C, the total width of the wall, has the same meaning as in the easy version. However, note that the number of bricks is now unlimited.Output the number of useless walls modulo 106 + 3.
The first and the only line of the input contains three space-separated integers C, W and H (1 ≀ C ≀ 108, 1 ≀ W, H ≀ 100).
Output the number of different walls, modulo 106 + 3, which are useless according to Heidi's criteria.
If there is no brick in any of the columns, the structure is considered as a useless wall.
Input: 1 1 1 | Output: 2
Hard
1
998
122
102
6
1,473
E
1473E
E. Minimum Path
2,400
graphs; shortest paths
You are given a weighted undirected connected graph consisting of \(n\) vertices and \(m\) edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Let's define the weight of the path consisting of \(k\) edges with indices \(e_1, e_2, \dots, e_k\) as \(\sum\limits_{i=1}^{k}{w_{e_i}} - \max\limits_{i=1}^{k}{w_{e_i}} + \min\limits_{i=1}^{k}{w_{e_i}}\), where \(w_i\) β€” weight of the \(i\)-th edge in the graph.Your task is to find the minimum weight of the path from the \(1\)-st vertex to the \(i\)-th vertex for each \(i\) (\(2 \le i \le n\)).
The first line contains two integers \(n\) and \(m\) (\(2 \le n \le 2 \cdot 10^5\); \(1 \le m \le 2 \cdot 10^5\)) β€” the number of vertices and the number of edges in the graph.Following \(m\) lines contains three integers \(v_i, u_i, w_i\) (\(1 \le v_i, u_i \le n\); \(1 \le w_i \le 10^9\); \(v_i \neq u_i\)) β€” endpoints of the \(i\)-th edge and its weight respectively.
Print \(n-1\) integers β€” the minimum weight of the path from \(1\)-st vertex to the \(i\)-th vertex for each \(i\) (\(2 \le i \le n\)).
Input: 5 4 5 3 4 2 1 1 3 2 2 2 4 2 | Output: 1 2 2 4
Expert
2
578
370
135
14
2,021
E3
2021E3
E3. Digital Village (Extreme Version)
2,800
data structures; dfs and similar; dp; dsu; graphs; greedy; math; trees
This is the extreme version of the problem. In the three versions, the constraints on \(n\) and \(m\) are different. You can make hacks only if all the versions of the problem are solved.Pak Chanek is setting up internet connections for the village of Khuntien. The village can be represented as a connected simple graph with \(n\) houses and \(m\) internet cables connecting house \(u_i\) and house \(v_i\), each with a latency of \(w_i\).There are \(p\) houses that require internet. Pak Chanek can install servers in at most \(k\) of the houses. The houses that need internet will then be connected to one of the servers. However, since each cable has its latency, the latency experienced by house \(s_i\) requiring internet will be the maximum latency of the cables between that house and the server it is connected to.For each \(k = 1,2,\ldots,n\), help Pak Chanek determine the minimum total latency that can be achieved for all the houses requiring internet.
Each 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 3 integers \(n\), \(m\), \(p\) (\(2 \le n \le 2 \cdot 10^5\); \(n-1 \le m \le 2 \cdot 10^5\); \(1 \le p \le n\)) β€” the number of houses, the number of cables, and the number of houses that need internet.The second line of each test case contains \(p\) integers \(s_1, s_2, \ldots, s_p\) (\(1 \le s_i \le n\)) β€” the houses that need internet. It is guaranteed that all elements of \(s\) are distinct. The \(i\)-th of the next \(m\) lines of each test case contains three integers \(u_i\), \(v_i\), and \(w_i\) (\(1 \le u_i < v_i \le n\); \(1 \le w_i \le 10^9\)) β€” the internet cable connecting house \(u_i\) and house \(v_i\) with latency of \(w_i\). It is guaranteed that the given edges form a connected simple graph.It is guaranteed that the sum of \(n\) and the sum of \(m\) do not exceed \(2 \cdot 10^5\).
For each test case, output \(n\) integers: the minimum total latency that can be achieved for all the houses requiring internet for each \(k = 1,2,\ldots,n\).
In the first test case for \(k=3\), a possible optimal solution is to install servers at vertices \(2\), \(6\) and \(8\) and obtain the following latency: \(\text{latency}(2) = 0\) \(\text{latency}(5) = \max(3, 5) = 5\) \(\text{latency}(6) = 0\) \(\text{latency}(8) = 0\) \(\text{latency}(9) = \max(2, 4) = 4\) So the total latency is \(9\).
Input: 29 8 52 5 6 8 91 2 11 3 23 4 104 5 34 6 51 7 107 8 47 9 23 3 23 11 2 12 3 31 3 2 | Output: 34 19 9 4 0 0 0 0 0 2 0 0
Master
8
965
1,012
158
20
698
E
698E
E. Cron
2,800
Sometime the classic solution are not powerful enough and we have to design our own. For the purpose of this problem you have to implement the part of the system of task scheduling.Each task should be executed at some particular moments of time. In our system you may set the exact value for the second, minute, hour, day of the week, day and month, when the task should be executed. Moreover, one can set a special value -1 that means any value of this parameter is valid.For example, if the parameter string is -1 59 23 -1 -1 -1, the problem will be executed every day at 23:59:00, 23:59:01, 23:59:02, ..., 23:59:59 (60 times in total).Seconds, minutes and hours are numbered starting from zero, while day, months and days of the week are numbered starting from one. The first day of the week is Monday.There is one special case that is treated separately. If both day of the week and day are given (i.e. differ from -1) to execute the task only one of these two (at least one, if both match this is fine too) parameters should match the current time (of course, all other parameters should match too). For example, the string of parameters 0 0 12 6 3 7 means that the task will be executed both on Saturday, July 2nd, 2016 and on Sunday, July 3rd, 2016 at noon.One should not forget about the existence of the leap years. The year is leap if it's number is divisible by 400, or is not divisible by 100, but is divisible by 4. Each leap year has 366 days instead of usual 365, by extending February to 29 days rather than the common 28.The current time is represented as the number of seconds passed after 00:00:00 January 1st, 1970 (Thursday).You are given the string of six parameters, describing the moments of time the task should be executed. You are also given a number of moments of time. For each of them you have to find the first moment of time strictly greater than the current when the task will be executed.
The first line of the input contains six integers s, m, h, day, date and month (0 ≀ s, m ≀ 59, 0 ≀ h ≀ 23, 1 ≀ day ≀ 7, 1 ≀ date ≀ 31, 1 ≀ month ≀ 12). Each of the number can also be equal to - 1. It's guaranteed, that there are infinitely many moments of time when this task should be executed.Next line contains the only integer n (1 ≀ n ≀ 1000) β€” the number of moments of time you have to solve the problem for. Each of the next n lines contains a single integer ti (0 ≀ ti ≀ 1012).
Print n lines, the i-th of them should contain the first moment of time strictly greater than ti, when the task should be executed.
The moment of time 1467372658 after the midnight of January 1st, 1970 is 11:30:58 July 1st, 2016.
Input: -1 59 23 -1 -1 -16146737265814674175401467417541146741759814674175991467417600 | Output: 146741754014674175411467417542146741759914675039401467503940
Master
0
1,922
485
131
6
444
A
444A
A. DZY Loves Physics
1,600
greedy; math
DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
The first line contains two space-separated integers n (1 ≀ n ≀ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges.The second line contains n space-separated integers xi (1 ≀ xi ≀ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≀ ai < bi ≀ n; 1 ≀ ci ≀ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.
Input: 1 01 | Output: 0.000000000000000
Medium
2
777
534
95
4
1,763
F
1763F
F. Edge Queries
3,000
data structures; dfs and similar; dp; dsu; graphs; trees
You are given an undirected, connected graph of \(n\) nodes and \(m\) edges. All nodes \(u\) of the graph satisfy the following: Let \(S_u\) be the set of vertices in the longest simple cycle starting and ending at \(u\). Let \(C_u\) be the union of the sets of vertices in any simple cycle starting and ending at \(u\). \(S_u = C_u\). You need to answer \(q\) queries.For each query, you will be given node \(a\) and node \(b\). Out of all the edges that belong to any simple path from \(a\) to \(b\), count the number of edges such that if you remove that edge, \(a\) and \(b\) are reachable from each other.
The first line contains two integers \(n\) and \(m\) (\(2 \le n \le 2 \cdot 10^5\), \(1 \le m \le \min\)(\(2 \cdot 10^5\), \((n \cdot (n-1))/2\))) β€” the total number of nodes and edges in the graph, respectively.The next \(m\) lines contain two integers \(u\) and \(v\) (\(1 \le\) \(u\), \(v\) \(\le n\), \(u \neq v\)) β€” describing an edge, implying that nodes \(u\) and \(v\) are connected to each other.It is guaranteed that there is at most one edge between any pair of vertices in the graph and the given graph is connected.The next line contains a single integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) β€” the number of queries.Then \(q\) lines follow, each representing a query. Each query contains two integers \(a\) and \(b\) (\(1 \le\) \(a\), \(b\) \(\le n\)).
For each query, output a single integer β€” answer to the query.
The graph in the first sample is : The first query is \((1, 4)\). There are \(5\) total edges that belong to any simple path from \(1\) to \(4\). Edges \((3, 4), (4, 5), (5, 3)\) will be counted in the answer to the query.The fourth query is \((2, 8)\). There is only one simple path from \(2\) to \(8\), thus none of the edges will be counted in the answer to the query.The fifth query is \((7, 10)\). There are \(4\) total edges that belong to any simple path from \(7\) to \(10\), all of them will be counted in the answer to the query.
Input: 10 11 1 2 2 3 3 4 4 5 5 3 2 7 7 9 9 10 10 6 6 7 1 8 5 1 4 5 10 3 5 2 8 7 10 | Output: 3 7 3 0 4
Master
6
610
765
62
17
1,260
F
1260F
F. Colored Tree
2,700
data structures; trees
You're given a tree with \(n\) vertices. The color of the \(i\)-th vertex is \(h_{i}\).The value of the tree is defined as \(\sum\limits_{h_{i} = h_{j}, 1 \le i < j \le n}{dis(i,j)}\), where \(dis(i,j)\) is the number of edges on the shortest path between \(i\) and \(j\). The color of each vertex is lost, you only remember that \(h_{i}\) can be any integer from \([l_{i}, r_{i}]\)(inclusive). You want to calculate the sum of values of all trees meeting these conditions modulo \(10^9 + 7\) (the set of edges is fixed, but each color is unknown, so there are \(\prod\limits_{i = 1}^{n} (r_{i} - l_{i} + 1)\) different trees).
The first line contains one integer \(n\) (\(2 \le n \le 10^5\)) β€” the number of vertices.Then \(n\) lines follow, each line contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le 10^5\)) denoting the range of possible colors of vertex \(i\).Then \(n - 1\) lines follow, each containing two integers \(u\) and \(v\) (\(1 \le u, v \le n\), \(u \ne v\)) denoting an edge of the tree. It is guaranteed that these edges form a tree.
Print one integer β€” the sum of values of all possible trees, taken modulo \(10^9 + 7\).
In the first example there are four different ways to color the tree (so, there are four different trees): a tree with vertices colored as follows: \(\lbrace 1,1,1,1 \rbrace\). The value of this tree is \(dis(1,2)+dis(1,3)+dis(1,4)+dis(2,3)+dis(2,4)+dis(3,4) = 10\); a tree with vertices colored as follows: \(\lbrace 1,2,1,1 \rbrace\). The value of this tree is \(dis(1,3)+dis(1,4)+dis(3,4)=4\); a tree with vertices colored as follows: \(\lbrace 1,1,1,2 \rbrace\). The value of this tree is \(dis(1,2)+dis(1,3)+dis(2,3)=4\); a tree with vertices colored as follows: \(\lbrace 1,2,1,2 \rbrace\). The value of this tree is \(dis(1,3)+dis(2,4)=4\). Overall the sum of all values is \(10+4+4+4=22\).
Input: 4 1 1 1 2 1 1 1 2 1 2 1 3 3 4 | Output: 22
Master
2
627
440
87
12
1,560
D
1560D
D. Make a Power of Two
1,300
greedy; math; strings
You are given an integer \(n\). In \(1\) move, you can do one of the following actions: erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is ""empty""); add one digit to the right. The actions may be performed in any order any number of times.Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number \(301\) the digit \(3\), the result is the number \(01\) (not \(1\)).You need to perform the minimum number of actions to make the number any power of \(2\) (i.e. there's an integer \(k\) (\(k \ge 0\)) such that the resulting number is equal to \(2^k\)). The resulting number must not have leading zeroes.E.g. consider \(n=1052\). The answer is equal to \(2\). First, let's add to the right one digit \(4\) (the result will be \(10524\)). Then let's erase the digit \(5\), so the result will be \(1024\) which is a power of \(2\).E.g. consider \(n=8888\). The answer is equal to \(3\). Let's erase any of the digits \(8\) three times. The result will be \(8\) which is a power of \(2\).
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.Each test case consists of one line containing one integer \(n\) (\(1 \le n \le 10^9\)).
For each test case, output in a separate line one integer \(m\) β€” the minimum number of moves to transform the number into any power of \(2\).
The answer for the first test case was considered above.The answer for the second test case was considered above.In the third test case, it's enough to add to the right the digit \(4\) β€” the number \(6\) will turn into \(64\).In the fourth test case, let's add to the right the digit \(8\) and then erase \(7\) and \(5\) β€” the taken number will turn into \(8\).The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move.In the seventh test case, you can delete first of all the digit \(3\) (the result is \(01\)) and then the digit \(0\) (the result is \(1\)).
Input: 12 1052 8888 6 75 128 1 301 12048 1504 6656 1000000000 687194767 | Output: 2 3 1 3 0 0 2 1 3 4 9 2
Easy
3
1,161
210
142
15
106
C
106C
C. Buns
1,700
dp
Lavrenty, a baker, is going to make several buns with stuffings and sell them.Lavrenty has n grams of dough as well as m different stuffing types. The stuffing types are numerated from 1 to m. Lavrenty knows that he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough to cook a bun with the i-th stuffing. Such bun can be sold for di tugriks.Also he can make buns without stuffings. Each of such buns requires c0 grams of dough and it can be sold for d0 tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking.Find the maximum number of tugriks Lavrenty can earn.
The first line contains 4 integers n, m, c0 and d0 (1 ≀ n ≀ 1000, 1 ≀ m ≀ 10, 1 ≀ c0, d0 ≀ 100). Each of the following m lines contains 4 integers. The i-th line contains numbers ai, bi, ci and di (1 ≀ ai, bi, ci, di ≀ 100).
Print the only number β€” the maximum number of tugriks Lavrenty can earn.
To get the maximum number of tugriks in the first sample, you need to cook 2 buns with stuffing 1, 4 buns with stuffing 2 and a bun without any stuffing.In the second sample Lavrenty should cook 4 buns without stuffings.
Input: 10 2 2 17 3 2 10012 3 1 10 | Output: 241
Medium
1
751
224
72
1
41
A
41A
A. Translation
800
implementation; strings
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a Berlandish word differs from a Birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, making a mistake during the ""translation"" is easy. Vasya translated the word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not contain unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
If the word t is a word s, written reversely, print YES, otherwise print NO.
Input: codeedoc | Output: YES
Beginner
2
504
229
76
0
1,873
A
1873A
A. Short Sort
800
brute force; implementation
There are three cards with letters \(\texttt{a}\), \(\texttt{b}\), \(\texttt{c}\) placed in a row in some order. You can do the following operation at most once: Pick two cards, and swap them. Is it possible that the row becomes \(\texttt{abc}\) after the operation? Output ""YES"" if it is possible, and ""NO"" otherwise.
The first line contains a single integer \(t\) (\(1 \leq t \leq 6\)) β€” the number of test cases.The only line of each test case contains a single string consisting of each of the three characters \(\texttt{a}\), \(\texttt{b}\), and \(\texttt{c}\) exactly once, representing the cards.
For each test case, output ""YES"" if you can make the row \(\texttt{abc}\) with at most one operation, or ""NO"" otherwise.You can output the answer in any case (for example, the strings ""yEs"", ""yes"", ""Yes"" and ""YES"" will be recognized as a positive answer).
In the first test case, we don't need to do any operations, since the row is already \(\texttt{abc}\).In the second test case, we can swap \(\texttt{c}\) and \(\texttt{b}\): \(\texttt{acb} \to \texttt{abc}\).In the third test case, we can swap \(\texttt{b}\) and \(\texttt{a}\): \(\texttt{bac} \to \texttt{abc}\).In the fourth test case, it is impossible to make \(\texttt{abc}\) using at most one operation.
Input: 6abcacbbacbcacabcba | Output: YES YES YES NO NO YES
Beginner
2
322
284
267
18
578
C
578C
C. Weakness and Poorness
2,000
ternary search
You are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.The poorness of a segment is defined as the absolute value of sum of the elements of segment.
The first line contains one integer n (1 ≀ n ≀ 200 000), the length of a sequence.The second line contains n integers a1, a2, ..., an (|ai| ≀ 10 000).
Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment ""-1"" or segment ""1"". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment ""-1.5 -0.5"" or ""0.5 1.5"". The poorness value (answer) equals to 2 in this case.
Input: 31 2 3 | Output: 1.000000000000000
Hard
1
399
150
187
5
1,098
E
1098E
E. Fedya the Potter
3,400
binary search; implementation; math; number theory
Fedya loves problems involving data structures. Especially ones about different queries on subsegments. Fedya had a nice array \(a_1, a_2, \ldots a_n\) and a beautiful data structure. This data structure, given \(l\) and \(r\), \(1 \le l \le r \le n\), could find the greatest integer \(d\), such that \(d\) divides each of \(a_l\), \(a_{l+1}\), ..., \(a_{r}\). Fedya really likes this data structure, so he applied it to every non-empty contiguous subarray of array \(a\), put all answers into the array and sorted it. He called this array \(b\). It's easy to see that array \(b\) contains \(n(n+1)/2\) elements.After that, Fedya implemented another cool data structure, that allowed him to find sum \(b_l + b_{l+1} + \ldots + b_r\) for given \(l\) and \(r\), \(1 \le l \le r \le n(n+1)/2\). Surely, Fedya applied this data structure to every contiguous subarray of array \(b\), called the result \(c\) and sorted it. Help Fedya find the lower median of array \(c\).Recall that for a sorted array of length \(k\) the lower median is an element at position \(\lfloor \frac{k + 1}{2} \rfloor\), if elements of the array are enumerated starting from \(1\). For example, the lower median of array \((1, 1, 2, 3, 6)\) is \(2\), and the lower median of \((0, 17, 23, 96)\) is \(17\).
First line contains a single integer \(n\) β€” number of elements in array \(a\) (\(1 \le n \le 50\,000\)). Second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) β€” elements of the array (\(1 \le a_i \le 100\,000\)).
Print a single integer β€” the lower median of array \(c\).
In the first sample array \(b\) is equal to \({3, 3, 6}\), then array \(c\) is equal to \({3, 3, 6, 6, 9, 12}\), so the lower median is \(6\).In the second sample \(b\) is \({8, 8, 8}\), \(c\) is \({8, 8, 8, 16, 16, 24}\), so the lower median is \(8\).
Input: 2 6 3 | Output: 6
Master
4
1,278
221
57
10
887
F
887F
F. Row of Models
2,500
greedy; sortings
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it. Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc). She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.
In first line there are two integers n and k (1 ≀ n ≀ 5Β·105, 1 ≀ k ≀ n) β€” number of models and required distance.Second line contains n space-separated integers ai (1 ≀ ai ≀ 109) β€” height of each model. Pay attention that height of fashion designer is not given and can be less than 1.
Print Β«YESΒ» (without quotes) if it's possible to make row nice using at most one exchange, and Β«NOΒ» (without quotes) otherwise.
Input: 5 42 3 5 2 5 | Output: NO
Expert
2
1,143
285
127
8
1,927
D
1927D
D. Find the Different Ones!
1,300
binary search; brute force; data structures; dp; dsu; greedy; two pointers
You are given an array \(a\) of \(n\) integers, and \(q\) queries.Each query is represented by two integers \(l\) and \(r\) (\(1 \le l \le r \le n\)). Your task is to find, for each query, two indices \(i\) and \(j\) (or determine that they do not exist) such that: \(l \le i \le r\); \(l \le j \le r\); \(a_i \ne a_j\). In other words, for each query, you need to find a pair of different elements among \(a_l, a_{l+1}, \dots, a_r\), or report that such a pair does not exist.
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The descriptions of the test cases follow.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” the length of the array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^6\)) β€” the elements of the array \(a\).The third line of each test case contains a single integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) β€” the number of queries.The next \(q\) lines contain two integers each, \(l\) and \(r\) (\(1 \le l < r \le n\)) β€” the boundaries of the query.It is guaranteed that the sum of the values of \(n\) across all test cases does not exceed \(2 \cdot 10^5\). Similarly, it is guaranteed that the sum of the values of \(q\) across all test cases does not exceed \(2 \cdot 10^5\).
For each query, output two integers separated by space: \(i\) and \(j\) (\(l \le i, j \le r\)), for which \(a_i \ne a_j\). If such a pair does not exist, output \(i=-1\) and \(j=-1\).You may separate the outputs for the test cases with empty lines. This is not a mandatory requirement.
Input: 551 1 2 1 131 51 21 3630 20 20 10 10 2051 22 32 42 63 545 2 3 441 21 42 32 451 4 3 2 451 52 43 43 54 552 3 1 4 271 21 41 52 42 53 54 5 | Output: 2 3 -1 -1 1 3 2 1 -1 -1 4 2 4 6 5 3 1 2 1 2 2 3 3 2 1 3 2 4 3 4 5 3 5 4 1 2 4 2 1 3 2 3 3 2 5 4 5 4
Easy
7
477
889
285
19
1,471
A
1471A
A. Strange Partition
900
greedy; math; number theory
You are given an array \(a\) of length \(n\), and an integer \(x\). You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was \([3, 6, 9]\), in a single operation one can replace the last two elements by their sum, yielding an array \([3, 15]\), or replace the first two elements to get an array \([9, 9]\). Note that the size of the array decreases after each operation.The beauty of an array \(b=[b_1, \ldots, b_k]\) is defined as \(\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil\), which means that we divide each element by \(x\), round it up to the nearest integer, and sum up the resulting values. For example, if \(x = 3\), and the array is \([4, 11, 6]\), the beauty of the array is equal to \(\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8\).Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.
The first input line contains a single integer \(t\) β€” the number of test cases (\(1 \le t \le 1000\)).The first line of each test case contains two integers \(n\) and \(x\) (\(1 \leq n \leq 10^5\), \(1 \leq x \leq 10^9\)).The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)), the elements of the array \(a\). It is guaranteed that the sum of values of \(n\) over all test cases does not exceed \(10^5\).
For each test case output two integers β€” the minimal and the maximal possible beauty.
In the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements \(4\) and \(11\) with their sum, yielding an array \([6, 15]\), which has its beauty equal to \(7\).
Input: 23 33 6 93 36 4 11 | Output: 6 6 7 8
Beginner
3
1,083
442
85
14
1,003
D
1003D
D. Coins and Queries
1,600
greedy
Polycarp has \(n\) coins, the value of the \(i\)-th coin is \(a_i\). It is guaranteed that all the values are integer powers of \(2\) (i.e. \(a_i = 2^d\) for some non-negative integer number \(d\)).Polycarp wants to know answers on \(q\) queries. The \(j\)-th query is described as integer number \(b_j\). The answer to the query is the minimum number of coins that is necessary to obtain the value \(b_j\) using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value \(b_j\), the answer to the \(j\)-th query is -1.The queries are independent (the answer on the query doesn't affect Polycarp's coins).
The first line of the input contains two integers \(n\) and \(q\) (\(1 \le n, q \le 2 \cdot 10^5\)) β€” the number of coins and the number of queries.The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) β€” values of coins (\(1 \le a_i \le 2 \cdot 10^9\)). It is guaranteed that all \(a_i\) are integer powers of \(2\) (i.e. \(a_i = 2^d\) for some non-negative integer number \(d\)).The next \(q\) lines contain one integer each. The \(j\)-th line contains one integer \(b_j\) β€” the value of the \(j\)-th query (\(1 \le b_j \le 10^9\)).
Print \(q\) integers \(ans_j\). The \(j\)-th integer must be equal to the answer on the \(j\)-th query. If Polycarp can't obtain the value \(b_j\) the answer to the \(j\)-th query is -1.
Input: 5 42 4 8 2 4851410 | Output: 1-132
Medium
1
641
557
186
10
682
B
682B
B. Alyona and Mex
1,200
sortings
Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1, b2, ..., bn such that 1 ≀ bi ≀ ai for every 1 ≀ i ≀ n. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.
The first line of the input contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of elements in the Alyona's array.The second line of the input contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the array.
Print one positive integer β€” the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.
In the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements.
Input: 51 3 3 3 6 | Output: 5
Easy
1
807
229
129
6
1,598
A
1598A
A. Computer Game
800
brute force; dfs and similar; dp; implementation
Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of \(2\) rows and \(n\) columns. Monocarp controls a character, which starts in cell \((1, 1)\) β€” at the intersection of the \(1\)-st row and the \(1\)-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell \((x_1, y_1)\) to cell \((x_2, y_2)\) in one step if \(|x_1 - x_2| \le 1\) and \(|y_1 - y_2| \le 1\). Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell \((2, n)\) β€” at the intersection of row \(2\) and column \(n\).Help Monocarp determine if it is possible to complete the level.
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases. Then the test cases follow. Each test case consists of three lines.The first line contains a single integer \(n\) (\(3 \le n \le 100\)) β€” the number of columns.The next two lines describe the level. The \(i\)-th of these lines describes the \(i\)-th line of the level β€” the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell.Additional constraint on the input: cells \((1, 1)\) and \((2, n)\) are safe.
For each test case, output YES if it is possible to complete the level, and NO otherwise.
Consider the example from the statement.In the first test case, one of the possible paths is \((1, 1) \rightarrow (2, 2) \rightarrow (2, 3)\).In the second test case, one of the possible paths is \((1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)\).In the fourth test case, one of the possible paths is \((1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)\).
Input: 4 3 000 000 4 0011 1100 4 0111 1110 6 010101 101010 | Output: YES YES NO YES
Beginner
4
894
584
89
15
1,557
A
1557A
A. Ezzat and Two Subsequences
800
brute force; math; sortings
Ezzat has an array of \(n\) integers (maybe negative). He wants to split it into two non-empty subsequences \(a\) and \(b\), such that every element from the array belongs to exactly one subsequence, and the value of \(f(a) + f(b)\) is the maximum possible value, where \(f(x)\) is the average of the subsequence \(x\). A sequence \(x\) is a subsequence of a sequence \(y\) if \(x\) can be obtained from \(y\) by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of \([1,5,6]\) is \((1+5+6)/3 = 12/3 = 4\), so \(f([1,5,6]) = 4\).
The first line contains a single integer \(t\) (\(1 \le t \le 10^3\))β€” the number of test cases. Each test case consists of two lines.The first line contains a single integer \(n\) (\(2 \le n \le 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^9 \le a_i \le 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3\cdot10^5\).
For each test case, print a single value β€” the maximum value that Ezzat can achieve.Your answer is considered correct if its absolute or relative error does not exceed \(10^{-6}\).Formally, let your answer be \(a\), and the jury's answer be \(b\). Your answer is accepted if and only if \(\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}\).
In the first test case, the array is \([3, 1, 2]\). These are all the possible ways to split this array: \(a = [3]\), \(b = [1,2]\), so the value of \(f(a) + f(b) = 3 + 1.5 = 4.5\). \(a = [3,1]\), \(b = [2]\), so the value of \(f(a) + f(b) = 2 + 2 = 4\). \(a = [3,2]\), \(b = [1]\), so the value of \(f(a) + f(b) = 2.5 + 1 = 3.5\). Therefore, the maximum possible value \(4.5\).In the second test case, the array is \([-7, -6, -6]\). These are all the possible ways to split this array: \(a = [-7]\), \(b = [-6,-6]\), so the value of \(f(a) + f(b) = (-7) + (-6) = -13\). \(a = [-7,-6]\), \(b = [-6]\), so the value of \(f(a) + f(b) = (-6.5) + (-6) = -12.5\). Therefore, the maximum possible value \(-12.5\).
Input: 4 3 3 1 2 3 -7 -6 -6 3 2 2 2 4 17 3 5 -3 | Output: 4.500000000 -12.500000000 4.000000000 18.666666667
Beginner
3
671
389
334
15
1,172
D
1172D
D. Nauuo and Portals
2,900
constructive algorithms
Nauuo is a girl who loves playing games related to portals.One day she was playing a game as follows.In an \(n\times n\) grid, the rows are numbered from \(1\) to \(n\) from top to bottom, the columns are numbered from \(1\) to \(n\) from left to right. We denote a cell on the intersection of the \(r\)-th row and \(c\)-th column as \((r,c)\).A portal is a pair of doors. You can travel from one of them to another without changing your direction. More formally, if you walk into a cell with a door, you will teleport to the cell with the other door of the same portal and then walk into the next cell facing the original direction. There can not be more than one doors in a single cell.The ""next cell"" is the nearest cell in the direction you are facing. For example, if you are facing bottom, the next cell of \((2,5)\) is \((3,5)\).If you walk into a cell without a door, you must walk into the next cell after that without changing the direction. If the next cell does not exist, you must exit the grid.You have to set some (possibly zero) portals in the grid, so that if you walk into \((i,1)\) facing right, you will eventually exit the grid from \((r_i,n)\), if you walk into \((1, i)\) facing bottom, you will exit the grid from \((n,c_i)\).It is guaranteed that both \(r_{1..n}\) and \(c_{1..n}\) are permutations of \(n\) elements. A permutation of \(n\) elements is a sequence of numbers \(p_1,p_2,\ldots,p_n\) in which every integer from \(1\) to \(n\) appears exactly once.She got confused while playing the game, can you help her to find a solution?
The first line contains a single integer \(n\) (\(1\le n\le 1000\)) β€” the side length of the grid.The second line contains \(n\) integers \(r_1,r_2,\ldots,r_n\) (\(1\le r_i\le n\)) β€” if you walk into \((i,1)\) facing right, you should exit the grid from \((r_i,n)\). It is guaranteed that \(r_{1..n}\) is a permutation of \(n\) elements.The third line contains \(n\) integers \(c_1,c_2,\ldots,c_n\) (\(1\le c_i\le n\)) β€” if you walk into \((1,i)\) facing bottom, you should exit the grid from \((n,c_i)\). It is guaranteed that \(c_{1..n}\) is a permutation of \(n\) elements.
If it is impossible to satisfy the rule, print the only number \(-1\).Otherwise the first line should contain a single integer \(m\) (\(0\le m\le\frac{n^2}2\)) β€” the number of portals you set.In the following \(m\) lines, each line should contain four integers \(x_1,y_1,x_2,y_2\), represents that you set a portal consisting of two doors in \((x_1,y_1)\) and \((x_2,y_2)\).If there are multiple answers, print any. You do not have to minimize \(m\).
Example 1The cells with the same letter are a portal. You can set portals in this way:It satisfies the rule, because:Example 2You can set portals in this way:
Input: 3 1 3 2 3 1 2 | Output: 2 1 1 1 3 2 2 3 1
Master
1
1,566
576
450
11
1,450
H2
1450H2
H2. Multithreading (Hard Version)
3,300
combinatorics; implementation; math
The only difference between the two versions of the problem is that there are no updates in the easy version.There are \(n\) spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.For any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.Coloring is an assignment of colors (white and black) to the spools. A coloring is called valid if it has at least one matching. That is if the number of black spools and the number of white spools are both even.Given a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If \(c\) is a valid coloring, let \(f(c)\) denote the minimum number of such intersections out of all possible matchings. The circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so \(f(\text{bwbbbwww}) = 1\). You are given a string \(s\) representing an unfinished coloring, with black, white, and uncolored spools. A coloring \(c\) is called \(s\)-reachable if you can achieve it by assigning colors to the uncolored spools of \(s\) without changing the others.A coloring \(c\) is chosen uniformly at random among all valid, \(s\)-reachable colorings. Compute the expected value of \(f(c)\). You should find it by modulo \(998244353\).There will be \(m\) updates to change one character of \(s\). After each update, you should again compute the expected value of \(f(c)\).We can show that each answer can be written in the form \(\frac{p}{q}\) where \(p\) and \(q\) are relatively prime integers and \(q\not\equiv 0\pmod{998244353}\). The answer by modulo \(998244353\) is equal to \((p\cdot q^{-1})\) modulo \(998244353\).
The first line contains two integers \(n\), \(m\) (\(2\le n\le 2\cdot 10^5\), \(n\) is even, \(0\le m\le 2\cdot 10^5\)) β€” the number of spools and the number of updates, respectively.The second line contains a string \(s\) of length \(n\) β€” the unfinished coloring of the spools. The \(i\)-th character will be 'w', 'b', or '?', describing if the \(i\)-th spool is white, black, or uncolored, respectively.Each of the next \(m\) lines contains an integer \(i\) (\(1 \leq i \leq n\)) β€” the position of the character in \(s\) to be updated, and a character \(c\) (\(c \in \{\text{w}, \text{b}, \text{?}\}\)) β€” the new color of the spool \(i\) after the update.It is guaranteed there exists at least one uncolored spool initially and after each update.
Print \(m+1\) lines: the expected value of \(f(c)\) initially and after each update. All values should be found by modulo \(998244353\).
The first test corresponds closely to the image. Coloring '?' as 'w' does not create a valid coloring because the number of black spools is odd. Then the only reachable valid coloring is 'bwbbbwww' and \(f(\text{bwbbbwww}) = 1\), so the expected value is \(1\).In the second test, the string after each update is: ????w?wb?? ??????wb?? ?w????wb?? In the third test, the string after each update is: ww?b wb?b wb?b
Input: 8 0 bwbb?www | Output: 1
Master
3
2,224
749
136
14
376
B
376B
B. I.O.U.
1,300
implementation
Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles.Assume that the people are numbered by integers from 1 to n.It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).
Print a single integer β€” the minimum sum of debts in the optimal rearrangement.
In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.In the second sample, there are no debts.In the third sample, you can annul all the debts.
Input: 5 31 2 102 3 12 4 1 | Output: 10
Easy
1
893
479
79
3
13
D
13D
D. Triangles
2,600
dp; geometry
Little Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.
The first line contains two non-negative integer numbers N and M (0 ≀ N ≀ 500, 0 ≀ M ≀ 500) β€” the number of red and blue points respectively. The following N lines contain two integer numbers each β€” coordinates of red points. The following M lines contain two integer numbers each β€” coordinates of blue points. All coordinates do not exceed 109 by absolute value.
Output one integer β€” the number of distinct triangles with vertices in red points which do not contain any blue point inside.
Input: 4 10 010 010 105 42 1 | Output: 2
Expert
2
257
363
125
0
2,023
C
2023C
C. C+K+S
2,400
constructive algorithms; dfs and similar; graphs; greedy; hashing; implementation; strings
You are given two strongly connected\(^{\dagger}\) directed graphs, each with exactly \(n\) vertices, but possibly different numbers of edges. Upon closer inspection, you noticed an important feature β€” the length of any cycle in these graphs is divisible by \(k\).Each of the \(2n\) vertices belongs to exactly one of two types: incoming or outgoing. For each vertex, its type is known to you.You need to determine whether it is possible to draw exactly \(n\) directed edges between the source graphs such that the following four conditions are met: The ends of any added edge lie in different graphs. From each outgoing vertex, exactly one added edge originates. Into each incoming vertex, exactly one added edge enters. In the resulting graph, the length of any cycle is divisible by \(k\). \(^{\dagger}\)A strongly connected graph is a graph in which there is a path from every vertex to every other vertex.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(k\) (\(2 \le k \le n \le 2 \cdot 10^5\)) β€” the number of vertices in each graph and the value by which the length of each cycle is divisible.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(a_i \in \{0, 1\}\)). If \(a_i = 0\), then vertex \(i\) of the first graph is incoming. If \(a_i = 1\), then vertex \(i\) of the first graph is outgoing.The third line of each test case contains a single integer \(m_1\) (\(1 \le m_1 \le 5 \cdot 10^5\)) β€” the number of edges in the first graph.The next \(m_1\) lines contain descriptions of the edges of the first graph. The \(i\)-th of them contains two integers \(v_i\) and \(u_i\) (\(1 \le v_i, u_i \le n\)) β€” an edge in the first graph leading from vertex \(v_i\) to vertex \(u_i\).Next, in the same format, follows the description of the second graph.The next line contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(b_i \in \{0, 1\}\)). If \(b_i = 0\), then vertex \(i\) of the second graph is incoming. If \(b_i = 1\), then vertex \(i\) of the second graph is outgoing.The next line contains a single integer \(m_2\) (\(1 \le m_2 \le 5 \cdot 10^5\)) β€” the number of edges in the second graph.The next \(m_2\) lines contain descriptions of the edges of the second graph. The \(i\)-th of them contains two integers \(v_i\) and \(u_i\) (\(1 \le v_i, u_i \le n\)) β€” an edge in the second graph leading from vertex \(v_i\) to vertex \(u_i\).It is guaranteed that both graphs are strongly connected, and the lengths of all cycles are divisible by \(k\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\). It is guaranteed that the sum of \(m_1\) and the sum of \(m_2\) over all test cases does not exceed \(5 \cdot 10^5\).
For each test case, output ""YES"" (without quotes) if it is possible to draw \(n\) new edges such that all conditions are met, and ""NO"" (without quotes) otherwise.You may output the answer in any case (for example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as a positive answer).
In the first test case, it is possible to draw edges from the first graph to the second graph as \((1, 3)\) and \((4, 2)\) (the first number in the pair is the vertex number in the first graph, and the second number in the pair is the vertex number in the second graph), and from the second graph to the first graph as \((1, 2)\), \((4, 3)\) (the first number in the pair is the vertex number in the second graph, and the second number in the pair is the vertex number in the first graph).In the second test case, there are a total of \(4\) incoming vertices and \(2\) outgoing vertices, so it is not possible to draw \(3\) edges.
Input: 34 21 0 0 141 22 33 44 11 0 0 141 33 22 44 13 30 0 031 22 33 11 1 031 22 33 14 21 1 1 141 22 33 44 10 0 0 061 22 11 33 11 44 1 | Output: YES NO YES
Expert
7
910
1,992
310
20
1,674
D
1674D
D. A-B-C Sort
1,200
constructive algorithms; implementation; sortings
You are given three arrays \(a\), \(b\) and \(c\). Initially, array \(a\) consists of \(n\) elements, arrays \(b\) and \(c\) are empty.You are performing the following algorithm that consists of two steps: Step \(1\): while \(a\) is not empty, you take the last element from \(a\) and move it in the middle of array \(b\). If \(b\) currently has odd length, you can choose: place the element from \(a\) to the left or to the right of the middle element of \(b\). As a result, \(a\) becomes empty and \(b\) consists of \(n\) elements. Step \(2\): while \(b\) is not empty, you take the middle element from \(b\) and move it to the end of array \(c\). If \(b\) currently has even length, you can choose which of two middle elements to take. As a result, \(b\) becomes empty and \(c\) now consists of \(n\) elements. Refer to the Note section for examples.Can you make array \(c\) sorted in non-decreasing order?
The first line contains a single integer \(t\) (\(1 \le t \le 2 \cdot 10^4\)) β€” the number of test cases. Next \(t\) cases follow.The first line of each test case contains the single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the length of array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^6\)) β€” the array \(a\) itself.It's guaranteed that the sum of \(n\) doesn't exceed \(2 \cdot 10^5\).
For each test, print YES (case-insensitive), if you can make array \(c\) sorted in non-decreasing order. Otherwise, print NO (case-insensitive).
In the first test case, we can do the following for \(a = [3, 1, 5, 3]\):Step \(1\): \(a\)\([3, 1, 5, 3]\)\(\Rightarrow\)\([3, 1, 5]\)\(\Rightarrow\)\([3, 1]\)\(\Rightarrow\)\([3]\)\(\Rightarrow\)\([]\)\(b\)\([]\)\([\underline{3}]\)\([3, \underline{5}]\)\([3, \underline{1}, 5]\)\([3, \underline{3}, 1, 5]\)Step \(2\): \(b\)\([3, 3, \underline{1}, 5]\)\(\Rightarrow\)\([3, \underline{3}, 5]\)\(\Rightarrow\)\([\underline{3}, 5]\)\(\Rightarrow\)\([\underline{5}]\)\(\Rightarrow\)\([]\)\(c\)\([]\)\([1]\)\([1, 3]\)\([1, 3, 3]\)\([1, 3, 3, 5]\) As a result, array \(c = [1, 3, 3, 5]\) and it's sorted.
Input: 343 1 5 333 2 117331 | Output: YES NO YES
Easy
3
909
459
144
16
1,303
E
1303E
E. Erase Subsequences
2,200
dp; strings
You are given a string \(s\). You can build new string \(p\) from \(s\) using the following operation no more than two times: choose any subsequence \(s_{i_1}, s_{i_2}, \dots, s_{i_k}\) where \(1 \le i_1 < i_2 < \dots < i_k \le |s|\); erase the chosen subsequence from \(s\) (\(s\) can become empty); concatenate chosen subsequence to the right of the string \(p\) (in other words, \(p = p + s_{i_1}s_{i_2}\dots s_{i_k}\)). Of course, initially the string \(p\) is empty. For example, let \(s = \text{ababcd}\). At first, let's choose subsequence \(s_1 s_4 s_5 = \text{abc}\) β€” we will get \(s = \text{bad}\) and \(p = \text{abc}\). At second, let's choose \(s_1 s_2 = \text{ba}\) β€” we will get \(s = \text{d}\) and \(p = \text{abcba}\). So we can build \(\text{abcba}\) from \(\text{ababcd}\).Can you build a given string \(t\) using the algorithm above?
The first line contains the single integer \(T\) (\(1 \le T \le 100\)) β€” the number of test cases.Next \(2T\) lines contain test cases β€” two per test case. The first line contains string \(s\) consisting of lowercase Latin letters (\(1 \le |s| \le 400\)) β€” the initial string.The second line contains string \(t\) consisting of lowercase Latin letters (\(1 \le |t| \le |s|\)) β€” the string you'd like to build.It's guaranteed that the total length of strings \(s\) doesn't exceed \(400\).
Print \(T\) answers β€” one per test case. Print YES (case insensitive) if it's possible to build \(t\) and NO (case insensitive) otherwise.
Input: 4 ababcd abcba a b defi fed xyz x | Output: YES NO NO YES
Hard
2
855
487
138
13
1,284
G
1284G
G. Seollal
3,300
graphs
It 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.
Your 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\)).
For 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.
Input: 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
Master
1
2,031
812
1,362
12
650
E
650E
E. Clockwork Bomb
3,200
data structures; dfs and similar; dsu; greedy; trees
My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment.I was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner.I see n contacts connected by n - 1 wires. Contacts are numbered with integers from 1 to n. Bomb has a security mechanism that ensures the following condition: if there exist k β‰₯ 2 contacts c1, c2, ..., ck forming a circuit, i. e. there exist k distinct wires between contacts c1 and c2, c2 and c3, ..., ck and c1, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length 2. It is also prohibited to connect a contact with itself.On the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than n - 2 wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear.I know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused.
The first line of the input contains n (2 ≀ n ≀ 500 000), the number of contacts.Each of the following n - 1 lines contains two of integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi) denoting the contacts currently connected by the i-th wire.The remaining n - 1 lines contain the description of the sought scheme in the same format.It is guaranteed that the starting and the ending schemes are correct (i. e. do not contain cicuits nor wires connecting contact with itself).
The first line should contain k (k β‰₯ 0) β€” the minimum number of moves of unplugging and plugging back some wire required to defuse the bomb.In each of the following k lines output four integers ai, bi, ci, di meaning that on the i-th step it is neccesary to unplug the wire connecting the contacts ai and bi and plug it to the contacts ci and di. Of course the wire connecting contacts ai and bi should be present in the scheme.If there is no correct sequence transforming the existing scheme into the sought one, output -1.
Picture with the clarification for the sample tests:
Input: 31 22 31 33 2 | Output: 11 2 1 3
Master
5
1,719
467
524
6
234
D
234D
D. Cinema
1,600
implementation
Overall there are m actors in Berland. Each actor has a personal identifier β€” an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.Help the boy to determine the following for each movie: whether it surely will be his favourite movie; whether it surely won't be his favourite movie; can either be favourite or not.
The first line of the input contains two integers m and k (1 ≀ m ≀ 100, 1 ≀ k ≀ m) β€” the number of actors in Berland and the number of Vasya's favourite actors. The second line contains k distinct integers ai (1 ≀ ai ≀ m) β€” the identifiers of Vasya's favourite actors.The third line contains a single integer n (1 ≀ n ≀ 100) β€” the number of movies in Vasya's list.Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines: the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β€” the movie's title, the second line contains a non-negative integer di (1 ≀ di ≀ m) β€” the number of actors who starred in this movie, the third line has di integers bi, j (0 ≀ bi, j ≀ m) β€” the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors. All movies have distinct names. The numbers on the lines are separated by single spaces.
Print n lines in the output. In the i-th line print: 0, if the i-th movie will surely be the favourite; 1, if the i-th movie won't surely be the favourite; 2, if the i-th movie can either be favourite, or not favourite.
Note to the second sample: Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors. Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5. Movie matrix can have exactly one favourite actor. Movie sourcecode doesn't have any favourite actors. Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.
Input: 5 31 2 36firstfilm30 0 0secondfilm40 0 4 5thirdfilm12fourthfilm15fifthfilm14sixthfilm21 0 | Output: 221112
Medium
1
1,051
1,122
219
2
2,124
B
2124B
B. Minimise Sum
1,000
greedy
This problem differs from problem G. In this problem, you must output the minimum sum of prefix minimums after at most one operation.You are given an array \(a\) of length \(n\), with elements satisfying \(\boldsymbol{0 \le a_i \le n}\). You can perform the following operation at most once: Choose two indices \(i\) and \(j\) such that \(i < j\). Set \(a_i := a_i + a_j\). Then, set \(a_j = 0\). Output the minimum possible value of \(\min(a_1) + \min(a_1,a_2) + \ldots + \min(a_1, a_2, \ldots, a_n)\) that you can get.
Each 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 an integer \(n\) (\(2 \leq n \leq 2\cdot 10^5\)) β€” the length of \(a\).The following line contains \(n\) space-separated integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le n\)) β€” denoting the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
For each test case, output an integer on a new line, the minimum possible value of \(\min(a_1) + \min(a_1,a_2) + \ldots + \min(a_1, a_2, \ldots, a_n)\).
In the second test case, it is optimal to perform the operation with \(i=2\) and \(j=3\).In the third test case, it is optimal to not perform any operations. The answer is \(3\).
Input: 321 231 2 343 0 2 3 | Output: 2 2 3
Beginner
1
520
500
152
21
1,997
A
1997A
A. Strong Password
800
brute force; implementation; strings
Monocarp's current password on Codeforces is a string \(s\), consisting of lowercase Latin letters. Monocarp thinks that his current password is too weak, so he wants to insert exactly one lowercase Latin letter into the password to make it stronger. Monocarp can choose any letter and insert it anywhere, even before the first character or after the last character.Monocarp thinks that the password's strength is proportional to the time it takes him to type the password. The time it takes to type the password is calculated as follows: the time to type the first character is \(2\) seconds; for each character other than the first, the time it takes to type it is \(1\) second if it is the same as the previous character, or \(2\) seconds otherwise. For example, the time it takes to type the password abacaba is \(14\); the time it takes to type the password a is \(2\); the time it takes to type the password aaabacc is \(11\).You have to help Monocarp β€” insert a lowercase Latin letter into his password so that the resulting password takes the maximum possible amount of time to type.
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.Each test case consists of one line containing the string \(s\) (\(1 \le |s| \le 10\)), consisting of lowercase Latin letters.
For each test case, print one line containing the new password β€” a string which can be obtained from \(s\) by inserting one lowercase Latin letter. The string you print should have the maximum possible required time to type it. If there are multiple answers, print any of them.
Input: 4aaaaabbpassword | Output: wa aada abcb pastsword
Beginner
3
1,091
218
277
19
1,499
F
1499F
F. Diameter Cuts
2,400
combinatorics; dfs and similar; dp; trees
You are given an integer \(k\) and an undirected tree, consisting of \(n\) vertices.The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to \(k\).Two sets of edges are different if there is an edge such that it appears in only one of the sets.Count the number of valid sets of edges modulo \(998\,244\,353\).
The first line contains two integers \(n\) and \(k\) (\(2 \le n \le 5000\), \(0 \le k \le n - 1\)) β€” the number of vertices of the tree and the maximum allowed diameter, respectively.Each of the next \(n-1\) lines contains a description of an edge: two integers \(v\) and \(u\) (\(1 \le v, u \le n\), \(v \neq u\)).The given edges form a tree.
Print a single integer β€” the number of valid sets of edges modulo \(998\,244\,353\).
In the first example the diameter of the given tree is already less than or equal to \(k\). Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to \(k\). There are \(2^3\) sets, including the empty one.In the second example you have to remove the only edge. Otherwise, the diameter will be \(1\), which is greater than \(0\).Here are the trees for the third and the fourth examples:
Input: 4 3 1 2 1 3 1 4 | Output: 8
Expert
4
716
343
84
14
71
C
71C
C. Round Table Knights
1,600
dp; math; number theory
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
The first line contains number n, which is the number of knights at the round table (3 ≀ n ≀ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. ""1"" means that the knight is in a good mood an ""0"" means that he is in a bad mood.
Print ""YES"" without the quotes if the following month will turn out to be lucky. Otherwise, print ""NO"".
Input: 31 1 1 | Output: YES
Medium
3
835
300
107
0