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,537
B
1537B
B. Bad Boy
900
constructive algorithms; greedy; math
Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.Anton's room can be represented as a grid with \(n\) rows and \(m\) columns. Let \((i, j)\) denote the cell in row \(i\) and column \(j\). Anton is currently standing at position \((i, j)\) in his room. To annoy Anton, Riley decided to throw exactly two yo-yos in cells of the room (they can be in the same cell).Because Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to \((i, j)\) by travelling only to adjacent by side cells. That is, if he is in cell \((x, y)\) then he can travel to the cells \((x + 1, y)\), \((x - 1, y)\), \((x, y + 1)\) and \((x, y - 1)\) in one step (if a cell with those coordinates exists).Riley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is maximized. But because he is very busy, he asked you to tell him.
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.The only line of each test case contains four integers \(n\), \(m\), \(i\), \(j\) (\(1 \leq n, m \leq 10^9\), \(1\le i\le n\), \(1\le j\le m\)) β€” the dimensions of the room, and the cell at which Anton is currently standing.
For each test case, print four integers \(x_1\), \(y_1\), \(x_2\), \(y_2\) (\(1 \leq x_1, x_2 \leq n\), \(1\le y_1, y_2\le m\)) β€” the coordinates of where the two yo-yos should be thrown. They will be thrown at coordinates \((x_1,y_1)\) and \((x_2,y_2)\).If there are multiple answers, you may print any.
Here is a visualization of the first test case.
Input: 7 2 3 1 1 4 4 1 2 3 5 2 2 5 1 2 1 3 1 3 1 1 1 1 1 1000000000 1000000000 1000000000 50 | Output: 1 2 2 3 4 1 4 4 3 1 1 5 5 1 1 1 1 1 2 1 1 1 1 1 50 1 1 1000000000
Beginner
3
1,106
353
304
15
1,746
D
1746D
D. Paths on the Tree
1,900
dfs and similar; dp; greedy; sortings; trees
You are given a rooted tree consisting of \(n\) vertices. The vertices are numbered from \(1\) to \(n\), and the root is the vertex \(1\). You are also given a score array \(s_1, s_2, \ldots, s_n\).A multiset of \(k\) simple paths is called valid if the following two conditions are both true. Each path starts from \(1\). Let \(c_i\) be the number of paths covering vertex \(i\). For each pair of vertices \((u,v)\) (\(2\le u,v\le n\)) that have the same parent, \(|c_u-c_v|\le 1\) holds. The value of the path multiset is defined as \(\sum\limits_{i=1}^n c_i s_i\).It can be shown that it is always possible to find at least one valid multiset. Find the maximum value among all valid multisets.
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains two space-separated integers \(n\) (\(2 \le n \le 2 \cdot 10^5\)) and \(k\) (\(1 \le k \le 10^9\)) β€” the size of the tree and the required number of paths.The second line contains \(n - 1\) space-separated integers \(p_2,p_3,\ldots,p_n\) (\(1\le p_i\le n\)), where \(p_i\) is the parent of the \(i\)-th vertex. It is guaranteed that this value describe a valid tree with root \(1\).The third line contains \(n\) space-separated integers \(s_1,s_2,\ldots,s_n\) (\(0 \le s_i \le 10^4\)) β€” the scores of the vertices.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10 ^ 5\).
For each test case, print a single integer β€” the maximum value of a path multiset.
In the first test case, one of optimal solutions is four paths \(1 \to 2 \to 3 \to 5\), \(1 \to 2 \to 3 \to 5\), \(1 \to 4\), \(1 \to 4\), here \(c=[4,2,2,2,2]\). The value equals to \(4\cdot 6+ 2\cdot 2+2\cdot 1+2\cdot 5+2\cdot 7=54\).In the second test case, one of optimal solution is three paths \(1 \to 2 \to 3 \to 5\), \(1 \to 2 \to 3 \to 5\), \(1 \to 4\), here \(c=[3,2,2,1,2]\). The value equals to \(3\cdot 6+ 2\cdot 6+2\cdot 1+1\cdot 4+2\cdot 10=56\).
Input: 25 41 2 1 36 2 1 5 75 31 2 1 36 6 1 4 10 | Output: 54 56
Hard
5
696
832
82
17
292
A
292A
A. SMSC
1,100
implementation
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci β€” the receiving time (the second) and the number of the text messages, correspondingly.Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows: If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
The first line contains a single integer n (1 ≀ n ≀ 103) β€” the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≀ ti, ci ≀ 106) β€” the time (the second) when the i-th task was received and the number of messages to send, correspondingly.It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≀ i < n).
In a single line print two space-separated integers β€” the time when the last text message was sent and the maximum queue size at a certain moment of time.
In the first test sample: second 1: the first message has appeared in the queue, the queue's size is 1; second 2: the first message is sent, the second message has been received, the queue's size is 1; second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Input: 21 12 1 | Output: 3 1
Easy
1
1,659
525
154
2
689
A
689A
A. Mike and Cellphone
1,400
brute force; constructive algorithms; implementation
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number ""586"" are the same as finger movements for number ""253"": Mike has already put in a number by his ""finger memory"" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
The first line of the input contains the only integer n (1 ≀ n ≀ 9) β€” the number of digits in the phone number that Mike put in.The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.
If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print ""YES"" (without quotes) in the only line.Otherwise print ""NO"" (without quotes) in the first line.
You can find the picture clarifying the first sample case in the statement above.
Input: 3586 | Output: NO
Easy
3
878
257
226
6
913
D
913D
D. Too Easy Problems
1,800
binary search; brute force; data structures; greedy; sortings
You are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly ti milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer ai to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than ai problems overall (including problem i).Formally, suppose you solve problems p1, p2, ..., pk during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that k ≀ apj.You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.
The first line contains two integers n and T (1 ≀ n ≀ 2Β·105; 1 ≀ T ≀ 109) β€” the number of problems in the exam and the length of the exam in milliseconds, respectively.Each of the next n lines contains two integers ai and ti (1 ≀ ai ≀ n; 1 ≀ ti ≀ 104). The problems are numbered from 1 to n.
In the first line, output a single integer s β€” your maximum possible final score.In the second line, output a single integer k (0 ≀ k ≀ n) β€” the number of problems you should solve.In the third line, output k distinct integers p1, p2, ..., pk (1 ≀ pi ≀ n) β€” the indexes of problems you should solve, in any order.If there are several optimal sets of problems, you may output any of them.
In the first example, you should solve problems 3, 1, and 4. In this case you'll spend 80 + 100 + 90 = 270 milliseconds, falling within the length of the exam, 300 milliseconds (and even leaving yourself 30 milliseconds to have a rest). Problems 3 and 1 will bring you a point each, while problem 4 won't. You'll score two points.In the second example, the length of the exam is catastrophically not enough to solve even a single problem.In the third example, you have just enough time to solve both problems in 42 + 58 = 100 milliseconds and hand your solutions to the teacher with a smile.
Input: 5 3003 1004 1504 802 902 300 | Output: 233 1 4
Medium
5
1,135
291
387
9
2,131
D
2131D
D. Arboris Contractio
0
data structures; graphs; greedy; trees
Kagari is preparing to archive a tree, and she knows the cost of doing so will depend on its diameter\(^{\text{βˆ—}}\). To keep the expense down, her goal is to shrink the diameter as much as possible first. She can perform the following operation on the tree: Choose two vertices \(s\) and \(t\). Let the sequence of vertices on the simple path\(^{\text{†}}\) from \(s\) to \(t\) be \(v_0, v_1, \dots, v_k\), where \(v_0 = s\) and \(v_k = t\). Remove all edges along the path. In other words, remove edges \((v_0, v_1), (v_1, v_2), \dots, (v_{k-1}, v_k)\). Connect vertices \(v_1, v_2, \dots, v_k\) directly to \(v_0\). In other words, add edges \((v_0, v_1), (v_0, v_2), \dots, (v_0, v_k)\). It can be shown that the graph is still a tree after the operation.Help her determine the minimum number of operations required to achieve the minimal diameter.\(^{\text{βˆ—}}\)The diameter of a tree is the longest possible distance between any pair of vertices. The distance itself is measured by the number of edges on the unique simple path connecting them.\(^{\text{†}}\)A simple path is a path between two vertices in a tree that does not visit any vertex more than once. It can be shown that the simple path between any two vertices is always unique.
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 one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” the number of the vertices in the tree.The following \(n-1\) lines of each test case describe the tree. Each of the lines contains two integers \(u\) and \(v\) (\(1 \le u, v \le n\), \(u \neq v\)) that indicate an edge between vertex \(u\) and \(v\). It is guaranteed that these edges form a tree.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output one integer β€” the minimum number of operations to minimize the diameter.
In the first test case, the diameter of the original tree is \(3\). Kagari can perform an operation on \(s = 3\) and \(t = 4\). As the figure depicts, the operations includes the following steps: Remove edges \((3, 1)\), \((1, 2)\) and \((2, 4)\). Add edges \((3, 1)\), \((3, 2)\) and \((3, 4)\). After the operation, the diameter reduces to \(2\). It can be shown that \(2\) is the minimum diameter.In the second test case, the diameter of the tree is \(1\). It can be shown that \(1\) is already the minimum, so Kagari can perform no operation.
Input: 441 21 32 422 141 22 32 4111 21 32 43 53 85 65 77 97 105 11 | Output: 1 0 0 4
Beginner
4
1,246
644
99
21
1,417
A
1417A
A. Copy-paste
800
greedy; math
β€” Hey folks, how do you like this problem?β€” That'll do it. BThero is a powerful magician. He has got \(n\) piles of candies, the \(i\)-th pile initially contains \(a_i\) candies. BThero can cast a copy-paste spell as follows: He chooses two piles \((i, j)\) such that \(1 \le i, j \le n\) and \(i \ne j\). All candies from pile \(i\) are copied into pile \(j\). Formally, the operation \(a_j := a_j + a_i\) is performed. BThero can cast this spell any number of times he wants to β€” but unfortunately, if some pile contains strictly more than \(k\) candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?
The first line contains one integer \(T\) (\(1 \le T \le 500\)) β€” the number of test cases.Each test case consists of two lines: the first line contains two integers \(n\) and \(k\) (\(2 \le n \le 1000\), \(2 \le k \le 10^4\)); the second line contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) (\(1 \le a_i \le k\)). It is guaranteed that the sum of \(n\) over all test cases does not exceed \(1000\), and the sum of \(k\) over all test cases does not exceed \(10^4\).
For each test case, print one integer β€” the maximum number of times BThero can cast the spell without losing his magic power.
In the first test case we get either \(a = [1, 2]\) or \(a = [2, 1]\) after casting the spell for the first time, and it is impossible to cast it again.
Input: 3 2 2 1 1 3 5 1 2 3 3 7 3 2 2 | Output: 1 5 4
Beginner
2
670
473
125
14
1,618
C
1618C
C. Paint the Array
1,100
math
You are given an array \(a\) consisting of \(n\) positive integers. You have to choose a positive integer \(d\) and paint all elements into two colors. All elements which are divisible by \(d\) will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of \(d\) which yields a beautiful coloring, or report that it is impossible.
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of testcases.The first line of each testcase contains one integer \(n\) (\(2 \le n \le 100\)) β€” the number of elements of the array.The second line of each testcase contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^{18}\)).
For each testcase print a single integer. If there is no such value of \(d\) that yields a beautiful coloring, print \(0\). Otherwise, print any suitable value of \(d\) (\(1 \le d \le 10^{18}\)).
Input: 5 5 1 2 3 4 5 3 10 5 15 3 100 10 200 10 9 8 2 6 6 2 8 6 5 4 2 1 3 | Output: 2 0 100 0 3
Easy
1
476
325
195
16
2,034
H
2034H
H. Rayan vs. Rayaneh
3,300
brute force; dfs and similar; dp; number theory
Rayan makes his final efforts to win Reyhaneh's heart by claiming he is stronger than Rayaneh (i.e., computer in Persian). To test this, Reyhaneh asks Khwarizmi for help. Khwarizmi explains that a set is integer linearly independent if no element in the set can be written as an integer linear combination of the others. Rayan is given a set of integers each time and must identify one of the largest possible integer linearly independent subsets.Note that a single element is always considered an integer linearly independent subset.An integer linearly combination of \(a_1, \ldots, a_k\) is any sum of the form \(c_1 \cdot a_1 + c_2 \cdot a_2 + \ldots + c_k \cdot a_k\) where \(c_1, c_2, \ldots, c_k\) are integers (which may be zero, positive, or negative).
The first line contains an integer \(t\) (\(1 \leq t \leq 100\)), the number of test cases.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 10^5\)), the size of the set. The second line contains \(n\) distinct integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^5\)).The sum of \(n\) over all test cases does not exceed \(3 \cdot 10^6\).
In the first line of each test case print the size of the largest integer linearly independent subset.In the next line, print one such subset in any order. If there are multiple valid subsets, print any one of them.
In example 1, \(\{4, 6\}\) is an integer linearly independent subset. It can be proven that there is no integer linearly independent subset with at least \(3\) elements.In example 2, \(\{35, 21, 30\}\) is an integer linearly independent subset because no integer linear combination of any two elements can create the third. There is no integer linearly independent subset with at least \(4\) elements.In example 3, \(\{2, 3, 6\}\) is not an integer linearly independent subset since \(6\) can be written as \(6 \cdot 2 + (-2) \cdot 3\), which is an integer linear combination of \(\{2, 3\}\).
Input: 352 4 6 8 10512 15 21 30 3532 3 6 | Output: 2 4 6 3 35 21 30 2 2 3
Master
4
760
369
215
20
2,128
D
2128D
D. Sum of LDS
1,600
brute force; combinatorics; dp; greedy; math
You're given a permutation\(^{\text{βˆ—}}\) \(p_1, \ldots, p_n\) such that \(\max(p_i, p_{i+1}) > p_{i+2}\) for all \(1 \leq i \leq n-2\).Compute the sum of the length of the longest decreasing subsequence\(^{\text{†}}\) of the subarray \([p_l, p_{l+1}, \ldots, p_r]\) over all pairs \(1 \leq l \leq r \leq n\).\(^{\text{βˆ—}}\)A permutation of length \(n\) 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). \(^{\text{†}}\)Given an array \(b\) of size \(|b|\), a decreasing subsequence of length \(k\) is a sequence of indices \(i_1, \ldots, i_k\) such that: \(1 \leq i_1 < i_2 < \ldots < i_k \leq |b|\) \(b_{i_1} > b_{i_2} > \ldots > b_{i_k}\)
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10\,000\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(3 \leq n \leq 500\,000\)).The second line of each test case contains \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(1 \le p_i \le n\), \(p_i\) are pairwise distinct).It is guaranteed that \(\max(p_i, p_{i+1}) > p_{i+2}\) for all \(1 \leq i \leq n-2\).The sum of \(n\) over all test cases does not exceed \(500\,000\).
For each test case, output the sum over all subarrays of the length of its longest decreasing subsequence.
For any array \(a\), we define \(\text{LDS}(a)\) as the length of the longest decreasing subsequence of \(a\).In the first test case, all subarrays are decreasing. In the second one, we have \(\text{LDS}([4]) = \text{LDS}([3]) = \text{LDS}([1]) = \text{LDS}([2]) = 1\) \(\text{LDS}([4,3]) = \text{LDS}([3,1]) = 2, \text{LDS}([1, 2]) = 1\) \(\text{LDS}([4,3,1]) = 3, \text{LDS}([3,1,2]) = 2\) \(\text{LDS}([4,3,1,2]) = 3\)So the answer is \(1+1+1+1+2+2+1+3+2+3=17\).
Input: 433 2 144 3 1 266 1 5 2 4 332 3 1 | Output: 10 17 40 8
Medium
5
885
547
106
21
1,282
B2
1282B2
B2. K for the Price of One (Hard Version)
1,600
dp; greedy; sortings
This is the hard version of this problem. The only difference is the constraint on \(k\) β€” the number of gifts in the offer. In this version: \(2 \le k \le n\).Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β€” today the offer ""\(k\) of goods for the price of one"" is held in store.Using this offer, Vasya can buy exactly \(k\) of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by \(a_i\) β€” the number of coins it costs. Initially, Vasya has \(p\) coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index \(i\) if he currently has enough coins (i.e \(p \ge a_i\)). After buying this good, the number of Vasya's coins will decrease by \(a_i\), (i.e it becomes \(p := p - a_i\)). Vasya can buy a good with the index \(i\), and also choose exactly \(k-1\) goods, the price of which does not exceed \(a_i\), if he currently has enough coins (i.e \(p \ge a_i\)). Thus, he buys all these \(k\) goods, and his number of coins decreases by \(a_i\) (i.e it becomes \(p := p - a_i\)). Please note that each good can be bought no more than once.For example, if the store now has \(n=5\) goods worth \(a_1=2, a_2=4, a_3=3, a_4=5, a_5=7\), respectively, \(k=2\), and Vasya has \(6\) coins, then he can buy \(3\) goods. A good with the index \(1\) will be bought by Vasya without using the offer and he will pay \(2\) coins. Goods with the indices \(2\) and \(3\) Vasya will buy using the offer and he will pay \(4\) coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases in the test.The next lines contain a description of \(t\) test cases. The first line of each test case contains three integers \(n, p, k\) (\(2 \le n \le 2 \cdot 10^5\), \(1 \le p \le 2\cdot10^9\), \(2 \le k \le n\)) β€” the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.The second line of each test case contains \(n\) integers \(a_i\) (\(1 \le a_i \le 10^4\)) β€” the prices of goods.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case in a separate line print one integer \(m\) β€” the maximum number of goods that Vasya can buy.
Input: 8 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 3 2 3 4 2 6 5 2 3 10 1 3 9 2 2 10000 2 10000 10000 2 9999 2 10000 10000 4 6 4 3 2 3 2 5 5 3 1 2 2 1 2 | Output: 3 4 1 1 2 0 4 5
Medium
3
1,883
665
111
12
1,748
E
1748E
E. Yet Another Array Counting Problem
2,300
binary search; data structures; divide and conquer; dp; flows; math; trees
The position of the leftmost maximum on the segment \([l; r]\) of array \(x = [x_1, x_2, \ldots, x_n]\) is the smallest integer \(i\) such that \(l \le i \le r\) and \(x_i = \max(x_l, x_{l+1}, \ldots, x_r)\).You are given an array \(a = [a_1, a_2, \ldots, a_n]\) of length \(n\). Find the number of integer arrays \(b = [b_1, b_2, \ldots, b_n]\) of length \(n\) that satisfy the following conditions: \(1 \le b_i \le m\) for all \(1 \le i \le n\); for all pairs of integers \(1 \le l \le r \le n\), the position of the leftmost maximum on the segment \([l; r]\) of the array \(b\) is equal to the position of the leftmost maximum on the segment \([l; r]\) of the array \(a\). Since the answer might be very large, print its remainder modulo \(10^9+7\).
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^3\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(m\) (\(2 \le n,m \le 2 \cdot 10^5\), \(n \cdot m \le 10^6\)).The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1 \le a_i \le m\)) β€” the array \(a\).It is guaranteed that the sum of \(n \cdot m\) over all test cases doesn't exceed \(10^6\).
For each test case print one integer β€” the number of arrays \(b\) that satisfy the conditions from the statement, modulo \(10^9+7\).
In the first test case, the following \(8\) arrays satisfy the conditions from the statement: \([1,2,1]\); \([1,2,2]\); \([1,3,1]\); \([1,3,2]\); \([1,3,3]\); \([2,3,1]\); \([2,3,2]\); \([2,3,3]\). In the second test case, the following \(5\) arrays satisfy the conditions from the statement: \([1,1,1,1]\); \([2,1,1,1]\); \([2,2,1,1]\); \([2,2,2,1]\); \([2,2,2,2]\).
Input: 43 31 3 24 22 2 2 26 96 9 6 9 6 99 10010 40 20 20 100 60 80 60 60 | Output: 8 5 11880 351025663
Expert
7
752
477
132
17
1,278
F
1278F
F. Cards
2,600
combinatorics; dp; math; number theory; probabilities
Consider the following experiment. You have a deck of \(m\) cards, and exactly one card is a joker. \(n\) times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.Let \(x\) be the number of times you have taken the joker out of the deck during this experiment. Assuming that every time you shuffle the deck, all \(m!\) possible permutations of cards are equiprobable, what is the expected value of \(x^k\)? Print the answer modulo \(998244353\).
The only line contains three integers \(n\), \(m\) and \(k\) (\(1 \le n, m < 998244353\), \(1 \le k \le 5000\)).
Print one integer β€” the expected value of \(x^k\), taken modulo \(998244353\) (the answer can always be represented as an irreducible fraction \(\frac{a}{b}\), where \(b \mod 998244353 \ne 0\); you have to print \(a \cdot b^{-1} \mod 998244353\)).
Input: 1 1 1 | Output: 1
Expert
5
505
112
247
12
1,303
G
1303G
G. Sum of Prefix Sums
2,700
data structures; divide and conquer; geometry; trees
We define the sum of prefix sums of an array \([s_1, s_2, \dots, s_k]\) as \(s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + \dots + (s_1 + s_2 + \dots + s_k)\).You are given a tree consisting of \(n\) vertices. Each vertex \(i\) has an integer \(a_i\) written on it. We define the value of the simple path from vertex \(u\) to vertex \(v\) as follows: consider all vertices appearing on the path from \(u\) to \(v\), write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.Your task is to calculate the maximum value over all paths in the tree.
The first line contains one integer \(n\) (\(2 \le n \le 150000\)) β€” the number of vertices in the tree.Then \(n - 1\) lines follow, representing the edges of the tree. Each line contains two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n\), \(u_i \ne v_i\)), denoting an edge between vertices \(u_i\) and \(v_i\). It is guaranteed that these edges form a tree.The last line contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) (\(1 \le a_i \le 10^6\)).
Print one integer β€” the maximum value over all paths in the tree.
The best path in the first example is from vertex \(3\) to vertex \(1\). It gives the sequence \([3, 3, 7, 1]\), and the sum of prefix sums is \(36\).
Input: 4 4 2 3 2 4 1 1 3 3 7 | Output: 36
Master
4
633
461
65
13
1,604
A
1604A
A. Era
800
greedy
Shohag has an integer sequence \(a_1, a_2, \ldots, a_n\). He can perform the following operation any number of times (possibly, zero): Select any positive integer \(k\) (it can be different in different operations). Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert \(k\) into the sequence at this position. This way, the sequence \(a\) changes, and the next operation is performed on this changed sequence. For example, if \(a=[3,3,4]\) and he selects \(k = 2\), then after the operation he can obtain one of the sequences \([\underline{2},3,3,4]\), \([3,\underline{2},3,4]\), \([3,3,\underline{2},4]\), or \([3,3,4,\underline{2}]\).Shohag wants this sequence to satisfy the following condition: for each \(1 \le i \le |a|\), \(a_i \le i\). Here, \(|a|\) denotes the size of \(a\).Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.
The first line contains a single integer \(t\) (\(1 \le t \le 200\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 100\)) β€” the initial length of the sequence.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the elements of the sequence.
For each test case, print a single integer β€” the minimum number of operations needed to perform to achieve the goal mentioned in the statement.
In the first test case, we have to perform at least one operation, as \(a_2=3>2\). We can perform the operation \([1, 3, 4] \rightarrow [1, \underline{2}, 3, 4]\) (the newly inserted element is underlined), now the condition is satisfied.In the second test case, Shohag can perform the following operations:\([1, 2, 5, 7, 4] \rightarrow [1, 2, \underline{3}, 5, 7, 4] \rightarrow [1, 2, 3, \underline{4}, 5, 7, 4] \rightarrow [1, 2, 3, 4, 5, \underline{3}, 7, 4]\).In the third test case, the sequence already satisfies the condition.
Input: 4 3 1 3 4 5 1 2 5 7 4 1 1 3 69 6969 696969 | Output: 1 3 0 696966
Beginner
1
1,083
360
143
16
2,045
E
2045E
E. Narrower Passageway
2,700
combinatorics; data structures
You are a strategist of The ICPC Kingdom. You received an intel that there will be monster attacks on a narrow passageway near the kingdom. The narrow passageway can be represented as a grid with \(2\) rows (numbered from \(1\) to \(2\)) and \(N\) columns (numbered from \(1\) to \(N\)). Denote \((r, c)\) as the cell in row \(r\) and column \(c\). A soldier with a power of \(P_{r, c}\) is assigned to protect \((r, c)\) every single day.It is known that the passageway is very foggy. Within a day, each column in the passageway has a \(50\%\) chance of being covered in fog. If a column is covered in fog, the two soldiers assigned to that column are not deployed that day. Otherwise, the assigned soldiers will be deployed.Define a connected area \([u, v]\) (\(u \leq v\)) as a maximal set of consecutive columns from \(u\) to \(v\) (inclusive) such that each column in the set is not covered in fog. The following illustration is an example of connected areas. The grayed cells are cells covered in fog. There are \(4\) connected areas: \([1, 2]\), \([4, 6]\), \([9, 9]\), and \([11, 11]\). The strength of a connected area \([u, v]\) can be calculated as follows. Let \(m_1\) and \(m_2\) be the maximum power of the soldiers in the first and second rows of the connected area, respectively. Formally, \(m_r = \max (P_{r, u}, P_{r, u + 1}, \dots, P_{r, v})\) for \(r \in \{ 1, 2\}\). If \(m_1 = m_2\), then the strength is \(0\). Otherwise, the strength is \(\min (m_1, m_2)\).The total strength of the deployment is the sum of the strengths for all connected areas. Determine the expected total strength of the deployment on any single day.
The first line consists of an integer \(N\) (\(1 \leq N \leq 100\,000\)).Each of the next two lines consists of \(N\) integers \(P_{r, c}\) (\(1 \leq P_{r, c} \leq 200\,000\)).
Let \(M = 998\,244\,353\). It can be shown that the expected total strength can be expressed as an irreducible fraction \(\frac{x}{y}\) such that \(x\) and \(y\) are integers and \(y \not\equiv 0 \pmod{M}\). Output an integer \(k\) in a single line such that \(0 \leq k < M\) and \(k \cdot y \equiv x \pmod{M}\).
Explanation for the sample input/output #1There are \(8\) possible scenarios for the passageway. Each scenario is equally likely to happen. Therefore, the expected total strength is \((0 + 5 + 10 + 5 + 5 + 0 + 5 + 0) / 8 = \frac{15}{4}\). Since \(249\,561\,092 \cdot 4 \equiv 15 \pmod{998\,244\,353}\), the output of this sample is \(249\,561\,092\).Explanation for the sample input/output #2The expected total strength is \(\frac{67}{16}\).
Input: 3 8 4 5 5 4 8 | Output: 249561092
Master
2
1,645
176
312
20
784
F
784F
F. Crunching Numbers Just for You
1,900
*special; implementation
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...You are given an array of integers. Sort it in non-descending order.
The input consists of a single line of space-separated integers. The first number is n (1 ≀ n ≀ 10) β€” the size of the array. The following n numbers are the elements of the array (1 ≀ ai ≀ 100).
Output space-separated elements of the sorted array.
Remember, this is a very important feature, and you have to make sure the customers appreciate it!
Input: 3 3 1 2 | Output: 1 2 3
Hard
2
274
194
52
7
1,878
A
1878A
A. How Much Does Daytona Cost?
800
greedy
We define an integer to be the most common on a subsegment, if its number of occurrences on that subsegment is larger than the number of occurrences of any other integer in that subsegment. A subsegment of an array is a consecutive segment of elements in the array \(a\).Given an array \(a\) of size \(n\), and an integer \(k\), determine if there exists a non-empty subsegment of \(a\) where \(k\) is the most common element.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases. The description of test cases follows.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le n \le 100\), \(1 \le k \le 100\)) β€” the number of elements in array and the element which must be the most common.The second line of each test case contains \(n\) integers \(a_1\), \(a_2\), \(a_3\), \(\dots\), \(a_n\) (\(1 \le a_i \le 100\)) β€” elements of the array.
For each test case output ""YES"" if there exists a subsegment in which \(k\) is the most common element, and ""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 need to check if there is a subsegment where the most common element is \(4\).On the subsegment \([2,5]\) the elements are \(4, \ 3, \ 4, \ 1\). \(4\) appears \(2\) times; \(1\) appears \(1\) time; \(3\) appears \(1\) time.This means that \(4\) is the most common element on the subsegment \([2, 5]\), so there exists a subsegment where \(4\) is the most common element.
Input: 75 41 4 3 4 14 12 3 4 45 643 5 60 4 22 51 54 15 3 3 11 335 33 4 1 5 5 | Output: YES NO NO YES YES YES YES
Beginner
1
426
525
271
18
1,549
A
1549A
A. Gregor and Cryptography
800
math; number theory
Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is \(P\). Gregor wants to find two bases of \(P\). Formally, Gregor is looking for two integers \(a\) and \(b\) which satisfy both of the following properties. \(P \bmod a = P \bmod b\), where \(x \bmod y\) denotes the remainder when \(x\) is divided by \(y\), and \(2 \le a < b \le P\). Help Gregor find two bases of his favorite prime number!
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)).Each subsequent line contains the integer \(P\) (\(5 \le P \le {10}^9\)), with \(P\) guaranteed to be prime.
Your output should consist of \(t\) lines. Each line should consist of two integers \(a\) and \(b\) (\(2 \le a < b \le P\)). If there are multiple possible solutions, print any.
The first query is \(P=17\). \(a=3\) and \(b=5\) are valid bases in this case, because \(17 \bmod 3 = 17 \bmod 5 = 2\). There are other pairs which work as well.In the second query, with \(P=5\), the only solution is \(a=2\) and \(b=4\).
Input: 2 17 5 | Output: 3 5 2 4
Beginner
2
527
226
177
15
1,986
G2
1986G2
G2. Permutation Problem (Hard Version)
2,500
brute force; data structures; hashing; math; number theory
This is the hard version of the problem. The only difference is that in this version \(n \leq 5 \cdot 10^5\) and the sum of \(n\) for all sets of input data does not exceed \(5 \cdot 10^5\).You are given a permutation \(p\) of length \(n\). Calculate the number of index pairs \(1 \leq i < j \leq n\) such that \(p_i \cdot p_j\) is divisible by \(i \cdot j\) without remainder.A permutation is a sequence of \(n\) integers, in which each integer from \(1\) to \(n\) occurs exactly once. For example, \([1]\), \([3,5,2,1,4]\), \([1,3,2]\) are permutations, while \([2,3,2]\), \([4,3,1]\), \([0]\) are not.
Each test consists of several sets of input data. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of sets of input data. Then follows their description.The first line of each set of input data contains a single integer \(n\) (\(1 \leq n \leq 5 \cdot 10^5\)) β€” the length of the permutation \(p\).The second line of each set of input data contains \(n\) distinct integers \(p_1, p_2, \ldots, p_n\) (\(1 \leq p_i \leq n\)) β€” the permutation \(p\).It is guaranteed that the sum of \(n\) for all sets of input data does not exceed \(5 \cdot 10^5\).
For each set of input data, output the number of index pairs \(1 \leq i < j \leq n\) such that \(p_i \cdot p_j\) is divisible by \(i \cdot j\) without remainder.
In the first set of input data, there are no index pairs, as the size of the permutation is \(1\).In the second set of input data, there is one index pair \((1, 2)\) and it is valid.In the third set of input data, the index pair \((1, 2)\) is valid.In the fourth set of input data, the index pairs \((1, 2)\), \((1, 5)\), and \((2, 5)\) are valid.
Input: 61121 232 3 152 4 1 3 5128 9 7 12 1 10 6 3 2 4 11 5151 2 4 6 8 10 12 14 3 9 15 5 7 11 13 | Output: 0 1 1 3 9 3
Expert
5
604
581
161
19
35
B
35B
B. Warehouse
1,700
implementation
Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won’t describe his work in detail and take a better look at a simplified version of the warehouse.The warehouse has one set of shelving. It has n shelves, each of which is divided into m sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf’s beginning. If DravDe still can’t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught.After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you.The process of counting contains two types of query messages: Β«+1 x y idΒ» (where x, y are integers, 1 ≀ x ≀ n, 1 ≀ y ≀ m, and id is a string of lower case Latin letters β€” from 1 to 10 characters long). That query means that the warehouse got a box identified as id, which should be put in the section y on the shelf x. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don’t have to answer this query. Β«-1 idΒ» (where id is a string of lower case Latin letters β€” from 1 to 10 characters long). That query means that a box identified as id is removed from the warehouse. You have to answer this query (see output format).
The first input line contains integers n, m and k (1 ≀ n, m ≀ 30, 1 ≀ k ≀ 2000) β€” the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following k lines the queries are given in the order of appearance in the format described above.
For each query of the Β«-1 idΒ» type output two numbers in a separate line β€” index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output Β«-1 -1Β» without quotes.
Input: 2 2 9+1 1 1 cola+1 1 1 fanta+1 1 1 sevenup+1 1 1 whitekey-1 cola-1 fanta-1 sevenup-1 whitekey-1 cola | Output: 1 11 22 12 2-1 -1
Medium
1
2,521
296
256
0
1,431
J
1431J
J. Zero-XOR Array
3,400
*special; dp
You are given an array of integers \(a\) of size \(n\). This array is non-decreasing, i. e. \(a_1 \le a_2 \le \dots \le a_n\).You have to find arrays of integers \(b\) of size \(2n - 1\), such that: \(b_{2i-1} = a_i\) (\(1 \le i \le n\)); array \(b\) is non-decreasing; \(b_1 \oplus b_2 \oplus \dots \oplus b_{2n-1} = 0\) (\(\oplus\) denotes bitwise XOR operation: https://en.wikipedia.org/wiki/Exclusive_or. In Kotlin, it is xor function). Calculate the number of arrays that meet all the above conditions, modulo \(998244353\).
The first line contains a single integer \(n\) (\(2 \le n \le 17\)) β€” the size of the array \(a\).The second line contains \(n\) integers (\(0 \le a_i \le 2^{60} - 1; a_i \le a_{i+1}\)) β€” elements of the array \(a\).
Print a single integer β€” the number of arrays that meet all the above conditions, modulo \(998244353\).
Input: 3 0 1 3 | Output: 2
Master
2
529
216
103
14
796
F
796F
F. Sequence Recovery
2,800
bitmasks; data structures; greedy
Zane once had a good sequence a consisting of n integers a1, a2, ..., an β€” but he has lost it.A sequence is said to be good if and only if all of its integers are non-negative and do not exceed 109 in value. However, Zane remembers having played around with his sequence by applying m operations to it.There are two types of operations:1. Find the maximum value of integers with indices i such that l ≀ i ≀ r, given l and r.2. Assign d as the value of the integer with index k, given k and d.After he finished playing, he restored his sequence to the state it was before any operations were applied. That is, sequence a was no longer affected by the applied type 2 operations. Then, he lost his sequence at some time between now and then.Fortunately, Zane remembers all the operations and the order he applied them to his sequence, along with the distinct results of all type 1 operations. Moreover, among all good sequences that would produce the same results when the same operations are applied in the same order, he knows that his sequence a has the greatest cuteness.We define cuteness of a sequence as the bitwise OR result of all integers in such sequence. For example, the cuteness of Zane's sequence a is a1 OR a2 OR ... OR an.Zane understands that it might not be possible to recover exactly the lost sequence given his information, so he would be happy to get any good sequence b consisting of n integers b1, b2, ..., bn that:1. would give the same results when the same operations are applied in the same order, and2. has the same cuteness as that of Zane's original sequence a.If there is such a sequence, find it. Otherwise, it means that Zane must have remembered something incorrectly, which is possible.
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of integers in Zane's original sequence and the number of operations that have been applied to the sequence, respectively.The i-th of the following m lines starts with one integer ti () β€” the type of the i-th operation.If the operation is type 1 (ti = 1), then three integers li, ri, and xi follow (1 ≀ li ≀ ri ≀ n, 0 ≀ xi ≀ 109) β€” the leftmost index to be considered, the rightmost index to be considered, and the maximum value of all integers with indices between li and ri, inclusive, respectively.If the operation is type 2 (ti = 2), then two integers ki and di follow (1 ≀ ki ≀ n, 0 ≀ di ≀ 109) β€” meaning that the integer with index ki should become di after this operation.It is guaranteed that xi β‰  xj for all pairs (i, j) where 1 ≀ i < j ≀ m and ti = tj = 1.The operations are given in the same order they were applied. That is, the operation that is given first was applied first, the operation that is given second was applied second, and so on.
If there does not exist a valid good sequence, print ""NO"" (without quotation marks) in the first line.Otherwise, print ""YES"" (without quotation marks) in the first line, and print n space-separated integers b1, b2, ..., bn (0 ≀ bi ≀ 109) in the second line.If there are multiple answers, print any of them.
In the first sample, it is easy to verify that this good sequence is valid. In particular, its cuteness is 19 OR 0 OR 0 OR 0 OR 1 = 19.In the second sample, the two operations clearly contradict, so there is no such good sequence.
Input: 5 41 1 5 191 2 5 12 5 1001 1 5 100 | Output: YES19 0 0 0 1
Master
3
1,720
1,032
310
7
1,101
A
1101A
A. Minimum Integer
1,000
math
You are given \(q\) queries in the following form:Given three integers \(l_i\), \(r_i\) and \(d_i\), find minimum positive integer \(x_i\) such that it is divisible by \(d_i\) and it does not belong to the segment \([l_i, r_i]\).Can you answer all the queries?Recall that a number \(x\) belongs to segment \([l, r]\) if \(l \le x \le r\).
The first line contains one integer \(q\) (\(1 \le q \le 500\)) β€” the number of queries.Then \(q\) lines follow, each containing a query given in the format \(l_i\) \(r_i\) \(d_i\) (\(1 \le l_i \le r_i \le 10^9\), \(1 \le d_i \le 10^9\)). \(l_i\), \(r_i\) and \(d_i\) are integers.
For each query print one integer: the answer to this query.
Input: 5 2 4 2 5 10 4 3 10 1 1 2 3 4 6 5 | Output: 6 4 1 3 10
Beginner
1
338
281
59
11
82
E
82E
E. Corridor
2,600
geometry
Consider a house plan. Let the house be represented by an infinite horizontal strip defined by the inequality - h ≀ y ≀ h. Strictly outside the house there are two light sources at the points (0, f) and (0, - f). Windows are located in the walls, the windows are represented by segments on the lines y = h and y = - h. Also, the windows are arranged symmetrically about the line y = 0.Your task is to find the area of the floor at the home, which will be lighted by the sources of light.
The first line of the input file contains three integers n, h and f (1 ≀ n ≀ 500, 1 ≀ h ≀ 10, h < f ≀ 1000). Next, n lines contain two integers each li, ri ( - 5000 ≀ li < ri ≀ 5000), each entry indicates two segments. Endpoints of the first segment are (li, h)-(ri, h), and endpoints of the second segment are (li, - h)-(ri, - h). These segments describe location of windows. Numbers in the lines are space-separated. It is guaranteed that no two distinct segments have common points.
Print the single real number β€” the area of the illuminated part of the floor with an absolute or relative error of no more than 10 - 4.
The second sample test is shown on the figure. Green area is the desired area of the illuminated part of the floor. Violet segments indicate windows.
Input: 1 1 2-1 1 | Output: 10.0000000000
Expert
1
487
485
135
0
1,370
E
1370E
E. Binary Subsequence Rotation
2,100
binary search; constructive algorithms; data structures; greedy
Naman has two binary strings \(s\) and \(t\) of length \(n\) (a binary string is a string which only consists of the characters ""0"" and ""1""). He wants to convert \(s\) into \(t\) using the following operation as few times as possible.In one operation, he can choose any subsequence of \(s\) and rotate it clockwise once.For example, if \(s = 1\textbf{1}101\textbf{00}\), he can choose a subsequence corresponding to indices (\(1\)-based) \(\{2, 6, 7 \}\) and rotate them clockwise. The resulting string would then be \(s = 1\textbf{0}101\textbf{10}\).A string \(a\) is said to be a subsequence of string \(b\) if \(a\) can be obtained from \(b\) by deleting some characters without changing the ordering of the remaining characters.To perform a clockwise rotation on a sequence \(c\) of size \(k\) is to perform an operation which sets \(c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}\) simultaneously.Determine the minimum number of operations Naman has to perform to convert \(s\) into \(t\) or say that it is impossible.
The first line contains a single integer \(n\) \((1 \le n \le 10^6)\) β€” the length of the strings.The second line contains the binary string \(s\) of length \(n\).The third line contains the binary string \(t\) of length \(n\).
If it is impossible to convert \(s\) to \(t\) after any number of operations, print \(-1\).Otherwise, print the minimum number of operations required.
In the first test, Naman can choose the subsequence corresponding to indices \(\{2, 6\}\) and rotate it once to convert \(s\) into \(t\).In the second test, he can rotate the subsequence corresponding to all indices \(5\) times. It can be proved, that it is the minimum required number of operations.In the last test, it is impossible to convert \(s\) into \(t\).
Input: 6 010000 000001 | Output: 1
Hard
4
1,031
227
150
13
1,516
E
1516E
E. Baby Ehab Plays with Permutations
2,500
combinatorics; dp; math
This time around, Baby Ehab will play with permutations. He has \(n\) cubes arranged in a row, with numbers from \(1\) to \(n\) written on them. He'll make exactly \(j\) operations. In each operation, he'll pick up \(2\) cubes and switch their positions.He's wondering: how many different sequences of cubes can I have at the end? Since Baby Ehab is a turbulent person, he doesn't know how many operations he'll make, so he wants the answer for every possible \(j\) between \(1\) and \(k\).
The only line contains \(2\) integers \(n\) and \(k\) (\(2 \le n \le 10^9\), \(1 \le k \le 200\)) β€” the number of cubes Baby Ehab has, and the parameter \(k\) from the statement.
Print \(k\) space-separated integers. The \(i\)-th of them is the number of possible sequences you can end up with if you do exactly \(i\) operations. Since this number can be very large, print the remainder when it's divided by \(10^9+7\).
In the second example, there are \(3\) sequences he can get after \(1\) swap, because there are \(3\) pairs of cubes he can swap. Also, there are \(3\) sequences he can get after \(2\) swaps: \([1,2,3]\), \([3,1,2]\), \([2,3,1]\).
Input: 2 3 | Output: 1 1 1
Expert
3
490
178
240
15
1,662
B
1662B
B. Toys
0
greedy; strings
Vittorio has three favorite toys: a teddy bear, an owl, and a raccoon. Each of them has a name. Vittorio takes several sheets of paper and writes a letter on each side of every sheet so that it is possible to spell any of the three names by arranging some of the sheets in a row (sheets can be reordered and flipped as needed). The three names do not have to be spelled at the same time, it is sufficient that it is possible to spell each of them using all the available sheets (and the same sheet can be used to spell different names).Find the minimum number of sheets required. In addition, produce a list of sheets with minimum cardinality which can be used to spell the three names (if there are multiple answers, print any).
The first line contains a string \(t\) consisting of uppercase letters of the English alphabet (\(1\le |t| \le 1000\)) β€” the name of the teddy bear.The second line contains a string \(o\) consisting of uppercase letters of the English alphabet (\(1\le |o| \le 1000\)) β€” the name of the owl.The third line contains a string \(r\) consisting of uppercase letters of the English alphabet (\(1\le |r| \le 1000\)) β€” the name of the raccoon.The values \(|t|\), \(|o|\), \(|r|\) denote the length of the three names \(t\), \(o\), \(r\).
The first line of the output contains a single integer \(m\) β€” the minimum number of sheets required.Then \(m\) lines follow: the \(j\)-th of these lines contains a string of two uppercase letters of the English alphabet β€” the letters appearing on the two sides of the \(j\)-th sheet.Note that you can print the sheets and the two letters of each sheet in any order.
In the first sample, the solution uses two sheets: the first sheet has A on one side and G on the other side; the second sheet has A on one side and M on the other side.The name AA can be spelled using the A side of both sheets. The name GA can be spelled using the G side of the first sheet and the A side of the second sheet. Finally, the name MA can be spelled using the M side of the second sheet and the A side of the first sheet.
Input: AA GA MA | Output: 2 AG AM
Beginner
2
729
529
366
16
70
E
70E
E. Information Reform
2,700
dp; implementation; trees
Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal.The North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes k fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news.For every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to dlen fishlars per year, where len is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go.Your task is to minimize the costs to carry out the reform.
The first line contains two given numbers n and k (1 ≀ n ≀ 180, 1 ≀ k ≀ 105).The second line contains n - 1 integers di, numbered starting with 1 (di ≀ di + 1, 0 ≀ di ≀ 105).Next n - 1 lines contain the pairs of cities connected by a road.
On the first line print the minimum number of fishlars needed for a year's maintenance. On the second line print n numbers, where the i-th number will represent the number of the regional center, appointed to the i-th city. If the i-th city is a regional center itself, then you should print number i.If there are several solutions to that problem, print any of them.
Input: 8 102 5 9 11 15 19 201 41 31 74 62 82 33 5 | Output: 383 3 3 4 3 4 3 3
Master
3
1,033
239
367
0
1,562
F
1562F
F. Tubular Bells
2,900
interactive; math; number theory; probabilities
Do you know what tubular bells are? They are a musical instrument made up of cylindrical metal tubes. In an orchestra, tubular bells are used to mimic the ringing of bells.Mike has tubular bells, too! They consist of \(n\) tubes, and each of the tubes has a length that can be expressed by a integer from \(l\) to \(r\) inclusive. It is clear that the lengths of all the tubes are different (it makes no sense to make the same tubes). It is also known that \(r-l+1 = n\).Formally, we can say that Mike's tubular bells are described by a permutation \(a\) of length \(n\) that contains all numbers from \(l\) to \(r\) inclusive, with \(a_i\) denoting the length of the \(i\)-th tube.You are offered an interesting task: to guess what Mike's instrument looks like. Simply, you must guess the permutation.Mike won't tell you \(l\) or \(r\). He will only tell you \(n\), and will allow you to ask no more than \(n + 5000\) queries.In each query, you name two positive integers \(x\), \(y\) such that \(1 \le x, y \le n, x \neq y\). In response to this query, the program written by Mike will give you \(\mathrm{lcm}(a_x, a_y)\), where \(\mathrm{lcm}(c,d)\) denotes the least common multiple of \(c\) and \(d\).Solve Mike's problem!
Each test contains multiple test cases.The first line contains one positive integer \(t\) (\(1 \le t \le 20\)), denoting the number of test cases. Description of the test cases follows.The single line of each test case contains one positive integer \(n\) (\(3 \le n \le 10^5\)) β€” number of tubes in Mike's tubular bells. Also \(1 \le l \le r \le 2 \cdot 10^5\), i.e. the lengths of the tubes do not exceed \(2 \cdot 10^5\).It is guaranteed that the sum of maximal number of queries (i.e. \(n + 5000\)) over all test cases does not exceed \(10^5 + 5000\). It means that sum of \(n\) does not exceed \(10^5 + 5000 - t \cdot 5000\).
Input: 3 5 8 10 7 6 9 5 24 25 28 27 26 7 1 2 3 4 5 6 7 | Output: ? 1 2 40 ? 2 5 90 ? 3 1 56 ? 4 5 18 ! 8 10 7 6 9 ? 1 5 312 ? 2 4 675 ! 24 25 28 27 26 ? 1 4 4 ? 2 5 10 ? 3 7 21 ? 6 2 6 ? 2 5 10 ? 1 2 2 ? 1 2 2 ? 1 2 2 ? 1 2 2 ? 1 2 2 ! 1 2 3 4 5 6 7
Master
4
1,227
629
0
15
696
D
696D
D. Legen...
2,500
data structures; dp; matrices; strings
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. Initially, happiness level of Nora is 0. Nora loves some pickup lines like ""I'm falling for you"" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.Due to texting app limits, Barney's text may have up to l characters.Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
The first line of input contains two integers n and l (1 ≀ n ≀ 200, 1 ≀ l ≀ 1014) β€” the number of pickup lines and the maximum length of Barney's text.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line.The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200.All strings are not empty.
Print the only integer β€” the maximum possible value of Nora's happiness level after reading Barney's text.
An optimal answer for the first sample case is hearth containing each pickup line exactly once.An optimal answer for the second sample case is artart.
Input: 3 63 2 1heartearthart | Output: 6
Expert
4
890
522
106
6
2,094
H
2094H
H. La Vaca Saturno Saturnita
1,900
binary search; brute force; math; number theory
Saturnita's mood depends on an array \(a\) of length \(n\), which only he knows the meaning of, and a function \(f(k, a, l, r)\), which only he knows how to compute. Shown below is the pseudocode for his function \(f(k, a, l, r)\). function f(k, a, l, r): ans := 0 for i from l to r (inclusive): while k is divisible by a[i]: k := k/a[i] ans := ans + k return ansYou are given \(q\) queries, each containing integers \(k\), \(l\), and \(r\). For each query, please output \(f(k,a,l,r)\).
The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n \leq 10^5, 1 \leq q \leq 5\cdot 10^4\)).The following line contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(2 \leq a_i \leq 10^5\)).The following \(q\) lines each contain three integers \(k\), \(l\), and \(r\) (\(1 \leq k \leq 10^5, 1 \leq l \leq r \leq n\)).It is guaranteed that the sum of \(n\) does not exceed \(10^5\) over all test cases, and the sum of \(q\) does not exceed \(5\cdot 10^4\) over all test cases.
For each query, output the answer on a new line.
Input: 25 32 3 5 7 112 1 52 2 42310 1 54 318 12 8 9216 1 248 2 482944 1 4 | Output: 5 6 1629 13 12 520
Hard
4
487
594
48
20
161
E
161E
E. Polycarpus the Safecracker
2,500
brute force; dp
Polycarpus has t safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them.Polycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote a prime number in each row of each matrix. To his surprise, he found that all the matrices turned out to be symmetrical (that is, they remain the same after transposition). Now, years later, Polycarp was irritated to find out that he remembers only the prime numbers pi, written in the first lines of the password matrices.For each safe find the number of matrices which can be passwords to it.The number of digits in pi determines the number of rows and columns of the i-th matrix. One prime number can occur in several rows of the password matrix or in several matrices. The prime numbers that are written not in the first row of the matrix may have leading zeros.
The first line of the input contains an integer t (1 ≀ t ≀ 30) β€” the number of safes. Next t lines contain integers pi (10 ≀ pi ≀ 99999), pi is a prime number written in the first row of the password matrix for the i-th safe. All pi's are written without leading zeros.
Print t numbers, the i-th of them should be the number of matrices that can be a password to the i-th safe. Print the numbers on separate lines.
Here is a possible password matrix for the second safe: 239307977Here is a possible password matrix for the fourth safe: 9001000200021223
Input: 4112394019001 | Output: 428612834
Expert
2
982
269
144
1
1,969
D
1969D
D. Shop Game
1,900
data structures; greedy; math; sortings
Alice and Bob are playing a game in the shop. There are \(n\) items in the shop; each item has two parameters: \(a_i\) (item price for Alice) and \(b_i\) (item price for Bob).Alice wants to choose a subset (possibly empty) of items and buy them. After that, Bob does the following: if Alice bought less than \(k\) items, Bob can take all of them for free; otherwise, he will take \(k\) items for free that Alice bought (Bob chooses which \(k\) items it will be), and for the rest of the chosen items, Bob will buy them from Alice and pay \(b_i\) for the \(i\)-th item. Alice's profit is equal to \(\sum\limits_{i \in S} b_i - \sum\limits_{j \in T} a_j\), where \(S\) is the set of items Bob buys from Alice, and \(T\) is the set of items Alice buys from the shop. In other words, Alice's profit is the difference between the amount Bob pays her and the amount she spends buying the items.Alice wants to maximize her profit, Bob wants to minimize Alice's profit. Your task is to calculate Alice's profit if both Alice and Bob act optimally.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5\); \(0 \le k \le n\)).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)).The third line contains \(n\) integers \(b_1, b_2, \dots, b_n\) (\(1 \le b_i \le 10^9\)).Additional constraint on the input: the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, print a single integer β€” Alice's profit if both Alice and Bob act optimally.
In the first test case, Alice should buy the \(2\)-nd item and sell it to Bob, so her profit is \(2 - 1 = 1\).In the second test case, Alice should buy the \(1\)-st, the \(2\)-nd and the \(3\)-rd item; then Bob takes the \(1\)-st item for free and pays for the \(2\)-nd and the \(3\)-rd item. Alice's profit is \((3+2) - (1+2+1) = 1\). Bob could take \(2\)-nd item for free instead; this does not change Alice's profit. Bob won't take the \(3\)-rd item for free, since this would lead to a profit of \(2\).
Input: 42 02 11 24 11 2 1 43 3 2 34 22 1 1 14 2 3 26 21 3 4 9 1 37 6 8 10 6 8 | Output: 1 1 0 7
Hard
4
1,039
502
96
19
940
E
940E
E. Cashback
2,000
data structures; dp; greedy; math
Since you are the best Wraith King, Nizhniy Magazin Β«MirΒ» at the centre of Vinnytsia is offering you a discount.You are given an array a of length n and an integer c. The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.
The first line contains integers n and c (1 ≀ n, c ≀ 100 000).The second line contains n integers ai (1 ≀ ai ≀ 109) β€” elements of a.
Output a single integer β€” the smallest possible sum of values of these subarrays of some partition of a.
In the first example any partition yields 6 as the sum.In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.
Input: 3 51 2 3 | Output: 6
Hard
4
465
132
104
9
361
A
361A
A. Levko and Table
800
constructive algorithms; implementation
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
The single line contains two integers, n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000).
Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.If there are multiple suitable tables, you are allowed to print any of them.
In the first sample the sum in the first row is 1 + 3 = 4, in the second row β€” 3 + 1 = 4, in the first column β€” 1 + 3 = 4 and in the second column β€” 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.
Input: 2 4 | Output: 1 33 1
Beginner
2
304
75
212
3
1,851
A
1851A
A. Escalator Conversations
800
brute force; constructive algorithms; math
One day, Vlad became curious about who he can have a conversation with on the escalator in the subway. There are a total of \(n\) passengers. The escalator has a total of \(m\) steps, all steps indexed from \(1\) to \(m\) and \(i\)-th step has height \(i \cdot k\).Vlad's height is \(H\) centimeters. Two people with heights \(a\) and \(b\) can have a conversation on the escalator if they are standing on different steps and the height difference between them is equal to the height difference between the steps.For example, if two people have heights \(170\) and \(180\) centimeters, and \(m = 10, k = 5\), then they can stand on steps numbered \(7\) and \(5\), where the height difference between the steps is equal to the height difference between the two people: \(k \cdot 2 = 5 \cdot 2 = 10 = 180 - 170\). There are other possible ways.Given an array \(h\) of size \(n\), where \(h_i\) represents the height of the \(i\)-th person. Vlad is interested in how many people he can have a conversation with on the escalator individually.For example, if \(n = 5, m = 3, k = 3, H = 11\), and \(h = [5, 4, 14, 18, 2]\), Vlad can have a conversation with the person with height \(5\) (Vlad will stand on step \(1\), and the other person will stand on step \(3\)) and with the person with height \(14\) (for example, Vlad can stand on step \(3\), and the other person will stand on step \(2\)). Vlad cannot have a conversation with the person with height \(2\) because even if they stand on the extreme steps of the escalator, the height difference between them will be \(6\), while their height difference is \(9\). Vlad cannot have a conversation with the rest of the people on the escalator, so the answer for this example is \(2\).
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.Then the descriptions of the test cases follow.The first line of each test case contains integers: \(n, m, k, H\) (\(1 \le n,m \le 50\), \(1 \le k,H \le 10^6\)). Here, \(n\) is the number of people, \(m\) is the number of steps, \(k\) is the height difference between neighboring steps, and \(H\) is Vlad's height.The second line contains \(n\) integers: \(h_1, h_2, \ldots, h_n\) (\(1 \le h_i \le 10^6\)). Here, \(h_i\) represents the height of the \(i\)-th person.
For each test case, output a single integer β€” the number of people Vlad can have a conversation with on the escalator individually.
The first example is explained in the problem statement.In the second example, Vlad can have a conversation with the person with height \(11\).In the third example, Vlad can have a conversation with people with heights: \(44, 74, 98, 62\). Therefore, the answer is \(4\).In the fourth example, Vlad can have a conversation with the person with height \(73\).
Input: 75 3 3 115 4 14 18 22 9 5 611 910 50 3 1143 44 74 98 62 60 99 4 11 734 8 8 4968 58 82 737 1 4 6618 66 39 83 48 99 799 1 1 1326 23 84 6 60 87 40 41 256 13 3 2830 70 85 13 1 55 | Output: 2 1 4 1 0 0 3
Beginner
3
1,731
563
131
18
912
B
912B
B. New Year's Eve
1,300
bitmasks; constructive algorithms; number theory
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest ones β€” but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!A xor-sum of a sequence of integers a1, a2, ..., am is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found here.Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than k candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.
The sole string contains two integers n and k (1 ≀ k ≀ n ≀ 1018).
Output one number β€” the largest possible xor-sum.
In the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.In the second sample case, one can, for example, take all six candies and obtain the xor-sum of 7.
Input: 4 3 | Output: 7
Easy
3
919
65
49
9
250
B
250B
B. Restoring IPv6
1,500
implementation; strings
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons β€” 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: ""0124:5678:90ab:cdef:0124:5678:90ab:cdef"". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: ""a56f:00d3:0000:0124:0001:f19a:1000:0000"" β†’ ""a56f:d3:0:0124:01:f19a:1000:00"". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to ""::"". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: ""a56f:00d3:0000:0124:0001:0000:0000:0000"" β†’ ""a56f:00d3:0000:0124:0001::""; ""a56f:0000:0000:0124:0001:0000:1234:0ff0"" β†’ ""a56f::0124:0001:0000:1234:0ff0""; ""a56f:0000:0000:0000:0001:0000:1234:0ff0"" β†’ ""a56f:0000::0000:0001:0000:1234:0ff0""; ""a56f:00d3:0000:0124:0001:0000:0000:0000"" β†’ ""a56f:00d3:0000:0124:0001::0000""; ""0000:0000:0000:0000:0000:0000:0000:0000"" β†’ ""::"". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters ""::"" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.
The first line contains a single integer n β€” the number of records to restore (1 ≀ n ≀ 100).Each of the following n lines contains a string β€” the short IPv6 addresses. Each string only consists of string characters ""0123456789abcdef:"".It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
Input: 6a56f:d3:0:0124:01:f19a:1000:00a56f:00d3:0000:0124:0001::a56f::0124:0001:0000:1234:0ff0a56f:0000::0000:0001:0000:1234:0ff0::0ea::4d:f4:6:0 | Output: a56f:00d3:0000:0124:0001:f19a:1000:0000a56f:00d3:0000:0124:0001:0000:0000:0000a56f:0000:0000:0124:0001:0000:1234:0ff0a56f:0000:0000:0000:0001:0000:1234:0ff00000:0000:0000:0000:0000:0000:0000:000000ea:0000:0000:0000:004d:00f4:0006:0000
Medium
2
1,990
364
198
2
46
D
46D
D. Parking Lot
1,800
data structures; implementation
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
The first line contains three integers L, b ΠΈ f (10 ≀ L ≀ 100000, 1 ≀ b, f ≀ 100). The second line contains an integer n (1 ≀ n ≀ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Input: 30 1 261 51 41 52 21 51 4 | Output: 06111723
Medium
2
1,567
853
286
0
191
E
191E
E. Thwarting Demonstrations
2,200
binary search; data structures; trees
It is dark times in Berland. Berlyand opposition, funded from a neighboring state, has organized a demonstration in Berland capital Bertown. Through the work of intelligence we know that the demonstrations are planned to last for k days.Fortunately, Berland has a special police unit, which can save the country. It has exactly n soldiers numbered from 1 to n. Berland general, the commander of the detachment, must schedule the detachment's work in these difficult k days. In each of these days, the general must send a certain number of police officers to disperse riots. Since the detachment is large and the general is not very smart, he can only select a set of all soldiers numbered from l to r, inclusive, where l and r are selected arbitrarily.Now the general has exactly two problems. First, he cannot send the same group twice β€” then soldiers get bored and they rebel. Second, not all soldiers are equally reliable. Every soldier has a reliability of ai. The reliability of the detachment is counted as the sum of reliabilities of soldiers in it. The reliability of a single soldier can be negative, then when you include him in the detachment, he will only spoil things. The general is distinguished by his great greed and shortsightedness, so each day he sends to the dissolution the most reliable group of soldiers possible (that is, of all the groups that have not been sent yet).The Berland Government has decided to know what would be the minimum reliability of the detachment, sent to disperse the demonstrations during these k days. The general himself can not cope with such a difficult task. Help him to not embarrass himself in front of his superiors!
The first line contains two integers n and k β€” the number of soldiers in the detachment and the number of times somebody goes on duty.The second line contains n space-separated integers ai, their absolute value doesn't exceed 109 β€” the soldiers' reliabilities.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++, it is preferred to use cin, cout streams of the %I64d specifier.
Print a single number β€” the sought minimum reliability of the groups that go on duty during these k days.
Input: 3 41 4 2 | Output: 4
Hard
3
1,672
402
105
1
1,763
C
1763C
C. Another Array Problem
2,000
brute force; constructive algorithms; greedy
You are given an array \(a\) of \(n\) integers. You are allowed to perform the following operation on it as many times as you want (0 or more times): Choose \(2\) indices \(i\),\(j\) where \(1 \le i < j \le n\) and replace \(a_k\) for all \(i \leq k \leq j\) with \(|a_i - a_j|\) Print the maximum sum of all the elements of the final array that you can obtain in such a way.
The first line contains a single integer \(t\) (\(1 \le t \le 10^5\)) β€” the number of test cases.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, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the elements of array \(a\).It's guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print the sum of the final array.
In the first test case, it is not possible to achieve a sum \(> 3\) by using these operations, therefore the maximum sum is \(3\).In the second test case, it can be shown that the maximum sum achievable is \(16\). By using operation \((1,2)\) we transform the array from \([9,1]\) into \([8,8]\), thus the sum of the final array is \(16\). In the third test case, it can be shown that it is not possible to achieve a sum \(> 18\) by using these operations, therefore the maximum sum is \(18\).
Input: 331 1 129 134 9 5 | Output: 3 16 18
Hard
3
375
455
53
17
656
E
656E
E. Out of Controls
2,000
*special
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
The first line of the input contains a single integer N (3 ≀ N ≀ 10).The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≀ aij ≀ 100 for i β‰  j.
Output the maximum length of the shortest path between any pair of vertices in the graph.
You're running short of keywords, so you can't use some of them:definedoforforeachwhilerepeatuntilifthenelseelifelsifelseifcaseswitch
Input: 30 1 11 0 41 4 0 | Output: 2
Hard
1
238
262
89
6
1,354
F
1354F
F. Summoning Minions
2,500
constructive algorithms; dp; flows; graph matchings; greedy; sortings
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon \(n\) different minions. The initial power level of the \(i\)-th minion is \(a_i\), and when it is summoned, all previously summoned minions' power levels are increased by \(b_i\). The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than \(k\) minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
The first line contains one integer \(T\) (\(1 \le T \le 75\)) β€” the number of test cases.Each test case begins with a line containing two integers \(n\) and \(k\) (\(1 \le k \le n \le 75\)) β€” the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively.Then \(n\) lines follow, the \(i\)-th line contains \(2\) integers \(a_i\) and \(b_i\) (\(1 \le a_i \le 10^5\), \(0 \le b_i \le 10^5\)) β€” the parameters of the \(i\)-th minion.
For each test case print the optimal sequence of actions as follows:Firstly, print \(m\) β€” the number of actions which Polycarp has to perform (\(0 \le m \le 2n\)). Then print \(m\) integers \(o_1\), \(o_2\), ..., \(o_m\), where \(o_i\) denotes the \(i\)-th action as follows: if the \(i\)-th action is to summon the minion \(x\), then \(o_i = x\), and if the \(i\)-th action is to destroy the minion \(x\), then \(o_i = -x\). Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than \(k\) after every action.If there are multiple optimal sequences, print any of them.
Consider the example test.In the first test case, Polycarp can summon the minion \(2\) with power level \(7\), then summon the minion \(1\), which will increase the power level of the previous minion by \(3\), then destroy the minion \(1\), and finally, summon the minion \(5\). After this, Polycarp will have two minions with power levels of \(10\).In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Input: 3 5 2 5 3 7 0 5 0 4 0 10 0 2 1 10 100 50 10 5 5 1 5 2 4 3 3 4 2 5 1 | Output: 4 2 1 -1 5 1 2 5 5 4 3 2 1
Expert
6
841
499
720
13
2,121
B
2121B
B. Above the Clouds
800
constructive algorithms; greedy; strings
You are given a string \(s\) of length \(n\), consisting of lowercase letters of the Latin alphabet. Determine whether there exist three non-empty strings \(a\), \(b\), and \(c\) such that: \(a + b + c = s\), meaning the concatenation\(^{\text{βˆ—}}\) of strings \(a\), \(b\), and \(c\) equals \(s\). The string \(b\) is a substring\(^{\text{†}}\) of the string \(a + c\), which is the concatenation of strings \(a\) and \(c\). \(^{\text{βˆ—}}\)Concatenation of strings \(a\) and \(b\) is defined as the string \(a + b = a_1a_2 \ldots a_pb_1b_2 \ldots b_q\), where \(p\) and \(q\) are the lengths of strings \(a\) and \(b\), respectively. For example, the concatenation of the strings ""code"" and ""forces"" is ""codeforces"". \(^{\text{†}}\)A string \(a\) is a substring of a string \(b\) if \(a\) can be obtained from \(b\) by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(3 \leq n \leq 10^5\)) β€” the length of the string \(s\). The second line of each test case contains the string \(s\) of length \(n\), consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output ""Yes"" if there exist three non-empty strings \(a\), \(b\), and \(c\) that satisfy the conditions, and ""No"" otherwise. You may output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive answers.
In the first test case, there exist unique non-empty strings \(a\), \(b\), and \(c\) such that \(a + b + c = s\). These are the strings \(a =\) ""a"", \(b =\) ""a"", and \(c =\) ""a"". The concatenation of strings \(a\) and \(c\) equals \(a + c = \) ""aa"". The string \(b\) is a substring of this string. In the sixth test case, one can choose \(a = \) ""a"", \(b = \) ""ab"", and \(c = \) ""b"". The concatenation of strings \(a\) and \(c\) equals \(a + c = \) ""ab"". The string \(b\) is a substring of this string. In the seventh test case, one can choose \(a = \) ""ab"", \(b = \) ""a"", and \(c = \) ""ca"". The concatenation of strings \(a\) and \(c\) equals \(a + c = \) ""abca"". The string \(b\) is a substring of this string.
Input: 123aaa3aba3aab4abca4abba4aabb5abaca5abcda5abcba6abcbbf6abcdaa3abb | Output: Yes No Yes No Yes Yes Yes No Yes Yes Yes Yes
Beginner
3
964
535
308
21
1,851
C
1851C
C. Tiles Comeback
1,000
greedy
Vlad remembered that he had a series of \(n\) tiles and a number \(k\). The tiles were numbered from left to right, and the \(i\)-th tile had colour \(c_i\).If you stand on the first tile and start jumping any number of tiles right, you can get a path of length \(p\). The length of the path is the number of tiles you stood on.Vlad wants to see if it is possible to get a path of length \(p\) such that: it ends at tile with index \(n\); \(p\) is divisible by \(k\) the path is divided into blocks of length exactly \(k\) each; tiles in each block have the same colour, the colors in adjacent blocks are not necessarily different. For example, let \(n = 14\), \(k = 3\).The colours of the tiles are contained in the array \(c\) = [\(\color{red}{1}, \color{violet}{2}, \color{red}{1}, \color{red}{1}, \color{gray}{7}, \color{orange}{5}, \color{green}{3}, \color{green}{3}, \color{red}{1}, \color{green}{3}, \color{blue}{4}, \color{blue}{4}, \color{violet}{2}, \color{blue}{4}\)]. Then we can construct a path of length \(6\) consisting of \(2\) blocks:\(\color{red}{c_1} \rightarrow \color{red}{c_3} \rightarrow \color{red}{c_4} \rightarrow \color{blue}{c_{11}} \rightarrow \color{blue}{c_{12}} \rightarrow \color{blue}{c_{14}}\)All tiles from the \(1\)-st block will have colour \(\color{red}{\textbf{1}}\), from the \(2\)-nd block will have colour \(\color{blue}{\textbf{4}}\).It is also possible to construct a path of length \(9\) in this example, in which all tiles from the \(1\)-st block will have colour \(\color{red}{\textbf{1}}\), from the \(2\)-nd block will have colour \(\color{green}{\textbf{3}}\), and from the \(3\)-rd block will have colour \(\color{blue}{\textbf{4}}\).
The first line of input data 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\) (\(1 \le k \le n \le 2 \cdot 10^5\))β€”the number of tiles in the series and the length of the block.The second line of each test case contains \(n\) integers \(c_1, c_2, c_3, \dots, c_n\) (\(1 \le c_i \le n\)) β€” the colours of the tiles.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output on a separate line: YES if you can get a path that satisfies these conditions; NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as positive response).
In the first test case, you can jump from the first tile to the last tile;The second test case is explained in the problem statement.
Input: 104 21 1 1 114 31 2 1 1 7 5 3 3 1 3 4 4 2 43 33 1 310 41 2 1 2 1 2 1 2 1 26 21 3 4 1 6 62 21 14 22 1 1 12 11 23 22 2 24 11 1 2 2 | Output: YES YES NO NO YES YES NO YES YES YES
Beginner
1
1,687
552
243
18
1,468
M
1468M
M. Similar Sets
2,300
data structures; graphs; implementation
You are given \(n\) sets of integers. The \(i\)-th set contains \(k_i\) integers.Two sets are called similar if they share at least two common elements, i. e. there exist two integers \(x\) and \(y\) such that \(x \ne y\), and they both belong to each of the two sets.Your task is to find two similar sets among the given ones, or report that there is no such pair of sets.
The first line contains a single integer \(t\) (\(1 \le t \le 50000\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 10^5\)) the number of given sets. The following \(n\) lines describe the sets. The \(i\)-th line starts with an integer \(k_i\) (\(2 \le k_i \le 10^5\)) β€” the number of integers in the \(i\)-th set. Then \(k_i\) integers \(a_{i,1}\), \(a_{i,2}\), ..., \(a_{i,k_i}\) (\(1 \le a_{i,j} \le 10^9\)) follow β€” the elements of the \(i\)-th set. It is guaranteed that all elements in each set are different.The total number of elements in all sets in all test cases is not greater than \(2\cdot 10^5\).
For each test case, print the answer on a single line. If there is no pair of similar sets, print -1. Otherwise, print two different integers β€” the indices of the similar sets. The sets are numbered from \(1\) to \(n\) in the order they are given in the input. If there are multiple answers, print any of them.
Input: 342 1 103 1 3 55 5 4 3 2 13 10 20 3034 1 2 3 44 2 3 4 54 3 4 5 623 1 3 53 4 3 2 | Output: 2 3 1 2 -1
Expert
3
373
702
310
14
1,599
H
1599H
H. Hidden Fortress
2,100
interactive; math
This is an interactive problem!As part of your contribution in the Great Bubble War, you have been tasked with finding the newly built enemy fortress. The world you live in is a giant \(10^9 \times 10^9\) grid, with squares having both coordinates between \(1\) and \(10^9\). You know that the enemy base has the shape of a rectangle, with the sides parallel to the sides of the grid. The people of your world are extremely scared of being at the edge of the world, so you know that the base doesn't contain any of the squares on the edges of the grid (the \(x\) or \(y\) coordinate being \(1\) or \(10^9\)). To help you locate the base, you have been given a device that you can place in any square of the grid, and it will tell you the manhattan distance to the closest square of the base. The manhattan distance from square \((a, b)\) to square \((p, q)\) is calculated as \(|aβˆ’p|+|bβˆ’q|\). If you try to place the device inside the enemy base, you will be captured by the enemy. Because of this, you need to make sure to never place the device inside the enemy base. Unfortunately, the device is powered by a battery and you can't recharge it. This means that you can use the device at most \(40\) times.
The input contains the answers to your queries.
Input: 1 1 2 1 | Output: ? 2 2 ? 5 5 ? 4 7 ? 1 5 ! 2 3 4 5
Hard
2
1,207
47
0
15
1,431
H
1431H
H. Rogue-like Game
2,600
*special; brute force; greedy; two pointers
Marina plays a new rogue-like game. In this game, there are \(n\) different character species and \(m\) different classes. The game is played in runs; for each run, Marina has to select a species and a class for her character. If she selects the \(i\)-th species and the \(j\)-th class, she will get \(c_{i, j}\) points for this run.Initially, some species and classes are unlocked, all others are locked. To unlock the \(i\)-th species, Marina has to get at least \(a_i\) points in total for previous runs β€” that is, as soon as her total score for played runs is at least \(a_i\), this species is unlocked. Similarly, to unlock the \(j\)-th class, she has to get at least \(b_j\) points in total for previous runs. If \(a_i = 0\) for some \(i\), then this species is unlocked initially (the same applies to classes with \(b_j = 0\)).Marina wants to unlock all species and classes in the minimum number of runs. Before playing the game, she can read exactly one guide on some combination of species and class, and reading a guide will increase the score she gets for all runs with that combination by \(k\) (formally, before playing the game, she can increase exactly one value of \(c_{i, j}\) by \(k\)).What is the minimum number of runs she has to play to unlock all species and classes if she chooses the combination to read a guide on optimally?
The first line contains three integers \(n\), \(m\) and \(k\) (\(1 \le n, m \le 1500\); \(0 \le k \le 10^9\)).The second line contains \(n\) integers \(a_1\), \(a_2\), ..., \(a_n\) (\(0 = a_1 \le a_2 \le \dots \le a_n \le 10^{12}\)), where \(a_i\) is the number of points required to unlock the \(i\)-th species (or \(0\), if it is unlocked initially). Note that \(a_1 = 0\), and these values are non-descending.The third line contains \(m\) integers \(b_1\), \(b_2\), ..., \(b_m\) (\(0 = b_1 \le b_2 \le \dots \le b_m \le 10^{12}\)), where \(b_i\) is the number of points required to unlock the \(i\)-th class (or \(0\), if it is unlocked initially). Note that \(b_1 = 0\), and these values are non-descending.Then \(n\) lines follow, each of them contains \(m\) integers. The \(j\)-th integer in the \(i\)-th line is \(c_{i, j}\) (\(1 \le c_{i, j} \le 10^9\)) β€” the score Marina gets for a run with the \(i\)-th species and the \(j\)-th class.
Print one integer β€” the minimum number of runs Marina has to play to unlock all species and all classes if she can read exactly one guide before playing the game.
The explanation for the first test: Marina reads a guide on the combination of the \(1\)-st species and the \(2\)-nd class. Thus, \(c_{1, 2}\) becomes \(7\). Initially, only the \(1\)-st species and the \(1\)-st class are unlocked. Marina plays a run with the \(1\)-st species and the \(1\)-st class. Her score becomes \(2\), and she unlocks the \(2\)-nd class. Marina plays a run with the \(1\)-st species and the \(2\)-nd class. Her score becomes \(9\), and she unlocks everything except the \(4\)-th class. Marina plays a run with the \(3\)-rd species and the \(3\)-rd class. Her score becomes \(11\), and she unlocks the \(4\)-th class. She has unlocked everything in \(3\) runs. Note that this way to unlock everything is not the only one.The explanation for the second test: Marina reads a guide on the combination of the \(2\)-nd species and the \(1\)-st class. Thus, \(c_{2, 1}\) becomes \(6\). Initially, only the \(1\)-st species and the \(1\)-st class are unlocked. Marina plays a run with the \(1\)-st species and the \(1\)-st class. Her score becomes \(3\), and she unlocks the \(2\)-nd species and the \(2\)-nd class. Marina plays a run with the \(2\)-nd species and the \(1\)-st class. Her score becomes \(9\), and she unlocks the \(3\)-rd species and the \(4\)-th species. She has unlocked everything in \(2\) runs. As in the \(1\)-st example, this is not the only way to unlock everything in \(2\) runs.
Input: 3 4 2 0 5 7 0 2 6 10 2 5 5 2 5 3 4 4 3 4 2 4 | Output: 3
Expert
4
1,349
945
162
14
1,998
B
1998B
B. Minimize Equal Sum Subarrays
1,000
constructive algorithms; math; number theory
It is known that Farmer John likes Permutations, but I like them too!β€” Sun Tzu, The Art of Constructing PermutationsYou are given a permutation\(^{\text{βˆ—}}\) \(p\) of length \(n\).Find a permutation \(q\) of length \(n\) that minimizes the number of pairs (\(i, j\)) (\(1 \leq i \leq j \leq n\)) such that \(p_i + p_{i+1} + \ldots + p_j = q_i + q_{i+1} + \ldots + q_j\).\(^{\text{βˆ—}}\)A permutation of length \(n\) 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).
The first line contains \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases.The first line of each test case contains \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)).The following line contains \(n\) space-separated integers \(p_1, p_2, \ldots, p_n\) (\(1 \leq p_i \leq n\)) β€” denoting the permutation \(p\) of length \(n\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output one line containing any permutation of length \(n\) (the permutation \(q\)) such that \(q\) minimizes the number of pairs.
For the first test, there exists only one pair (\(i, j\)) (\(1 \leq i \leq j \leq n\)) such that \(p_i + p_{i+1} + \ldots + p_j = q_i + q_{i+1} + \ldots + q_j\), which is (\(1, 2\)). It can be proven that no such \(q\) exists for which there are no pairs.
Input: 321 251 2 3 4 574 7 5 1 2 6 3 | Output: 2 1 3 5 4 2 1 6 2 1 4 7 3 5
Beginner
3
710
413
149
19
1,167
C
1167C
C. News Distribution
1,400
dfs and similar; dsu; graphs
In some social network, there are \(n\) users communicating with each other in \(m\) groups of friends. Let's analyze the process of distributing some news between users.Initially, some user \(x\) receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user \(x\) you have to determine what is the number of users that will know the news if initially only user \(x\) starts distributing it.
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 5 \cdot 10^5\)) β€” the number of users and the number of groups of friends, respectively.Then \(m\) lines follow, each describing a group of friends. The \(i\)-th line begins with integer \(k_i\) (\(0 \le k_i \le n\)) β€” the number of users in the \(i\)-th group. Then \(k_i\) distinct integers follow, denoting the users belonging to the \(i\)-th group.It is guaranteed that \(\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5\).
Print \(n\) integers. The \(i\)-th integer should be equal to the number of users that will know the news if user \(i\) starts distributing it.
Input: 7 5 3 2 5 4 0 2 1 2 1 1 2 6 7 | Output: 4 4 1 4 4 2 2
Easy
3
711
495
143
11
345
F
345F
F. Superstitions Inspection
2,700
*special
You read scientific research regarding popularity of most famous superstitions across various countries, and you want to analyze their data. More specifically, you want to know which superstitions are popular in most countries.The data is given as a single file in the following format: country name on a separate line, followed by a list of superstitions popular in it, one entry per line. Each entry of the list is formatted as an asterisk ""*"" followed by a single space and then by the superstition name. Entries are unique within each country. The first line of input will represent a country. The input will contain at least one superstition. Country name is a non-empty sequence of words, where each word consists of only English letters. The words of the name of some country will be separated in input with one or more spaces.Superstition name is a non-empty sequence of words, where each word consists of only English letters and digits. The words of the name of some superstition will be separated in input with one or more spaces.You can consider two names equal, if corresponding sequences of words are equal. You shouldn't consider the case of the letters when you compare the words.Output the list of superstitions which are observed in the greatest number of countries. It's guaranteed that all countries have distinct names.
The input contains between 2 and 50 lines. Every line of input will contain between 1 and 50 characters, inclusive.No line has leading or trailing spaces.
Output the list of superstitions which are observed in the greatest number of countries in alphabetical order. Each superstition must be converted to lowercase (one superstition can be written with varying capitalization in different countries).The alphabetical order of superstitions means the lexicographical order of sequences of words (their names).
Input: Ukraine* Friday the 13th* black cat* knock the woodUSA* wishing well* friday the 13thHollandFrance* Wishing Well | Output: friday the 13th wishing well
Master
1
1,342
154
353
3
1,931
D
1931D
D. Divisible Pairs
1,300
combinatorics; math; number theory
Polycarp has two favorite integers \(x\) and \(y\) (they can be equal), and he has found an array \(a\) of length \(n\).Polycarp considers a pair of indices \(\langle i, j \rangle\) (\(1 \le i < j \le n\)) beautiful if: \(a_i + a_j\) is divisible by \(x\); \(a_i - a_j\) is divisible by \(y\). For example, if \(x=5\), \(y=2\), \(n=6\), \(a=\)[\(1, 2, 7, 4, 9, 6\)], then the only beautiful pairs are: \(\langle 1, 5 \rangle\): \(a_1 + a_5 = 1 + 9 = 10\) (\(10\) is divisible by \(5\)) and \(a_1 - a_5 = 1 - 9 = -8\) (\(-8\) is divisible by \(2\)); \(\langle 4, 6 \rangle\): \(a_4 + a_6 = 4 + 6 = 10\) (\(10\) is divisible by \(5\)) and \(a_4 - a_6 = 4 - 6 = -2\) (\(-2\) is divisible by \(2\)). Find the number of beautiful pairs in the array \(a\).
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Then the descriptions of the test cases follow.The first line of each test case contains three integers \(n\), \(x\), and \(y\) (\(2 \le n \le 2 \cdot 10^5\), \(1 \le x, y \le 10^9\)) β€” the size of the array and Polycarp's favorite integers.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single integer β€” the number of beautiful pairs in the array \(a\).
Input: 76 5 21 2 7 4 9 67 9 51 10 15 3 8 12 159 4 1014 10 2 2 11 11 13 5 69 5 610 7 6 7 9 7 7 10 109 6 24 9 7 1 2 2 13 3 159 2 314 6 1 15 12 15 8 2 1510 5 713 3 3 2 12 11 3 7 13 14 | Output: 2 0 1 3 5 7 0
Easy
3
750
580
95
19
1,479
E
1479E
E. School Clubs
3,500
dp; fft; math; number theory; probabilities
In Homer's school, there are \(n\) students who love clubs. Initially, there are \(m\) clubs, and each of the \(n\) students is in exactly one club. In other words, there are \(a_i\) students in the \(i\)-th club for \(1 \leq i \leq m\) and \(a_1+a_2+\dots+a_m = n\).The \(n\) students are so unfriendly that every day one of them (chosen uniformly at random from all of the \(n\) students) gets angry. The student who gets angry will do one of the following things. With probability \(\frac 1 2\), he leaves his current club, then creates a new club himself and joins it. There is only one student (himself) in the new club he creates. With probability \(\frac 1 2\), he does not create new clubs. In this case, he changes his club to a new one (possibly the same club he is in currently) with probability proportional to the number of students in it. Formally, suppose there are \(k\) clubs and there are \(b_i\) students in the \(i\)-th club for \(1 \leq i \leq k\) (before the student gets angry). He leaves his current club, and then joins the \(i\)-th club with probability \(\frac {b_i} {n}\). We note that when a club becomes empty, students will never join it because any student who gets angry will join an empty club with probability \(0\) according to the above statement.Homer wonders the expected number of days until every student is in the same club for the first time.We can prove that the answer can be represented as a rational number \(\frac p q\) with \(\gcd(p, q) = 1\). Therefore, you are asked to find the value of \(pq^{-1} \bmod 998\,244\,353\). It can be shown that \(q \bmod 998\,244\,353 \neq 0\) under the given constraints of the problem.
The first line contains an integer \(m\) (\(1 \leq m \leq 1000\)) β€” the number of clubs initially.The second line contains \(m\) integers \(a_1, a_2, \dots, a_m\) (\(1 \leq a_i \leq 4 \cdot 10^8\)) with \(1 \leq a_1+a_2+\dots+a_m \leq 4 \cdot 10^8\), where \(a_i\) denotes the number of students in the \(i\)-th club initially.
Print one integer β€” the expected number of days until every student is in the same club for the first time, modulo \(998\,244\,353\).
In the first example, no matter which student gets angry, the two students will become in the same club with probability \(\frac 1 4\). So the expected number of days until every student is in the same club should be \(4\).In the second example, we note that in the first day: The only student in the first club will get angry with probability \(\frac 1 3\). If he gets angry, then he will create a new club and join it with probability \(\frac 1 2\) (In this case, there will be three clubs which have \(0, 1, 2\) students in it, respectively), leave his current club and join the second club with probability \(\frac 1 2 \cdot \frac 2 3 = \frac 1 3\), or stay still with probability \(\frac 1 2 \cdot \frac 1 3 = \frac 1 6\); Each of the two students in the second club will get angry with probability \(\frac 1 3\). If one of them gets angry, then he will create a new club and join it with probability \(\frac 1 2\), leave his current club and join the second club with probability \(\frac 1 2 \cdot \frac 1 3 = \frac 1 6\), or stay still with probability \(\frac 1 2 \cdot \frac 2 3 = \frac 1 3\). In the fourth example, there is only one club initially. That is, every student has already been in the same club. So the answer is \(0\).
Input: 2 1 1 | Output: 4
Master
5
1,669
327
133
14
853
C
853C
C. Boredom
2,100
data structures
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n Γ— n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly nΒ·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
The first line of input contains two integers n and q (2 ≀ n ≀ 200 000, 1 ≀ q ≀ 200 000) β€” the size of the grid and the number of query rectangles.The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≀ pi ≀ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right.The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ u ≀ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.
For each query rectangle output its beauty degree on a separate line.
The first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below: There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:
Input: 2 31 21 1 1 11 1 1 21 1 2 2 | Output: 111
Hard
1
1,075
711
69
8
770
C
770C
C. Online Courses In BSU
1,500
*special; dfs and similar; graphs; implementation
Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.
The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105.
Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them.
In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
Input: 6 25 30002 2 11 41 5 | Output: 51 2 3 4 5
Medium
4
743
717
396
7
1,957
B
1957B
B. A BIT of a Construction
1,100
bitmasks; constructive algorithms; greedy; implementation
Given integers \(n\) and \(k\), construct a sequence of \(n\) non-negative (i.e. \(\geq 0\)) integers \(a_1, a_2, \ldots, a_n\) such that \(\sum\limits_{i = 1}^n a_i = k\) The number of \(1\)s in the binary representation of \(a_1 | a_2 | \ldots | a_n\) is maximized, where \(|\) denotes the bitwise OR operation.
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases.The only line of each test case contains two integers \(n\) and \(k\) (\(1 \leq n \leq 2 \cdot 10^5\), \(1 \leq k \leq 10^9\)) β€” the number of non-negative integers to be printed and the sum respectively.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a sequence \(a_1, a_2, \ldots, a_n\) on a new line that satisfies the conditions given above.If there are multiple solutions, print any of them.
In the first test case, we have to print exactly one integer, hence we can only output \(5\) as the answer.In the second test case, we output \(1, 2\) which sum up to \(3\), and \(1 | 2 = (11)_2\) has two \(1\)s in its binary representation, which is the maximum we can achieve in these constraints.In the fourth test case, we output \(3, 1, 1, 32, 2, 12\) which sum up to \(51\), and \(3 | 1 | 1 | 32 | 2 | 12 = (101\,111)_2\) has five \(1\)s in its binary representation, which is the maximum we can achieve in these constraints.
Input: 41 52 32 56 51 | Output: 5 1 2 5 0 3 1 1 32 2 12
Easy
4
313
395
171
19
802
F
802F
F. Marmots (hard)
2,800
math; probabilities
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request.Also, there are now villages with as few as a single inhabitant, meaning that .Can you help Heidi find out whether a village follows a Poisson or a uniform distribution?
Same as for the easy and medium versions. But remember that now 1 ≀ P ≀ 1000 and that the marmots may provide positive as well as negative integers.
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answers came from a uniform distribution.
Master
2
347
148
226
8
1,808
D
1808D
D. Petya, Petya, Petr, and Palindromes
2,100
binary search; brute force; data structures; two pointers
Petya and his friend, the robot Petya++, have a common friend β€” the cyborg Petr#. Sometimes Petr# comes to the friends for a cup of tea and tells them interesting problems.Today, Petr# told them the following problem.A palindrome is a sequence that reads the same from left to right as from right to left. For example, \([38, 12, 8, 12, 38]\), \([1]\), and \([3, 8, 8, 3]\) are palindromes.Let's call the palindromicity of a sequence \(a_1, a_2, \dots, a_n\) the minimum count of elements that need to be replaced to make this sequence a palindrome. For example, the palindromicity of the sequence \([38, 12, 8, 38, 38]\) is \(1\) since it is sufficient to replace the number \(38\) at the fourth position with the number \(12\). And the palindromicity of the sequence \([3, 3, 5, 5, 5]\) is two since you can replace the first two threes with fives, and the resulting sequence \([5, 5, 5, 5, 5]\) is a palindrome.Given a sequence \(a\) of length \(n\), and an odd integer \(k\), you need to find the sum of palindromicity of all subarrays of length \(k\), i. e., the sum of the palindromicity values for the sequences \(a_i, a_{i+1}, \dots, a_{i+k-1}\) for all \(i\) from \(1\) to \(n-k+1\).The students quickly solved the problem. Can you do it too?
The first line of the input contains two integers \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5\), \(1 \le k \le n\), \(k\) is odd) β€” the length of the sequence and the length of subarrays for which it is necessary to determine whether they are palindromes.The second line of the input contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 2 \cdot 10^5\)) β€” the sequence itself.
Output a single integer β€” the total palindromicity of all subarrays of length \(k\).
In the first example, the palindromicity of the subarray \([1, 2, 8, 2, 5]\) is \(1\), the palindromicity of the string \([2, 8, 2, 5, 2]\) is also \(1\), the palindromicity of the string \([8, 2, 5, 2, 8]\) is \(0\), and the palindromicity of the string \([2, 5, 2, 8, 6]\) is \(2\). The total palindromicity is \(1+1+0+2 = 4\).In the second example, the only substring of length \(9\) coincides with the entire string, and its palindromicity is \(0\), so the answer is also \(0\).
Input: 8 5 1 2 8 2 5 2 8 6 | Output: 4
Hard
4
1,251
389
84
18
2,090
B
2090B
B. Pushing Balls
1,000
brute force; dp; implementation
Ecrade has an \(n \times m\) grid, originally empty, and he has pushed several (possibly, zero) balls in it.Each time, he can push one ball into the grid either from the leftmost edge of a particular row or the topmost edge of a particular column of the grid.When a ball moves towards a position: If there is no ball originally at that position, the incoming ball will stop and occupy the position. If there is already a ball at that position, the incoming ball will stop and occupy the position, while the original ball will continue moving to the next position in the same direction. Note that if a row or column is full (i.e., all positions in that row or column have balls), he cannot push a ball into that row or column.Given the final state of whether there is a ball at each position of the grid, you need to determine whether it is possible for Ecrade to push the balls to reach the final state.
The first line contains an integer \(t\) (\(1 \le t \le 10\,000\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n, m \le 50\)).This is followed by \(n\) lines, each containing exactly \(m\) characters and consisting only of \(0\) and \(1\), describing the final state of the grid. There is a ball at one position of the grid if and only if the corresponding position of the given input is \(1\).It is guaranteed that the sum of \(n\cdot m\) over all test cases does not exceed \(10\,000\).
For each test case, output ""Yes"" (without quotes) if it is possible for Ecrade to push the balls to reach the final state, and ""No"" (without quotes) otherwise.You can output ""Yes"" and ""No"" in any case (for example, strings ""YES"", ""yEs"" and ""yes"" will be recognized as a positive response).
For simplicity, if Ecrade pushes a ball from the leftmost edge of the \(i\)-th row, we call the operation \(\text{ROW}\ i\); if he pushes a ball from the topmost edge of the \(i\)-th column, we call the operation \(\text{COL}\ i\).For intuitive understanding, a non-zero number \(x\) in the matrix given below represents the \(x\)-th ball that is pushed in.In the first test case, a possible series of operations:\(\begin{pmatrix}0&0&0\\0&0&0\\0&0&0\end{pmatrix}\xrightarrow{\text{ROW}\ 3}\xrightarrow{\text{ROW}\ 3} \begin{pmatrix}0&0&0\\0&0&0\\2&1&0\end{pmatrix}\xrightarrow{\text{COL}\ 3}\xrightarrow{\text{COL}\ 3} \begin{pmatrix}0&0&4\\0&0&3\\2&1&0\end{pmatrix}\)In the second test case, a possible series of operations:\(\begin{pmatrix}0&0&0\\0&0&0\\0&0&0\end{pmatrix}\xrightarrow{\text{ROW}\ 2}\xrightarrow{\text{ROW}\ 2}\xrightarrow{\text{ROW}\ 2} \begin{pmatrix}0&0&0\\3&2&1\\0&0&0\end{pmatrix}\xrightarrow{\text{COL}\ 2}\xrightarrow{\text{COL}\ 2} \begin{pmatrix}0&5&0\\3&4&1\\0&2&0\end{pmatrix}\)In the third test case, a possible series of operations:\(\begin{pmatrix}0&0&0\\0&0&0\\0&0&0\end{pmatrix}\xrightarrow{\text{ROW}\ 1}\xrightarrow{\text{ROW}\ 2}\xrightarrow{\text{ROW}\ 3} \begin{pmatrix}1&0&0\\2&0&0\\3&0&0\end{pmatrix}\xrightarrow{\text{COL}\ 3}\xrightarrow{\text{COL}\ 3}\xrightarrow{\text{COL}\ 3} \begin{pmatrix}1&0&6\\2&0&5\\3&0&4\end{pmatrix}\xrightarrow{\text{ROW}\ 1}\xrightarrow{\text{ROW}\ 2}\xrightarrow{\text{ROW}\ 3} \begin{pmatrix}7&1&6\\8&2&5\\9&3&4\end{pmatrix}\)
Input: 53 30010011103 30101110103 31111111113 30000000003 3000000001 | Output: YES YES YES YES NO
Beginner
3
903
594
303
20
792
E
792E
E. Colored Balls
2,500
greedy; math; number theory
There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that: each ball belongs to exactly one of the sets, there are no empty sets, there is no set containing two (or more) balls of different colors (each set contains only balls of one color), there are no two sets such that the difference between their sizes is greater than 1. Print the minimum possible number of sets.
The first line contains one integer number n (1 ≀ n ≀ 500).The second line contains n integer numbers a1, a2, ... , an (1 ≀ ai ≀ 109).
Print one integer number β€” the minimum possible number of sets.
In the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color.
Input: 34 7 8 | Output: 5
Expert
3
526
134
63
7
1,221
E
1221E
E. Game With String
2,500
games
Alice and Bob play a game. Initially they have a string \(s_1, s_2, \dots, s_n\), consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length \(a\), and Bob must select a substring of length \(b\). It is guaranteed that \(a > b\).For example, if \(s =\) ...X.. and \(a = 3\), \(b = 2\), then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string \(s =\) ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX.Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally.You have to answer \(q\) independent queries.
The first line contains one integer \(q\) (\(1 \le q \le 3 \cdot 10^5\)) β€” the number of queries.The first line of each query contains two integers \(a\) and \(b\) (\(1 \le b < a \le 3 \cdot 10^5\)).The second line of each query contains the string \(s\) (\(1 \le |s| \le 3 \cdot 10^5\)), consisting of only characters . and X.It is guaranteed that sum of all \(|s|\) over all queries not exceed \(3 \cdot 10^5\).
For each test case print YES if Alice can win and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
In the first query Alice can select substring \(s_3 \dots s_5\). After that \(s\) turns into XXXXX...XX...X. After that, no matter what move Bob makes, Alice can make the move (this will be her second move), but Bob can't make his second move.In the second query Alice can not win because she cannot even make one move.In the third query Alice can choose substring \(s_2 \dots s_6\). After that \(s\) turns into .XXXXX.X..X, and Bob can't make a move after that.
Input: 3 3 2 XX......XX...X 4 2 X...X.X..X 5 3 .......X..X | Output: YES NO YES
Expert
1
822
413
206
12
255
B
255B
B. Code Parsing
1,200
implementation
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters ""x"" and ""y"", and uses two following operations at runtime: Find two consecutive characters in the string, such that the first of them equals ""y"", and the second one equals ""x"" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. Find in the string two consecutive characters, such that the first of them equals ""x"" and the second one equals ""y"". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows: If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.
The first line contains a non-empty string s. It is guaranteed that the string only consists of characters ""x"" and ""y"". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.
In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.
In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.In the second test the transformation will be like this: string ""yxyxy"" transforms into string ""xyyxy""; string ""xyyxy"" transforms into string ""xyxyy""; string ""xyxyy"" transforms into string ""xxyyy""; string ""xxyyy"" transforms into string ""xyy""; string ""xyy"" transforms into string ""y"". As a result, we've got string ""y"". In the third test case only one transformation will take place: string ""xxxxxy"" transforms into string ""xxxx"". Thus, the answer will be string ""xxxx"".
Input: x | Output: x
Easy
1
1,308
283
143
2
585
B
585B
B. Phillip and Trains
1,700
dfs and similar; graphs; shortest paths
The mobile application store has a new game called ""Subway Roller"".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.
Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≀ t ≀ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) β€” the number of sets.Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n, k (2 ≀ n ≀ 100, 1 ≀ k ≀ 26) β€” the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.
For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.
In the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.
Input: 216 4...AAAAA........s.BBB......CCCCC........DDDDD...16 4...AAAAA........s.BBB....CCCCC.........DDDDD.... | Output: YESNO
Medium
3
1,241
932
120
5
1,356
A3
1356A3
A3. Distinguish Z from S
0
*special
You are given an operation that implements a single-qubit unitary transformation: either the Z gate or the S gate. The operation will have Adjoint and Controlled variants defined.Your task is to perform necessary operations and measurements to figure out which unitary it was and to return 0 if it was the Z gate or 1 if it was the S gate. You are allowed to apply the given operation and its adjoint/controlled variants exactly twice.You have to implement an operation which takes a single-qubit operation as an input and returns an integer. Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Intrinsic; operation Solve (unitary : (Qubit => Unit is Adj+Ctl)) : Int { // your code here }}
Beginner
1
727
0
0
13
898
D
898D
D. Alarm Clock
1,600
greedy
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai β€” number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on.
First line contains three integers n, m and k (1 ≀ k ≀ n ≀ 2Β·105, 1 ≀ m ≀ 106) β€” number of alarm clocks, and conditions of Vitalya's waking up. Second line contains sequence of distinct integers a1, a2, ..., an (1 ≀ ai ≀ 106) in which ai equals minute on which i-th alarm clock will ring. Numbers are given in arbitrary order. Vitalya lives in a Berland in which day lasts for 106 minutes.
Output minimal number of alarm clocks that Vitalya should turn off to sleep all next day long.
In first example Vitalya should turn off first alarm clock which rings at minute 3.In second example Vitalya shouldn't turn off any alarm clock because there are no interval of 10 consequence minutes in which 3 alarm clocks will ring.In third example Vitalya should turn off any 6 alarm clocks.
Input: 3 3 23 5 1 | Output: 1
Medium
1
848
389
94
8
38
A
38A
A. Army
800
implementation
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.
The first input line contains an integer n (2 ≀ n ≀ 100). The second line contains n - 1 integers di (1 ≀ di ≀ 100). The third input line contains two integers a and b (1 ≀ a < b ≀ n). The numbers on the lines are space-separated.
Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.
Input: 35 61 2 | Output: 5
Beginner
1
487
230
100
0
335
F
335F
F. Buy One, Get One Free
3,000
dp; greedy
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
Input will begin with an integer n (1 ≀ n ≀ 500000), the number of pies you wish to acquire. Following this is a line with n integers, each indicating the cost of a pie. All costs are positive integers not exceeding 109.
Print the minimum cost to acquire all the pies.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
In the first test case you can pay for a pie with cost 5 and get a pie with cost 4 for free, then pay for a pie with cost 5 and get a pie with cost 3 for free, then pay for a pie with cost 4 and get a pie with cost 3 for free.In the second test case you have to pay full price for every pie.
Input: 63 4 5 3 4 5 | Output: 14
Master
2
270
220
194
3
222
D
222D
D. Olympiad
1,900
binary search; greedy; sortings; two pointers
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.Help Vasya's teacher, find two numbers β€” the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.
The first line contains two space-separated integers n, x (1 ≀ n ≀ 105; 0 ≀ x ≀ 2Β·105) β€” the number of Olympiad participants and the minimum number of points Vasya earned.The second line contains n space-separated integers: a1, a2, ..., an (0 ≀ ai ≀ 105) β€” the participants' points in the first tour.The third line contains n space-separated integers: b1, b2, ..., bn (0 ≀ bi ≀ 105) β€” the participants' points in the second tour.The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad β€” there are two integers i, j (1 ≀ i, j ≀ n) such, that ai + bj β‰₯ x.
Print two space-separated integers β€” the best and the worst place Vasya could have got on the Olympiad.
In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that β€” {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.In the worst case scenario Vasya can get the fifth place if the table looks like that β€” {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
Input: 5 21 1 1 1 11 1 1 1 1 | Output: 1 5
Hard
4
805
612
103
2
911
A
911A
A. Nearest Minimums
1,100
implementation
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
The first line contains positive integer n (2 ≀ n ≀ 105) β€” size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≀ ai ≀ 109) β€” elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Print the only number β€” distance between two nearest minimums in the array.
Input: 23 3 | Output: 1
Easy
1
200
251
75
9
402
E
402E
E. Strictly Positive Matrix
2,200
graphs; math
You have matrix a of size n Γ— n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions: for any numbers i, j (1 ≀ i, j ≀ n) the following inequality holds: aij β‰₯ 0; . Matrix b is strictly positive, if for any numbers i, j (1 ≀ i, j ≀ n) the inequality bij > 0 holds. You task is to determine if there is such integer k β‰₯ 1, that matrix ak is strictly positive.
The first line contains integer n (2 ≀ n ≀ 2000) β€” the number of rows and columns in matrix a.The next n lines contain the description of the rows of matrix a. The i-th line contains n non-negative integers ai1, ai2, ..., ain (0 ≀ aij ≀ 50). It is guaranteed that .
If there is a positive integer k β‰₯ 1, such that matrix ak is strictly positive, print ""YES"" (without the quotes). Otherwise, print ""NO"" (without the quotes).
Input: 21 00 1 | Output: NO
Hard
2
571
265
161
4
1,741
B
1741B
B. Funny Permutation
800
constructive algorithms; math
A sequence of \(n\) numbers is called permutation if it contains all numbers from \(1\) to \(n\) exactly once. For example, the sequences \([3, 1, 4, 2]\), [\(1\)] and \([2,1]\) are permutations, but \([1,2,1]\), \([0,1]\) and \([1,3,4]\) are not.For a given number \(n\) you need to make a permutation \(p\) such that two requirements are satisfied at the same time: For each element \(p_i\), at least one of its neighbors has a value that differs from the value of \(p_i\) by one. That is, for each element \(p_i\) (\(1 \le i \le n\)), at least one of its neighboring elements (standing to the left or right of \(p_i\)) must be \(p_i + 1\), or \(p_i - 1\). the permutation must have no fixed points. That is, for every \(i\) (\(1 \le i \le n\)), \(p_i \neq i\) must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let \(n = 4\). Then [\(4, 3, 1, 2\)] is a funny permutation, since: to the right of \(p_1=4\) is \(p_2=p_1-1=4-1=3\); to the left of \(p_2=3\) is \(p_1=p_2+1=3+1=4\); to the right of \(p_3=1\) is \(p_4=p_3+1=1+1=2\); to the left of \(p_4=2\) is \(p_3=p_4-1=2-1=1\). for all \(i\) is \(p_i \ne i\). For a given positive integer \(n\), output any funny permutation of length \(n\), or output -1 if funny permutation of length \(n\) does not exist.
The first line of input data contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The description of the test cases follows.Each test case consists of f single line containing one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print on a separate line: any funny permutation \(p\) of length \(n\); or the number -1 if the permutation you are looking for does not exist.
The first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations \([1, 2, 3]\), \([1, 3, 2]\), \([2, 1, 3]\), \([3, 2, 1]\) have fixed points, and in \([2, 3, 1]\) and \([3, 1, 2]\) the first condition is met not for all positions.
Input: 543752 | Output: 3 4 2 1 -1 6 7 4 5 3 2 1 5 4 1 2 3 2 1
Beginner
2
1,307
346
162
17
778
A
778A
A. String Game
1,700
binary search; greedy; strings
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = ""nastya"" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words ""nastya"" ""nastya"" ""nastya"" ""nastya"" ""nastya"" ""nastya"" ""nastya"".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≀ |p| < |t| ≀ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t.Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≀ ai ≀ |t|, all ai are distinct).
Print a single integer number, the maximum number of letters that Nastya can remove.
In the first sample test sequence of removing made by Nastya looks like this:""ababcba"" ""ababcba"" ""ababcba"" ""ababcba"" Nastya can not continue, because it is impossible to get word ""abb"" from word ""ababcba"".So, Nastya will remove only three letters.
Input: ababcbaabb5 3 4 1 7 6 2 | Output: 3
Medium
3
1,147
422
84
7
1,187
F
1187F
F. Expected Square Beauty
2,500
dp; math; probabilities
Let \(x\) be an array of integers \(x = [x_1, x_2, \dots, x_n]\). Let's define \(B(x)\) as a minimal size of a partition of \(x\) into subsegments such that all elements in each subsegment are equal. For example, \(B([3, 3, 6, 1, 6, 6, 6]) = 4\) using next partition: \([3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6]\).Now you don't have any exact values of \(x\), but you know that \(x_i\) can be any integer value from \([l_i, r_i]\) (\(l_i \le r_i\)) uniformly at random. All \(x_i\) are independent.Calculate expected value of \((B(x))^2\), or \(E((B(x))^2)\). It's guaranteed that the expected value can be represented as rational fraction \(\frac{P}{Q}\) where \((P, Q) = 1\), so print the value \(P \cdot Q^{-1} \mod 10^9 + 7\).
The first line contains the single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the size of the array \(x\).The second line contains \(n\) integers \(l_1, l_2, \dots, l_n\) (\(1 \le l_i \le 10^9\)).The third line contains \(n\) integers \(r_1, r_2, \dots, r_n\) (\(l_i \le r_i \le 10^9\)).
Print the single integer β€” \(E((B(x))^2)\) as \(P \cdot Q^{-1} \mod 10^9 + 7\).
Let's describe all possible values of \(x\) for the first sample: \([1, 1, 1]\): \(B(x) = 1\), \(B^2(x) = 1\); \([1, 1, 2]\): \(B(x) = 2\), \(B^2(x) = 4\); \([1, 1, 3]\): \(B(x) = 2\), \(B^2(x) = 4\); \([1, 2, 1]\): \(B(x) = 3\), \(B^2(x) = 9\); \([1, 2, 2]\): \(B(x) = 2\), \(B^2(x) = 4\); \([1, 2, 3]\): \(B(x) = 3\), \(B^2(x) = 9\); So \(E = \frac{1}{6} (1 + 4 + 4 + 9 + 4 + 9) = \frac{31}{6}\) or \(31 \cdot 6^{-1} = 166666673\).All possible values of \(x\) for the second sample: \([3, 4, 5]\): \(B(x) = 3\), \(B^2(x) = 9\); \([3, 4, 6]\): \(B(x) = 3\), \(B^2(x) = 9\); \([3, 5, 5]\): \(B(x) = 2\), \(B^2(x) = 4\); \([3, 5, 6]\): \(B(x) = 3\), \(B^2(x) = 9\); \([4, 4, 5]\): \(B(x) = 2\), \(B^2(x) = 4\); \([4, 4, 6]\): \(B(x) = 2\), \(B^2(x) = 4\); \([4, 5, 5]\): \(B(x) = 2\), \(B^2(x) = 4\); \([4, 5, 6]\): \(B(x) = 3\), \(B^2(x) = 9\); So \(E = \frac{1}{8} (9 + 9 + 4 + 9 + 4 + 4 + 4 + 9) = \frac{52}{8}\) or \(13 \cdot 2^{-1} = 500000010\).
Input: 3 1 1 1 1 2 3 | Output: 166666673
Expert
3
719
291
79
11
1,044
E
1044E
E. Grid Sort
3,100
implementation
You are given an \(n \times m\) grid. Each grid cell is filled with a unique integer from \(1\) to \(nm\) so that each integer appears exactly once.In one operation, you can choose an arbitrary cycle of the grid and move all integers along that cycle one space over. Here, a cycle is any sequence that satisfies the following conditions: There are at least four squares. Each square appears at most once. Every pair of adjacent squares, and also the first and last squares, share an edge. For example, if we had the following grid: We can choose an arbitrary cycle like this one: To get the following grid: In this particular case, the chosen cycle can be represented as the sequence \([1, 2, 3, 6, 5, 8, 7, 4]\), the numbers are in the direction that we want to rotate them in.Find any sequence of operations to sort the grid so that the array created by concatenating the rows from the highest to the lowest is sorted (look at the first picture above).Note you do not need to minimize number of operations or sum of cycle lengths. The only constraint is that the sum of all cycles lengths must not be greater than \(10^5\). We can show that an answer always exists under the given constraints. Output any valid sequence of moves that will sort the grid.
The first line contains two integers \(n\) and \(m\) (\(3 \leq n,m \leq 20\)) β€” the dimensions of the grid.Each of the next \(n\) lines contains \(m\) integers \(x_{i,1}, x_{i,2}, \ldots, x_{i, m}\) (\(1 \leq x_{i,j} \leq nm\)), denoting the values of the block in row \(i\) and column \(j\). It is guaranteed that all \(x_{i,j}\) are distinct.
First, print a single integer \(k\), the number of operations (\(k \geq 0\)).On each of the next \(k\) lines, print a cycle as follows:$$$\(s\ y_1\ y_2\ \ldots\ y_s\)\(Here, \)s\( is the number of blocks to move (\)s \geq 4\(). Here we have block \)y_1\( moving to where block \)y_2\( is, block \)y_2\( moving to where block \)y_3\( is, and so on with block \)y_s\( moving to where block \)y_1\( is.The sum of \)s\( over all operations must be at most \)10^5$$$.
The first sample is the case in the statement. Here, we can use the cycle in reverse order to sort the grid.
Input: 3 34 1 27 6 38 5 9 | Output: 18 1 4 7 8 5 6 3 2
Master
1
1,255
344
462
10
1,945
G
1945G
G. Cook and Porridge
2,500
binary search; constructive algorithms; data structures; implementation
Finally, lunchtime!\(n\) schoolchildren have lined up in a long queue at the cook's tent for porridge. The cook will be serving porridge for \(D\) minutes. The schoolchild standing in the \(i\)-th position in the queue has a priority of \(k_i\) and eats one portion of porridge in \(s_i\) minutes.At the beginning of each minute of the break, the cook serves the first schoolchild in the queue one portion of porridge, after which the schoolchild goes to eat their portion. If the \(i\)-th schoolchild is served a portion at the beginning of the \(x\)-th minute, then they will return to the queue at the end of the \((x + s_i)\)-th minute.When the \(i\)-th schoolchild returns to the queue, the schoolchildren at the end of the queue whose priority is strictly lower than that of the \(i\)-th schoolchild must let them pass. Thus, they will stand in the queue behind the last schoolchild whose priority is not lower than their own. That is, behind the last schoolchild \(j\) with \(k_j \ge k_i\). If there is no such schoolchild in the queue, the \(i\)-th schoolchild will stand at the front of the queue.If several schoolchildren return at the same time, they will return to the queue in ascending order of their \(s_i\).For example, if \(n = 3\), \(D = 3\), \(k = [2, 3, 2]\), and \(s = [2, 1, 3]\), the serving will occur as follows: At the beginning of minute \(1\), the students in the queue are \([1, 2, 3]\), and student \(1\) is served porridge; at the beginning of minute \(2\), the students in the queue are \([2, 3]\), and student \(2\) is served porridge; at the beginning of minute \(3\), the student in the queue is \([3]\), and student \(3\) is served porridge; at the end of minute \(3\), student \(2\) returns to the queue, and the queue becomes \([2]\); at the end of minute \(3\), student \(1\) returns to the queue, and the queue becomes \([2, 1]\), as his priority is lower. Determine the minimum number of minutes after the start of the break that each schoolchild will receive porridge at least once, or report that this will not happen within \(D\) minutes.
Each test consists of several test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases. This is followed by a description of the test cases.The first line of each test case contains two integers \(n\) and \(D\) (\(1 \le n \le 2 \cdot 10^5\), \(1 \le D \le 3\cdot 10^5\)) β€” the number of schoolchildren in the queue and the break time, respectively.The next \(n\) lines contain two integers \(k_i\) and \(s_i\) (\(1 \le k_i, s_i, \le 10^9\)) β€” the priority and the time to eat one portion of porridge for the respective schoolchild. The schoolchildren are given in the order they stand in the queue (from the front to the end).It is guaranteed that the sum of the values of \(n\) for all input data sets does not exceed \(2\cdot 10^5\). Similarly, it is guaranteed that the sum of the values of \(D\) for all input data sets does not exceed \(3\cdot 10^5\).
For each test case, output the minimum number of minutes after which each schoolchild will receive porridge at least once. If this does not happen within the break time, output \(-1\).
Input: 73 32 23 12 35 1010 37 111 35 16 15 204 27 28 51 53 15 171 38 28 32 21 15 148 24 21 38 36 41 114 55 148 24 21 38 36 4 | Output: 3 -1 12 6 6 1 6
Expert
4
2,082
908
184
19
29
A
29A
A. Spit Problem
1,000
brute force
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.
The first line contains integer n (1 ≀ n ≀ 100) β€” the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≀ xi ≀ 104, 1 ≀ |di| ≀ 2Β·104) β€” records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.
If there are two camels, which spitted at each other, output YES. Otherwise, output NO.
Input: 20 11 -1 | Output: YES
Beginner
1
485
445
87
0
1,734
C
1734C
C. Removing Smallest Multiples
1,200
greedy; math
You are given a set \(S\), which contains the first \(n\) positive integers: \(1, 2, \ldots, n\).You can perform the following operation on \(S\) any number of times (possibly zero): Choose a positive integer \(k\) where \(1 \le k \le n\), such that there exists a multiple of \(k\) in \(S\). Then, delete the smallest multiple of \(k\) from \(S\). This operation requires a cost of \(k\). You are given a set \(T\), which is a subset of \(S\). Find the minimum possible total cost of operations such that \(S\) would be transformed into \(T\). We can show that such a transformation is always possible.
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10\,000\)) β€” the number of test cases. The description of the test cases follows.The first line contains a single positive integer \(n\) (\(1 \le n \le 10^6\)).The second line of each test case contains a binary string of length \(n\), describing the set \(T\). The \(i\)-th character of the string is '1' if and only if \(i\) is an element of \(T\), and '0' otherwise.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, output one non-negative integer β€” the minimum possible total cost of operations such that \(S\) would be transformed into \(T\).
In the first test case, we shall not perform any operations as \(S\) is already equal to \(T\), which is the set \(\{1, 2, 3, 4, 5, 6\}\).In the second test case, initially, \(S = \{1, 2, 3, 4, 5, 6, 7\}\), and \(T = \{1, 2, 4, 7\}\). We shall perform the following operations: Choose \(k=3\), then delete \(3\) from \(S\). Choose \(k=3\), then delete \(6\) from \(S\). Choose \(k=5\), then delete \(5\) from \(S\). The total cost is \(3+3+5 = 11\). It can be shown that this is the smallest cost possible.In the third test case, initially, \(S = \{1, 2, 3, 4\}\) and \(T = \{\}\) (empty set). We shall perform \(4\) operations of \(k=1\) to delete \(1\), \(2\), \(3\), and \(4\).In the fourth test case, initially, \(S = \{1, 2, 3, 4\}\) and \(T = \{3\}\). We shall perform two operations with \(k=1\) to delete \(1\) and \(2\), then perform one operation with \(k=2\) to delete \(4\).
Input: 6611111171101001400004001081001010115110011100101100 | Output: 0 11 4 4 17 60
Easy
2
603
528
148
17
1,694
A
1694A
A. Creep
800
greedy; implementation
Define the score of some binary string \(T\) as the absolute difference between the number of zeroes and ones in it. (for example, \(T=\) 010001 contains \(4\) zeroes and \(2\) ones, so the score of \(T\) is \(|4-2| = 2\)).Define the creepiness of some binary string \(S\) as the maximum score among all of its prefixes (for example, the creepiness of \(S=\) 01001 is equal to \(2\) because the score of the prefix \(S[1 \ldots 4]\) is \(2\) and the rest of the prefixes have a score of \(2\) or less).Given two integers \(a\) and \(b\), construct a binary string consisting of \(a\) zeroes and \(b\) ones with the minimum possible creepiness.
The first line contains a single integer \(t\) \((1\le t\le 1000)\) β€” the number of test cases. The description of the test cases follows.The only line of each test case contains two integers \(a\) and \(b\) (\( 1 \le a, b \le 100\)) β€” the numbers of zeroes and ones correspondingly.
For each test case, print a binary string consisting of \(a\) zeroes and \(b\) ones with the minimum possible creepiness. If there are multiple answers, print any of them.
In the first test case, the score of \(S[1 \ldots 1]\) is \(1\), and the score of \(S[1 \ldots 2]\) is \(0\).In the second test case, the minimum possible creepiness is \(1\) and one of the other answers is 101.In the third test case, the minimum possible creepiness is \(3\) and one of the other answers is 0001100.
Input: 5 1 1 1 2 5 2 4 5 3 7 | Output: 10 011 0011000 101010101 0001111111
Beginner
2
643
283
171
16
2,039
C1
2039C1
C1. Shohag Loves XOR (Easy Version)
1,200
bitmasks; brute force; math; number theory
This is the easy version of the problem. The differences between the two versions are highlighted in bold. You can only make hacks if both versions of the problem are solved.Shohag has two integers \(x\) and \(m\). Help him count the number of integers \(1 \le y \le m\) such that \(\mathbf{x \neq y}\) and \(x \oplus y\) is a divisor\(^{\text{βˆ—}}\) of either \(x\), \(y\), or both. Here \(\oplus\) is the bitwise XOR operator.\(^{\text{βˆ—}}\)The number \(b\) is a divisor of the number \(a\) if there exists an integer \(c\) such that \(a = b \cdot c\).
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 two space-separated integers \(x\) and \(m\) (\(1 \le x \le 10^6\), \(1 \le m \le 10^{18}\)).It is guaranteed that the sum of \(x\) over all test cases does not exceed \(10^7\).
For each test case, print a single integer β€” the number of suitable \(y\).
In the first test case, for \(x = 6\), there are \(3\) valid values for \(y\) among the integers from \(1\) to \(m = 9\), and they are \(4\), \(5\), and \(7\). \(y = 4\) is valid because \(x \oplus y = 6 \oplus 4 = 2\) and \(2\) is a divisor of both \(x = 6\) and \(y = 4\). \(y = 5\) is valid because \(x \oplus y = 6 \oplus 5 = 3\) and \(3\) is a divisor of \(x = 6\). \(y = 7\) is valid because \(x \oplus y = 6 \oplus 7 = 1\) and \(1\) is a divisor of both \(x = 6\) and \(y = 7\). In the second test case, for \(x = 5\), there are \(2\) valid values for \(y\) among the integers from \(1\) to \(m = 7\), and they are \(4\) and \(6\). \(y = 4\) is valid because \(x \oplus y = 5 \oplus 4 = 1\) and \(1\) is a divisor of both \(x = 5\) and \(y = 4\). \(y = 6\) is valid because \(x \oplus y = 5 \oplus 6 = 3\) and \(3\) is a divisor of \(y = 6\).
Input: 56 95 72 36 44 1 | Output: 3 2 1 1 0
Easy
4
553
325
74
20
1,523
D
1523D
D. Love-Hate
2,400
bitmasks; brute force; dp; probabilities
William is hosting a party for \(n\) of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.For each William's friend \(i\) it is known whether he likes currency \(j\). There are \(m\) currencies in total. It is also known that a trader may not like more than \(p\) currencies.Because friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least \(\lceil \frac{n}{2} \rceil\) friends (rounded up) who like each currency in this subset.
The first line contains three integers \(n, m\) and \(p\) \((1 \le n \le 2 \cdot 10^5, 1 \le p \le m \le 60, 1 \le p \le 15)\), which is the number of trader friends, the number of currencies, the maximum number of currencies each friend can like.Each of the next \(n\) lines contain \(m\) characters. The \(j\)-th character of \(i\)-th line is \(1\) if friend \(i\) likes the currency \(j\) and \(0\) otherwise. It is guaranteed that the number of ones in each line does not exceed \(p\).
Print a string of length \(m\), which defines the subset of currencies of the maximum size, which are liked by at least half of all friends. Currencies belonging to this subset must be signified by the character \(1\).If there are multiple answers, print any.
In the first sample test case only the first currency is liked by at least \(\lceil \frac{3}{2} \rceil = 2\) friends, therefore it's easy to demonstrate that a better answer cannot be found.In the second sample test case the answer includes \(2\) currencies and will be liked by friends \(1\), \(2\), and \(5\). For this test case there are other currencies that are liked by at least half of the friends, but using them we cannot achieve a larger subset size.
Input: 3 4 3 1000 0110 1001 | Output: 1000
Expert
4
685
489
259
15
135
E
135E
E. Weak Subsequence
3,000
combinatorics
Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to k. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string s if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals w.String a with the length of n is considered the weak subsequence of the string s with the length of m, if there exists such a set of indexes 1 ≀ i1 < i2 < ... < in ≀ m, that has the following two properties: ak = sik for all k from 1 to n; there exists at least one such k (1 ≀ k < n), for which ik + 1 – ik > 1. Petya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo 1000000007 (109 + 7). If there are infinitely many such strings, print ""-1"".
The first line contains two integers k (1 ≀ k ≀ 106) and w (2 ≀ w ≀ 109) β€” the alphabet size and the required length of the maximum substring that also is the weak subsequence, correspondingly.
Print a single number β€” the number of strings Petya can buy using the voucher, modulo 1000000007 (109 + 7). If there are infinitely many such strings, print ""-1"" (without the quotes).
In the first sample Petya can buy the following strings: aaa, aab, abab, abb, abba, baa, baab, baba, bba, bbb.
Input: 2 2 | Output: 10
Master
1
1,076
193
185
1
1,523
H
1523H
H. Hopping Around the Array
3,500
data structures; dp
William really wants to get a pet. Since his childhood he dreamt about getting a pet grasshopper. William is being very responsible about choosing his pet, so he wants to set up a trial for the grasshopper!The trial takes place on an array \(a\) of length \(n\), which defines lengths of hops for each of \(n\) cells. A grasshopper can hop around the sells according to the following rule: from a cell with index \(i\) it can jump to any cell with indices from \(i\) to \(i+a_i\) inclusive.Let's call the \(k\)-grasshopper value of some array the smallest number of hops it would take a grasshopper to hop from the first cell to the last, but before starting you can select no more than \(k\) cells and remove them from the array. When a cell is removed all other cells are renumbered but the values of \(a_i\) for each cell remains the same. During this the first and the last cells may not be removed.It is required to process \(q\) queries of the following format: you are given three numbers \(l\), \(r\), \(k\). You are required to find the \(k\)-grasshopper value for an array, which is a subarray of the array \(a\) with elements from \(l\) to \(r\) inclusive.
The first line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 20000\)), the length of the array and the number of queries respectively.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) – the elements of the array.The following \(q\) lines contain queries: each line contains three integers \(l\), \(r\) and \(k\) (\(1 \le l \le r \le n\), \(0 \le k \le min(30, r-l)\)), which are the edges of the subarray and the number of the grasshopper value respectively.
For each query print a single number in a new line β€” the response to a query.
For the second query the process occurs like this: For the third query the process occurs like this:
Input: 9 5 1 1 2 1 3 1 2 1 1 1 1 0 2 5 1 5 9 1 2 8 2 1 9 4 | Output: 0 2 1 2 2
Master
2
1,167
506
77
15
233
B
233B
B. Non-square Equation
1,400
binary search; brute force; math
Let's consider equation:x2 + s(x)Β·x - n = 0, where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.
A single line contains integer n (1 ≀ n ≀ 1018) β€” the equation parameter.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Print -1, if the equation doesn't have integer positive roots. Otherwise print such smallest integer x (x > 0), that the equation given in the statement holds.
In the first test case x = 1 is the minimum root. As s(1) = 1 and 12 + 1Β·1 - 2 = 0.In the second test case x = 10 is the minimum root. As s(10) = 1 + 0 = 1 and 102 + 1Β·10 - 110 = 0.In the third test case the equation has no roots.
Input: 2 | Output: 1
Easy
3
299
216
159
2
894
B
894B
B. Ralph And His Magic Field
1,800
combinatorics; constructive algorithms; math; number theory
Ralph has a magic field which is divided into n Γ— m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 109 + 7.Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.
The only line contains three integers n, m and k (1 ≀ n, m ≀ 1018, k is either 1 or -1).
Print a single number denoting the answer modulo 1000000007.
In the first example the only way is to put -1 into the only block.In the second example the only way is to put 1 into every block.
Input: 1 1 -1 | Output: 1
Medium
4
787
88
60
8
888
F
888F
F. Connecting Vertices
2,500
dp; graphs
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 109 + 7.
The first line contains one number n (3 ≀ n ≀ 500) β€” the number of marked points.Then n lines follow, each containing n elements. ai, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise ai, j = 0). It is guaranteed that for any pair of points ai, j = aj, i, and for any point ai, i = 0.
Print the number of ways to connect points modulo 109 + 7.
Input: 30 0 10 0 11 1 0 | Output: 1
Expert
2
1,038
330
58
8
1,218
C
1218C
C. Jumping Transformers
2,600
dp
You, the mighty Blackout, are standing in the upper-left \((0,0)\) corner of \(N\)x\(M\) matrix. You must move either right or down each second. There are \(K\) transformers jumping around the matrix in the following way. Each transformer starts jumping from position \((x,y)\), at time \(t\), and jumps to the next position each second. The \(x\)-axes grows downwards, and \(y\)-axes grows to the right. The order of jumping positions is defined as \({(x,y),(x+d,y-d),(x+d,y),(x,y+d)}\), and is periodic. Before time \(t\) transformer is not in the matrix.You want to arrive to the bottom-right corner \((N-1,M-1)\), while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer.After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted.
In the first line, integers \(N\),\(M\) (\(1 \leq N, M \leq 500\)), representing size of the matrix, and \(K\) (\(0 \leq K \leq 5*10^5\)) , the number of jumping transformers.In next \(K\) lines, for each transformer, numbers \(x\), \(y\), \(d\) (\(d \geq 1\)), \(t\) (\(0 \leq t \leq N+M-2\)), and \(e\) (\(0 \leq e \leq 10^9\)), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it.It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates
Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner.
If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value.
Input: 3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 | Output: 9
Expert
1
1,022
600
114
12
1,991
E
1991E
E. Coloring Game
1,900
constructive algorithms; dfs and similar; games; graphs; greedy; interactive
This is an interactive problem.Consider an undirected connected graph consisting of \(n\) vertices and \(m\) edges. Each vertex can be colored with one of three colors: \(1\), \(2\), or \(3\). Initially, all vertices are uncolored.Alice and Bob are playing a game consisting of \(n\) rounds. In each round, the following two-step process happens: Alice chooses two different colors. Bob chooses an uncolored vertex and colors it with one of the two colors chosen by Alice. Alice wins if there exists an edge connecting two vertices of the same color. Otherwise, Bob wins.You are given the graph. Your task is to decide which player you wish to play as and win the game.
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases. The description of test cases follows.The first line of each test case contains two integers \(n\), \(m\) (\(1 \le n \le 10^4\), \(n - 1 \le m \le \min(\frac{n \cdot (n - 1)}{2}, 10^4)\)) β€” the number of vertices and the number of edges in the graph, respectively.Each of the next \(m\) lines of each test case contains two integers \(u_i\), \(v_i\) (\(1 \le u_i, v_i \le n\)) β€” the edges of the graph. It is guaranteed that the graph is connected and there are no multiple edges or self-loops.It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases does not exceed \(10^4\).
Note that the sample test cases are example games and do not necessarily represent the optimal strategy for both players.In the first test case, you choose to play as Alice. Alice chooses two colors: \(3\) and \(1\). Bob chooses vertex \(3\) and colors it with color \(1\). Alice chooses two colors: \(1\) and \(2\). Bob chooses vertex \(2\) and colors it with color \(2\). Alice chooses two colors: \(2\) and \(1\). Bob chooses vertex \(1\) and colors it with color \(1\). Alice wins because the edge \((3, 1)\) connects two vertices of the same color.In the second test case, you choose to play as Bob. Alice chooses two colors: \(2\) and \(3\). Bob chooses vertex \(1\) and colors it with color \(2\). Alice chooses two colors: \(1\) and \(2\). Bob chooses vertex \(2\) and colors it with color \(1\). Alice chooses two colors: \(2\) and \(1\). Bob chooses vertex \(4\) and colors it with color \(1\). Alice chooses two colors: \(3\) and \(1\). Bob chooses vertex \(3\) and colors it with color \(3\). Bob wins because there are no edges with vertices of the same color.
Input: 2 3 3 1 2 2 3 3 1 3 1 2 2 1 1 4 4 1 2 2 3 3 4 4 1 2 3 1 2 2 1 3 1 | Output: Alice 3 1 1 2 2 1 Bob 1 2 2 1 4 1 3 3
Hard
6
669
737
0
19
1,772
A
1772A
A. A+B?
800
implementation
You are given an expression of the form \(a{+}b\), where \(a\) and \(b\) are integers from \(0\) to \(9\). You have to evaluate it and print the result.
The first line contains one integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases.Each test case consists of one line containing an expression of the form \(a{+}b\) (\(0 \le a, b \le 9\), both \(a\) and \(b\) are integers). The integers are not separated from the \(+\) sign.
For each test case, print one integer β€” the result of the expression.
Input: 44+20+03+78+9 | Output: 6 0 10 17
Beginner
1
152
284
69
17
186
B
186B
B. Growing Mushrooms
1,200
greedy; sortings
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
The first input line contains four integer numbers n, t1, t2, k (1 ≀ n, t1, t2 ≀ 1000; 1 ≀ k ≀ 100) β€” the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.Each of the following n lines contains two integers. The i-th (1 ≀ i ≀ n) line contains space-separated integers ai, bi (1 ≀ ai, bi ≀ 1000) β€” the speeds which the participant number i chose.
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Input: 2 3 3 502 44 2 | Output: 1 15.002 15.00
Easy
2
2,183
461
265
1
715
E
715E
E. Complete the Permutations
3,400
combinatorics; fft; graphs; math
ZS the Coder is given two permutations p and q of {1, 2, ..., n}, but some of their elements are replaced with 0. The distance between two permutations p and q is defined as the minimum number of moves required to turn p into q. A move consists of swapping exactly 2 elements of p.ZS the Coder wants to determine the number of ways to replace the zeros with positive integers from the set {1, 2, ..., n} such that p and q are permutations of {1, 2, ..., n} and the distance between p and q is exactly k.ZS the Coder wants to find the answer for all 0 ≀ k ≀ n - 1. Can you help him?
The first line of the input contains a single integer n (1 ≀ n ≀ 250) β€” the number of elements in the permutations.The second line contains n integers, p1, p2, ..., pn (0 ≀ pi ≀ n) β€” the permutation p. It is guaranteed that there is at least one way to replace zeros such that p is a permutation of {1, 2, ..., n}.The third line contains n integers, q1, q2, ..., qn (0 ≀ qi ≀ n) β€” the permutation q. It is guaranteed that there is at least one way to replace zeros such that q is a permutation of {1, 2, ..., n}.
Print n integers, i-th of them should denote the answer for k = i - 1. Since the answer may be quite large, and ZS the Coder loves weird primes, print them modulo 998244353 = 223Β·7Β·17 + 1, which is a prime.
In the first sample case, there is the only way to replace zeros so that it takes 0 swaps to convert p into q, namely p = (1, 2, 3), q = (1, 2, 3).There are two ways to replace zeros so that it takes 1 swap to turn p into q. One of these ways is p = (1, 2, 3), q = (3, 2, 1), then swapping 1 and 3 from p transform it into q. The other way is p = (1, 3, 2), q = (1, 2, 3). Swapping 2 and 3 works in this case.Finally, there is one way to replace zeros so that it takes 2 swaps to turn p into q, namely p = (1, 3, 2), q = (3, 2, 1). Then, we can transform p into q like following: .
Input: 31 0 00 2 0 | Output: 1 2 1
Master
4
581
512
206
7
1,485
C
1485C
C. Floor and Mod
1,700
binary search; brute force; math; number theory
A pair of positive integers \((a,b)\) is called special if \(\lfloor \frac{a}{b} \rfloor = a \bmod b\). Here, \(\lfloor \frac{a}{b} \rfloor\) is the result of the integer division between \(a\) and \(b\), while \(a \bmod b\) is its remainder.You are given two integers \(x\) and \(y\). Find the number of special pairs \((a,b)\) such that \(1\leq a \leq x\) and \(1 \leq b \leq y\).
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases.The only line of the description of each test case contains two integers \(x\), \(y\) (\(1 \le x,y \le 10^9\)).
For each test case print the answer on a single line.
In the first test case, the only special pair is \((3, 2)\).In the second test case, there are no special pairs.In the third test case, there are two special pairs: \((3, 2)\) and \((4, 3)\).
Input: 9 3 4 2 100 4 3 50 3 12 4 69 420 12345 6789 123456 789 12345678 9 | Output: 1 0 2 3 5 141 53384 160909 36
Medium
4
382
207
53
14
107
A
107A
A. Dorm Water Supply
1,400
dfs and similar; graphs
The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
The first line contains two space-separated integers n and p (1 ≀ n ≀ 1000, 0 ≀ p ≀ n) β€” the number of houses and the number of pipes correspondingly. Then p lines follow β€” the description of p pipes. The i-th line contains three integers ai bi di, indicating a pipe of diameter di going from house ai to house bi (1 ≀ ai, bi ≀ n, ai β‰  bi, 1 ≀ di ≀ 106).It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it.
Print integer t in the first line β€” the number of tank-tap pairs of houses.For the next t lines, print 3 integers per line, separated by spaces: tanki, tapi, and diameteri, where tanki β‰  tapi (1 ≀ i ≀ t). Here tanki and tapi are indexes of tank and tap houses respectively, and diameteri is the maximum amount of water that can be conveyed. All the t lines should be ordered (increasingly) by tanki.
Input: 3 21 2 102 3 20 | Output: 11 3 10
Easy
2
1,325
468
399
1
204
D
204D
D. Little Elephant and Retro Strings
2,400
dp
The Little Elephant has found a ragged old black-and-white string s on the attic.The characters of string s are numbered from the left to the right from 1 to |s|, where |s| is the length of the string. Let's denote the i-th character of string s as si. As the string is black-and-white, each character of the string is either letter ""B"", or letter ""W"". Unfortunately, the string is very old and some characters are damaged. The damaged positions are denoted as ""X"".The Little Elephant in determined to restore the string and hang it on the wall. For that he needs to replace each character ""X"" by a ""B"" or a ""W"". The string must look good on the wall, so it must be beautiful. The Little Elephant considers a string beautiful if it has two non-intersecting substrings of a given length k, such that the left one fully consists of characters ""B"", and the right one fully consists of characters ""W"". More formally, there are four integers a, b, c, d (1 ≀ a ≀ b < c ≀ d ≀ |s|; b - a + 1 = d - c + 1 = k) such that si = ""B"" (a ≀ i ≀ b) and sj = ""W"" (c ≀ j ≀ d). Help the Little Elephant find the number of different beautiful strings he can obtain from string s. Two strings are considered different if there is such position, where the character in the first string differs from the corresponding character in the second string. If this string doesn't contain characters Β«XΒ» and it is already beautiful β€” the answer is 1.As the answer can be rather large, print it modulo 1000000007 (109 + 7).
The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 106). The second line contains string s. String s has length n and only consists of characters ""W"", ""B"" and ""X"".
On a single line print an integer β€” the answer to the problem modulo 1000000007 (109 + 7).
Input: 3 2XXX | Output: 0
Expert
1
1,510
192
90
2
1,720
D2
1720D2
D2. Xor-Subsequence (hard version)
2,400
bitmasks; data structures; dp; strings; trees
It is the hard version of the problem. The only difference is that in this version \(a_i \le 10^9\).You are given an array of \(n\) integers \(a_0, a_1, a_2, \ldots a_{n - 1}\). Bryap wants to find the longest beautiful subsequence in the array.An array \(b = [b_0, b_1, \ldots, b_{m-1}]\), where \(0 \le b_0 < b_1 < \ldots < b_{m - 1} < n\), is a subsequence of length \(m\) of the array \(a\).Subsequence \(b = [b_0, b_1, \ldots, b_{m-1}]\) of length \(m\) is called beautiful, if the following condition holds: For any \(p\) (\(0 \le p < m - 1\)) holds: \(a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p\). Here \(a \oplus b\) denotes the bitwise XOR of \(a\) and \(b\). For example, \(2 \oplus 4 = 6\) and \(3 \oplus 1=2\).Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^5\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(2 \leq n \leq 3 \cdot 10^5\)) β€” the length of the array.The second line of each test case contains \(n\) integers \(a_0,a_1,...,a_{n-1}\) (\(0 \leq a_i \leq 10^9\)) β€” the elements of the array.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3 \cdot 10^5\).
For each test case print a single integer β€” the length of the longest beautiful subsequence.
In the first test case, we can pick the whole array as a beautiful subsequence because \(1 \oplus 1 < 2 \oplus 0\).In the second test case, we can pick elements with indexes \(1\), \(2\) and \(4\) (in \(0\) indexation). For this elements holds: \(2 \oplus 2 < 4 \oplus 1\) and \(4 \oplus 4 < 1 \oplus 2\).
Input: 321 255 2 4 3 1103 8 8 2 9 1 6 2 8 3 | Output: 2 3 6
Expert
5
868
495
92
17
1,684
B
1684B
B. Z mod X = C
800
constructive algorithms; math
You are given three positive integers \(a\), \(b\), \(c\) (\(a < b < c\)). You have to find three positive integers \(x\), \(y\), \(z\) such that:$$$\(x \bmod y = a,\)\( \)\(y \bmod z = b,\)\( \)\(z \bmod x = c.\)\(Here \)p \bmod q\( denotes the remainder from dividing \)p\( by \)q$$$. It is possible to show that for such constraints the answer always exists.
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10\,000\)) β€” the number of test cases. Description of the test cases follows.Each test case contains a single line with three integers \(a\), \(b\), \(c\) (\(1 \le a < b < c \le 10^8\)).
For each test case output three positive integers \(x\), \(y\), \(z\) (\(1 \le x, y, z \le 10^{18}\)) such that \(x \bmod y = a\), \(y \bmod z = b\), \(z \bmod x = c\).You can output any correct answer.
In the first test case:$$$\(x \bmod y = 12 \bmod 11 = 1;\)\[\(y \bmod z = 11 \bmod 4 = 3;\)\]\(z \bmod x = 4 \bmod 12 = 4.\)$$$
Input: 4 1 3 4 127 234 421 2 7 8 59 94 388 | Output: 12 11 4 1063 234 1484 25 23 8 2221 94 2609
Beginner
2
361
291
202
16
1,425
F
1425F
F. Flamingoes of Mystery
1,400
interactive
This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java β€” System.out.flush(), in Pascal β€” flush(output) and in Python β€” sys.stdout.flush().Mr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize.There are \(N\) mysterious cages, which are numbered from \(1\) to \(N\). Cage \(i\) has \(A_i\) \((0 \le A_i \le 10^3)\) flamingoes inside \((1 \le i \le N)\). However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage.Coincidentally, Mr. Chanek has \(N\) coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered \(L\) to \(R\) inclusive? With \(L < R\).
Use standard input to read the responses of your questions.Initially, the judge will give an integer \(N\) \((3 \le N \le 10^3)\), the number of cages, and the number of coins Mr. Chanek has.For each of your questions, the jury will give an integer that denotes the number of flamingoes from cage \(L\) to \(R\) inclusive.If your program does not guess the flamingoes or ask other questions, you will get ""Wrong Answer"". Of course, if your program asks more questions than the allowed number, your program will get ""Wrong Answer"".
To ask questions, your program must use standard output.Then, you can ask at most \(N\) questions. Questions are asked in the format ""? L R"", (\(1 \le L < R \le N\)). To guess the flamingoes, print a line that starts with ""!"" followed by \(N\) integers where the \(i\)-th integer denotes the number of flamingo in cage \(i\). After answering, your program must terminate or will receive the ""idle limit exceeded"" verdict. You can only guess the flamingoes once.
In the sample input, the correct flamingoes amount is \([1, 4, 4, 6, 7, 8]\).
Input: 6 5 15 10 | Output: ? 1 2 ? 5 6 ? 3 4 ! 1 4 4 6 7 8
Easy
1
972
534
467
14
1,547
B
1547B
B. Alphabetical Strings
800
greedy; implementation; strings
A string \(s\) of length \(n\) (\(1 \le n \le 26\)) is called alphabetical if it can be obtained using the following algorithm: first, write an empty string to \(s\) (i.e. perform the assignment \(s\) := """"); then perform the next step \(n\) times; at the \(i\)-th step take \(i\)-th lowercase letter of the Latin alphabet and write it either to the left of the string \(s\) or to the right of the string \(s\) (i.e. perform the assignment \(s\) := \(c+s\) or \(s\) := \(s+c\), where \(c\) is the \(i\)-th letter of the Latin alphabet). In other words, iterate over the \(n\) first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string \(s\) or append a letter to the right of the string \(s\). Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: ""a"", ""ba"", ""ab"", ""bac"" and ""ihfcbadeg"". The following strings are not alphabetical: ""z"", ""aa"", ""ca"", ""acb"", ""xyz"" and ""ddcba"".From the given string, determine if it is alphabetical.
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 is written on a separate line that contains one string \(s\). String \(s\) consists of lowercase letters of the Latin alphabet and has a length between \(1\) and \(26\), inclusive.
Output \(t\) lines, each of them must contain the answer to the corresponding test case. Output YES if the given string \(s\) is alphabetical and NO otherwise.You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).
The example contains test cases from the main part of the condition.
Input: 11 a ba ab bac ihfcbadeg z aa ca acb xyz ddcba | Output: YES YES YES YES YES NO NO NO NO NO NO
Beginner
3
1,070
317
282
15
2,080
A
2080A
3,200
*special; constructive algorithms; graphs
Master
3
0
0
0
20
769
B
769B
B. News About Credit
1,200
*special; greedy; two pointers
Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net ""TheContacnt!"".Not all students are equally sociable. About each student you know the value ai β€” the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that: the student i sends no more than ai messages (for all i from 1 to n); all students knew the news about the credit (initially only Polycarp knew it); the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.
The first line contains the positive integer n (2 ≀ n ≀ 100) β€” the number of students. The second line contains the sequence a1, a2, ..., an (0 ≀ ai ≀ 100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.
Print -1 to the first line if it is impossible to inform all students about credit. Otherwise, in the first line print the integer k β€” the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit. If there are several answers, it is acceptable to print any of them.
In the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.
Input: 41 2 1 0 | Output: 31 22 42 3
Easy
3
1,171
296
619
7