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
122
A
122A
A. Lucky Division
1,000
brute force; number theory
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky.
The single line contains an integer n (1 ≤ n ≤ 1000) — the number that needs to be checked.
In the only line print ""YES"" (without the quotes), if number n is almost lucky. Otherwise, print ""NO"" (without the quotes).
Note that all lucky numbers are almost lucky as any number is evenly divisible by itself.In the first sample 47 is a lucky number. In the second sample 16 is divisible by 4.
Input: 47 | Output: YES
Beginner
2
360
91
127
1
45
G
45G
G. Prime Problem
2,200
number theory
In Berland prime numbers are fashionable — the respectable citizens dwell only on the floors with numbers that are prime numbers. The numismatists value particularly high the coins with prime nominal values. All the prime days are announced holidays!Yet even this is not enough to make the Berland people happy. On the main street of the capital stand n houses, numbered from 1 to n. The government decided to paint every house a color so that the sum of the numbers of the houses painted every color is a prime number.However it turned out that not all the citizens approve of this decision — many of them protest because they don't want many colored houses on the capital's main street. That's why it is decided to use the minimal possible number of colors. The houses don't have to be painted consecutively, but every one of n houses should be painted some color. The one-colored houses should not stand consecutively, any way of painting is acceptable.There are no more than 5 hours left before the start of painting, help the government find the way when the sum of house numbers for every color is a prime number and the number of used colors is minimal.
The single input line contains an integer n (2 ≤ n ≤ 6000) — the number of houses on the main streets of the capital.
Print the sequence of n numbers, where the i-th number stands for the number of color for house number i. Number the colors consecutively starting from 1. Any painting order is allowed. If there are several solutions to that problem, print any of them. If there's no such way of painting print the single number -1.
Input: 8 | Output: 1 2 2 1 1 1 1 2
Hard
1
1,160
117
315
0
808
G
808G
G. Anthem of Berland
2,300
dp; strings
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.The anthem is the string s of no more than 105 small Latin letters and question marks. The most glorious victory is the string t of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.Note that the occurrences of string t in s can overlap. Check the third example for clarification.
The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 105).The second line contains string of small Latin letters t (1 ≤ |t| ≤ 105).Product of lengths of strings |s|·|t| won't exceed 107.
Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.
In the first example the resulting string s is ""winlosewinwinlwinwin""In the second example the resulting string s is ""glorytoreorand"". The last letter of the string can be arbitrary.In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is ""abcabcab"".
Input: winlose???winl???w??win | Output: 5
Expert
2
865
219
142
8
1,769
B1
1769B1
B1. Копирование файлов I
1,000
*special; brute force; implementation; math
В этой версии задачи размеры копируемых файлов не превышают \(1000\) байт.Вы копируете с одного сервера на другой \(n\) файлов размером \(a_1, a_2, \ldots, a_n\) байт. Файлы копируются последовательно в заданном порядке.При копировании вы видите два прогресс-бара: первый показывает процент скопированных данных в текущем файле, а второй — общий процент скопированных данных по всем \(n\) файлам. Оба процента отображаются округлёнными вниз до целого числа. Значения на прогресс-барах обновляются после копирования каждого байта.Формально, после копирования байта номер \(x\) из файла номер \(i\) первый прогресс-бар показывает \(\lfloor \frac{100 \cdot x}{a_i} \rfloor\) процентов, а второй — \(\lfloor \frac{100 \cdot (a_1 + a_2 + \ldots + a_{i - 1} + x)}{a_1 + a_2 + \ldots + a_n} \rfloor\) процентов. В самом начале копирования оба прогресс-бара показывают \(0\) процентов.Найдите все такие целые числа от \(0\) до \(100\) включительно, что существует момент времени, в который оба прогресс-бара одновременно показывают это число. Выведите эти числа в порядке возрастания.
В первой строке задано одно целое число \(n\) (\(1 \le n \le 100\)) — число копируемых файлов.Во второй строке заданы \(n\) целых чисел \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 1000\)) — размеры файлов в байтах в том порядке, в котором они будут копироваться.
Выведите в возрастающем порядке все числа от \(0\) до \(100\) включительно такие, что существует момент времени, в который на обоих прогресс-барах одновременно показывается это число.
В первом тесте копируется всего один файл, поэтому оба прогресс-бара всегда показывают одинаковые значения.Во втором тесте первый прогресс-бар сразу же уйдёт вперёд, потом сбросится в ноль и начнёт догонять второй прогресс-бар заново. В конце копирования прогресс-бары некоторое время будут показывать одно и то же число.
Input: 1 6 | Output: 0 16 33 50 66 83 100
Beginner
4
1,076
261
183
17
1,924
E
1924E
E. Paper Cutting Again
3,100
combinatorics; probabilities
There is a rectangular sheet of paper with initial height \(n\) and width \(m\). Let the current height and width be \(h\) and \(w\) respectively. We introduce a \(xy\)-coordinate system so that the four corners of the sheet are \((0, 0), (w, 0), (0, h)\), and \((w, h)\). The sheet can then be cut along the lines \(x = 1,2,\ldots,w-1\) and the lines \(y = 1,2,\ldots,h-1\). In each step, the paper is cut randomly along any one of these \(h+w-2\) lines. After each vertical and horizontal cut, the right and bottom piece of paper respectively are discarded.Find the expected number of steps required to make the area of the sheet of paper strictly less than \(k\). It can be shown that this answer can always be expressed as a fraction \(\dfrac{p}{q}\) where \(p\) and \(q\) are coprime integers. Calculate \(p\cdot q^{-1} \bmod (10^9+7)\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 57000\)). Description of the test cases follows.The first line of each test case contains 3 integers \(n\), \(m\), and \(k\) (\(1 \le n, m \le 10^6\), \(2 \le k \le 10^{12}\)).It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases do not exceed \(10^6\).
For each test case, print one integer — the answer to the problem.
For the first test case, the area is already less than \(10\) so no cuts are required.For the second test case, the area is exactly \(8\) so any one of the \(4\) possible cuts would make the area strictly less than \(8\).For the third test case, the final answer is \(\frac{17}{6} = 833\,333\,342\bmod (10^9+7)\).For the fourth test case, the final answer is \(\frac{5}{4} = 250\,000\,003\bmod (10^9+7)\).
Input: 42 4 102 4 82 4 22 4 6 | Output: 0 1 833333342 250000003
Master
2
842
389
66
19
1,005
D
1005D
D. Polycarp and Div 3
1,500
dp; greedy; number theory
Polycarp likes numbers that are divisible by 3.He has a huge number \(s\). Polycarp wants to cut from it the maximum number of numbers that are divisible by \(3\). To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after \(m\) such cuts, there will be \(m+1\) parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by \(3\).For example, if the original number is \(s=3121\), then Polycarp can cut it into three parts with two cuts: \(3|1|21\). As a result, he will get two numbers that are divisible by \(3\).Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by \(3\) that Polycarp can obtain?
The first line of the input contains a positive integer \(s\). The number of digits of the number \(s\) is between \(1\) and \(2\cdot10^5\), inclusive. The first (leftmost) digit is not equal to 0.
Print the maximum number of numbers divisible by \(3\) that Polycarp can get by making vertical cuts in the given number \(s\).
In the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by \(3\).In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and \(33\) digits 0. Each of the \(33\) digits 0 forms a number that is divisible by \(3\).In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers \(0\), \(9\), \(201\) and \(81\) are divisible by \(3\).
Input: 3121 | Output: 2
Medium
3
1,054
197
127
10
1,607
B
1607B
B. Odd Grasshopper
900
math
The grasshopper is located on the numeric axis at the point with coordinate \(x_0\).Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate \(x\) with a distance \(d\) to the left moves the grasshopper to a point with a coordinate \(x - d\), while jumping to the right moves him to a point with a coordinate \(x + d\).The grasshopper is very fond of positive integers, so for each integer \(i\) starting with \(1\) the following holds: exactly \(i\) minutes after the start he makes a jump with a distance of exactly \(i\). So, in the first minutes he jumps by \(1\), then by \(2\), and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after \(18\) consecutive jumps he arrives at the point with a coordinate \(7\), he will jump by a distance of \(19\) to the right, since \(7\) is an odd number, and will end up at a point \(7 + 19 = 26\). Since \(26\) is an even number, the next jump the grasshopper will make to the left by a distance of \(20\), and it will move him to the point \(26 - 20 = 6\).Find exactly which point the grasshopper will be at after exactly \(n\) jumps.
The first line of input contains an integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases.Each of the following \(t\) lines contains two integers \(x_0\) (\(-10^{14} \leq x_0 \leq 10^{14}\)) and \(n\) (\(0 \leq n \leq 10^{14}\)) — the coordinate of the grasshopper's initial position and the number of jumps.
Print exactly \(t\) lines. On the \(i\)-th line print one integer — the answer to the \(i\)-th test case — the coordinate of the point the grasshopper will be at after making \(n\) jumps from the point \(x_0\).
The first two test cases in the example correspond to the first two jumps from the point \(x_0 = 0\). Since \(0\) is an even number, the first jump of length \(1\) is made to the left, and the grasshopper ends up at the point \(0 - 1 = -1\).Then, since \(-1\) is an odd number, a jump of length \(2\) is made to the right, bringing the grasshopper to the point with coordinate \(-1 + 2 = 1\).
Input: 9 0 1 0 2 10 10 10 99 177 13 10000000000 987654321 -433494437 87178291199 1 0 -1 1 | Output: -1 1 11 110 190 9012345679 -87611785637 1 0
Beginner
1
1,314
320
210
16
1,950
D
1950D
D. Product of Binary Decimals
1,100
brute force; dp; implementation; number theory
Let's call a number a binary decimal if it is a positive integer and all digits in its decimal notation are either \(0\) or \(1\). For example, \(1\,010\,111\) is a binary decimal, while \(10\,201\) and \(787\,788\) are not.Given a number \(n\), you are asked whether or not it is possible to represent \(n\) as a product of some (not necessarily distinct) binary decimals.
The first line contains a single integer \(t\) (\(1 \leq t \leq 5 \cdot 10^4\)) — the number of test cases.The only line of each test case contains a single integer \(n\) (\(1 \leq n \leq 10^5\)).
For each test case, output ""YES"" (without quotes) if \(n\) can be represented as a product of binary decimals, 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).
The first five test cases can be represented as a product of binary decimals as follows: \(121 = 11 \times 11\). \(1 = 1\) is already a binary decimal. \(14\,641 = 11 \times 11 \times 11 \times 11\). \(12\,221 = 11 \times 11 \times 101\). \(10\,110 = 10\,110\) is already a binary decimal.
Input: 111211146411222110110100000991122024124211001 | Output: YES YES YES YES YES YES NO NO NO NO YES
Easy
4
373
196
292
19
530
A
530A
A. Quadratic equation
1,500
*special
You are given a quadratic equation with integer coefficients A * X2 + B * X + C = 0. It is guaranteed that A ≠ 0 and that the equation has at least one real root. Output the roots of the equation.
The only line of input contains integers A, B and C ( - 1000 ≤ A, B, C ≤ 1000, A ≠ 0), separated by spaces.
Output the roots of the equation in increasing order. If the equation has a single root of multiplicity 2, output it once. The root is considered to be correct if its absolute or relative error does not exceed 10 - 4.
Input: 1 -2 1 | Output: 1
Medium
1
196
107
217
5
858
E
858E
E. Tests Renumeration
2,200
greedy; implementation
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, ""1"", ""2"", ..., ""n', where n is the total number of tests.Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.The only operation Vladimir can perform is the ""move"" command. Vladimir wants to write a script file, each of the lines in which is ""move file_1 file_2"", that means that the file ""file_1"" is to be renamed to ""file_2"". If there is a file ""file_2"" at the moment of this line being run, then this file is to be rewritten. After the line ""move file_1 file_2"" the file ""file_1"" doesn't exist, but there is a file ""file_2"" with content equal to the content of ""file_1"" before the ""move"" command.Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: all examples are the first several tests having filenames ""1"", ""2"", ..., ""e"", where e is the total number of examples; all other files contain regular tests with filenames ""e + 1"", ""e + 2"", ..., ""n"", where n is the total number of all tests.
The first line contains single integer n (1 ≤ n ≤ 105) — the number of files with tests.n lines follow, each describing a file with test. Each line has a form of ""name_i type_i"", where ""name_i"" is the filename, and ""type_i"" equals ""1"", if the i-th file contains an example test, and ""0"" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct.
In the first line print the minimum number of lines in Vladimir's script file.After that print the script file, each line should be ""move file_1 file_2"", where ""file_1"" is an existing at the moment of this line being run filename, and ""file_2"" — is a string of digits and small English letters with length from 1 to 6.
Input: 501 02 12extra 03 199 0 | Output: 4move 3 1move 01 5move 2extra 4move 99 3
Hard
2
1,687
479
324
8
1,287
A
1287A
A. Angry Students
800
greedy; implementation
It's a walking tour day in SIS.Winter, so \(t\) groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters ""A"" and ""P"": ""A"" corresponds to an angry student ""P"" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index \(i\) in the string describing a group then they will throw a snowball at the student that corresponds to the character with index \(i+1\) (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.
The first line contains a single integer \(t\) — the number of groups of students (\(1 \le t \le 100\)). The following \(2t\) lines contain descriptions of groups of students.The description of the group starts with an integer \(k_i\) (\(1 \le k_i \le 100\)) — the number of students in the group, followed by a string \(s_i\), consisting of \(k_i\) letters ""A"" and ""P"", which describes the \(i\)-th group of students.
For every group output single integer — the last moment a student becomes angry.
In the first test, after \(1\) minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after \(1\) minute — AAPAAPPAAPPP after \(2\) minutes — AAAAAAPAAAPP after \(3\) minutes — AAAAAAAAAAAP after \(4\) minutes all \(12\) students are angry In the second group after \(1\) minute, all students are angry.
Input: 1 4 PPAP | Output: 1
Beginner
2
1,342
422
80
12
1,857
F
1857F
F. Sum and Product
1,600
binary search; data structures; math
You have an array \(a\) of length \(n\).Your task is to answer \(q\) queries: given \(x,y\), find the number of pairs \(i\) and \(j\) (\(1 \le i < j \le n\)) that both \(a_i + a_j = x\) and \(a_i \cdot a_j = y\).That is, for the array \([1,3,2]\) and asking for \(x=3,y=2\) the answer is \(1\): \(i=1\) and \(j=2\) fail because \(1 + 3 = 4\) and not \(3,\) also \(1 \cdot 3=3\) and not \(2\); \(i=1\) and \(j=3\) satisfies both conditions; \(i=2\) and \(j=3\) fail because \(3 + 2 = 5\) and not \(3,\) also \(3 \cdot 2=6\) and not \(2\);
The first line contains one integer \(t\) (\(1\le t\le 10^4\)) — the number of test cases.The second line of each test case contains one integer \(n\) (\(1 \le n \le 2\cdot 10^5\)) — the length of the array \(a\).The third line of each test case contains \(n\) integers \(a_1,a_2,\dots,a_n\) (\(1 \le |a_i| \le 10^9\)) — array \(a\).The fourth line of each test case contains the integer \(q\) (\(1 \le q \le 2\cdot 10^5\)) — the number of requests.The next \(q\) lines contain two numbers each \(x\) and \(y\) (\(1 \le |x|\le 2\cdot 10^9,1\le |y|\le 10^{18}\)) — request.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\). This is also guaranteed for the sum of \(q\) values.
For each test case print a line with \(q\) numbers — the answers to the queries.
For the first test case, let's analyze each pair of numbers separately: pair \((a_1,a_2)\): \(a_1 + a_2 = 4\), \(a_1 \cdot a_2 = 3\) pair \((a_1,a_3)\): \(a_1 + a_3 = 3\), \(a_1 \cdot a_3 = 2\) pair \((a_2,a_3)\): \(a_2 + a_3 = 5\), \(a_2 \cdot a_3 = 6\) From this, we can see that for the first query, the pair \((a_1,a_3)\) is suitable, for the second query, it is \((a_2,a_3)\), and there are no suitable pairs for the third and fourth queries.In the second test case, all combinations of pairs are suitable.
Input: 331 3 243 25 63 15 541 1 1 112 161 4 -2 3 3 332 -8-1 -27 12 | Output: 1 1 0 0 6 1 1 3
Medium
3
537
716
80
18
764
B
764B
B. Timofey and cubes
900
constructive algorithms; implementation
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.It can be shown that the answer is unique.
Consider the first sample. At the begining row was [2, 3, 9, 6, 7, 1, 4]. After first operation row was [4, 1, 7, 6, 9, 3, 2]. After second operation row was [4, 3, 9, 6, 7, 1, 2]. After third operation row was [4, 3, 7, 6, 9, 1, 2]. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].
Input: 74 3 7 6 9 1 2 | Output: 2 3 9 6 7 1 4
Beginner
2
797
235
138
7
1,726
E
1726E
E. Almost Perfect
2,400
combinatorics; fft; math
A permutation \(p\) of length \(n\) is called almost perfect if for all integer \(1 \leq i \leq n\), it holds that \(\lvert p_i - p^{-1}_i \rvert \le 1\), where \(p^{-1}\) is the inverse permutation of \(p\) (i.e. \(p^{-1}_{k_1} = k_2\) if and only if \(p_{k_2} = k_1\)).Count the number of almost perfect permutations of length \(n\) modulo \(998244353\).
The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) — the number of test cases. The description of each test case follows.The first and only line of each test case contains a single integer \(n\) (\(1 \leq n \leq 3 \cdot 10^5\)) — the length of the permutation.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3 \cdot 10^5\).
For each test case, output a single integer — the number of almost perfect permutations of length \(n\) modulo \(998244353\).
For \(n = 2\), both permutations \([1, 2]\), and \([2, 1]\) are almost perfect.For \(n = 3\), there are only \(6\) permutations. Having a look at all of them gives us: \([1, 2, 3]\) is an almost perfect permutation. \([1, 3, 2]\) is an almost perfect permutation. \([2, 1, 3]\) is an almost perfect permutation. \([2, 3, 1]\) is NOT an almost perfect permutation (\(\lvert p_2 - p^{-1}_2 \rvert = \lvert 3 - 1 \rvert = 2\)). \([3, 1, 2]\) is NOT an almost perfect permutation (\(\lvert p_2 - p^{-1}_2 \rvert = \lvert 1 - 3 \rvert = 2\)). \([3, 2, 1]\) is an almost perfect permutation. So we get \(4\) almost perfect permutations.
Input: 32350 | Output: 2 4 830690567
Expert
3
356
373
125
17
1,039
B
1039B
B. Subway Pursuit
2,100
binary search; interactive; probabilities
This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with \(n\) stations, indexed consecutively from \(1\) to \(n\). At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers \(l\) and \(r\) (\(l \le r\)), and then check, whether the train is located on a station with index between \(l\) and \(r\), inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most \(k\) stations away. Formally, if the train was at the station \(x\) when the gadget was applied, then at the next application of the gadget the train can appear at any station \(y\) such that \(\max(1, x - k) \leq y \leq \min(n, x + k)\).Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than \(4500\) applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than \(4500\) applications of the gadgets?
The first line contains two integers \(n\) and \(k\) (\(1 \leq n \leq 10^{18}\), \(0 \leq k \leq 10\)) — the number of stations and the maximum number of stations the train can move between two applications of the gadget.
In the first sample, the train was initially at the station \(5\), after the first application of the gadget it did not move, after the second application it moved to the station \(3\), and after the third application moved again to the station \(5\).
Input: 10 2YesNoYesYes | Output: 3 53 33 45 5
Hard
3
1,773
221
0
10
164
B
164B
B. Ancient Berland Hieroglyphs
2,000
two pointers
Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them).Polycarpus wants to save these pictures on his laptop, but the problem is, laptops do not allow to write hieroglyphs circles. So Polycarp had to break each circle and write down all of its hieroglyphs in a clockwise order in one line. A line obtained from the first circle will be called a, and the line obtained from the second one will be called b.There are quite many ways to break hieroglyphic circles, so Polycarpus chooses the method, that makes the length of the largest substring of string a, which occurs as a subsequence in string b, maximum.Help Polycarpus — find the maximum possible length of the desired substring (subsequence) if the first and the second circles are broken optimally.The length of string s is the number of characters in it. If we denote the length of string s as |s|, we can write the string as s = s1s2... s|s|.A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, ""code"" and ""force"" are substrings of ""codeforces"", while ""coders"" is not. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, ""coders"" is a subsequence of ""codeforces"".
The first line contains two integers la and lb (1 ≤ la, lb ≤ 1000000) — the number of hieroglyphs in the first and second circles, respectively.Below, due to difficulties with encoding of Berland hieroglyphs, they are given as integers from 1 to 106.The second line contains la integers — the hieroglyphs in the first picture, in the clockwise order, starting with one of them.The third line contains lb integers — the hieroglyphs in the second picture, in the clockwise order, starting with one of them.It is guaranteed that the first circle doesn't contain a hieroglyph, which occurs twice. The second circle also has this property.
Print a single number — the maximum length of the common substring and subsequence. If at any way of breaking the circles it does not exist, print 0.
In the first test Polycarpus picks a string that consists of hieroglyphs 5 and 1, and in the second sample — from hieroglyphs 1, 3 and 5.
Input: 5 41 2 3 4 51 3 5 6 | Output: 2
Hard
1
1,478
634
149
1
702
A
702A
A. Maximum Increase
800
dp; greedy; implementation
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
The first line contains single positive integer n (1 ≤ n ≤ 105) — the number of integers.The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Print the maximum length of an increasing subarray of the given array.
Input: 51 7 2 11 15 | Output: 3
Beginner
3
290
165
70
7
1,978
D
1978D
D. Elections
1,600
data structures; greedy; implementation; math
Elections are taking place in Berland. There are \(n\) candidates participating in the elections, numbered from \(1\) to \(n\). The \(i\)-th candidate has \(a_i\) fans who will vote for him. Additionally, there are \(c\) people who are undecided about their favorite candidate, let's call them undecided. Undecided people will vote for the candidate with the lowest number.The candidate who receives the maximum number of votes wins the elections, and if multiple candidates receive the same maximum number of votes, the candidate with the lowest number among them wins.You found these elections too boring and predictable, so you decided to exclude some candidates from them. If you do not allow candidate number \(i\) to participate in the elections, all \(a_i\) of his fans will become undecided, and will vote for the candidate with the lowest number.You are curious to find, for each \(i\) from \(1\) to \(n\), the minimum number of candidates that need to be excluded from the elections for candidate number \(i\) to win the elections.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 2 \cdot 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 \(c\) (\(1 \le n \le 2 \cdot 10^5\), \(0 \le c \le 10^9\)) — the number of candidates in the elections and the number of undecided people.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 10^9\)) — the number of fans for each candidate.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output \(n\) integers, the \(i\)-th of which should be equal to the minimum number of candidates that need to be excluded from the elections for candidate number \(i\) to win.
In the first test case: If all candidates are allowed, candidate number \(1\) will receive \(3\) votes (\(1\) undecided person will vote for him), candidate number \(2\) will receive \(0\) votes, and candidate number \(3\) will receive \(3\) votes. Therefore, candidate number \(1\) wins (he received the same number of votes as candidate \(3\), but his number is lower), so the answer for him is \(0\). If candidate number \(1\) is not allowed, his \(2\) fans will become undecided. Then candidate number \(2\) will receive \(3\) votes (\(3\) undecided people will vote for him) and candidate number \(3\) will receive \(3\) votes. Therefore, candidate number \(2\) wins (he received the same number of votes as candidate \(3\), but his number is lower), so the answer for him is \(1\). If candidates with numbers \(1\) and \(2\) are not allowed, candidate number \(3\) wins, so the answer for him is \(2\).In the second test case, candidate number \(1\) will win if candidate number \(2\) is not allowed to participate.
Input: 53 12 0 32 30 105 35 4 3 2 14 53 10 7 16 02 2 2 3 3 3 | Output: 0 1 2 1 0 0 1 2 3 4 1 0 2 3 1 1 2 0 4 5
Medium
4
1,041
637
195
19
1,485
A
1485A
A. Add and Divide
1,000
brute force; greedy; math; number theory
You have two positive integers \(a\) and \(b\).You can perform two kinds of operations: \(a = \lfloor \frac{a}{b} \rfloor\) (replace \(a\) with the integer part of the division between \(a\) and \(b\)) \(b=b+1\) (increase \(b\) by \(1\)) Find the minimum number of operations required to make \(a=0\).
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 \(a\), \(b\) (\(1 \le a,b \le 10^9\)).
For each test case, print a single integer: the minimum number of operations required to make \(a=0\).
In the first test case, one of the optimal solutions is: Divide \(a\) by \(b\). After this operation \(a = 4\) and \(b = 2\). Divide \(a\) by \(b\). After this operation \(a = 2\) and \(b = 2\). Increase \(b\). After this operation \(a = 2\) and \(b = 3\). Divide \(a\) by \(b\). After this operation \(a = 0\) and \(b = 3\).
Input: 6 9 2 1337 1 1 1 50000000 4 991026972 997 1234 5678 | Output: 4 9 2 12 3 1
Beginner
4
301
207
102
14
228
A
228A
A. Is your horseshoe on the other hoof?
800
implementation
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
The first line contains four space-separated integers s1, s2, s3, s4 (1 ≤ s1, s2, s3, s4 ≤ 109) — the colors of horseshoes Valera has.Consider all possible colors indexed with integers.
Print a single integer — the minimum number of horseshoes Valera needs to buy.
Input: 1 7 3 3 | Output: 1
Beginner
1
775
185
78
2
883
M
883M
M. Quadcopter Competition
1,100
greedy; math
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: start the race from some point of a field, go around the flag, close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the point where the flag is situated (x2, y2). Polycarp’s quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (x, y) to any of four points: (x - 1, y), (x + 1, y), (x, y - 1) or (x, y + 1).Thus the quadcopter path is a closed cycle starting and finishing in (x1, y1) and containing the point (x2, y2) strictly inside. The picture corresponds to the first example: the starting (and finishing) point is in (1, 5) and the flag is in (5, 2). What is the minimal length of the quadcopter path?
The first line contains two integer numbers x1 and y1 ( - 100 ≤ x1, y1 ≤ 100) — coordinates of the quadcopter starting (and finishing) point.The second line contains two integer numbers x2 and y2 ( - 100 ≤ x2, y2 ≤ 100) — coordinates of the flag.It is guaranteed that the quadcopter starting point and the flag do not coincide.
Print the length of minimal path of the quadcopter to surround the flag and return back.
Input: 1 55 2 | Output: 18
Easy
2
901
327
88
8
2,078
D
2078D
D. Scammy Game Ad
1,800
dp; greedy; implementation
Consider the following game. In this game, a level consists of \(n\) pairs of gates. Each pair contains one left gate and one right gate. Each gate performs one of two operations: Addition Operation (+ a): Increases the number of people in a lane by a constant amount \(a\). Multiplication Operation (x a): Multiplies the current number of people in a lane by an integer \(a\). This means the number of people increases by \((a - 1)\) times the current count in that lane. The additional people gained from each operation can be assigned to either lane. However, people already in a lane cannot be moved to the other lane.Initially, there is one person in each lane. Your task is to determine the maximum total number of people that can be achieved by the end of the level.
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 one integer \(n\) (\(1 \leq n \le 30\)) — the number of pairs of gates.The next \(n\) lines of each test case provide the information for the left gate followed by the right gate of each gate pair. The information for each gate is given in the form + \(a\) (\(1 \le a \le 1000\)) or x \(a\) (\(2 \le a \le 3\)) for some integer \(a\).
For each test case, output a single integer — the maximum total number of people at the end of the level.
In the first case, here is one possible way to play this game optimally.Initially, we have \(l=1\) person in the left lane and \(r=1\) person in the right lane.After passing through the first pair of gates, we gain \(4\) people from the left gate and \(1 \cdot (2-1) = 1\) person from the right gate, for a total of \(4+1=5\) people. We allocate \(2\) people to the left lane and \(3\) people to the right lane. This results in \(l=1+2=3\) people in the left lane and \(r=1+3=4\) people in the right lane.After passing through the second pair of gates, we gain \(3 \cdot (3-1) = 6\) people from the left gate and \(4 \cdot (3-1) = 8\) people from the right gate, for a total of \(6+8=14\) people. We allocate \(7\) people to the left lane and \(7\) people to the right lane. This results in \(l=3+7=10\) people in the left lane and \(r=4+7=11\) people in the right lane.After passing through the last pair of gates, we gain \(7\) people from the left gate and \(4\) people from the right gate, for a total of \(7+4=11\) people. We allocate \(6\) people to the left lane and \(5\) people to the right lane. This results in \(l=10+6=16\) people in the left lane and \(r=11+5=16\) people in the right lane.At the end, the total number of people is \(16+16=32\).
Input: 43+ 4 x 2x 3 x 3+ 7 + 44+ 9 x 2x 2 x 3+ 9 + 10x 2 + 14x 2 + 1+ 9 + 10x 2 x 3+ 9 x 25x 3 x 3x 2 x 2+ 21 + 2x 2 x 3+ 41 x 3 | Output: 32 98 144 351
Medium
3
773
469
105
20
939
C
939C
C. Convenient For Everybody
1,600
binary search; two pointers
In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time ""0 hours"", instead of it ""n hours"" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.Help platform select such an hour, that the number of people who will participate in the contest is maximum.
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day.The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest.The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).
Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.
In the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.In second example only people from the third and the fourth timezones will participate.
Input: 31 2 31 3 | Output: 3
Medium
2
1,061
347
224
9
2,045
B
2045B
B. ICPC Square
2,000
math; number theory
ICPC Square is a hotel provided by the ICPC Committee for the accommodation of the participants. It consists of \(N\) floors (numbered from \(1\) to \(N\)). This hotel has a very unique elevator. If a person is currently at floor \(x\), by riding the elevator once, they can go to floor \(y\) if and only if \(y\) is a multiple of \(x\) and \(y - x \leq D\).You are currently at floor \(S\). You want to go to the highest possible floor by riding the elevator zero or more times. Determine the highest floor you can reach.
A single line consisting of three integers \(N\) \(D\) \(S\) (\(2 \leq N \leq 10^{12}; 1 \leq D \leq N - 1; 1 \leq S \leq N\)).
Output a single integer representing the highest floor you can reach by riding the elevator zero or more times.
Explanation for the sample input/output #1First, ride the elevator from floor \(3\) to floor \(15\). This is possible because \(15\) is a multiple of \(3\) and \(15 - 3 \leq 35\). Then, ride the elevator from floor \(15\) to floor \(30\). This is possible because \(30\) is a multiple of \(15\) and \(30 - 15 \leq 35\). Finally, ride the elevator from floor \(30\) to floor \(60\). This is possible because \(60\) is a multiple of \(30\) and \(60 - 30 \leq 35\).
Input: 64 35 3 | Output: 60
Hard
2
522
127
111
20
19
A
19A
A. World Football Cup
1,400
implementation
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: the final tournament features n teams (n is always even) the first n / 2 teams (according to the standings) come through to the knockout stage the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
The first input line contains the only integer n (1 ≤ n ≤ 50) — amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 — names of the teams; num1, num2 (0 ≤ num1, num2 ≤ 100) — amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
Output n / 2 lines — names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
Input: 4ABCDA-B 1:1A-C 2:2A-D 1:0B-C 1:0B-D 0:3C-D 0:3 | Output: AD
Easy
1
1,060
738
294
0
1,454
D
1454D
D. Number into Sequence
1,300
constructive algorithms; math; number theory
You are given an integer \(n\) (\(n > 1\)).Your task is to find a sequence of integers \(a_1, a_2, \ldots, a_k\) such that: each \(a_i\) is strictly greater than \(1\); \(a_1 \cdot a_2 \cdot \ldots \cdot a_k = n\) (i. e. the product of this sequence is \(n\)); \(a_{i + 1}\) is divisible by \(a_i\) for each \(i\) from \(1\) to \(k-1\); \(k\) is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer \(n > 1\).You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 5000\)) — the number of test cases. Then \(t\) test cases follow.The only line of the test case contains one integer \(n\) (\(2 \le n \le 10^{10}\)).It is guaranteed that the sum of \(n\) does not exceed \(10^{10}\) (\(\sum n \le 10^{10}\)).
For each test case, print the answer: in the first line, print one positive integer \(k\) — the maximum possible length of \(a\). In the second line, print \(k\) integers \(a_1, a_2, \ldots, a_k\) — the sequence of length \(k\) satisfying the conditions from the problem statement.If there are several answers, you can print any. It can be proven that at least one valid sequence always exists for any integer \(n > 1\).
Input: 4 2 360 4999999937 4998207083 | Output: 1 2 3 2 2 90 1 4999999937 1 4998207083
Easy
3
630
311
420
14
1,278
D
1278D
D. Segment Tree
2,100
data structures; dsu; graphs; trees
As the name of the task implies, you are asked to do some work with segments and trees.Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.You are given \(n\) segments \([l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]\), \(l_i < r_i\) for every \(i\). It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.Let's generate a graph with \(n\) vertices from these segments. Vertices \(v\) and \(u\) are connected by an edge if and only if segments \([l_v, r_v]\) and \([l_u, r_u]\) intersect and neither of it lies fully inside the other one.For example, pairs \(([1, 3], [2, 4])\) and \(([5, 10], [3, 7])\) will induce the edges but pairs \(([1, 2], [3, 4])\) and \(([5, 7], [3, 10])\) will not.Determine if the resulting graph is a tree or not.
The first line contains a single integer \(n\) (\(1 \le n \le 5 \cdot 10^5\)) — the number of segments.The \(i\)-th of the next \(n\) lines contain the description of the \(i\)-th segment — two integers \(l_i\) and \(r_i\) (\(1 \le l_i < r_i \le 2n\)).It is guaranteed that all segments borders are pairwise distinct.
Print ""YES"" if the resulting graph is a tree and ""NO"" otherwise.
The graph corresponding to the first example:The graph corresponding to the second example:The graph corresponding to the third example:
Input: 6 9 12 2 11 1 3 6 10 5 7 4 8 | Output: YES
Hard
4
992
317
68
12
1,430
B
1430B
B. Barrels
800
greedy; implementation; sortings
You have \(n\) barrels lined up in a row, numbered from left to right from one. Initially, the \(i\)-th barrel contains \(a_i\) liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels \(x\) and \(y\) (the \(x\)-th barrel shouldn't be empty) and pour any possible amount of water from barrel \(x\) to barrel \(y\) (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most \(k\) times.Some examples: if you have four barrels, each containing \(5\) liters of water, and \(k = 1\), you may pour \(5\) liters from the second barrel into the fourth, so the amounts of water in the barrels are \([5, 0, 5, 10]\), and the difference between the maximum and the minimum is \(10\); if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still \(0\).
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le k < n \le 2 \cdot 10^5\)) — the number of barrels and the number of pourings you can make.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(0 \le a_i \le 10^{9}\)), where \(a_i\) is the initial amount of water the \(i\)-th barrel has.It's guaranteed that the total sum of \(n\) over test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most \(k\) times.
Input: 2 4 1 5 5 5 5 3 2 0 0 0 | Output: 10 0
Beginner
3
1,081
516
168
14
1,620
B
1620B
B. Triangles on a Rectangle
1,000
geometry; greedy; math
A rectangle with its opposite corners in \((0, 0)\) and \((w, h)\) and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that: exactly two of them belong to the same side of a rectangle; the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of testcases.The first line of each testcase contains two integers \(w\) and \(h\) (\(3 \le w, h \le 10^6\)) — the coordinates of the corner of a rectangle.The next two lines contain the description of the points on two horizontal sides. First, an integer \(k\) (\(2 \le k \le 2 \cdot 10^5\)) — the number of points. Then, \(k\) integers \(x_1 < x_2 < \dots < x_k\) (\(0 < x_i < w\)) — the \(x\) coordinates of the points in the ascending order. The \(y\) coordinate for the first line is \(0\) and for the second line is \(h\).The next two lines contain the description of the points on two vertical sides. First, an integer \(k\) (\(2 \le k \le 2 \cdot 10^5\)) — the number of points. Then, \(k\) integers \(y_1 < y_2 < \dots < y_k\) (\(0 < y_i < h\)) — the \(y\) coordinates of the points in the ascending order. The \(x\) coordinate for the first line is \(0\) and for the second line is \(w\).The total number of points on all sides in all testcases doesn't exceed \(2 \cdot 10^5\).
For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.
The points in the first testcase of the example: \((1, 0)\), \((2, 0)\); \((2, 8)\), \((3, 8)\), \((4, 8)\); \((0, 1)\), \((0, 4)\), \((0, 6)\); \((5, 4)\), \((5, 5)\). The largest triangle is formed by points \((0, 1)\), \((0, 6)\) and \((5, 4)\) — its area is \(\frac{25}{2}\). Thus, the doubled area is \(25\). Two points that are on the same side are: \((0, 1)\) and \((0, 6)\).
Input: 3 5 8 2 1 2 3 2 3 4 3 1 4 6 2 4 5 10 7 2 3 9 2 1 7 3 1 3 4 3 4 5 6 11 5 3 1 6 8 3 3 6 8 3 1 3 4 2 2 4 | Output: 25 42 35
Beginner
3
612
1,070
159
16
425
E
425E
E. Sereja and Sets
2,500
dp
Let's assume that set S consists of m distinct intervals [l1, r1], [l2, r2], ..., [lm, rm] (1 ≤ li ≤ ri ≤ n; li, ri are integers).Let's assume that f(S) is the maximum number of intervals that you can choose from the set S, such that every two of them do not intersect. We assume that two intervals, [l1, r1] and [l2, r2], intersect if there is an integer x, which meets two inequalities: l1 ≤ x ≤ r1 and l2 ≤ x ≤ r2.Sereja wonders, how many sets S are there, such that f(S) = k? Count this number modulo 1000000007 (109 + 7).
The first line contains integers n, k (1 ≤ n ≤ 500; 0 ≤ k ≤ 500).
In a single line, print the answer to the problem modulo 1000000007 (109 + 7).
Input: 3 1 | Output: 23
Expert
1
526
65
78
4
891
A
891A
A. Pride
1,500
brute force; dp; greedy; math; number theory
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?
The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array.The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.
Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.
In the first sample you can turn all numbers to 1 using the following 5 moves: [2, 2, 3, 4, 6]. [2, 1, 3, 4, 6] [2, 1, 3, 1, 6] [2, 1, 1, 1, 6] [1, 1, 1, 1, 6] [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
Input: 52 2 3 4 6 | Output: 5
Medium
5
317
215
144
8
1,110
H
1110H
H. Modest Substrings
3,500
dp; strings
You are given two integers \(l\) and \(r\).Let's call an integer \(x\) modest, if \(l \le x \le r\).Find a string of length \(n\), consisting of digits, which has the largest possible number of substrings, which make a modest integer. Substring having leading zeros are not counted. If there are many answers, find lexicographically smallest one.If some number occurs multiple times as a substring, then in the counting of the number of modest substrings it is counted multiple times as well.
The first line contains one integer \(l\) (\(1 \le l \le 10^{800}\)).The second line contains one integer \(r\) (\(l \le r \le 10^{800}\)).The third line contains one integer \(n\) (\(1 \le n \le 2\,000\)).
In the first line, print the maximum possible number of modest substrings.In the second line, print a string of length \(n\) having exactly that number of modest substrings.If there are multiple such strings, print the lexicographically smallest of them.
In the first example, string «101» has modest substrings «1», «10», «1».In the second example, string «111» has modest substrings «1» (\(3\) times) and «11» (\(2\) times).
Input: 1 10 3 | Output: 3 101
Master
2
492
206
254
11
9
D
9D
D. How many trees?
1,900
combinatorics; divide and conquer; dp
In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game...For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this.However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User.This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with n nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from 1 to n. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf).In Hexadecimal's game all the trees are different, but the height of each is not lower than h. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you?
The input data contains two space-separated positive integer numbers n and h (n ≤ 35, h ≤ n).
Output one number — the answer to the problem. It is guaranteed that it does not exceed 9·1018.
Input: 3 2 | Output: 5
Hard
3
1,939
93
95
0
1,938
A
1938A
3,500
Master
0
0
0
0
19
1,773
L
1773L
L. Lisa's Sequences
3,500
dp
Lisa loves playing with the sequences of integers. When she gets a new integer sequence \(a_i\) of length \(n\), she starts looking for all monotone subsequences. A monotone subsequence \([l, r]\) is defined by two indices \(l\) and \(r\) (\(1 \le l < r \le n\)) such that \(\forall i = l, l+1, \ldots, r-1: a_i \le a_{i+1}\) or \(\forall i = l, l+1, \ldots, r-1: a_i \ge a_{i+1}\). Lisa considers a sequence \(a_i\) to be boring if there is a monotone subsequence \([l, r]\) that is as long as her boredom threshold \(k\), that is when \(r - l + 1 = k\).Lucas has a sequence \(b_i\) that he wants to present to Lisa, but the sequence might be boring for Lisa. So, he wants to change some elements of his sequence \(b_i\), so that Lisa does not get bored playing with it. However, Lucas is lazy and wants to change as few elements of the sequence \(b_i\) as possible. Your task is to help Lucas find the required changes.
The first line of the input contains two integers \(n\) and \(k\) (\(3 \le k \le n \le 10^6\)) — the length of the sequence and Lisa's boredom threshold. The second line contains \(n\) integers \(b_i\) (\(1 \le b_i \le 99\,999\)) — the original sequence that Lucas has.
On the first line output an integer \(m\) — the minimal number of elements in \(b_i\) that needs to be changed to make the sequence not boring for Lisa. On the second line output \(n\) integers \(a_i\) (\(0 \le a_i \le 100\,000\)), so that the sequence of integers \(a_i\) is not boring for Lisa and is different from the original sequence \(b_i\) in exactly \(m\) positions.
Input: 5 3 1 2 3 4 5 | Output: 2 1 0 3 0 5
Master
1
921
269
375
17
1,935
C
1935C
C. Messenger in MAC
1,800
binary search; brute force; constructive algorithms; data structures; dp; greedy; sortings
In the new messenger for the students of the Master's Assistance Center, Keftemerum, an update is planned, in which developers want to optimize the set of messages shown to the user. There are a total of \(n\) messages. Each message is characterized by two integers \(a_i\) and \(b_i\). The time spent reading the set of messages with numbers \(p_1, p_2, \ldots, p_k\) (\(1 \le p_i \le n\), all \(p_i\) are distinct) is calculated by the formula:$$$\(\Large \sum_{i=1}^{k} a_{p_i} + \sum_{i=1}^{k - 1} |b_{p_i} - b_{p_{i+1}}|\)\(Note that the time to read a set of messages consisting of one message with number \)p_1\( is equal to \)a_{p_1}\(. Also, the time to read an empty set of messages is considered to be \)0\(.The user can determine the time \)l\( that he is willing to spend in the messenger. The messenger must inform the user of the maximum possible size of the set of messages, the reading time of which does not exceed \)l\(. Note that the maximum size of the set of messages can be equal to \)0$$$.The developers of the popular messenger failed to implement this function, so they asked you to solve this problem.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 5 \cdot 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 \(l\) (\(1 \leq n \leq 2000\), \(1 \leq l \leq 10^9\)) — the number of messages and the time the user is willing to spend in the messenger.The \(i\)-th of the next \(n\) lines contains two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le 10^9\)) — characteristics of the \(i\)-th message.It is guaranteed that the sum of \(n^2\) over all test cases does not exceed \(4 \cdot 10^6\).
For each test case, output a single integer — the maximum possible size of a set of messages, the reading time of which does not exceed \(l\).
In the first test case, you can take a set of three messages with numbers \(p_1 = 3\), \(p_2 = 2\), and \(p_3 = 5\). The time spent reading this set is equal to \(a_3 + a_2 + a_5 + |b_3 - b_2| + |b_2 - b_5| = 2 + 1 + 2 + |4 - 5| + |5 - 3| = 8\).In the second test case, you can take a set of one message with number \(p_1 = 1\). The time spent reading this set is equal to \(a_1 = 4\).In the fifth test case, it can be shown that there is no such non-empty set of messages, the reading time of which does not exceed \(l\).
Input: 55 84 31 52 44 32 31 64 103 124 82 12 125 2624 78 2830 223 817 175 1415 31000000000 998244353179 239228 1337993 1007 | Output: 3 1 2 1 0
Medium
7
1,128
642
142
19
2,008
H
2008H
H. Sakurako's Test
2,100
binary search; brute force; greedy; math; number theory
Sakurako will soon take a test. The test can be described as an array of integers \(n\) and a task on it:Given an integer \(x\), Sakurako can perform the following operation any number of times: Choose an integer \(i\) (\(1\le i\le n\)) such that \(a_i\ge x\); Change the value of \(a_i\) to \(a_i-x\). Using this operation any number of times, she must find the minimum possible median\(^{\text{∗}}\) of the array \(a\).Sakurako knows the array but does not know the integer \(x\). Someone let it slip that one of the \(q\) values of \(x\) will be in the next test, so Sakurako is asking you what the answer is for each such \(x\).\(^{\text{∗}}\)The median of an array of length \(n\) is the element that stands in the middle of the sorted array (at the \(\frac{n+2}{2}\)-th position for even \(n\), and at the \(\frac{n+1}{2}\)-th for odd)
The first line contains one 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 \(q\) (\(1\le n,q\le 10^5\)) — the number of elements in the array and the number of queries.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1\le a_i\le n\)) — the elements of the array.The following \(q\) lines each contain one integer \(x\) (\(1\le x\le n\)).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(10^5\). The same guarantee applies to the sum of \(q\) across all test cases.
For each test case, output \(q\) integers — the answer for each query.
Input: 25 51 2 3 4 5123456 31 2 6 4 1 3215 | Output: 0 1 1 1 2 1 0 2
Hard
5
841
610
70
20
1,463
C
1463C
C. Busy Robot
1,800
implementation
You have a robot that can move along a number line. At time moment \(0\) it stands at point \(0\).You give \(n\) commands to the robot: at time \(t_i\) seconds you command the robot to go to point \(x_i\). Whenever the robot receives a command, it starts moving towards the point \(x_i\) with the speed of \(1\) unit per second, and he stops when he reaches that point. However, while the robot is moving, it ignores all the other commands that you give him.For example, suppose you give three commands to the robot: at time \(1\) move to point \(5\), at time \(3\) move to point \(0\) and at time \(6\) move to point \(4\). Then the robot stands at \(0\) until time \(1\), then starts moving towards \(5\), ignores the second command, reaches \(5\) at time \(6\) and immediately starts moving to \(4\) to execute the third command. At time \(7\) it reaches \(4\) and stops there.You call the command \(i\) successful, if there is a time moment in the range \([t_i, t_{i + 1}]\) (i. e. after you give this command and before you give another one, both bounds inclusive; we consider \(t_{n + 1} = +\infty\)) when the robot is at point \(x_i\). Count the number of successful commands. Note that it is possible that an ignored command is successful.
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases. The next lines describe the test cases.The first line of a test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the number of commands.The next \(n\) lines describe the commands. The \(i\)-th of these lines contains two integers \(t_i\) and \(x_i\) (\(1 \le t_i \le 10^9\), \(-10^9 \le x_i \le 10^9\)) — the time and the point of the \(i\)-th command.The commands are ordered by time, that is, \(t_i < t_{i + 1}\) for all possible \(i\).The sum of \(n\) over test cases does not exceed \(10^5\).
For each testcase output a single integer — the number of successful commands.
The movements of the robot in the first test case are described in the problem statement. Only the last command is successful.In the second test case the second command is successful: the robot passes through target point \(4\) at time \(5\). Also, the last command is eventually successful.In the third test case no command is successful, and the robot stops at \(-5\) at time moment \(7\).Here are the \(0\)-indexed sequences of the positions of the robot in each second for each testcase of the example. After the cut all the positions are equal to the last one: \([0, 0, 1, 2, 3, 4, 5, 4, 4, \dots]\) \([0, 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -5, \dots]\) \([0, 0, 0, -1, -2, -3, -4, -5, -5, \dots]\) \([0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, \dots]\) \([0, 0, 1, 0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -7, -8, -9, -9, -9, -9, -8, -7, -6, -5, -4, -3, -2, -1, -1, \dots]\) \([0, 0, -1, -2, -3, -4, -4, -3, -2, -1, -1, \dots]\) \([0, 0, 1, 2, 2, \dots]\) \([0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -7, \dots]\)
Input: 8 3 1 5 3 0 6 4 3 1 5 2 4 10 -5 5 2 -5 3 1 4 1 5 1 6 1 4 3 3 5 -3 9 2 12 0 8 1 1 2 -6 7 2 8 3 12 -9 14 2 18 -1 23 9 5 1 -4 4 -7 6 -1 7 -3 8 -7 2 1 2 2 -2 6 3 10 5 5 8 0 12 -4 14 -7 19 -5 | Output: 1 2 0 2 1 1 0 2
Medium
1
1,247
607
78
14
1,809
A
1809A
A. Garland
800
implementation
You have a garland consisting of \(4\) colored light bulbs, the color of the \(i\)-th light bulb is \(s_i\).Initially, all the light bulbs are turned off. Your task is to turn all the light bulbs on. You can perform the following operation any number of times: select a light bulb and switch its state (turn it on if it was off, and turn it off if it was on). The only restriction on the above operation is that you can apply the operation to a light bulb only if the previous operation was applied to a light bulb of a different color (the first operation can be applied to any light bulb).Calculate the minimum number of operations to turn all the light bulbs on, or report that this is impossible.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The single line of each test case contains \(s\) — a sequence of \(4\) characters, where each character is a decimal digit. The \(i\)-th character denotes the color of the \(i\)-th light bulb.
For each test case, print one integer — the minimum number of operations to turn all the light bulbs on. If it is impossible to turn all the bulbs on, print -1.
In the first example, all the colors are different, so you can just turn all the bulbs on in \(4\) operations.In the second example, it is impossible to turn all the bulbs on, because after you switch one light bulb, it is impossible to turn the others on.In the third example, you can proceed as follows: turn the first light bulb on, turn the third light bulb on, turn the fourth light bulb on, turn the third light bulb off, turn the second light bulb on, turn the third light bulb on.
Input: 3954600003313 | Output: 4 -1 6
Beginner
1
700
289
160
18
501
B
501B
B. Misha and Changing Handles
1,100
data structures; dsu; strings
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.Next q lines contain the descriptions of the requests, one per line.Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
In the first line output the integer n — the number of users that changed their handles at least once.In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.Each user who changes the handle must occur exactly once in this description.
Input: 5Misha ILoveCodeforcesVasya PetrovPetrov VasyaPetrov123ILoveCodeforces MikeMirzayanovPetya Ivanov | Output: 3Petya IvanovMisha MikeMirzayanovVasya VasyaPetrov123
Easy
3
436
568
481
5
633
D
633D
D. Fibonacci-ish
2,000
brute force; dp; hashing; implementation; math
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28.
Input: 31 2 -1 | Output: 3
Hard
5
407
168
104
6
51
A
51A
A. Cheaterius's Problem
1,300
implementation
Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2 × 2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2 × 2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk.
The first line contains an integer n (1 ≤ n ≤ 1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line ""**"" is located.
Print the required number of piles.
Input: 43123**3123**1332**3213 | Output: 1
Easy
1
1,031
280
35
0
1,808
E2
1808E2
E2. Minibuses on Venus (medium version)
2,500
combinatorics; divide and conquer; dp; matrices
This is the medium version of the problem. The only difference between the three versions is the constraints on \(n\) and \(k\). You can make hacks only if all versions of the problem are solved.Maxim is a minibus driver on Venus.To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of \(n\) digits. However, as we know, the residents of Venus use a numeral system with base \(k\), rather than the decimal system. Therefore, the ticket number can be considered as a sequence of \(n\) integers from \(0\) to \(k-1\), inclusive.The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo \(k\). For example, if \(k=10\), then the ticket \(7135\) is lucky because \(7 + 1 + 5 \equiv 3 \pmod{10}\). On the other hand, the ticket \(7136\) is not lucky because no digit is equal to the sum of the others modulo \(10\).Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number \(m\).
The only line of the input contains three integers \(n\), \(k\) and \(m\) (\(1 \le n \le 10^{18}\), \(1 \le k \le 100\), \(10^8 \le m \le 10^9 + 7\), \(m\) is a prime number) — the number of digits on the ticket, the base of the numeral system on Venus, and the module for answer calculation.
Print one integer — the number of lucky tickets modulo \(m\), i. e. the remainder after dividing the answer by \(m\).
In the first example, there are only four lucky tickets: \(000\), \(011\), \(101\), and \(110\).
Input: 3 2 1000000007 | Output: 4
Expert
4
1,129
292
117
18
109
D
109D
D. Lucky Sorting
2,000
constructive algorithms; sortings
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya got an array consisting of n numbers, it is the gift for his birthday. Now he wants to sort it in the non-decreasing order. However, a usual sorting is boring to perform, that's why Petya invented the following limitation: one can swap any two numbers but only if at least one of them is lucky. Your task is to sort the array according to the specified limitation. Find any possible sequence of the swaps (the number of operations in the sequence should not exceed 2n).
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n positive integers, not exceeding 109 — the array that needs to be sorted in the non-decreasing order.
On the first line print number k (0 ≤ k ≤ 2n) — the number of the swaps in the sorting. On the following k lines print one pair of distinct numbers (a pair per line) — the indexes of elements to swap. The numbers in the array are numbered starting from 1. If it is impossible to sort the given sequence, print the single number -1.If there are several solutions, output any. Note that you don't have to minimize k. Any sorting with no more than 2n swaps is accepted.
Input: 24 7 | Output: 0
Hard
2
693
218
466
1
40
B
40B
B. Repaintings
1,600
math
A chessboard n × m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues ad infinitum. You have to figure out how many squares we repainted exactly x times.The upper left square of the board has to be assumed to be always black. Two squares are called corner-adjacent, if they have exactly one common point.
The first line contains integers n and m (1 ≤ n, m ≤ 5000). The second line contains integer x (1 ≤ x ≤ 109).
Print how many squares will be painted exactly x times.
Input: 3 31 | Output: 4
Medium
1
553
109
55
0
629
A
629A
A. Far Relative’s Birthday Cake
800
brute force; combinatorics; constructive algorithms; implementation
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.
In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake.Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.
Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.
If we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are: (1, 2) and (1, 3) (3, 1) and (3, 3) Pieces that share the same column are: (2, 1) and (3, 1) (1, 3) and (3, 3)
Input: 3.CCC..C.C | Output: 4
Beginner
4
731
256
131
6
2,044
H
2044H
H. Hard Demon Problem
2,100
constructive algorithms; data structures; dp; implementation; math
Swing is opening a pancake factory! A good pancake factory must be good at flattening things, so Swing is going to test his new equipment on 2D matrices.Swing is given an \(n \times n\) matrix \(M\) containing positive integers. He has \(q\) queries to ask you. For each query, he gives you four integers \(x_1\), \(y_1\), \(x_2\), \(y_2\) and asks you to flatten the submatrix bounded by \((x_1, y_1)\) and \((x_2, y_2)\) into an array \(A\). Formally, \(A = [M_{(x1,y1)}, M_{(x1,y1+1)}, \ldots, M_{(x1,y2)}, M_{(x1+1,y1)}, M_{(x1+1,y1+1)}, \ldots, M_{(x2,y2)}]\). The following image depicts the flattening of a submatrix bounded by the red dotted lines. The orange arrows denote the direction that the elements of the submatrix are appended to the back of \(A\), and \(A\) is shown at the bottom of the image. Afterwards, he asks you for the value of \(\sum_{i=1}^{|A|} A_i \cdot i\) (sum of \(A_i \cdot i\) over all \(i\)).
The first line contains an integer \(t\) (\(1 \leq t \leq 10^3\)) — the number of test cases.The first line of each test contains two integers \(n\) and \(q\) (\(1 \leq n \leq 2000, 1 \leq q \leq 10^6\)) — the length of \(M\) and the number of queries.The following \(n\) lines contain \(n\) integers each, the \(i\)'th of which contains \(M_{(i,1)}, M_{(i,2)}, \ldots, M_{(i,n)}\) (\(1 \leq M_{(i, j)} \leq 10^6\)).The following \(q\) lines contain four integers \(x_1\), \(y_1\), \(x_2\), and \(y_2\) (\(1 \leq x_1 \leq x_2 \leq n, 1 \leq y_1 \leq y_2 \leq n\)) — the bounds of the query.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\) and the sum of \(q\) over all test cases does not exceed \(10^6\).
For each test case, output the results of the \(q\) queries on a new line.
In the second query of the first test case, \(A = [9, 5, 5, 2]\). Therefore, the sum is \(1 \cdot 9 + 2 \cdot 5 + 3 \cdot 5 + 4 \cdot 2 = 42\).
Input: 24 31 5 2 44 9 5 34 5 2 31 5 5 21 1 4 42 2 3 31 2 4 33 31 2 34 5 67 8 91 1 1 31 3 3 32 2 2 2 | Output: 500 42 168 14 42 5
Hard
5
927
740
74
20
126
C
126C
C. E-reader Display
2,000
constructive algorithms; greedy
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.The display is represented by n × n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like ""x, y"". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color.For example, if initially a display 5 × 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes: You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.
The first line contains number n (1 ≤ n ≤ 2000).Next n lines contain n characters each: the description of the picture that needs to be shown. ""0"" represents the white color and ""1"" represents the black color.
Print one integer z — the least number of commands needed to display the picture.
Input: 50111010010100011001111110 | Output: 4
Hard
2
1,298
213
81
1
176
C
176C
C. Playing with Superglue
2,000
combinatorics; constructive algorithms
Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.We'll describe the rules of the game in more detail.The players move in turns. The first player begins.With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible — he can always spread the glue on the square from which the first player has just moved the chip.We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
The first line contains six integers n, m, x1, y1, x2, y2 — the board sizes and the coordinates of the first and second chips, correspondingly (1 ≤ n, m ≤ 100; 2 ≤ n × m; 1 ≤ x1, x2 ≤ n; 1 ≤ y1, y2 ≤ m). The numbers in the line are separated by single spaces.It is guaranteed that the chips are located in different squares.
If the first player wins, print ""First"" without the quotes. Otherwise, print ""Second"" without the quotes.
Input: 1 6 1 2 1 6 | Output: First
Hard
2
1,827
324
109
1
407
C
407C
C. Curious Array
2,500
brute force; combinatorics; implementation; math
You've got an array consisting of n integers: a[1], a[2], ..., a[n]. Moreover, there are m queries, each query can be described by three integers li, ri, ki. Query li, ri, ki means that we should add to each element a[j], where li ≤ j ≤ ri.Record means the binomial coefficient, or the number of combinations from y elements into groups of x elements.You need to fulfil consecutively all queries and then print the final array.
The first line contains integers n, m (1 ≤ n, m ≤ 105).The second line contains n integers a[1], a[2], ..., a[n] (0 ≤ ai ≤ 109) — the initial array.Next m lines contain queries in the format li, ri, ki — to all elements of the segment li... ri add number (1 ≤ li ≤ ri ≤ n; 0 ≤ k ≤ 100).
Print n integers: the i-th number is the value of element a[i] after all the queries. As the values can be rather large, print them modulo 1000000007 (109 + 7).
Input: 5 10 0 0 0 01 5 0 | Output: 1 1 1 1 1
Expert
4
427
286
160
4
1,632
E2
1632E2
E2. Distance Tree (hard version)
2,700
binary search; dfs and similar; shortest paths; trees
This version of the problem differs from the previous one only in the constraint on \(n\).A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.You are given a weighted tree with \(n\) vertices, each edge has a weight of \(1\). Denote \(d(v)\) as the distance between vertex \(1\) and vertex \(v\).Let \(f(x)\) be the minimum possible value of \(\max\limits_{1 \leq v \leq n} \ {d(v)}\) if you can temporarily add an edge with weight \(x\) between any two vertices \(a\) and \(b\) \((1 \le a, b \le n)\). Note that after this operation, the graph is no longer a tree.For each integer \(x\) from \(1\) to \(n\), find \(f(x)\).
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 a single integer \(n\) (\(2 \le n \le 3 \cdot 10^5\)).Each of the next \(n−1\) lines contains two integers \(u\) and \(v\) (\(1 \le u,v \le n\)) indicating that there is an edge between vertices \(u\) and \(v\). It is guaranteed that the given edges form a tree.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(3 \cdot 10^5\).
For each test case, print \(n\) integers in a single line, \(x\)-th of which is equal to \(f(x)\) for all \(x\) from \(1\) to \(n\).
In the first testcase: For \(x = 1\), we can an edge between vertices \(1\) and \(3\), then \(d(1) = 0\) and \(d(2) = d(3) = d(4) = 1\), so \(f(1) = 1\). For \(x \ge 2\), no matter which edge we add, \(d(1) = 0\), \(d(2) = d(4) = 1\) and \(d(3) = 2\), so \(f(x) = 2\).
Input: 341 22 31 421 271 21 33 43 53 65 7 | Output: 1 2 2 2 1 1 2 2 3 3 3 3 3
Master
4
770
492
132
16
1,195
D2
1195D2
D2. Submarine in the Rybinsk Sea (hard edition)
1,800
combinatorics; math; number theory
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers \(a_1, a_2, \dots, a_n\).A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers \(f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)\), where \(a_1 \dots a_p\) and \(b_1 \dots b_q\) are digits of two integers written in the decimal notation without leading zeros.In other words, the function \(f(x, y)\) alternately shuffles the digits of the numbers \(x\) and \(y\) by writing them from the lowest digits to the older ones, starting with the number \(y\). The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$\(f(1111, 2222) = 12121212\)\( \)\(f(7777, 888) = 7787878\)\( \)\(f(33, 44444) = 4443434\)\( \)\(f(555, 6) = 5556\)\( \)\(f(111, 2222) = 2121212\)\(Formally, if \)p \ge q\( then \)f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q\(; if \)p < q\( then \)f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q\(. Mishanya gives you an array consisting of \)n\( integers \)a_i\(, your task is to help students to calculate \)\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)\( modulo \)998\,244\,353$$$.
The first line of the input contains a single integer \(n\) (\(1 \le n \le 100\,000\)) — the number of elements in the array. The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)) — the elements of the array.
Print the answer modulo \(998\,244\,353\).
Input: 3 12 3 45 | Output: 12330
Medium
3
1,878
257
42
11
550
B
550B
B. Preparing Olympiad
1,400
bitmasks; brute force
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least l and at most r. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least x.Find the number of ways to choose a problemset for the contest.
The first line contains four integers n, l, r, x (1 ≤ n ≤ 15, 1 ≤ l ≤ r ≤ 109, 1 ≤ x ≤ 106) — the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively.The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 106) — the difficulty of each problem.
Print the number of ways to choose a suitable problemset for the contest.
In the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems.In the second example, two sets of problems are suitable — the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30.In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable.
Input: 3 5 6 11 2 3 | Output: 2
Easy
2
539
410
73
5
290
E
290E
E. HQ
2,500
*special; constructive algorithms
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ...
The only line of the input is a string between 1 and 106 characters long.
Output ""Yes"" or ""No"".
The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience.
Input: HHHH | Output: Yes
Expert
2
131
73
25
2
1,092
C
1092C
C. Prefixes and Suffixes
1,700
strings
Ivan wants to play a game with you. He picked some string \(s\) of length \(n\) consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from \(1\) to \(n-1\)), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given \(2n-2\) strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!
The first line of the input contains one integer number \(n\) (\(2 \le n \le 100\)) — the length of the guessed string \(s\).The next \(2n-2\) lines are contain prefixes and suffixes, one per line. Each of them is the string of length from \(1\) to \(n-1\) consisting only of lowercase Latin letters. They can be given in arbitrary order.It is guaranteed that there are exactly \(2\) strings of each length from \(1\) to \(n-1\). It is also guaranteed that these strings are prefixes and suffixes of some existing string of length \(n\).
Print one string of length \(2n-2\) — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The \(i\)-th character of this string should be 'P' if the \(i\)-th of the input strings is the prefix and 'S' otherwise.If there are several possible answers, you can print any.
The only string which Ivan can guess in the first example is ""ababa"".The only string which Ivan can guess in the second example is ""aaa"". Answers ""SPSP"", ""SSPP"" and ""PSPS"" are also acceptable.In the third example Ivan can guess the string ""ac"" or the string ""ca"". The answer ""SP"" is also acceptable.
Input: 5 ba a abab a aba baba ab aba | Output: SPPSPSPS
Medium
1
710
537
348
10
1,302
C
1302C
C. Segment tree or Fenwick?
0
data structures
This is an unusual problem in an unusual contest, here is the announcement: http://codeforces.com/blog/entry/73543You are given an array \(A\) of length \(n\), initially filled with zeros. You need to process \(q\) queries to the array, each of one of the following types: 1 x y: you need to assign \(A_x=y\); 2 l r: you need to print \(\sum\limits_{i=l}^r A_i\). Furthermore, there are \(T\) independent tests you need to process.
The first line contains an integer \(T\) (\(1 \leq T \leq 10^5\)) — the number of test cases.Each test case description starts with two integers \(n, q\) (\(1 \leq n, q \leq 10^5\)) — the length of the array and the number of queries. The following \(q\) lines contain the description of queries: \(1~x~y\) (\(1 \leq x \leq n\), \(0 \leq y \leq 10^9\)) for queries of the first type and \(2~l~r\) (\(1 \leq l \leq r \leq n\)) for queries of the second type. It is guaranteed that the sum of \(n\) as well as the sum of \(q\) does not exceed \(10^6\).
For each query of the second type print its result on a separate line.
Input: 2 6 5 2 1 6 1 3 2 2 2 4 1 6 3 2 1 6 5 3 1 3 7 1 1 4 2 1 5 | Output: 0 2 5 11
Beginner
1
431
550
70
13
1,106
D
1106D
D. Lunar New Year and a Wander
1,500
data structures; dfs and similar; graphs; greedy; shortest paths
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with \(n\) nodes and \(m\) bidirectional edges. Initially Bob is at the node \(1\) and he records \(1\) on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes \(a_1, a_2, \ldots, a_n\) is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence \(x\) is lexicographically smaller than a sequence \(y\) if and only if one of the following holds: \(x\) is a prefix of \(y\), but \(x \ne y\) (this is impossible in this problem as all considered sequences have the same length); in the first position where \(x\) and \(y\) differ, the sequence \(x\) has a smaller element than the corresponding element in \(y\).
The first line contains two positive integers \(n\) and \(m\) (\(1 \leq n, m \leq 10^5\)), denoting the number of nodes and edges, respectively.The following \(m\) lines describe the bidirectional edges in the graph. The \(i\)-th of these lines contains two integers \(u_i\) and \(v_i\) (\(1 \leq u_i, v_i \leq n\)), representing the nodes the \(i\)-th edge connects.Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.
Output a line containing the lexicographically smallest sequence \(a_1, a_2, \ldots, a_n\) Bob can record.
In the first sample, Bob's optimal wandering path could be \(1 \rightarrow 2 \rightarrow 1 \rightarrow 3\). Therefore, Bob will obtain the sequence \(\{1, 2, 3\}\), which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be \(1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5\). Therefore, Bob will obtain the sequence \(\{1, 4, 3, 2, 5\}\), which is the lexicographically smallest one.
Input: 3 2 1 2 1 3 | Output: 1 2 3
Medium
5
1,135
502
106
11
581
D
581D
D. Three Logos
1,700
bitmasks; brute force; constructive algorithms; geometry; implementation; math
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
If it is impossible to place all the three logos on a square shield, print a single integer ""-1"" (without the quotes).If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters ""A"", ""B"" or ""C"". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters ""A"" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters ""B"" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters ""C"" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.See the samples to better understand the statement.
Input: 5 1 2 5 5 2 | Output: 5AAAAABBBBBBBBBBCCCCCCCCCC
Medium
6
613
210
1,042
5
316
E1
316E1
E1. Summer Homework
1,500
brute force; data structures
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type: if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105); if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n); if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105). The input limits for scoring 30 points are (subproblem E1): It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): No extra limitations.
For each query print the calculated sum modulo 1000000000 (109).
Input: 5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5 | Output: 1232850
Medium
2
632
972
64
3
470
H
470H
H. Array Sorting
2,300
*special
Sorting arrays is traditionally associated with high-level languages. How hard can it be in FALSE? Sort the given array 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.
Input: 3 3 1 2 | Output: 1 2 3
Expert
1
144
194
52
4
799
F
799F
F. Beautiful fountains rows
3,500
data structures
Butler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not.The butler wants to show Arkady n gardens. Each garden is a row of m cells, the i-th garden has one fountain in each of the cells between li and ri inclusive, and there are no more fountains in that garden. The issue is that some of the gardens contain even number of fountains, it is wrong to show them to Arkady.Ostin wants to choose two integers a ≤ b and show only part of each of the gardens that starts at cell a and ends at cell b. Of course, only such segments suit Ostin that each garden has either zero or odd number of fountains on this segment. Also, it is necessary that at least one garden has at least one fountain on the segment from a to b.Help Ostin to find the total length of all such segments, i.e. sum up the value (b - a + 1) for each suitable pair (a, b).
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of gardens and the length of each garden.n lines follow. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ m) — the bounds of the segment that contains fountains in the i-th garden.
Print one integer: the total length of all suitable segments.
In the first example the following pairs suit Ostin: (a, b): (1, 2), (1, 4), (1, 5), (2, 2), (2, 4), (2, 5), (3, 3), (4, 4), (4, 5).In the second example the following pairs suit Ostin: (a, b): (1, 2), (1, 5), (2, 2), (2, 5), (3, 3), (4, 4), (4, 6), (5, 5), (6, 6).
Input: 1 52 4 | Output: 23
Master
1
912
279
61
7
1,638
C
1638C
C. Inversion Graph
1,300
data structures; dsu; graphs; math
You are given a permutation \(p_1, p_2, \dots, p_n\). Then, an undirected graph is constructed in the following way: add an edge between vertices \(i\), \(j\) such that \(i < j\) if and only if \(p_i > p_j\). Your task is to count the number of connected components in this graph.Two vertices \(u\) and \(v\) belong to the same connected component if and only if there is at least one path along edges connecting \(u\) and \(v\).A permutation is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array) and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^5\)) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the length of the permutation.The second line of each test case contains \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\)) — the elements of the permutation.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print one integer \(k\) — the number of connected components.
Each separate test case is depicted in the image below. The colored squares represent the elements of the permutation. For one permutation, each color represents some connected component. The number of distinct colors is the answer.
Input: 631 2 352 1 4 3 566 1 4 2 5 31163 2 1 6 5 453 1 5 2 4 | Output: 3 3 1 1 2 1
Easy
4
736
527
81
16
912
D
912D
D. Fishes
2,100
data structures; graphs; greedy; probabilities; shortest paths
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).The gift bundle also includes a square scoop of size r × r, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x, y), all fishes inside the square (x, y)...(x + r - 1, y + r - 1) get caught. Note that the scoop-net should lie completely inside the pond when used.Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (n - r + 1)·(m - r + 1) possible positions, the average number of caught fishes is as high as possible.
The only line contains four integers n, m, r, k (1 ≤ n, m ≤ 105, 1 ≤ r ≤ min(n, m), 1 ≤ k ≤ min(n·m, 105)).
Print a single number — the maximum possible expected number of caught fishes.You answer is considered correct, is its absolute or relative error does not exceed 10 - 9. Namely, let your answer be a, and the jury's answer be b. Your answer is considered correct, if .
In the first example you can put the fishes in cells (2, 1), (2, 2), (2, 3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value.
Input: 3 3 2 3 | Output: 2.0000000000
Hard
5
1,055
107
267
9
1,873
H
1873H
H. Mad City
1,700
dfs and similar; dsu; games; graphs; shortest paths; trees
Marcel and Valeriu are in the mad city, which is represented by \(n\) buildings with \(n\) two-way roads between them. Marcel and Valeriu start at buildings \(a\) and \(b\) respectively. Marcel wants to catch Valeriu, in other words, be in the same building as him or meet on the same road. During each move, they choose to go to an adjacent building of their current one or stay in the same building. Because Valeriu knows Marcel so well, Valeriu can predict where Marcel will go in the next move. Valeriu can use this information to make his move. They start and end the move at the same time.It is guaranteed that any pair of buildings is connected by some path and there is at most one road between any pair of buildings.Assuming both players play optimally, answer if Valeriu has a strategy to indefinitely escape Marcel.
The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) — the number of test cases.The first line of each test case contains three space-separated integers \(n\), \(a\), \(b\) (\(3 \leq n \leq 2 \cdot 10^5\); \(1 \leq a, b \leq n\)) — the number of buildings (which equals the number of roads) and the starting buildings of Marcel and Valeriu.The following \(n\) lines each contain two integers \(u_i\), \(v_i\) (\(1 \le u_i, v_i \le n\), \(u_i \neq v_i\)) — there is a road between buildings \(u_i\) and \(v_i\). There is at most one road between any unordered pair of buildings.The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).The roads are given that it is possible to get from any building to any other building going along the roads.
For each test case output ""YES"" if Valeriu can escape Marcel forever 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 the graph looks as follows: Marcel starts at building \(2\), while Valeriu starts at building \(1\). Valeriu knows which way Marcel will move around the triangle, and he can simply always move in the same way to avoid Marcel forever.In the second test case the graph looks as follows: Marcel starts at building \(1\), while Valeriu starts at building \(4\). Marcel can go to building \(4\) on his first move and win, since Valeriu must either go to building \(1\) (then he meets Marcel on the road from \(1\) to \(4\)) or stay at building \(4\) (then he meets Marcel at building \(4\)). So there is no strategy for Valeriu to win.
Input: 63 2 12 13 21 34 1 41 41 21 32 34 1 21 22 32 43 47 1 14 12 15 34 64 27 53 48 5 38 35 12 66 81 24 85 76 710 6 11 24 35 87 810 41 92 48 16 23 1 | Output: YES NO YES NO NO YES
Medium
6
826
775
235
18
1,617
A
1617A
A. Forbidden Subsequence
800
constructive algorithms; greedy; sortings; strings
You are given strings \(S\) and \(T\), consisting of lowercase English letters. It is guaranteed that \(T\) is a permutation of the string abc. Find string \(S'\), the lexicographically smallest permutation of \(S\) such that \(T\) is not a subsequence of \(S'\).String \(a\) is a permutation of string \(b\) if the number of occurrences of each distinct character is the same in both strings.A string \(a\) is a subsequence of a string \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) elements.A string \(a\) is lexicographically smaller than a string \(b\) if and only if one of the following holds: \(a\) is a prefix of \(b\), but \(a \ne b\); in the first position where \(a\) and \(b\) differ, the string \(a\) has a letter that appears earlier in the alphabet than the corresponding letter in \(b\).
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases. Description of the test cases follows.The first line of each test case contains a string \(S\) (\(1 \le |S| \le 100\)), consisting of lowercase English letters.The second line of each test case contains a string \(T\) that is a permutation of the string abc. (Hence, \(|T| = 3\)).Note that there is no limit on the sum of \(|S|\) across all test cases.
For each test case, output a single string \(S'\), the lexicographically smallest permutation of \(S\) such that \(T\) is not a subsequence of \(S'\).
In the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence.
Input: 7 abacaba abc cccba acb dbsic bac abracadabra abc dddddddddddd cba bbc abc ac abc | Output: aaaacbb abccc bcdis aaaaacbbdrr dddddddddddd bbc ac
Beginner
4
845
490
150
16
1,989
D
1989D
D. Smithing Skill
1,900
brute force; data structures; dp; greedy; math; sortings; two pointers
You are playing a famous computer game (that just works) where you have various skills you can level up. Today, you focused on the ""Smithing"" skill. Your tactic is obvious: forging weapons from ingots and then melting them back to return the materials partially. For simplicity, every time you create an item, you get \(1\) experience point, and every time you melt an item, you also get \(1\) experience point.There are \(n\) classes of weapons you can forge and \(m\) types of metal ingots.You can create one weapon of the \(i\)-th class, spending \(a_i\) ingots of metal of the same type. Melting a weapon of the \(i\)-th class (which you crafted earlier) returns you \(b_i\) ingots of the type of metal it was made of.You have \(c_j\) metal ingots of the \(j\)-th type, and you know that you can craft a weapon of any class from any metal type. Each combination of a weapon class and a metal type can be used any number of times.What is the maximum total amount of experience you can earn by crafting and melting weapons?
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 10^6\)) — the number of weapon classes and metal types.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^6\)), where \(a_i\) is the number of ingots you need to forge one weapon of the \(i\)-th class.The third line contains \(n\) integers \(b_1, b_2, \dots, b_n\) (\(0 \le b_i < a_i\)), where \(b_i\) is the number of ingots you return by melting one weapon of the \(i\)-th class you forged earlier.The fourth line contains \(m\) integers \(c_1, c_2, \dots, c_m\) (\(1 \le c_j \le 10^9\)) — the number of ingots you have of the corresponding metal type.
Print one integer — the maximum total experience points you can gain by repeatedly forging and melting weapons.
In the first example, you can do the following: craft one weapon of the \(1\)-st class from the \(1\)-st type of metal, spending \(9\) ingots; melt that weapon, returning \(8\) ingots of the \(1\)-st metal type; again, craft and melt one weapon of the \(1\)-st class from the \(1\)-st metal type; craft and melt one weapon of the \(3\)-rd class from the \(1\)-st metal type; craft and melt one weapon of the \(3\)-rd class from the \(3\)-rd metal type; craft and melt one weapon of the \(4\)-th class from the \(1\)-st metal type; craft and melt one weapon of the \(5\)-th class from the \(3\)-rd metal type; In the end you'll have \(c = [2, 4, 2]\) ingots left. In total, you've crafted \(6\) weapons and melted \(6\) weapons, gaining \(12\) experience points in total.
Input: 5 39 6 7 5 58 4 5 1 210 4 7 | Output: 12
Hard
7
1,027
659
111
19
1,440
B
1440B
B. Sum of Medians
900
greedy; math
A median of an array of integers of length \(n\) is the number standing on the \(\lceil {\frac{n}{2}} \rceil\) (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with \(1\). For example, a median of the array \([2, 6, 4, 1, 3, 5]\) is equal to \(3\). There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers \(n\) and \(k\) and non-decreasing array of \(nk\) integers. Divide all numbers into \(k\) arrays of size \(n\), such that each number belongs to exactly one array.You want the sum of medians of all \(k\) arrays to be the maximum possible. Find this maximum possible sum.
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) — the number of test cases. The next \(2t\) lines contain descriptions of test cases.The first line of the description of each test case contains two integers \(n\), \(k\) (\(1 \leq n, k \leq 1000\)).The second line of the description of each test case contains \(nk\) integers \(a_1, a_2, \ldots, a_{nk}\) (\(0 \leq a_i \leq 10^9\)) — given array. It is guaranteed that the array is non-decreasing: \(a_1 \leq a_2 \leq \ldots \leq a_{nk}\).It is guaranteed that the sum of \(nk\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case print a single integer — the maximum possible sum of medians of all \(k\) arrays.
The examples of possible divisions into arrays for all test cases of the first test:Test case \(1\): \([0, 24], [34, 58], [62, 64], [69, 78]\). The medians are \(0, 34, 62, 69\). Their sum is \(165\).Test case \(2\): \([27, 61], [81, 91]\). The medians are \(27, 81\). Their sum is \(108\).Test case \(3\): \([2, 91, 92, 95], [4, 36, 53, 82], [16, 18, 21, 27]\). The medians are \(91, 36, 18\). Their sum is \(145\).Test case \(4\): \([3, 33, 35], [11, 94, 99], [12, 38, 67], [22, 69, 71]\). The medians are \(33, 94, 38, 69\). Their sum is \(234\).Test case \(5\): \([11, 41]\). The median is \(11\). The sum of the only median is \(11\).Test case \(6\): \([1, 1, 1], [1, 1, 1], [1, 1, 1]\). The medians are \(1, 1, 1\). Their sum is \(3\).
Input: 6 2 4 0 24 34 58 62 64 69 78 2 2 27 61 81 91 4 3 2 4 16 18 21 27 36 53 82 91 92 95 3 4 3 11 12 22 33 35 38 67 69 71 94 99 2 1 11 41 3 3 1 1 1 1 1 1 1 1 1 | Output: 165 108 145 234 11 3
Beginner
2
694
604
100
14
559
E
559E
E. Gerald and Path
3,000
dp; sortings
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
The first line contains integer n (1 ≤ n ≤ 100) — the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≤ ai ≤ 108, 1 ≤ li ≤ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates.It is guaranteed that all the ai's are distinct.
Print a single integer — the maximum total length of the illuminated part of the path.
Input: 31 12 23 3 | Output: 5
Master
2
1,024
350
86
5
1,982
D
1982D
D. Beauty of the mountains
1,700
brute force; data structures; implementation; math; number theory
Nikita loves mountains and has finally decided to visit the Berlyand mountain range! The range was so beautiful that Nikita decided to capture it on a map. The map is a table of \(n\) rows and \(m\) columns, with each cell containing a non-negative integer representing the height of the mountain.He also noticed that mountains come in two types: With snowy caps. Without snowy caps. Nikita is a very pragmatic person. He wants the sum of the heights of the mountains with snowy caps to be equal to the sum of the heights of the mountains without them. He has arranged with the mayor of Berlyand, Polikarp Polikarpovich, to allow him to transform the landscape.Nikita can perform transformations on submatrices of size \(k \times k\) as follows: he can add an integer constant \(c\) to the heights of the mountains within this area, but the type of the mountain remains unchanged. Nikita can choose the constant \(c\) independently for each transformation. Note that \(c\) can be negative.Before making the transformations, Nikita asks you to find out if it is possible to achieve equality of the sums, or if it is impossible. It doesn't matter at what cost, even if the mountains turn into canyons and have negative heights.If only one type of mountain is represented on the map, then the sum of the heights of the other type of mountain is considered to be zero.
Each test consists of several test cases. The first line contains an integer \(t\) (\(1 \le t \le 10^{4}\)) — the number of test cases. This is followed by a description of test cases.The first line of each test case contains three integers \(n, m, k\) (\(1 \le n, m \le 500, 1 \le k \le min(n, m)\)).The next \(n\) lines of each test case contain \(m\) integers \(a_{i j}\) (\(0 \le a_{i j} \le 10^{9}\)) — the initial heights of the mountains.The next \(n\) binary strings of length \(m\) for each test case determine the type of mountain, '\(0\)' — with snowy caps, '\(1\)' — without them.It is guaranteed that the sum of \(n \cdot m\) for all test cases does not exceed \(250\,000\).
For each test case, output ""YES"" without quotes if it is possible to equalize the sums of the mountain heights, otherwise output ""NO"" without quotes. You can output each letter in any case (for example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as a positive answer).
The mountain array from the first test case looks like this: Initially, the sum of the heights of the mountains with snowy caps is \(11 + 3 + 4 + 3 + 0 + 1 + 15 = 37\), and without them is \(7 + 2 = 9\).To equalize these sums, we can perform two transformations:First transformation: Note that the constant \(c\) can be negative.After the first transformation, the mountain array looks like this: Second transformation: As a result, the mountain array looks like this: The sum of the heights of the mountains with snowy caps is \(17 + 9 + 9 - 16 - 20 - 19 + 15 = -5\), and without them is \(7 - 12 = -5\), thus the answer is YES.
Input: 83 3 27 11 34 2 30 1 151000100004 4 3123 413 24 233123 42 0 21622 1 1 53427 763 22 601011111101001013 3 22 1 11 1 21 5 40101010103 3 22 1 11 1 21 5 30101010103 4 346 49 50 119 30 23 1230 25 1 461000010000105 4 439 30 0 1722 42 30 1310 44 46 3512 19 9 3921 0 45 40100011110011011111002 2 23 46 700002 2 20 02 00100 | Output: YES NO YES NO YES NO YES YES
Medium
5
1,364
687
299
19
37
C
37C
C. Old Berland Language
1,900
data structures; greedy; trees
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.
The first line contains one integer N (1 ≤ N ≤ 1000) — the number of words in Old Berland language. The second line contains N space-separated integers — the lengths of these words. All the lengths are natural numbers not exceeding 1000.
If there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next N lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.
Input: 31 2 3 | Output: YES010110
Hard
3
632
237
253
0
775
A
775A
A. University Schedule
2,900
*special
In this problem your task is to come up with a week schedule of classes in university for professors and student groups. Consider that there are 6 educational days in week and maximum number of classes per educational day is 7 (classes numerated from 1 to 7 for each educational day).It is known that in university n students study, m professors work and there are a classrooms for conducting classes. Also you have two-dimensional array with n × m size which contains the following information. The number which stays in i-th row and j-th column equals to the number of classes which professor j must conduct with the group i in a single week. The schedule which you output must satisfy to array described above.There are several other conditions for schedule. Single professor can not conduct more than one class. Similarly, single student group can not be on more than one class at the same time.Let define a fatigue function for professors and student groups. Call this function f.To single professor fatigue calculated in the following way. Let look on classes which this professor must conduct in each of the 6-th educational days. Let x be the number of class which professor will firstly conduct in day i and let y — the last class for this professor. Then the value (2 + y - x + 1)·(2 + y - x + 1) must be added to professor's fatigue. If professor has no classes in day i, nothing is added to professor's fatigue. For single student group fatigue is calculated similarly. Lets look at classes of this group in each of the 6 educational days. Let x be the number of first class for this group on day i and let y — the last class for this group. Then the value (2 + y - x + 1)·(2 + y - x + 1) must be added to this group's fatigue. If student group has no classes in day i, nothing is added to group's fatigue.So the value of function f equals to total {fatigue} for all n student groups and for all m professors.Your task is to come up with such a schedule which minimizes the value of function f.Jury prepared some solution of this problem. For each test you will get a certain number of points. It equals to result of division of the value of function f from the jury solution by the value of function f for schedule which your program output (i. e. the smaller value of {fatigue} function your program find the more points you will get), multiplied by 100. In the other words if the value of f for jury solution equals to p and for your solution — to q, you will get 100·p / q points (note, that the number of points is a real number). The points will be added together for all tests. The goal is to score as many points as possible.
The first line contains three integers n, m and a (1 ≤ n, m, a ≤ 60) — the number of groups, the number of professors and the number of classrooms.Each of the following n lines contains m integers from 0 to 24 — j-th number in i-th line equals to the number of classes with the professor j must conduct with the i-th student group.It is guaranteed that the number of classes in week for each professor and for each student group does not exceed 24. Also guaranteed that the total number of classes in week does not exceed 75% from a maximum number of classes which can be conducted based on the number of classrooms. For all tests there is at least one schedule satisfying all described conditions.
In the first line print the minimized value of function f.After that print blank line.After that print the schedule for each student group in increasing order of group number. For each student group print 7 lines. Each line must contains 6 numbers. Let the number at i-th line and j-th column equals to x. If in j-th day current group has no class number i, x must be equals to zero. Otherwise x must be equals to the number of professor who will conduct the corresponding class with the corresponding student group. The number of classes which will be conducted simultaneously must not exceeds the number of classrooms a.Separate the description of the schedules for groups with a blank line.
During the main part of the competition (one week) you solution will be judged on 100 preliminary tests. The first 10 preliminary tests are available for download by a link http://assets.codeforces.com/files/vk/vkcup-2017-wr2-materials-v1.tar.gz.After the end of the contest (i.e., a week after its start) the last solution you sent (having positive score) will be chosen to be launched on the extended final tests.
Input: 3 3 11 0 00 1 00 0 1 | Output: 541 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Master
1
2,645
698
693
7
535
A
535A
A. Tavas and Nafas
1,000
brute force; implementation
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words. He ate coffee mix without water again, so right now he's really messed up and can't think.Your task is to help him by telling him what to type.
The first and only line of input contains an integer s (0 ≤ s ≤ 99), Tavas's score.
In the first and only line of output, print a single string consisting only from English lowercase letters and hyphens ('-'). Do not use spaces.
You can find all you need to know about English numerals in http://en.wikipedia.org/wiki/English_numerals .
Input: 6 | Output: six
Beginner
2
435
83
144
5
482
E
482E
E. ELCA
3,200
data structures; trees
You have a root tree containing n vertexes. Let's number the tree vertexes with integers from 1 to n. The tree root is in the vertex 1.Each vertex (except fot the tree root) v has a direct ancestor pv. Also each vertex v has its integer value sv. Your task is to perform following queries: P v u (u ≠ v). If u isn't in subtree of v, you must perform the assignment pv = u. Otherwise you must perform assignment pu = v. Note that after this query the graph continues to be a tree consisting of n vertexes. V v t. Perform assignment sv = t. Your task is following. Before starting performing queries and after each query you have to calculate expected value written on the lowest common ancestor of two equiprobably selected vertices i and j. Here lowest common ancestor of i and j is the deepest vertex that lies on the both of the path from the root to vertex i and the path from the root to vertex j. Please note that the vertices i and j can be the same (in this case their lowest common ancestor coincides with them).
The first line of the input contains integer n (2 ≤ n ≤ 5·104) — the number of the tree vertexes. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the description of the tree edges. It is guaranteed that those numbers form a tree.The third line contains n integers — s1, s2, ... sn (0 ≤ si ≤ 106) — the values written on each vertex of the tree.The next line contains integer q (1 ≤ q ≤ 5·104) — the number of queries. Each of the following q lines contains the description of the query in the format described in the statement. It is guaranteed that query arguments u and v lie between 1 and n. It is guaranteed that argument t in the queries of type V meets limits 0 ≤ t ≤ 106.
Print q + 1 number — the corresponding expected values. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
Note that in the query P v u if u lies in subtree of v you must perform assignment pu = v. An example of such case is the last query in the sample.
Input: 51 2 2 11 2 3 4 55P 3 4P 4 5V 2 3P 5 2P 1 4 | Output: 1.6400000001.8000000002.2800000002.3200000002.8000000001.840000000
Master
2
1,020
700
151
4
920
B
920B
B. Tea Queue
1,200
implementation
Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).
The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000).Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students.Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea.It is guaranteed that for every condition li - 1 ≤ li holds.The sum of n over all test cases doesn't exceed 1000.Note that in hacks you have to set t = 1.
For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.
The example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.
Input: 221 31 431 51 12 3 | Output: 1 2 1 0 2
Easy
1
1,047
568
140
9
323
C
323C
C. Two permutations
2,400
data structures
You are given two permutations p and q, consisting of n elements, and m queries of the form: l1, r1, l2, r2 (l1 ≤ r1; l2 ≤ r2). The response for the query is the number of such integers from 1 to n, that their position in the first permutation is in segment [l1, r1] (borders included), and position in the second permutation is in segment [l2, r2] (borders included too).A permutation of n elements is the sequence of n distinct integers, each not less than 1 and not greater than n.Position of number v (1 ≤ v ≤ n) in permutation g1, g2, ..., gn is such number i, that gi = v.
The first line contains one integer n (1 ≤ n ≤ 106), the number of elements in both permutations. The following line contains n integers, separated with spaces: p1, p2, ..., pn (1 ≤ pi ≤ n). These are elements of the first permutation. The next line contains the second permutation q1, q2, ..., qn in same format.The following line contains an integer m (1 ≤ m ≤ 2·105), that is the number of queries.The following m lines contain descriptions of queries one in a line. The description of the i-th query consists of four integers: a, b, c, d (1 ≤ a, b, c, d ≤ n). Query parameters l1, r1, l2, r2 are obtained from the numbers a, b, c, d using the following algorithm: Introduce variable x. If it is the first query, then the variable equals 0, else it equals the response for the previous query plus one. Introduce function f(z) = ((z - 1 + x) mod n) + 1. Suppose l1 = min(f(a), f(b)), r1 = max(f(a), f(b)), l2 = min(f(c), f(d)), r2 = max(f(c), f(d)).
Print a response for each query in a separate line.
Input: 33 1 23 2 111 2 3 3 | Output: 1
Expert
1
578
951
51
3
1,344
D
1344D
D. Résumé Review
2,700
binary search; greedy; math
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)You have completed many programming projects. In fact, there are exactly \(n\) types of programming projects, and you have completed \(a_i\) projects of type \(i\). Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:$$$\( f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). \)\(Here, \)b_i\( denotes the number of projects of type \)i\( you include in your résumé. Of course, you cannot include more projects than you have completed, so you require \)0\le b_i \le a_i\( for all \)i\(.Your résumé only has enough room for \)k\( projects, and you will absolutely not be hired if your résumé has empty space, so you require \)\sum\limits_{i=1}^n b_i=k\(.Find values for \)b_1,\ldots, b_n\( that maximize the value of \)f(b_1,\ldots,b_n)$$$ while satisfying the above two constraints.
The first line contains two integers \(n\) and \(k\) (\(1\le n\le 10^5\), \(1\le k\le \sum\limits_{i=1}^n a_i\)) — the number of types of programming projects and the résumé size, respectively.The next line contains \(n\) integers \(a_1,\ldots,a_n\) (\(1\le a_i\le 10^9\)) — \(a_i\) is equal to the number of completed projects of type \(i\).
In a single line, output \(n\) integers \(b_1,\ldots, b_n\) that achieve the maximum value of \(f(b_1,\ldots,b_n)\), while satisfying the requirements \(0\le b_i\le a_i\) and \(\sum\limits_{i=1}^n b_i=k\). If there are multiple solutions, output any.Note that you do not have to output the value \(f(b_1,\ldots,b_n)\).
For the first test, the optimal answer is \(f=-269\). Note that a larger \(f\) value is possible if we ignored the constraint \(\sum\limits_{i=1}^n b_i=k\).For the second test, the optimal answer is \(f=9\).
Input: 10 32 1 2 3 4 5 5 5 5 5 5 | Output: 1 2 3 3 3 4 4 4 4 4
Master
3
1,343
342
318
13
731
E
731E
E. Funny Game
2,200
dp; games
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall.The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right.
Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3.
Input: 32 4 8 | Output: 14
Hard
2
1,297
258
132
7
2,034
C
2034C
C. Trapped in the Witch's Labyrinth
1,400
constructive algorithms; dfs and similar; graphs; implementation
In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of \(n\) rows and \(m\) columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell. If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.
The first line of the input contains an integer \(t\) (\(1 \leq t \leq 10^4\)), the number of test cases.For each test case: The first line contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 1000\)), representing the number of rows and columns in the maze. Each of the next \(n\) lines contains a string of \(m\) characters representing the directions in the maze. Each character is one of the following: U (up) D (down) L (left) R (right) ? (unspecified direction) It's guaranteed that the sum of \(n \cdot m\) over all test cases is at most \(10^6\).
For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.
In the first test case, all of the cells will be good no matter what you do.In the second test case, if you assign the ?s like the picture below, all of the cells will be bad: In the third test case, if you assign the ?s like the picture below, you will have \(5\) bad cells (red-shaded cells):
Input: 33 3UUUL?RDDD2 3??????3 3?U?R?LRDL | Output: 0 6 5
Easy
4
906
559
185
20
378
A
378A
A. Playing with Dice
800
brute force
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.The first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
The single line contains two integers a and b (1 ≤ a, b ≤ 6) — the numbers written on the paper by the first and second player, correspondingly.
Print three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly.
The dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct.You can assume that number a is closer to number x than number b, if |a - x| < |b - x|.
Input: 2 5 | Output: 3 0 3
Beginner
1
423
144
160
3
585
C
585C
C. Alice, Bob, Oranges and Apples
2,400
number theory
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Input: 1 4 | Output: 3B
Expert
1
1,040
148
824
5
1,368
G
1368G
G. Shifting Dominoes
3,200
data structures; geometry; graphs; trees
Bill likes to play with dominoes. He took an \(n \times m\) board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and no two dominoes cover the same cell twice).After that Bill decided to play with the covered board and share some photos of it on social media. First, he removes exactly one domino from the board, freeing two of the cells. Next, he moves dominoes around. A domino can only be moved along the line parallel to its longer side. A move in the chosen direction is possible if the next cell in this direction is currently free. Bill doesn't want to lose track of what the original tiling looks like, so he makes sure that at any point each domino shares at least one cell with its original position.After removing a domino and making several (possibly, zero) moves Bill takes a photo of the board and posts it. However, with the amount of filters Bill is using, domino borders are not visible, so only the two free cells of the board can be identified. When the photo is posted, Bill reverts the board to its original state and starts the process again.Bill wants to post as many photos as possible, but he will not post any photo twice. How many distinct photos can he take? Recall that photos are different if the pairs of free cells in the photos are different.
The first line contains two positive integers \(n\) and \(m\) (\(nm \leq 2 \cdot 10^5\)) — height and width of the board respectively.The next \(n\) lines describe the tiling of the board, row by row from top to bottom. Each of these lines contains \(m\) characters, describing the cells in the corresponding row left to right. Each character is one of U, D, L, or R, meaning that the cell is covered with a top, bottom, left, or right half of a domino respectively.It is guaranteed that the described tiling is valid, that is, each half-domino has a counterpart in the relevant location. In particular, since tiling is possible, the number of cells in the board is even.
Print a single integer — the number of distinct photos Bill can take.
In the first sample case, no moves are possible after removing any domino, thus there are four distinct photos.In the second sample case, four photos are possible after removing the leftmost domino by independently moving/not moving the remaining two dominoes. Two more different photos are obtained by removing one of the dominoes on the right.
Input: 2 4 UUUU DDDD | Output: 4
Master
4
1,481
671
69
13
1,267
D
1267D
D. DevOps Best Practices
2,800
constructive algorithms
Daisy is a senior software engineer at RainyDay, LLC. She has just implemented three new features in their product: the first feature makes their product work, the second one makes their product fast, and the third one makes their product correct. The company encourages at least some testing of new features, so Daisy appointed her intern Demid to write some tests for the new features.Interestingly enough, these three features pass all the tests on Demid's development server, which has index 1, but might fail the tests on some other servers.After Demid has completed this task, Daisy appointed you to deploy these three features to all \(n\) servers of your company. For every feature \(f\) and every server \(s\), Daisy told you whether she wants the feature \(f\) to be deployed on the server \(s\). If she wants it to be deployed, it must be done even if the feature \(f\) fails the tests on the server \(s\). If she does not want it to be deployed, you may not deploy it there.Your company has two important instruments for the deployment of new features to servers: Continuous Deployment (CD) and Continuous Testing (CT). CD can be established between several pairs of servers, forming a directed graph. CT can be set up on some set of servers.If CD is configured from the server \(s_1\) to the server \(s_2\) then every time \(s_1\) receives a new feature \(f\) the system starts the following deployment process of \(f\) to \(s_2\): If the feature \(f\) is already deployed on the server \(s_2\), then nothing is done. Otherwise, if CT is not set up on the server \(s_1\), then the server \(s_1\) just deploys the feature \(f\) to the server \(s_2\) without any testing. Otherwise, the server \(s_1\) runs tests for the feature \(f\). If the tests fail on the server \(s_1\), nothing is done. If the tests pass, then the server \(s_1\) deploys the feature \(f\) to the server \(s_2\). You are to configure the CD/CT system, and after that Demid will deploy all three features on his development server. Your CD/CT system must deploy each feature exactly to the set of servers that Daisy wants.Your company does not have a lot of computing resources, so you can establish CD from one server to another at most \(264\) times.
The first line contains integer \(n\) (\(2 \le n \le 256\)) — the number of servers in your company.Next \(n\) lines contain three integers each. The \(j\)-th integer in the \(i\)-th line is \(1\) if Daisy wants the \(j\)-th feature to be deployed to the \(i\)-th server, or \(0\) otherwise.Next \(n\) lines contain three integers each. The \(j\)-th integer in the \(i\)-th line is \(1\) if tests pass for the \(j\)-th feature on the \(i\)-th server, or \(0\) otherwise.Demid's development server has index \(1\). It is guaranteed that Daisy wants all three features to be deployed to the server number 1, and all three features pass their tests on the server number 1.
If it is impossible to configure CD/CT system with CD being set up between at most \(264\) pairs of servers, then output the single line ""Impossible"".Otherwise, the first line of the output must contain the line ""Possible"".Next line must contain \(n\) space-separated integers — the configuration of CT. The \(i\)-th integer should be \(1\) if you set up CT on the \(i\)-th server, or \(0\) otherwise.Next line must contain the integer \(m\) (\(0 \le m \le 264\)) — the number of CD pairs you want to set up.Each of the next \(m\) lines must describe CD configuration, each line with two integers \(s_i\) and \(t_i\) (\(1 \le s_i, t_i \le n\); \(s_i \ne t_i\)), establishing automated deployment of new features from the server \(s_i\) to the server \(t_i\).
CD/CT system for the first sample test is shown below.
Input: 3 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 0 1 | Output: Possible 1 1 1 2 3 2 1 3
Master
1
2,235
669
762
12
831
C
831C
C. Jury Marks
1,700
brute force; constructive algorithms
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≤ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
The first line contains two integers k and n (1 ≤ n ≤ k ≤ 2 000) — the number of jury members and the number of scores Polycarp remembers.The second line contains k integers a1, a2, ..., ak ( - 2 000 ≤ ai ≤ 2 000) — jury's marks in chronological order.The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 ≤ bj ≤ 4 000 000) — the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.
Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print ""0"" (without quotes).
The answer for the first example is 3 because initially the participant could have - 10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4 002 000.
Input: 4 1-5 5 0 2010 | Output: 3
Medium
2
865
459
196
8
1,527
A
1527A
A. And Then There Were K
800
bitmasks
Given an integer \(n\), find the maximum value of integer \(k\) such that the following condition holds: \(n\) & (\(n-1\)) & (\(n-2\)) & (\(n-3\)) & ... (\(k\)) = \(0\) where & denotes the bitwise AND operation.
The first line contains a single integer \(t\) (\(1 \le t \le 3 \cdot 10^4\)). Then \(t\) test cases follow.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^9\)).
For each test case, output a single integer — the required integer \(k\).
In the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0. \(5 \, \& \, 4 \neq 0\), \(5 \, \& \, 4 \, \& \, 3 = 0\). Hence, 3 is the answer.
Input: 3 2 5 17 | Output: 1 3 15
Beginner
1
211
196
73
15
178
A1
178A1
A1. Educational Game
1,000
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1 ≤ i ≤ n) such that ai > 0 and an integer t (t ≥ 0) such that i + 2t ≤ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≤ k < n).
The first input line contains a single integer n. The second line contains n integers ai (0 ≤ ai ≤ 104), separated by single spaces.The input limitations for getting 20 points are: 1 ≤ n ≤ 300 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105
Print exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.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.
Input: 41 0 1 2 | Output: 113
Beginner
0
1,085
316
314
1
1,406
C
1406C
C. Link Cut Centroids
1,700
constructive algorithms; dfs and similar; graphs; trees
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.For example, the centroid of the following tree is \(2\), because when you cut it, the size of the largest connected component of the remaining graph is \(2\) and it can't be smaller. However, in some trees, there might be more than one centroid, for example: Both vertex \(1\) and vertex \(2\) are centroids because the size of the largest connected component is \(3\) after cutting each of them.Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.
The input consists of multiple test cases. The first line contains an 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 an integer \(n\) (\(3\leq n\leq 10^5\)) — the number of vertices.Each of the next \(n-1\) lines contains two integers \(x, y\) (\(1\leq x,y\leq n\)). It means, that there exists an edge connecting vertices \(x\) and \(y\).It's guaranteed that the given graph is a tree.It's guaranteed that the sum of \(n\) for all test cases does not exceed \(10^5\).
For each test case, print two lines.In the first line print two integers \(x_1, y_1\) (\(1 \leq x_1, y_1 \leq n\)), which means you cut the edge between vertices \(x_1\) and \(y_1\). There should exist edge connecting vertices \(x_1\) and \(y_1\).In the second line print two integers \(x_2, y_2\) (\(1 \leq x_2, y_2 \leq n\)), which means you add the edge between vertices \(x_2\) and \(y_2\).The graph after these two operations should be a tree.If there are multiple solutions you can print any.
Note that you can add the same edge that you cut.In the first test case, after cutting and adding the same edge, the vertex \(2\) is still the only centroid.In the second test case, the vertex \(2\) becomes the only centroid after cutting the edge between vertices \(1\) and \(3\) and adding the edge between vertices \(2\) and \(3\).
Input: 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 | Output: 1 2 1 2 1 3 2 3
Medium
4
1,136
570
498
14
1,174
E
1174E
E. Ehab and the Expected GCD Problem
2,500
combinatorics; dp; math; number theory
Let's define a function \(f(p)\) on a permutation \(p\) as follows. Let \(g_i\) be the greatest common divisor (GCD) of elements \(p_1\), \(p_2\), ..., \(p_i\) (in other words, it is the GCD of the prefix of length \(i\)). Then \(f(p)\) is the number of distinct elements among \(g_1\), \(g_2\), ..., \(g_n\).Let \(f_{max}(n)\) be the maximum value of \(f(p)\) among all permutations \(p\) of integers \(1\), \(2\), ..., \(n\).Given an integers \(n\), count the number of permutations \(p\) of integers \(1\), \(2\), ..., \(n\), such that \(f(p)\) is equal to \(f_{max}(n)\). Since the answer may be large, print the remainder of its division by \(1000\,000\,007 = 10^9 + 7\).
The only line contains the integer \(n\) (\(2 \le n \le 10^6\)) — the length of the permutations.
The only line should contain your answer modulo \(10^9+7\).
Consider the second example: these are the permutations of length \(3\): \([1,2,3]\), \(f(p)=1\). \([1,3,2]\), \(f(p)=1\). \([2,1,3]\), \(f(p)=2\). \([2,3,1]\), \(f(p)=2\). \([3,1,2]\), \(f(p)=2\). \([3,2,1]\), \(f(p)=2\). The maximum value \(f_{max}(3) = 2\), and there are \(4\) permutations \(p\) such that \(f(p)=2\).
Input: 2 | Output: 1
Expert
4
676
97
59
11
724
G
724G
G. Xor-matic Number of the Graph
2,600
bitmasks; graphs; math; number theory; trees
You are given an undirected graph, constisting of n vertices and m edges. Each edge of the graph has some non-negative integer written on it.Let's call a triple (u, v, s) interesting, if 1 ≤ u < v ≤ n and there is a path (possibly non-simple, i.e. it can visit the same vertices and edges multiple times) between vertices u and v such that xor of all numbers written on the edges of this path is equal to s. When we compute the value s for some path, each edge is counted in xor as many times, as it appear on this path. It's not hard to prove that there are finite number of such triples.Calculate the sum over modulo 109 + 7 of the values of s over all interesting triples.
The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 0 ≤ m ≤ 200 000) — numbers of vertices and edges in the given graph.The follow m lines contain three integers ui, vi and ti (1 ≤ ui, vi ≤ n, 0 ≤ ti ≤ 1018, ui ≠ vi) — vertices connected by the edge and integer written on it. It is guaranteed that graph doesn't contain self-loops and multiple edges.
Print the single integer, equal to the described sum over modulo 109 + 7.
In the first example the are 6 interesting triples: (1, 2, 1) (1, 3, 2) (1, 4, 3) (2, 3, 3) (2, 4, 2) (3, 4, 1) The sum is equal to 1 + 2 + 3 + 3 + 2 + 1 = 12.In the second example the are 12 interesting triples: (1, 2, 1) (2, 3, 2) (1, 3, 3) (3, 4, 4) (2, 4, 6) (1, 4, 7) (1, 4, 8) (2, 4, 9) (3, 4, 11) (1, 3, 12) (2, 3, 13) (1, 2, 14) The sum is equal to 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 + 11 + 12 + 13 + 14 = 90.
Input: 4 41 2 11 3 22 3 33 4 1 | Output: 12
Expert
5
675
375
73
7
1,115
G3
1115G3
G3. Palindrome checker oracle
1,600
*special
Implement a quantum oracle on \(N\) qubits which checks whether the vector \(\vec{x}\) is a palindrome (i.e., implements the function \(f(\vec{x}) = 1\) if \(\vec{x}\) is a palindrome, and 0 otherwise).You have to implement an operation which takes the following inputs: an array of \(N\) (\(1 \le N \le 8\)) qubits \(x\) in an arbitrary state (input register), a qubit \(y\) in an arbitrary state (output qubit),and performs a transformation \(|x\rangle|y\rangle \rightarrow |x\rangle|y \oplus f(x)\rangle\). The operation doesn't have an output; its ""output"" is the state in which it leaves the qubits.Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Primitive; open Microsoft.Quantum.Canon; operation Solve (x : Qubit[], y : Qubit) : Unit { body (...) { // your code here } adjoint auto; }}
Medium
1
836
0
0
11
611
A
611A
A. New Year and Days
900
implementation
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month.Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.
The only line of the input is in one of the following two formats: ""x of week"" where x (1 ≤ x ≤ 7) denotes the day of the week. The 1-st day is Monday and the 7-th one is Sunday. ""x of month"" where x (1 ≤ x ≤ 31) denotes the day of the month.
Print one integer — the number of candies Limak will save in the year 2016.
Polar bears use the Gregorian calendar. It is the most common calendar and you likely use it too. You can read about it on Wikipedia if you want to – https://en.wikipedia.org/wiki/Gregorian_calendar. The week starts with Monday.In the first sample Limak wants to save one candy on each Thursday (the 4-th day of the week). There are 52 Thursdays in the 2016. Thus, he will save 52 candies in total.In the second sample Limak wants to save one candy on the 30-th day of each month. There is the 30-th day in exactly 11 months in the 2016 — all months but February. It means that Limak will save 11 candies in total.
Input: 4 of week | Output: 52
Beginner
1
604
246
75
6
1,195
D1
1195D1
D1. Submarine in the Rybinsk Sea (easy edition)
1,500
combinatorics; math; number theory
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers \(a_1, a_2, \dots, a_n\). Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers \(f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)\), where \(a_1 \dots a_p\) and \(b_1 \dots b_q\) are digits of two integers written in the decimal notation without leading zeros.In other words, the function \(f(x, y)\) alternately shuffles the digits of the numbers \(x\) and \(y\) by writing them from the lowest digits to the older ones, starting with the number \(y\). The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$\(f(1111, 2222) = 12121212\)\( \)\(f(7777, 888) = 7787878\)\( \)\(f(33, 44444) = 4443434\)\( \)\(f(555, 6) = 5556\)\( \)\(f(111, 2222) = 2121212\)\(Formally, if \)p \ge q\( then \)f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q\(; if \)p < q\( then \)f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q\(. Mishanya gives you an array consisting of \)n\( integers \)a_i\(. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate \)\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)\( modulo \)998\,244\,353$$$.
The first line of the input contains a single integer \(n\) (\(1 \le n \le 100\,000\)) — the number of elements in the array. The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)) — the elements of the array. All numbers \(a_1, a_2, \dots, a_n\) are of equal length (that is, they consist of the same number of digits).
Print the answer modulo \(998\,244\,353\).
Input: 3 12 33 45 | Output: 26730
Medium
3
2,099
368
42
11
1,016
C
1016C
C. Vasya And The Mushrooms
1,800
dp; implementation
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.
The first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade.The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade.The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.
Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.
In the first test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.
Input: 31 2 36 5 4 | Output: 70
Medium
2
973
334
185
10
2,081
A
2081A
A. Math Division
1,800
bitmasks; dp; math; probabilities
Ecrade has an integer \(x\). He will show you this number in the form of a binary number of length \(n\).There are two kinds of operations. Replace \(x\) with \(\left\lfloor \dfrac{x}{2}\right\rfloor\), where \(\left\lfloor \dfrac{x}{2}\right\rfloor\) is the greatest integer \(\le \dfrac{x}{2}\). Replace \(x\) with \(\left\lceil \dfrac{x}{2}\right\rceil\), where \(\left\lceil \dfrac{x}{2}\right\rceil\) is the smallest integer \(\ge \dfrac{x}{2}\). Ecrade will perform several operations until \(x\) becomes \(1\). Each time, he will independently choose to perform either the first operation or the second operation with probability \(\frac{1}{2}\).Ecrade wants to know the expected number of operations he will perform to make \(x\) equal to \(1\), modulo \(10^9 + 7\). However, it seems a little difficult, so please help him!
The first line contains a single integer \(t\) (\(1 \le t \le 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\) (\(1 \le n \le 10^5\)) — the length of \(x\) in binary representation.The second line of each test case contains a binary string of length \(n\): the number \(x\) in the binary representation, presented from the most significant bit to the least significant bit. It is guaranteed that the most significant bit of \(x\) is \(1\).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(10^5\).
For each test case, print a single integer representing the expected number of operations Ecrade will perform to make \(x\) equal to \(1\), modulo \(10^9+7\).Formally, let \(M = 10^9+7\). It can be shown that the exact answer can be expressed as an irreducible fraction \(\frac{p}{q}\), where \(p\) and \(q\) are integers and \(q \not \equiv 0 \pmod{M}\). Output the integer equal to \(p \cdot q^{-1} \bmod M\). In other words, output such an integer \(x\) that \(0 \le x < M\) and \(x \cdot q \equiv p \pmod{M}\).
For simplicity, we call the first operation \(\text{OPER 1}\) and the second operation \(\text{OPER 2}\).In the first test case, \(x=6\), and there are six possible series of operations: \(6 \xrightarrow{\text{OPER 1}} 3 \xrightarrow{\text{OPER 1}} 1\), the probability is \(\dfrac{1}{4}\). \(6 \xrightarrow{\text{OPER 1}} 3 \xrightarrow{\text{OPER 2}} 2 \xrightarrow{\text{OPER 1}} 1\), the probability is \(\dfrac{1}{8}\). \(6 \xrightarrow{\text{OPER 1}} 3 \xrightarrow{\text{OPER 2}} 2 \xrightarrow{\text{OPER 2}} 1\), the probability is \(\dfrac{1}{8}\). \(6 \xrightarrow{\text{OPER 2}} 3 \xrightarrow{\text{OPER 1}} 1\), the probability is \(\dfrac{1}{4}\). \(6 \xrightarrow{\text{OPER 2}} 3 \xrightarrow{\text{OPER 2}} 2 \xrightarrow{\text{OPER 1}} 1\), the probability is \(\dfrac{1}{8}\). \(6 \xrightarrow{\text{OPER 2}} 3 \xrightarrow{\text{OPER 2}} 2 \xrightarrow{\text{OPER 2}} 1\), the probability is \(\dfrac{1}{8}\). Thus, the expected number of operations is \(2 \cdot \dfrac{1}{4} + 3 \cdot \dfrac{1}{8} + 3 \cdot \dfrac{1}{8} + 2 \cdot \dfrac{1}{4} + 3 \cdot \dfrac{1}{8} + 3 \cdot \dfrac{1}{8} = \dfrac{5}{2} \equiv 500\,000\,006 \pmod{10^9 + 7}\).
Input: 331103100101101001011 | Output: 500000006 2 193359386
Medium
4
832
619
514
20
1,968
A
1968A
A. Maximize?
800
brute force; math; number theory
You are given an integer \(x\). Your task is to find any integer \(y\) \((1\le y<x)\) such that \(\gcd(x,y)+y\) is maximum possible.Note that if there is more than one \(y\) which satisfies the statement, you are allowed to find any.\(\gcd(a,b)\) is the Greatest Common Divisor of \(a\) and \(b\). For example, \(\gcd(6,4)=2\).
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.Each of the following \(t\) lines contains a single integer \(x\) (\(2 \le x \le 1000\)).
For each test case, output any \(y\) (\(1 \le y < x\)), which satisfies the statement.
Input: 710721100210006 | Output: 5 6 18 98 1 750 3
Beginner
3
327
186
86
19
26
E
26E
E. Multithreading
2,400
constructive algorithms
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1end repeatHere y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value.
In the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000).
On the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note.
For simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers.
Input: 1 1011 | Output: No
Expert
1
724
195
333
0
1,616
B
1616B
B. Mirror in the String
1,100
greedy; strings
You have a string \(s_1 s_2 \ldots s_n\) and you stand on the left of the string looking right. You want to choose an index \(k\) (\(1 \le k \le n\)) and place a mirror after the \(k\)-th letter, so that what you see is \(s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1\). What is the lexicographically smallest string you can see?A string \(a\) is lexicographically smaller than a string \(b\) if and only if one of the following holds: \(a\) is a prefix of \(b\), but \(a \ne b\); in the first position where \(a\) and \(b\) differ, the string \(a\) has a letter that appears earlier in the alphabet than the corresponding letter in \(b\).
The first line of input contains one integer \(t\) (\(1 \leq t \leq 10\,000\)): the number of test cases.The next \(t\) lines contain the description of the test cases, two lines per a test case.In the first line you are given one integer \(n\) (\(1 \leq n \leq 10^5\)): the length of the string.The second line contains the string \(s\) consisting of \(n\) lowercase English characters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case print the lexicographically smallest string you can see.
In the first test case choose \(k = 1\) to obtain ""cc"".In the second test case choose \(k = 3\) to obtain ""cbaabc"".In the third test case choose \(k = 1\) to obtain ""aa"".In the fourth test case choose \(k = 1\) to obtain ""bb"".
Input: 4 10 codeforces 9 cbacbacba 3 aaa 4 bbaa | Output: cc cbaabc aa bb
Easy
2
637
471
75
16
1,331
A
1331A
A. Is it rated?
0
*special
Beginner
1
0
0
0
13
995
B
995B
B. Suit and Tie
1,400
greedy; implementation; math
Allen is hosting a formal dinner party. \(2n\) people come to the event in \(n\) pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The \(2n\) people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.
The first line contains a single integer \(n\) (\(1 \le n \le 100\)), the number of pairs of people.The second line contains \(2n\) integers \(a_1, a_2, \dots, a_{2n}\). For each \(i\) with \(1 \le i \le n\), \(i\) appears exactly twice. If \(a_j = a_k = i\), that means that the \(j\)-th and \(k\)-th people in the line form a couple.
Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.
In the first sample case, we can transform \(1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4\) in two steps. Note that the sequence \(1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4\) also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need \(0\) swaps.
Input: 41 1 2 3 3 2 4 4 | Output: 2
Easy
3
499
335
150
9
1,348
C
1348C
C. Phoenix and Distribution
1,600
constructive algorithms; greedy; sortings; strings
Phoenix has a string \(s\) consisting of lowercase Latin letters. He wants to distribute all the letters of his string into \(k\) non-empty strings \(a_1, a_2, \dots, a_k\) such that every letter of \(s\) goes to exactly one of the strings \(a_i\). The strings \(a_i\) do not need to be substrings of \(s\). Phoenix can distribute letters of \(s\) and rearrange the letters within each string \(a_i\) however he wants.For example, if \(s = \) baba and \(k=2\), Phoenix may distribute the letters of his string in many ways, such as: ba and ba a and abb ab and ab aa and bb But these ways are invalid: baa and ba b and ba baba and empty string (\(a_i\) should be non-empty) Phoenix wants to distribute the letters of his string \(s\) into \(k\) strings \(a_1, a_2, \dots, a_k\) to minimize the lexicographically maximum string among them, i. e. minimize \(max(a_1, a_2, \dots, a_k)\). Help him find the optimal distribution and print the minimal possible value of \(max(a_1, a_2, \dots, a_k)\).String \(x\) is lexicographically less than string \(y\) if either \(x\) is a prefix of \(y\) and \(x \ne y\), or there exists an index \(i\) (\(1 \le i \le min(|x|, |y|))\) such that \(x_i\) < \(y_i\) and for every \(j\) \((1 \le j < i)\) \(x_j = y_j\). Here \(|x|\) denotes the length of the string \(x\).
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases. Each test case consists of two lines.The first line of each test case consists of two integers \(n\) and \(k\) (\(1 \le k \le n \le 10^5\)) — the length of string \(s\) and the number of non-empty strings, into which Phoenix wants to distribute letters of \(s\), respectively.The second line of each test case contains a string \(s\) of length \(n\) consisting only of lowercase Latin letters.It is guaranteed that the sum of \(n\) over all test cases is \(\le 10^5\).
Print \(t\) answers — one per test case. The \(i\)-th answer should be the minimal possible value of \(max(a_1, a_2, \dots, a_k)\) in the \(i\)-th test case.
In the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.
Input: 6 4 2 baba 5 2 baacb 5 3 baacb 5 3 aaaaa 6 4 aaxxzz 7 1 phoenix | Output: ab abbc b aa x ehinopx
Medium
4
1,300
603
157
13
1,938
E
1938E
2,200
Hard
0
0
0
0
19