contest_id
int32 1
2.13k
| index
stringclasses 62
values | problem_id
stringlengths 2
6
| title
stringlengths 0
67
| rating
int32 0
3.5k
| tags
stringlengths 0
139
| statement
stringlengths 0
6.96k
| input_spec
stringlengths 0
2.32k
| output_spec
stringlengths 0
1.52k
| note
stringlengths 0
5.06k
| sample_tests
stringlengths 0
1.02k
| difficulty_category
stringclasses 6
values | tag_count
int8 0
11
| statement_length
int32 0
6.96k
| input_spec_length
int16 0
2.32k
| output_spec_length
int16 0
1.52k
| contest_year
int16 0
21
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,349 |
F2
|
1349F2
|
F2. Slime and Sequences (Hard Version)
| 3,500 |
dp; fft; math
|
Note that the only differences between easy and hard versions are the constraints on \(n\) and the time limit. You can make hacks only if all versions are solved.Slime is interested in sequences. He defined good positive integer sequences \(p\) of length \(n\) as follows: For each \(k>1\) that presents in \(p\), there should be at least one pair of indices \(i,j\), such that \(1 \leq i < j \leq n\), \(p_i = k - 1\) and \(p_j = k\).For the given integer \(n\), the set of all good sequences of length \(n\) is \(s_n\). For the fixed integer \(k\) and the sequence \(p\), let \(f_p(k)\) be the number of times that \(k\) appears in \(p\). For each \(k\) from \(1\) to \(n\), Slime wants to know the following value:$$$\(\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353\)$$$
|
The first line contains one integer \(n\ (1\le n\le 100\,000)\).
|
Print \(n\) integers, the \(i\)-th of them should be equal to \(\left(\sum_{p\in s_n} f_p(i)\right)\ \textrm{mod}\ 998\,244\,353\).
|
In the first example, \(s=\{[1,1],[1,2]\}\).In the second example, \(s=\{[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,2],[1,2,3]\}\).In the third example, \(s=\{[1]\}\).
|
Input: 2 | Output: 3 1
|
Master
| 3 | 791 | 64 | 131 | 13 |
1,333 |
C
|
1333C
|
C. Eugene and an array
| 1,700 |
binary search; data structures; implementation; two pointers
|
Eugene likes working with arrays. And today he needs your help in solving one challenging task.An array \(c\) is a subarray of an array \(b\) if \(c\) can be obtained from \(b\) by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array \([-1, 2, -3]\) is good, as all arrays \([-1]\), \([-1, 2]\), \([-1, 2, -3]\), \([2]\), \([2, -3]\), \([-3]\) have nonzero sums of elements. However, array \([-1, 2, -1, -3]\) isn't good, as his subarray \([-1, 2, -1]\) has sum of elements equal to \(0\).Help Eugene to calculate the number of nonempty good subarrays of a given array \(a\).
|
The first line of the input contains a single integer \(n\) (\(1 \le n \le 2 \times 10^5\)) — the length of array \(a\).The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \le a_i \le 10^9\)) — the elements of \(a\).
|
Output a single integer — the number of good subarrays of \(a\).
|
In the first sample, the following subarrays are good: \([1]\), \([1, 2]\), \([2]\), \([2, -3]\), \([-3]\). However, the subarray \([1, 2, -3]\) isn't good, as its subarray \([1, 2, -3]\) has sum of elements equal to \(0\).In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray \([41, -41, 41]\) isn't good, as its subarray \([41, -41]\) has sum of elements equal to \(0\).
|
Input: 3 1 2 -3 | Output: 5
|
Medium
| 4 | 799 | 251 | 64 | 13 |
1,345 |
B
|
1345B
|
B. Card Constructions
| 1,100 |
binary search; brute force; dp; math
|
A card pyramid of height \(1\) is constructed by resting two cards against each other. For \(h>1\), a card pyramid of height \(h\) is constructed by placing a card pyramid of height \(h-1\) onto a base. A base consists of \(h\) pyramids of height \(1\), and \(h-1\) cards on top. For example, card pyramids of heights \(1\), \(2\), and \(3\) look as follows: You start with \(n\) cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1\le t\le 1000\)) — the number of test cases. Next \(t\) lines contain descriptions of test cases.Each test case contains a single integer \(n\) (\(1\le n\le 10^9\)) — the number of cards.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^9\).
|
For each test case output a single integer — the number of pyramids you will have constructed in the end.
|
In the first test, you construct a pyramid of height \(1\) with \(2\) cards. There is \(1\) card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height \(2\), with no cards remaining.In the third test, you build one pyramid of height \(3\), with no cards remaining.In the fourth test, you build one pyramid of height \(3\) with \(9\) cards remaining. Then you build a pyramid of height \(2\) with \(2\) cards remaining. Then you build a final pyramid of height \(1\) with no cards remaining.In the fifth test, one card is not enough to build any pyramids.
|
Input: 5 3 14 15 24 1 | Output: 1 2 1 3 0
|
Easy
| 4 | 659 | 365 | 105 | 13 |
449 |
B
|
449B
|
B. Jzzhu and Cities
| 2,000 |
graphs; greedy; shortest paths
|
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
|
The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105).Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109).Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109).It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.
|
Output a single integer representing the maximum number of the train routes which can be closed.
|
Input: 5 5 31 2 12 3 21 3 33 4 41 5 53 54 55 5 | Output: 2
|
Hard
| 3 | 733 | 487 | 96 | 4 |
|
1,275 |
F
|
1275F
|
F. Шардирование постов
| 0 |
*special; binary search; interactive
|
Это интерактивная задача.Когда данных становится слишком много и они не помещаются на один сервер, их приходится шардировать. Рассмотрим систему хранения постов пользователей, которая расположена на \(S\) серверах, нумеруемых с единицы. Каждый раз когда пользователь пишет пост, ему выдается уникальный идентификатор в пределах от 1 до \(10^{18}\) и сохраняется на случайный сервер. Чем позже был создан пост, тем больше его \(id\). Иногда посты удаляются, поэтому на серверах может лежать существенно разное количество постов.Рассмотрим все неудаленные \(id\) постов пользователя и отсортируем их по возрастанию. Вам хочется узнать \(k\)-й из них. Для этого вы можете послать не более 100 дополнительных запросов. Каждый запрос имеет формат «? \(i\) \(j\)». В ответ вы получите идентификатор \(j\)-го по возрастанию поста пользователя среди хранящихся на \(i\)-м сервере. Когда вы считаете, что знаете \(k\)-й по возрастанию идентификатор, вместо запроса необходимо вывести ответ в формате «! \(id\)».
|
В примере на первом сервере хранятся посты с \(id\) 1, 3 и 10. А на втором 5 и 7. Необходимо найти третье по возрастанию число, это 5.
|
Input: 1 2 3 2 3 3 5 10 | Output: ? 1 2 ? 2 1 ? 1 3 ! 5
|
Beginner
| 3 | 1,002 | 0 | 0 | 12 |
||
366 |
A
|
366A
|
A. Dima and Guards
| 1,100 |
implementation
|
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards...There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift.In order to pass through a guardpost, one needs to bribe both guards.The shop has an unlimited amount of juice and chocolate of any price starting with 1. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend exactly n rubles on it.Help him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that!
|
The first line of the input contains integer n (1 ≤ n ≤ 105) — the money Dima wants to spend. Then follow four lines describing the guardposts. Each line contains four integers a, b, c, d (1 ≤ a, b, c, d ≤ 105) — the minimum price of the chocolate and the minimum price of the juice for the first guard and the minimum price of the chocolate and the minimum price of the juice for the second guard, correspondingly.
|
In a single line of the output print three space-separated integers: the number of the guardpost, the cost of the first present and the cost of the second present. If there is no guardpost Dima can sneak Inna through at such conditions, print -1 in a single line. The guardposts are numbered from 1 to 4 according to the order given in the input.If there are multiple solutions, you can print any of them.
|
Explanation of the first example.The only way to spend 10 rubles to buy the gifts that won't be less than the minimum prices is to buy two 5 ruble chocolates to both guards from the first guardpost.Explanation of the second example.Dima needs 12 rubles for the first guardpost, 14 for the second one, 16 for the fourth one. So the only guardpost we can sneak through is the third one. So, Dima can buy 4 ruble chocolate for the first guard and 6 ruble juice of the second guard.
|
Input: 105 6 5 66 6 7 75 8 6 69 9 9 9 | Output: 1 5 5
|
Easy
| 1 | 1,194 | 415 | 405 | 3 |
1,845 |
A
|
1845A
|
A. Forbidden Integer
| 800 |
constructive algorithms; implementation; math; number theory
|
You are given an integer \(n\), which you want to obtain. You have an unlimited supply of every integer from \(1\) to \(k\), except integer \(x\) (there are no integer \(x\) at all).You are allowed to take an arbitrary amount of each of these integers (possibly, zero). Can you make the sum of taken integers equal to \(n\)?If there are multiple answers, print any of them.
|
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) — the number of testcases.The only line of each testcase contains three integers \(n, k\) and \(x\) (\(1 \le x \le k \le n \le 100\)).
|
For each test case, in the first line, print ""YES"" or ""NO"" — whether you can take an arbitrary amount of each integer from \(1\) to \(k\), except integer \(x\), so that their sum is equal to \(n\).If you can, the second line should contain a single integer \(m\) — the total amount of taken integers. The third line should contain \(m\) integers — each of them from \(1\) to \(k\), not equal to \(x\), and their sum is \(n\).If there are multiple answers, print any of them.
|
Another possible answer for the first testcase is \([3, 3, 3, 1]\). Note that you don't have to minimize the amount of taken integers. There also exist other answers.In the second testcase, you only have an unlimited supply of integer \(2\). There is no way to get sum \(5\) using only them.In the fifth testcase, there are no integers available at all, so you can't get any positive sum.
|
Input: 510 3 25 2 14 2 17 7 36 1 1 | Output: YES 6 3 1 1 1 1 3 NO YES 2 2 2 YES 1 7 NO
|
Beginner
| 4 | 373 | 203 | 478 | 18 |
1,701 |
A
|
1701A
|
A. Grass Field
| 800 |
implementation
|
There is a field of size \(2 \times 2\). Each cell of this field can either contain grass or be empty. The value \(a_{i, j}\) is \(1\) if the cell \((i, j)\) contains grass, or \(0\) otherwise.In one move, you can choose one row and one column and cut all the grass in this row and this column. In other words, you choose the row \(x\) and the column \(y\), then you cut the grass in all cells \(a_{x, i}\) and all cells \(a_{i, y}\) for all \(i\) from \(1\) to \(2\). After you cut the grass from a cell, it becomes empty (i. e. its value is replaced by \(0\)).Your task is to find the minimum number of moves required to cut the grass in all non-empty cells of the field (i. e. make all \(a_{i, j}\) zeros).You have to answer \(t\) independent test cases.
|
The first line of the input contains one integer \(t\) (\(1 \le t \le 16\)) — the number of test cases. Then \(t\) test cases follow.The test case consists of two lines, each of these lines contains two integers. The \(j\)-th integer in the \(i\)-th row is \(a_{i, j}\). If \(a_{i, j} = 0\) then the cell \((i, j)\) is empty, and if \(a_{i, j} = 1\) the cell \((i, j)\) contains grass.
|
For each test case, print one integer — the minimum number of moves required to cut the grass in all non-empty cells of the field (i. e. make all \(a_{i, j}\) zeros) in the corresponding test case.
|
Input: 30 00 01 00 11 11 1 | Output: 0 1 2
|
Beginner
| 1 | 757 | 385 | 197 | 17 |
|
1,949 |
C
|
1949C
|
C. Annual Ants' Gathering
| 1,900 |
dfs and similar; dp; greedy; trees
|
Deep within a forest lies an ancient tree, home to \(n\) ants living in \(n\) tiny houses, indexed from \(1\) to \(n\), connected by the branches of the tree. Once a year, all the ants need to gather to watch the EUC. For this, all ants move along the \(n-1\) branches of the tree they live on to meet at the home of one ant.However, this year the ants could not agree on where to meet and need your help to gather up. You can tell all the ants currently at house \(u\) to move to house \(v\) if there is a branch directly connecting those two houses. However, the ants ignore your command if there are fewer ants gathered in house \(v\) than in house \(u\), i.e., if it would be easier for the ants from house \(v\) to move. This even holds true if no ant at all is currently in house \(v\). You can give this kind of commands as many times as you want.Is it possible for you to gather all the ants in a single house?
|
The first line contains one integer \(n\) (\(1\leq n\leq 200\,000\)) — the number of ant homes.Each of the following \(n-1\) lines contains two integers \(u\) and \(v\) (\(1\leq u, v\leq n\)) — there is a branch directly connecting the house \(u\) and house \(v\). It is guaranteed that every ant can reach the house of any other ant just by following the branches of the tree.
|
Print \(\texttt{YES}\) if it is possible to gather all the ants in a single house. Otherwise, print \(\texttt{NO}\).
|
In the first sample, you can gather all the ants at house \(3\) as follows: You tell to the ant at house \(4\) to move to house \(6\). You tell to the ant at house \(2\) to move to house \(3\). You tell to the two ants at house \(6\) to move to house \(3\) (which already contains two ants). You tell to the ant at house \(5\) to move to house \(1\). You tell to the ant at house \(7\) to move to house \(1\) (which already contains two ants). You tell to the three ants at house \(1\) to move to house \(3\) (which already contains four ants). In the second sample, it is impossible to gather all the ants in a single house.
|
Input: 75 13 24 63 67 11 3 | Output: YES
|
Hard
| 4 | 918 | 377 | 116 | 19 |
1,667 |
A
|
1667A
|
A. Make it Increasing
| 1,300 |
brute force; greedy; math
|
You are given an array \(a\) consisting of \(n\) positive integers, and an array \(b\), with length \(n\). Initially \(b_i=0\) for each \(1 \leq i \leq n\).In one move you can choose an integer \(i\) (\(1 \leq i \leq n\)), and add \(a_i\) to \(b_i\) or subtract \(a_i\) from \(b_i\). What is the minimum number of moves needed to make \(b\) increasing (that is, every element is strictly greater than every element before it)?
|
The first line contains a single integer \(n\) (\(2 \leq n \leq 5000\)).The second line contains \(n\) integers, \(a_1\), \(a_2\), ..., \(a_n\) (\(1 \leq a_i \leq 10^9\)) — the elements of the array \(a\).
|
Print a single integer, the minimum number of moves to make \(b\) increasing.
|
Example \(1\): you can subtract \(a_1\) from \(b_1\), and add \(a_3\), \(a_4\), and \(a_5\) to \(b_3\), \(b_4\), and \(b_5\) respectively. The final array will be [\(-1\), \(0\), \(3\), \(4\), \(5\)] after \(4\) moves.Example \(2\): you can reach [\(-3\), \(-2\), \(-1\), \(0\), \(1\), \(2\), \(3\)] in \(10\) moves.
|
Input: 5 1 2 3 4 5 | Output: 4
|
Easy
| 3 | 426 | 205 | 77 | 16 |
316 |
C1
|
316C1
|
C1. Tidying Up
| 2,200 |
flows
|
Smart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dressing room becomes a mess.Smart Beaver from ABBYY is not only the brightest beaver in the area, but he also is the most domestically oriented. For example, on Mondays the Smart Beaver cleans everything in his home.It's Monday morning. Smart Beaver does not want to spend the whole day cleaning, besides, there is much in to do and it’s the gym day, so he wants to clean up as soon as possible. Now the floors are washed, the dust is wiped off — it’s time to clean up in the dressing room. But as soon as the Smart Beaver entered the dressing room, all plans for the day were suddenly destroyed: chaos reigned there and it seemed impossible to handle, even in a week. Give our hero some hope: tell him what is the minimum number of shoes need to change the position to make the dressing room neat.The dressing room is rectangular and is divided into n × m equal squares, each square contains exactly one shoe. Each pair of shoes has a unique number that is integer from 1 to , more formally, a square with coordinates (i, j) contains an integer number of the pair which is lying on it. The Smart Beaver believes that the dressing room is neat only when each pair of sneakers lies together. We assume that the pair of sneakers in squares (i1, j1) and (i2, j2) lies together if |i1 - i2| + |j1 - j2| = 1.
|
The first line contains two space-separated integers n and m. They correspond to the dressing room size. Next n lines contain m space-separated integers each. Those numbers describe the dressing room. Each number corresponds to a snicker. It is guaranteed that: n·m is even. All numbers, corresponding to the numbers of pairs of shoes in the dressing room, will lie between 1 and . Each number from 1 to will occur exactly twice. The input limits for scoring 30 points are (subproblem C1): 2 ≤ n, m ≤ 8. The input limits for scoring 100 points are (subproblems C1+C2): 2 ≤ n, m ≤ 80.
|
Print exactly one integer — the minimum number of the sneakers that need to change their location.
|
The second sample.
|
Input: 2 31 1 22 3 3 | Output: 2
|
Hard
| 1 | 1,621 | 583 | 98 | 3 |
162 |
E
|
162E
|
E. HQ9+
| 1,800 |
*special
|
HQ9+ is a joke programming language which has only four one-character instructions: ""H"" prints ""Hello, World!"", ""Q"" prints the whole source code of the program itself (at each call), ""9"" prints the lyrics of ""99 Bottles of Beer"" song, ""+"" increments the value stored in the internal accumulator.Instructions ""H"" and ""Q"" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
|
The input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.
|
Output ""YES"", if executing the program will produce any output, and ""NO"" otherwise (quotes for clarity only).
|
In the first case the program contains only one instruction — ""H"", which prints ""Hello, World!"".In the second case none of the program characters are language instructions.
|
Input: Hello! | Output: YES
|
Medium
| 1 | 566 | 239 | 113 | 1 |
135 |
B
|
135B
|
B. Rectangle and Square
| 1,600 |
brute force; geometry; math
|
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.
|
You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.
|
Print in the first output line ""YES"" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct.If the required partition does not exist, the first line should contain the word ""NO"" (without the quotes), after which no output is needed.
|
Pay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
|
Input: 0 010 1110 00 111 12 22 11 2 | Output: YES5 6 7 81 2 3 4
|
Medium
| 3 | 806 | 198 | 597 | 1 |
331 |
A2
|
331A2
|
A2. Oh Sweet Beaverette
| 1,500 |
data structures; sortings
|
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? — Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?
|
The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value. to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1); to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).
|
In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.
|
Input: 51 2 3 1 2 | Output: 8 11
|
Medium
| 2 | 1,133 | 444 | 440 | 3 |
|
1,349 |
C
|
1349C
|
C. Orac and Game of Life
| 2,000 |
dfs and similar; graphs; implementation; shortest paths
|
Please notice the unusual memory limit of this problem.Orac likes games. Recently he came up with the new game, ""Game of Life"".You should play this game on a black and white grid with \(n\) rows and \(m\) columns. Each cell is either black or white.For each iteration of the game (the initial iteration is \(0\)), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different.Two cells are adjacent if they have a mutual edge.Now Orac has set an initial situation, and he wants to know for the cell \((i,j)\) (in \(i\)-th row and \(j\)-th column), what will be its color at the iteration \(p\). He may ask you these questions several times.
|
The first line contains three integers \(n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)\), representing the number of rows, columns, and the number of Orac queries.Each of the following \(n\) lines contains a binary string of length \(m\), the \(j\)-th character in \(i\)-th line represents the initial color of cell \((i,j)\). '0' stands for white, '1' stands for black.Each of the following \(t\) lines contains three integers \(i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})\), representing a query from Orac.
|
Print \(t\) lines, in \(i\)-th line you should print the answer to the \(i\)-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'.
|
For the first example, the picture above shows the initial situation and the color of cells at the iteration \(1\), \(2\), and \(3\). We can see that the color of \((1,1)\) at the iteration \(1\) is black, the color of \((2,2)\) at the iteration \(2\) is black, and the color of \((3,3)\) at the iteration \(3\) is also black.For the second example, you can prove that the cells will never change their colors.
|
Input: 3 3 3 000 111 000 1 1 1 2 2 2 3 3 3 | Output: 1 1 1
|
Hard
| 4 | 861 | 517 | 185 | 13 |
190 |
D
|
190D
|
D. Non-Secret Cypher
| 1,900 |
two pointers
|
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).
|
The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.
|
Print the single number — the number of such subarrays of array a, that they have at least k equal integers.Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.
|
In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
|
Input: 4 21 2 1 2 | Output: 3
|
Hard
| 1 | 1,171 | 291 | 254 | 1 |
294 |
B
|
294B
|
B. Shaass and Bookshelf
| 1,700 |
dp; greedy
|
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights. Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
|
The first line of the input contains an integer n, (1 ≤ n ≤ 100). Each of the next n lines contains two integers ti and wi denoting the thickness and width of the i-th book correspondingly, (1 ≤ ti ≤ 2, 1 ≤ wi ≤ 100).
|
On the only line of the output print the minimum total thickness of the vertical books that we can achieve.
|
Input: 51 121 32 152 52 1 | Output: 5
|
Medium
| 2 | 745 | 217 | 107 | 2 |
|
2,066 |
D2
|
2066D2
|
D2. Club of Young Aircraft Builders (hard version)
| 2,900 |
combinatorics; dp; math
|
This is the hard version of the problem. The difference between the versions is that in this version, not necessary \(a_i = 0\). You can hack only if you solved all versions of this problem. There is a building with \(n\) floors, numbered from \(1\) to \(n\) from bottom to top. There is exactly one person living on each floor.All the residents of the building have an important goal today: to launch at least \(c\) paper airplanes collectively. The residents will launch the airplanes in turn. When a person from the \(i\)-th floor launches an airplane, all residents on floors from \(1\) to \(i\) can see it as it descends to the ground. If, from the perspective of the resident on the \(i\)-th floor, at least \(c\) airplanes have already been launched, they will no longer launch airplanes themselves. It is also known that by the end of the day, from the perspective of each resident in the building, at least \(c\) airplanes have been launched, and a total of \(m\) airplanes were thrown.You have been carefully monitoring this flash mob, and for each airplane, you recorded which resident from which floor threw it. Unfortunately, the information about who exactly threw some of the airplanes has been lost. Find the number of ways to fill in the gaps so that the information could be credible. Since the answer could be quite large, output it modulo \(10^9 + 7\).It is also possible that you made a mistake in your records, and there is no possible way to restore the gaps. In that case, the answer is considered to be \(0\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains three integers \(n, c, m\) (\(1 \le n \le 100\), \(1 \le c \le 100\), \(c \le m \le n \cdot c\)) — the number of floors in the building, the minimum required number of airplanes, and the number of airplanes actually launched.The second line of each test case contains \(m\) integers \(a_1, a_2, \ldots, a_m\) (\(0 \le a_i \le n\)) — \(a_i\) indicates the resident from which floor launched the \(i\)-th airplane; \(a_i = 0\) indicates a gap.It is guaranteed that the sum of the values of \(m\) across all test cases does not exceed \(10^4\).
|
For each test case, output the number of ways to fill in the gaps with numbers from \(1\) to \(n\), so that the chronology of the airplane launches could be credible, modulo \(10^9 + 7\).
|
In the first test example, all six possible ways to fill in the gaps are as follows: \([1, 1, 3, 3]\) \([1, 2, 3, 3]\) \([1, 3, 2, 3]\) \([2, 1, 3, 3]\) \([2, 2, 3, 3]\) \([3, 1, 2, 3]\)Note that the array \([2, 3, 1, 3]\) is not a valid way to fill in the gaps, as the third airplane could not have been launched by the person on the \(1\)st floor, since from their perspective, \(c = 2\) airplanes had already been launched.Also, the array \([1, 1, 2, 3]\) is not a valid way to fill in the gaps, as from the perspective of the person on the \(3\)rd floor, only \(1\) airplane has been launched, while \(c = 2\).
|
Input: 83 2 40 0 0 05 5 70 0 0 0 0 0 06 1 32 0 02 3 50 0 1 0 23 3 43 3 3 02 1 20 12 1 20 25 3 120 0 1 0 2 4 0 0 0 5 0 5 | Output: 6 190 3 2 0 0 1 14
|
Master
| 3 | 1,534 | 745 | 187 | 20 |
1,903 |
D1
|
1903D1
|
D1. Maximum And Queries (easy version)
| 1,700 |
binary search; bitmasks; brute force; greedy
|
This is the easy version of the problem. The only difference between the two versions is the constraint on \(n\) and \(q\), the memory and time limits. You can make hacks only if all versions of the problem are solved.Theofanis really likes to play with the bits of numbers. He has an array \(a\) of size \(n\) and an integer \(k\). He can make at most \(k\) operations in the array. In each operation, he picks a single element and increases it by \(1\).He found the maximum bitwise AND that array \(a\) can have after at most \(k\) operations.Theofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, Adaś, being the evil person that he is, decided to bully him by repeatedly changing the value of \(k\).Help Theofanis by calculating the maximum possible bitwise AND for \(q\) different values of \(k\). Note that queries are independent.
|
The first line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 10^5\) and \(n \cdot q \le 10^5\)) — the size of the array and the number of queries.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 10^6\)) — the elements of the array.Next \(q\) lines describe the queries. The \(i\)-th line contains one integer \(k_i\) (\(0 \le k_i \le 10^{18}\)) — the number of operations that can be done in the \(i\)-th query.
|
For each query, print one integer — the maximum bitwise AND that array \(a\) can have after at most \(k_i\) operations.
|
In the first test case, in the first query, we add \(1\) in the first and last elements of the array. Thus, the array becomes \([2,3,7,6]\) with bitwise AND equal to \(2\).In the second test case, in the first query, we add \(1\) in the first element, \(5\) in the second, and \(3\) in the third and now all the elements are equal to \(5\).
|
Input: 4 2 1 3 7 5 2 10 | Output: 2 6
|
Medium
| 4 | 889 | 455 | 119 | 19 |
1,267 |
F
|
1267F
| 2,600 |
graphs
|
Expert
| 1 | 0 | 0 | 0 | 12 |
||||||
1,428 |
E
|
1428E
|
E. Carrots for Rabbits
| 2,200 |
binary search; data structures; greedy; math; sortings
|
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought \(n\) carrots with lengths \(a_1, a_2, a_3, \ldots, a_n\). However, rabbits are very fertile and multiply very quickly. Zookeeper now has \(k\) rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into \(k\) pieces. For some reason, all resulting carrot lengths must be positive integers.Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size \(x\) is \(x^2\).Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.
|
The first line contains two integers \(n\) and \(k\) \((1 \leq n \leq k \leq 10^5)\): the initial number of carrots and the number of rabbits.The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) \((1 \leq a_i \leq 10^6)\): lengths of carrots.It is guaranteed that the sum of \(a_i\) is at least \(k\).
|
Output one integer: the minimum sum of time taken for rabbits to eat carrots.
|
For the first test, the optimal sizes of carrots are \(\{1,1,1,2,2,2\}\). The time taken is \(1^2+1^2+1^2+2^2+2^2+2^2=15\)For the second test, the optimal sizes of carrots are \(\{4,5,5,5\}\). The time taken is \(4^2+5^2+5^2+5^2=91\).
|
Input: 3 6 5 3 1 | Output: 15
|
Hard
| 5 | 654 | 312 | 77 | 14 |
965 |
E
|
965E
|
E. Short Code
| 2,200 |
data structures; dp; greedy; strings; trees
|
Arkady's code contains \(n\) variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.A string \(a\) is a prefix of a string \(b\) if you can delete some (possibly none) characters from the end of \(b\) and obtain \(a\).Please find this minimum possible total length of new names.
|
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) — the number of variables.The next \(n\) lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than \(10^5\). The variable names are distinct.
|
Print a single integer — the minimum possible total length of new variable names.
|
In the first example one of the best options is to shorten the names in the given order as ""cod"", ""co"", ""c"".In the second example we can shorten the last name to ""aac"" and the first name to ""a"" without changing the other names.
|
Input: 3codeforcescodehorsescode | Output: 6
|
Hard
| 5 | 668 | 319 | 81 | 9 |
549 |
C
|
549C
|
C. The Game Of Parity
| 2,200 |
games
|
There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.
|
The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.
|
Print string ""Daenerys"" (without the quotes), if Daenerys wins and ""Stannis"" (without the quotes), if Stannis wins.
|
In the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.
|
Input: 3 11 2 1 | Output: Stannis
|
Hard
| 1 | 831 | 319 | 119 | 5 |
1,706 |
D2
|
1706D2
|
D2. Chopping Carrots (Hard Version)
| 2,400 |
brute force; constructive algorithms; data structures; dp; greedy; math; number theory; two pointers
|
This is the hard version of the problem. The only difference between the versions is the constraints on \(n\), \(k\), \(a_i\), and the sum of \(n\) over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers \(a_1, a_2, \ldots, a_n\) of length \(n\), and an integer \(k\).The cost of an array of integers \(p_1, p_2, \ldots, p_n\) of length \(n\) is $$$\(\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).\)\(Here, \)\lfloor \frac{x}{y} \rfloor\( denotes the integer part of the division of \)x\( by \)y\(. Find the minimum cost of an array \)p\( such that \)1 \le p_i \le k\( for all \)1 \le i \le n$$$.
|
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) — the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le n, k \le 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_1 \le a_2 \le \ldots \le a_n \le 10^5\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
|
For each test case, print a single integer — the minimum possible cost of an array \(p\) satisfying the condition above.
|
In the first test case, the optimal array is \(p = [1, 1, 1, 2, 2]\). The resulting array of values of \(\lfloor \frac{a_i}{p_i} \rfloor\) is \([4, 5, 6, 4, 5]\). The cost of \(p\) is \(\max\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) - \min\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) = 6 - 4 = 2\). We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is \(p = [12, 12, 12, 12, 12]\), which results in all \(\lfloor \frac{a_i}{p_i} \rfloor\) being \(0\).In the third test case, the only possible array is \(p = [1, 1, 1]\).
|
Input: 75 24 5 6 8 115 124 5 6 8 113 12 9 157 32 3 5 5 6 9 106 5654 286 527 1436 2450 26813 9516 340 22412 21 3 | Output: 2 0 13 1 4 7 0
|
Expert
| 8 | 821 | 395 | 120 | 17 |
725 |
D
|
725D
|
D. Contest Balloons
| 1,800 |
data structures; greedy
|
One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.A contest has just finished. There are n teams, numbered 1 through n. The i-th team has ti balloons and weight wi. It's guaranteed that ti doesn't exceed wi so nobody floats initially.Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.What is the best place Limak can get?
|
The first line of the standard input contains one integer n (2 ≤ n ≤ 300 000) — the number of teams.The i-th of n following lines contains two integers ti and wi (0 ≤ ti ≤ wi ≤ 1018) — respectively the number of balloons and the weight of the i-th team. Limak is a member of the first team.
|
Print one integer denoting the best place Limak can get.
|
In the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is: Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified. Limak gives 1 balloon to each of two teams with 16 balloons initially. Limak has 20 - 6 - 6 - 1 - 1 = 6 balloons. There are three other teams left and their numbers of balloons are 40, 14 and 2. Limak gets the third place because there are two teams with more balloons. In the second sample, Limak has the second place and he can't improve it.In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81 000 000 000, 5 000 000 000 and 46 000 000 000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7).
|
Input: 820 100032 3740 100045 5016 1616 1614 10002 1000 | Output: 3
|
Medium
| 2 | 1,294 | 290 | 56 | 7 |
1,076 |
F
|
1076F
|
F. Summer Practice Report
| 2,500 |
dp; greedy
|
Vova has taken his summer practice this year and now he should write a report on how it went.Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly \(n\) pages and the \(i\)-th page will include \(x_i\) tables and \(y_i\) formulas. The pages are numbered from \(1\) to \(n\).Vova fills the pages one after another, he can't go filling page \(i + 1\) before finishing page \(i\) and he can't skip pages. However, if he draws strictly more than \(k\) tables in a row or writes strictly more than \(k\) formulas in a row then he will get bored. Vova wants to rearrange tables and formulas in each page in such a way that he doesn't get bored in the process. Vova can't move some table or some formula to another page.Note that the count doesn't reset on the start of the new page. For example, if the page ends with \(3\) tables and the next page starts with \(5\) tables, then it's counted as \(8\) tables in a row.Help Vova to determine if he can rearrange tables and formulas on each page in such a way that there is no more than \(k\) tables in a row and no more than \(k\) formulas in a row.
|
The first line contains two integers \(n\) and \(k\) (\(1 \le n \le 3 \cdot 10^5\), \(1 \le k \le 10^6\)).The second line contains \(n\) integers \(x_1, x_2, \dots, x_n\) (\(1 \le x_i \le 10^6\)) — the number of tables on the \(i\)-th page.The third line contains \(n\) integers \(y_1, y_2, \dots, y_n\) (\(1 \le y_i \le 10^6\)) — the number of formulas on the \(i\)-th page.
|
Print ""YES"" if Vova can rearrange tables and formulas on each page in such a way that there is no more than \(k\) tables in a row and no more than \(k\) formulas in a row.Otherwise print ""NO"".
|
In the first example the only option to rearrange everything is the following (let table be 'T' and formula be 'F'): page \(1\): ""TTFTTFT"" page \(2\): ""TFTTFTT"" That way all blocks of tables have length \(2\).In the second example there is no way to fit everything in such a way that there are no more than \(2\) tables in a row and \(2\) formulas in a row.
|
Input: 2 2 5 5 2 2 | Output: YES
|
Expert
| 2 | 1,182 | 375 | 196 | 10 |
916 |
E
|
916E
|
E. Jamie and Tree
| 2,400 |
data structures; trees
|
To your surprise, Jamie is the final boss! Ehehehe.Jamie has given you a tree with n vertices, numbered from 1 to n. Initially, the root of the tree is the vertex with number 1. Also, each vertex has a value on it.Jamie also gives you three types of queries on the tree:1 v — Change the tree's root to vertex with number v.2 u v x — For each vertex in the subtree of smallest size that contains u and v, add x to its value.3 v — Find sum of values of vertices in the subtree of vertex with number v.A subtree of vertex v is a set of vertices such that v lies on shortest path from this vertex to root of the tree. Pay attention that subtree of a vertex can change after changing the tree's root.Show your strength in programming to Jamie by performing the queries accurately!
|
The first line of input contains two space-separated integers n and q (1 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of vertices in the tree and the number of queries to process respectively.The second line contains n space-separated integers a1, a2, ..., an ( - 108 ≤ ai ≤ 108) — initial values of the vertices.Next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n) describing edge between vertices ui and vi in the tree.The following q lines describe the queries.Each query has one of following formats depending on its type:1 v (1 ≤ v ≤ n) for queries of the first type.2 u v x (1 ≤ u, v ≤ n, - 108 ≤ x ≤ 108) for queries of the second type.3 v (1 ≤ v ≤ n) for queries of the third type.All numbers in queries' descriptions are integers.The queries must be carried out in the given order. It is guaranteed that the tree is valid.
|
For each query of the third type, output the required answer. It is guaranteed that at least one query of the third type is given by Jamie.
|
The following picture shows how the tree varies after the queries in the first sample.
|
Input: 6 71 4 2 8 5 71 23 14 34 53 63 12 4 6 33 41 62 2 4 -51 43 3 | Output: 27195
|
Expert
| 2 | 775 | 849 | 139 | 9 |
724 |
F
|
724F
|
F. Uniformly Branched Trees
| 2,700 |
combinatorics; dp; trees
|
A tree is a connected graph without cycles.Two trees, consisting of n vertices each, are called isomorphic if there exists a permutation p: {1, ..., n} → {1, ..., n} such that the edge (u, v) is present in the first tree if and only if the edge (pu, pv) is present in the second tree.Vertex of the tree is called internal if its degree is greater than or equal to two.Count the number of different non-isomorphic trees, consisting of n vertices, such that the degree of each internal vertex is exactly d. Print the answer over the given prime modulo mod.
|
The single line of the input contains three integers n, d and mod (1 ≤ n ≤ 1000, 2 ≤ d ≤ 10, 108 ≤ mod ≤ 109) — the number of vertices in the tree, the degree of internal vertices and the prime modulo.
|
Print the number of trees over the modulo mod.
|
Input: 5 2 433416647 | Output: 1
|
Master
| 3 | 554 | 201 | 46 | 7 |
|
1,945 |
H
|
1945H
|
H. GCD is Greater
| 2,600 |
brute force; data structures; math; number theory
|
In the evenings during the hike, Kirill and Anton decided to take out an array of integers \(a\) of length \(n\) from their backpack and play a game with it. The rules are as follows: Kirill chooses from \(2\) to \((n-2)\) numbers and encircles them in red. Anton encircles all the remaining numbers in blue. Kirill calculates the greatest common divisor (GCD) of all the red numbers. Anton calculates the bitwise AND of all the blue numbers and adds the number \(x\) to the result. If the GCD of all the red numbers is strictly greater than the sum of the bitwise AND of all the blue numbers and the number \(x\), then Kirill wins; otherwise, Anton wins.Help Kirill to beat Anton or tell if it's impossible.
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 20\,000\)) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains two integers \(n\) and \(x\) (\(4\le n \le 4\cdot 10^5\), \(0 \le x \le 4\cdot 10^5\)) — the number of integers and the number \(x\) respectively.The second line contains an array \(a\) of length \(n\) (\(1 \le a_i \le 4\cdot 10^5\)).It is guaranteed that the sum of \(n\) for all test cases does not exceed \(4\cdot 10^5\). It is also guaranteed that the sum of the maximum values of \(a_i\) for each test case does not exceed \(4\cdot 10^5\).
|
For each test case, output ""YES"" on the first line if the condition can be met, on the second line, output the number of chosen numbers by Kirill and the numbers themselves in any order separated by a space, and on the third line, output the size of the second set and the numbers in it.Otherwise, output ""NO"".You can output each letter in any case (lowercase or uppercase). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be accepted as a positive answer.
|
Input: 84 14 3 1 84 14 5 8 45 01 1 1 1 15 231 63 127 63 314 11 3 3 38 34 3 4 1 2 2 5 34 21 4 3 68 4831 61 37 15 53 26 61 12 | Output: YES 2 4 8 2 3 1 YES 2 4 4 2 5 8 NO YES 2 63 63 3 31 127 31 YES 2 3 3 2 1 3 YES 2 4 4 6 3 1 2 2 5 3 YES 2 3 6 2 1 4 YES 2 61 61 6 31 37 15 53 26 12
|
Expert
| 4 | 708 | 677 | 481 | 19 |
|
2,082 |
B
|
2082B
|
B. Floor or Ceil
| 1,600 |
brute force; greedy
|
Ecrade has an integer \(x\). 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 exactly \(n\) first operations and \(m\) second operations in any order. He wants to know the minimum and the maximum possible value of \(x\) after \(n+m\) operations. However, it seems a little difficult, so please help him!
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The only line of each test case contains three integers \(x\), \(n\), and \(m\) (\(0 \le x, n, m \le 10^9\)).
|
For each test case, print two integers in one line, representing the minimum and the maximum possible value of \(x\) after \(n + m\) operations.
|
For simplicity, we call the first operation \(\text{OPER 1}\) and the second operation \(\text{OPER 2}\).In the first test case: If we perform \(12 \xrightarrow{\text{OPER 2}} 6 \xrightarrow{\text{OPER 2}} 3 \xrightarrow{\text{OPER 1}} 1\), we can obtain the minimum possible value \(1\). If we perform \(12 \xrightarrow{\text{OPER 2}} 6 \xrightarrow{\text{OPER 1}} 3 \xrightarrow{\text{OPER 2}} 2\), we can obtain the maximum possible value \(2\).
|
Input: 512 1 212 1 112 0 012 1000000000 1000000000706636307 0 3 | Output: 1 2 3 3 12 12 0 0 88329539 88329539
|
Medium
| 2 | 621 | 271 | 144 | 20 |
2,033 |
D
|
2033D
|
D. Kousuke's Assignment
| 1,300 |
data structures; dp; dsu; greedy; math
|
After a trip with Sakurako, Kousuke was very scared because he forgot about his programming assignment. In this assignment, the teacher gave him an array \(a\) of \(n\) integers and asked him to calculate the number of non-overlapping segments of the array \(a\), such that each segment is considered beautiful.A segment \([l,r]\) is considered beautiful if \(a_l + a_{l+1} + \dots + a_{r-1} + a_r=0\).For a fixed array \(a\), your task is to compute the maximum number of non-overlapping beautiful segments.
|
The first line of input contains the number \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Each test case consists of \(2\) lines. The first line contains one integer \(n\) (\(1 \le n \le 10^5\)) — the length of the array. The second line contains \(n\) integers \(a_i\) (\(-10^5 \le a_i \le 10^5\)) — the elements of the array \(a\). It is guaranteed that the sum of \(n\) across all test cases does not exceed \(3\cdot 10^5\).
|
For each test case, output a single integer: the maximum number of non-overlapping beautiful segments.
|
Input: 352 1 -3 2 1712 -4 4 43 -3 -5 860 -4 0 3 0 1 | Output: 1 2 3
|
Easy
| 5 | 508 | 438 | 102 | 20 |
|
2,005 |
B1
|
2005B1
|
B1. The Strict Teacher (Easy Version)
| 1,000 |
greedy; math; sortings
|
This is the easy version of the problem. The only differences between the two versions are the constraints on \(m\) and \(q\). In this version, \(m=2\) and \(q=1\). You can make hacks only if both versions of the problem are solved.Narek and Tsovak were busy preparing this round, so they have not managed to do their homework and decided to steal David's homework. Their strict teacher noticed that David has no homework and now wants to punish him. She hires other teachers to help her catch David. And now \(m\) teachers together are chasing him. Luckily, the classroom is big, so David has many places to hide.The classroom can be represented as a one-dimensional line with cells from \(1\) to \(n\), inclusive.At the start, all \(m\) teachers and David are in distinct cells. Then they make moves. During each move David goes to an adjacent cell or stays at the current one. Then, each of the \(m\) teachers simultaneously goes to an adjacent cell or stays at the current one. This continues until David is caught. David is caught if any of the teachers (possibly more than one) is located in the same cell as David. Everyone sees others' moves, so they all act optimally.Your task is to find how many moves it will take for the teachers to catch David if they all act optimally.Acting optimally means the student makes his moves in a way that maximizes the number of moves the teachers need to catch him; and the teachers coordinate with each other to make their moves in a way that minimizes the number of moves they need to catch the student.Also, as Narek and Tsovak think this task is easy, they decided to give you \(q\) queries on David's position. Note: this is the easy version, and you are given only one query.
|
In the first line of the input, you are given a single integer \(t\) (\(1 \le t \le 10^5\)) — the number of test cases. The description of each test case follows.In the first line of each test case, you are given three integers \(n\), \(m\), and \(q\) (\(3 \le n \le 10^9\), \(m=2\), \(q=1\)) — the number of cells on the line, the number of teachers, and the number of queries.In the second line of each test case, you are given \(m\) distinct integers \(b_1, b_2, \ldots, b_m\) (\(1 \le b_i \le n\)) — the cell numbers of the teachers.In the third line of each test case, you are given \(q\) integers \(a_1, a_2, \ldots, a_q\) (\(1 \le a_i \le n\)) — David's cell number for every query.It is guaranteed that for any \(i\), \(j\) such that \(1 \le i \le m\) and \(1 \le j \le q\), \(b_i \neq a_j\).
|
For each test case, output \(q\) lines, the \(i\)-th of them containing the answer of the \(i\)-th query.
|
In the first example, the student can just stay at cell \(2\). The teacher, initially located in cell \(1\), can reach cell \(2\) in one move. Therefore, the answer is \(1\).In the second example, the student should just stay at cell \(1\). The teacher, initially located in cell \(3\), can reach cell \(1\) in two moves. Therefore, the answer is \(2\).
|
Input: 310 2 11 428 2 13 618 2 13 68 | Output: 1 2 2
|
Beginner
| 3 | 1,726 | 800 | 105 | 20 |
1,217 |
B
|
1217B
|
B. Zmei Gorynich
| 1,600 |
greedy; math
|
You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has \(x\) heads. You can deal \(n\) types of blows. If you deal a blow of the \(i\)-th type, you decrease the number of Gorynich's heads by \(min(d_i, curX)\), there \(curX\) is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows \(h_i\) new heads. If \(curX = 0\) then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if \(curX = 10\), \(d = 7\), \(h = 10\) then the number of heads changes to \(13\) (you cut \(7\) heads off, but then Zmei grows \(10\) new ones), but if \(curX = 10\), \(d = 11\), \(h = 100\) then number of heads changes to \(0\) and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer \(t\) independent queries.
|
The first line contains one integer \(t\) (\(1 \le t \le 100\)) – the number of queries.The first line of each query contains two integers \(n\) and \(x\) (\(1 \le n \le 100\), \(1 \le x \le 10^9\)) — the number of possible types of blows and the number of heads Zmei initially has, respectively.The following \(n\) lines of each query contain the descriptions of types of blows you can deal. The \(i\)-th line contains two integers \(d_i\) and \(h_i\) (\(1 \le d_i, h_i \le 10^9\)) — the description of the \(i\)-th blow.
|
For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print \(-1\).
|
In the first query you can deal the first blow (after that the number of heads changes to \(10 - 6 + 3 = 7\)), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?
|
Input: 3 3 10 6 3 8 2 1 4 4 10 4 1 3 2 2 6 1 100 2 15 10 11 14 100 | Output: 2 3 -1
|
Medium
| 2 | 936 | 522 | 140 | 12 |
1,196 |
E
|
1196E
|
E. Connected Component on a Chessboard
| 1,800 |
constructive algorithms; implementation
|
You are given two integers \(b\) and \(w\). You have a chessboard of size \(10^9 \times 10^9\) with the top left cell at \((1; 1)\), the cell \((1; 1)\) is painted white.Your task is to find a connected component on this chessboard that contains exactly \(b\) black cells and exactly \(w\) white cells. Two cells are called connected if they share a side (i.e. for the cell \((x, y)\) there are at most four connected cells: \((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)\)). A set of cells is called a connected component if for every pair of cells \(C_1\) and \(C_2\) from this set, there exists a sequence of cells \(c_1\), \(c_2\), ..., \(c_k\) such that \(c_1 = C_1\), \(c_k = C_2\), all \(c_i\) from \(1\) to \(k\) are belong to this set of cells and for every \(i \in [1, k - 1]\), cells \(c_i\) and \(c_{i + 1}\) are connected.Obviously, it can be impossible to find such component. In this case print ""NO"". Otherwise, print ""YES"" and any suitable connected component.You have to answer \(q\) independent queries.
|
The first line of the input contains one integer \(q\) (\(1 \le q \le 10^5\)) — the number of queries. Then \(q\) queries follow.The only line of the query contains two integers \(b\) and \(w\) (\(1 \le b, w \le 10^5\)) — the number of black cells required and the number of white cells required.It is guaranteed that the sum of numbers of cells does not exceed \(2 \cdot 10^5\) (\(\sum w + \sum b \le 2 \cdot 10^5\)).
|
For each query, print the answer to it.If it is impossible to find the required component, print ""NO"" on the first line.Otherwise, print ""YES"" on the first line. In the next \(b + w\) lines print coordinates of cells of your component in any order. There should be exactly \(b\) black cells and \(w\) white cells in your answer. The printed component should be connected.If there are several answers, you can print any. All coordinates in the answer should be in the range \([1; 10^9]\).
|
Input: 3 1 1 1 4 2 5 | Output: YES 2 2 1 2 YES 2 3 1 3 3 3 2 2 2 4 YES 2 3 2 4 2 5 1 3 1 5 3 3 3 5
|
Medium
| 2 | 1,027 | 418 | 491 | 11 |
|
852 |
G
|
852G
|
G. Bathroom terminal
| 1,700 |
implementation
|
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message ""Play Me"". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:""Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle. You are given N strings which represent words. Each word is of the maximum length L and consists of characters 'a'-'e'. You are also given M strings which represent patterns. Pattern is a string of length ≤ L and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin.""Help Smith escape.
|
The first line of input contains two integers N and M (1 ≤ N ≤ 100 000, 1 ≤ M ≤ 5000), representing the number of words and patterns respectively.The next N lines represent each word, and after those N lines, following M lines represent each pattern. Each word and each pattern has a maximum length L (1 ≤ L ≤ 50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.
|
Output contains M lines and each line consists of one integer, representing the number of words that match the corresponding pattern.
|
If we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively.
|
Input: 3 1abcaecaca?c | Output: 3
|
Medium
| 1 | 1,181 | 455 | 133 | 8 |
637 |
D
|
637D
|
D. Running with Obstacles
| 1,600 |
*special; data structures; dp; greedy
|
A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.On the way of an athlete are n obstacles at coordinates x1, x2, ..., xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.
|
The first line of the input containsd four integers n, m, s and d (1 ≤ n ≤ 200 000, 2 ≤ m ≤ 109, 1 ≤ s, d ≤ 109) — the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly.The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ m - 1) — the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.
|
If the runner cannot reach the finishing point, print in the first line of the output ""IMPOSSIBLE"" (without the quotes).If the athlete can get from start to finish, print any way to do this in the following format: print a line of form ""RUN X>"" (where ""X"" should be a positive integer), if the athlete should run for ""X"" more meters; print a line of form ""JUMP Y"" (where ""Y"" should be a positive integer), if the sportsman starts a jump and should remain in air for ""Y"" more meters. All commands ""RUN"" and ""JUMP"" should strictly alternate, starting with ""RUN"", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish.
|
Input: 3 10 1 33 4 7 | Output: RUN 2JUMP 3RUN 1JUMP 2RUN 2
|
Medium
| 4 | 861 | 594 | 780 | 6 |
|
706 |
D
|
706D
|
D. Vasiliy's Multiset
| 1,800 |
binary search; bitmasks; data structures; trees
|
Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: ""+ x"" — add integer x to multiset A. ""- x"" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. ""? x"" — you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.
|
The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform.Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type.Note, that the integer 0 will always be present in the set A.
|
For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.
|
After first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer — maximum among integers , , , and .
|
Input: 10+ 8+ 9+ 11+ 6+ 1? 3- 8? 3? 8? 11 | Output: 11101413
|
Medium
| 4 | 625 | 375 | 150 | 7 |
1,978 |
B
|
1978B
|
B. New Bakery
| 800 |
binary search; greedy; math; ternary search
|
Bob decided to open a bakery. On the opening day, he baked \(n\) buns that he can sell. The usual price of a bun is \(a\) coins, but to attract customers, Bob organized the following promotion: Bob chooses some integer \(k\) (\(0 \le k \le \min(n, b)\)). Bob sells the first \(k\) buns at a modified price. In this case, the price of the \(i\)-th (\(1 \le i \le k\)) sold bun is \((b - i + 1)\) coins. The remaining \((n - k)\) buns are sold at \(a\) coins each.Note that \(k\) can be equal to \(0\). In this case, Bob will sell all the buns at \(a\) coins each.Help Bob determine the maximum profit he can obtain by selling all \(n\) buns.
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of the test cases follows.The only line of each test case contains three integers \(n\), \(a\), and \(b\) (\(1 \le n, a, b \le 10^9\)) — the number of buns, the usual price of a bun, and the price of the first bun to be sold at a modified price.
|
For each test case, output a single integer — the maximum profit that Bob can obtain.
|
In the first test case, it is optimal for Bob to choose \(k = 1\). Then he will sell one bun for \(5\) coins, and three buns at the usual price for \(4\) coins each. Then the profit will be \(5 + 4 + 4 + 4 = 17\) coins.In the second test case, it is optimal for Bob to choose \(k = 5\). Then he will sell all the buns at the modified price and obtain a profit of \(9 + 8 + 7 + 6 + 5 = 35\) coins.In the third test case, it is optimal for Bob to choose \(k = 0\). Then he will sell all the buns at the usual price and obtain a profit of \(10 \cdot 10 = 100\) coins.
|
Input: 74 4 55 5 910 10 55 5 111000000000 1000000000 10000000001000000000 1000000000 11000 1 1000 | Output: 17 35 100 45 1000000000000000000 1000000000000000000 500500
|
Beginner
| 4 | 640 | 402 | 85 | 19 |
341 |
E
|
341E
|
E. Candies Game
| 3,000 |
constructive algorithms; greedy
|
Iahub is playing an uncommon game. Initially, he has n boxes, numbered 1, 2, 3, ..., n. Each box has some number of candies in it, described by a sequence a1, a2, ..., an. The number ak represents the number of candies in box k. The goal of the game is to move all candies into exactly two boxes. The rest of n - 2 boxes must contain zero candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes i and j, such that ai ≤ aj. Then, Iahub moves from box j to box i exactly ai candies. Obviously, when two boxes have equal number of candies, box number j becomes empty.Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.
|
The first line of the input contains integer n (3 ≤ n ≤ 1000). The next line contains n non-negative integers: a1, a2, ..., an — sequence elements. It is guaranteed that sum of all numbers in sequence a is up to 106.
|
In case there exists no solution, output -1. Otherwise, in the first line output integer c (0 ≤ c ≤ 106), representing number of moves in your solution. Each of the next c lines should contain two integers i and j (1 ≤ i, j ≤ n, i ≠ j): integers i, j in the kth line mean that at the k-th move you will move candies from the j-th box to the i-th one.
|
For the first sample, after the first move the boxes will contain 3, 12 and 3 candies. After the second move, the boxes will contain 6, 12 and 0 candies. Now all candies are in exactly 2 boxes.For the second sample, you can observe that the given configuration is not valid, as all candies are in a single box and they should be in two boxes. Also, any move won't change the configuration, so there exists no solution.For the third sample, all candies are already in 2 boxes. Hence, no move is needed.
|
Input: 33 6 9 | Output: 22 31 3
|
Master
| 2 | 895 | 216 | 350 | 3 |
178 |
C2
|
178C2
|
C2. Smart Beaver and Resolving Collisions
| 1,900 |
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m) mod h. If it is also occupied, then we try cell (t + 2·m) mod h, then cell (t + 3·m) mod h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.The operation a mod b means that we take the remainder of the division of number a by number b.This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + i·m) mod h (i ≥ 0), then exactly i dummy calls have been performed.Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.
|
The first line of input contains three integers h, m and n (1 ≤ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations.The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows: ""+ id hash""This is the format of the operation that adds an object to the table. The first character is ""+"" (ASCII 43), followed by a single space, then the object identifier id (0 ≤ id ≤ 109), then another space, and the hash value of the given object hash (0 ≤ hash < h). The object identifier and the hash value of this object are integers. ""- id""This is the format of the operation that deletes an object from the table. The first character is ""-"" (ASCII 45), followed by a single space, then the object identifier id (0 ≤ id ≤ 109). The object identifier is an integer.It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects.The input limitations for getting 20 points are: 1 ≤ h ≤ 5000 1 ≤ n ≤ 5000 The input limitations for getting 50 points are: 1 ≤ h ≤ 5·104 1 ≤ n ≤ 5·104 The input limitations for getting 100 points are: 1 ≤ h ≤ 2·105 1 ≤ n ≤ 2·105
|
Print a single number — the total number of dummy calls to the hash table.Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams and the %I64d specifier.
|
Input: 10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0 | Output: 7
|
Hard
| 0 | 2,301 | 1,520 | 218 | 1 |
||
2,050 |
E
|
2050E
|
E. Three Strings
| 1,500 |
dp; implementation; strings
|
You are given three strings: \(a\), \(b\), and \(c\), consisting of lowercase Latin letters. The string \(c\) was obtained in the following way: At each step, either string \(a\) or string \(b\) was randomly chosen, and the first character of the chosen string was removed from it and appended to the end of string \(c\), until one of the strings ran out. After that, the remaining characters of the non-empty string were added to the end of \(c\). Then, a certain number of characters in string \(c\) were randomly changed. For example, from the strings \(a=\color{red}{\text{abra}}\) and \(b=\color{blue}{\text{cada}}\), without character replacements, the strings \(\color{blue}{\text{ca}}\color{red}{\text{ab}}\color{blue}{\text{d}}\color{red}{\text{ra}}\color{blue}{\text{a}}\), \(\color{red}{\text{abra}}\color{blue}{\text{cada}}\), \(\color{red}{\text{a}}\color{blue}{\text{cada}}\color{red}{\text{bra}}\) could be obtained.Find the minimum number of characters that could have been changed in string \(c\).
|
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^3\)) — the number of test cases.The first line of each test case contains one string of lowercase Latin letters \(a\) (\(1 \leq |a| \leq 10^3\)) — the first string, where \(|a|\) denotes the length of string \(a\).The second line of each test case contains one string of lowercase Latin letters \(b\) (\(1 \leq |b| \leq 10^3\)) — the second string, where \(|b|\) denotes the length of string \(b\).The third line of each test case contains one string of lowercase Latin letters \(c\) (\(|c| = |a| + |b|\)) — the third string.It is guaranteed that the sum of \(|a|\) across all test cases does not exceed \(2 \cdot 10^3\). Also, the sum of \(|b|\) across all test cases does not exceed \(2 \cdot 10^3\).
|
For each test case, output a single integer — the minimum number of characters that could have been changed in string \(c\).
|
Input: 7abcbabcdacbdabbaaabbxxxyyyxyxyxyabcddecfcodeshorsecodeforceseggannieegaegaeg | Output: 1 0 2 0 3 2 3
|
Medium
| 3 | 1,014 | 780 | 124 | 20 |
|
1,154 |
A
|
1154A
|
A. Restoring Three Numbers
| 800 |
math
|
Polycarp has guessed three positive integers \(a\), \(b\) and \(c\). He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: \(a+b\), \(a+c\), \(b+c\) and \(a+b+c\).You have to guess three numbers \(a\), \(b\) and \(c\) using given numbers. Print three guessed integers in any order.Pay attention that some given numbers \(a\), \(b\) and \(c\) can be equal (it is also possible that \(a=b=c\)).
|
The only line of the input contains four positive integers \(x_1, x_2, x_3, x_4\) (\(2 \le x_i \le 10^9\)) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number \(x_1, x_2, x_3, x_4\).
|
Print such positive integers \(a\), \(b\) and \(c\) that four numbers written on a board are values \(a+b\), \(a+c\), \(b+c\) and \(a+b+c\) written in some order. Print \(a\), \(b\) and \(c\) in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.
|
Input: 3 6 5 4 | Output: 2 1 3
|
Beginner
| 1 | 570 | 237 | 295 | 11 |
|
1,051 |
B
|
1051B
|
B. Relatively Prime Pairs
| 1,000 |
greedy; math; number theory
|
You are given a set of all integers from \(l\) to \(r\) inclusive, \(l < r\), \((r - l + 1) \le 3 \cdot 10^5\) and \((r - l)\) is always odd.You want to split these numbers into exactly \(\frac{r - l + 1}{2}\) pairs in such a way that for each pair \((i, j)\) the greatest common divisor of \(i\) and \(j\) is equal to \(1\). Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.
|
The only line contains two integers \(l\) and \(r\) (\(1 \le l < r \le 10^{18}\), \(r - l + 1 \le 3 \cdot 10^5\), \((r - l)\) is odd).
|
If any solution exists, print ""YES"" in the first line. Each of the next \(\frac{r - l + 1}{2}\) lines should contain some pair of integers. GCD of numbers in each pair should be equal to \(1\). All \((r - l + 1)\) numbers should be pairwise distinct and should have values from \(l\) to \(r\) inclusive.If there are multiple solutions, print any of them.If there exists no solution, print ""NO"".
|
Input: 1 8 | Output: YES2 74 13 86 5
|
Beginner
| 3 | 492 | 134 | 398 | 10 |
|
1,350 |
A
|
1350A
|
A. Orac and Factors
| 900 |
math
|
Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers \(a\) and \(b\), \(a\) is a divisor of \(b\) if and only if there exists an integer \(c\), such that \(a\cdot c=b\).For \(n \ge 2\), we will denote as \(f(n)\) the smallest positive divisor of \(n\), except \(1\).For example, \(f(7)=7,f(10)=2,f(35)=5\).For the fixed integer \(n\), Orac decided to add \(f(n)\) to \(n\). For example, if he had an integer \(n=5\), the new value of \(n\) will be equal to \(10\). And if he had an integer \(n=6\), \(n\) will be changed to \(8\).Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers \(n\) and \(k\), Orac asked you to add \(f(n)\) to \(n\) exactly \(k\) times (note that \(n\) will change after each operation, so \(f(n)\) may change too) and tell him the final value of \(n\).For example, if Orac gives you \(n=5\) and \(k=2\), at first you should add \(f(5)=5\) to \(n=5\), so your new value of \(n\) will be equal to \(n=10\), after that, you should add \(f(10)=2\) to \(10\), so your new (and the final!) value of \(n\) will be equal to \(12\).Orac may ask you these queries many times.
|
The first line of the input is a single integer \(t\ (1\le t\le 100)\): the number of times that Orac will ask you.Each of the next \(t\) lines contains two positive integers \(n,k\ (2\le n\le 10^6, 1\le k\le 10^9)\), corresponding to a query by Orac.It is guaranteed that the total sum of \(n\) is at most \(10^6\).
|
Print \(t\) lines, the \(i\)-th of them should contain the final value of \(n\) in the \(i\)-th query by Orac.
|
In the first query, \(n=5\) and \(k=1\). The divisors of \(5\) are \(1\) and \(5\), the smallest one except \(1\) is \(5\). Therefore, the only operation adds \(f(5)=5\) to \(5\), and the result is \(10\).In the second query, \(n=8\) and \(k=2\). The divisors of \(8\) are \(1,2,4,8\), where the smallest one except \(1\) is \(2\), then after one operation \(8\) turns into \(8+(f(8)=2)=10\). The divisors of \(10\) are \(1,2,5,10\), where the smallest one except \(1\) is \(2\), therefore the answer is \(10+(f(10)=2)=12\).In the third query, \(n\) is changed as follows: \(3 \to 6 \to 8 \to 10 \to 12\).
|
Input: 3 5 1 8 2 3 4 | Output: 10 12 12
|
Beginner
| 1 | 1,200 | 316 | 110 | 13 |
1,891 |
D
|
1891D
|
D. Suspicious logarithms
| 1,900 |
binary search; brute force; math
|
Let \(f\)(\(x\)) be the floor of the binary logarithm of \(x\). In other words, \(f\)(\(x\)) is largest non-negative integer \(y\), such that \(2^y\) does not exceed \(x\).Let \(g\)(\(x\)) be the floor of the logarithm of \(x\) with base \(f\)(\(x\)). In other words, \(g\)(\(x\)) is the largest non-negative integer \(z\), such that \({f(x)}^{z}\) does not exceed \(x\).You are given \(q\) queries. The \(i\)-th query consists of two integers \(l_i\) and \(r_i\). The answer to the query is the sum of \(g\)(\(k\)) across all integers \(k\), such that \(l_i \leq k \leq r_i\). Since the answers might be large, print them modulo \({10^9 + 7}\).
|
The first line contains a single integer \(q\) — the number of queries (\(1 \leq q \leq 10^5\)).The next \(q\) lines each contain two integers \(l_i\) and \(r_i\) — the bounds of the \(i\)-th query (\(4 \leq l_i \leq r_i \leq 10^{18}\)).
|
For each query, output the answer to the query modulo \(10^9 + 7\).
|
The table below contains the values of the functions \(f\)(\(x\)) and \(g\)(\(x\)) for all \(x\) such that \(1 \leq x \leq 8\). \(x\)\(1\)\(2\)\(3\)\(4\)\(5\)\(6\)\(7\)\(8\)\(f\)\(0\)\(1\)\(1\)\(2\)\(2\)\(2\)\(2\)\(3\)\(g\)\(-\)\(-\)\(-\)\(2\)\(2\)\(2\)\(2\)\(1\)
|
Input: 12 4 6 4 7 4 8 4 100000 179 1000000000000000000 57 179 4 201018959 7 201018960 729 50624 728 50624 728 50625 729 50625 | Output: 6 8 9 348641 41949982 246 1 0 149688 149690 149694 149692
|
Hard
| 3 | 645 | 237 | 67 | 18 |
723 |
F
|
723F
|
F. st-Spanning Tree
| 2,300 |
dsu; graphs; greedy; implementation
|
You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n - 1 edges and can be obtained by removing some of the edges from G.The degree of a vertex is the number of edges incident to this vertex.
|
The first line of the input contains two integers n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ min(400 000, n·(n - 1) / 2)) — the number of vertices and the number of edges in the graph. The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected.The last line contains four integers s, t, ds, dt (1 ≤ s, t ≤ n, s ≠ t, 1 ≤ ds, dt ≤ n - 1).
|
If the answer doesn't exist print ""No"" (without quotes) in the only line of the output. Otherwise, in the first line print ""Yes"" (without quotes). In the each of the next (n - 1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once.You can output edges in any order. You can output the ends of each edge in any order.If there are several solutions, print any of them.
|
Input: 3 31 22 33 11 2 1 1 | Output: Yes3 21 3
|
Expert
| 4 | 765 | 537 | 464 | 7 |
|
2,120 |
F
|
2120F
|
F. Superb Graphs
| 2,600 |
2-sat; graphs
|
As we all know, Aryan is a funny guy. He decides to create fun graphs. For a graph \(G\), he defines fun graph \(G'\) of \(G\) as follows: Every vertex \(v'\) of \(G'\) maps to a non-empty independent set\(^{\text{∗}}\) or clique\(^{\text{†}}\) in \(G\). The sets of vertices of \(G\) that the vertices of \(G'\) map to are pairwise disjoint and combined cover all the vertices of \(G\), i.e., the sets of vertices of \(G\) mapped by vertices of \(G'\) form a partition of the vertex set of \(G\). If an edge connects two vertices \(v_1'\) and \(v_2'\) in \(G'\), then there is an edge between every vertex of \(G\) in the set mapped to \(v_1'\) and every vertex of \(G\) in the set mapped to \(v_2'\). If an edge does not connect two vertices \(v_1'\) and \(v_2'\) in \(G'\), then there is not an edge between any vertex of \(G\) in the set mapped to \(v_1'\) and any vertex of \(G\) in the set mapped to \(v_2'\). As we all know again, Harshith is a superb guy. He decides to use fun graphs to create his own superb graphs. For a graph \(G\), a fun graph \(G' '\) is called a superb graph of \(G\) if \(G' '\) has the minimum number of vertices among all possible fun graphs of \(G\).Aryan gives Harshith \(k\) simple undirected graphs\(^{\text{‡}}\) \(G_1, G_2,\ldots,G_k\), all on the same vertex set \(V\). Harshith then wonders if there exist \(k\) other graphs \(H_1, H_2,\ldots,H_k\), all on some other vertex set \(V'\) such that: \(G_i\) is a superb graph of \(H_i\) for all \(i\in \{1,2,\ldots,k\}\). If a vertex \(v\in V\) maps to an independent set of size greater than \(1\) in one \(G_i, H_i\) (\(1\leq i\leq k\)) pair, then there exists no pair \(G_j, H_j\) (\(1\leq j\leq k, j\neq i\)) where \(v\) maps to a clique of size greater than \(1\). Help Harshith solve his wonder.\(^{\text{∗}}\)For a graph \(G\), a subset \(S\) of vertices is called an independent set if no two vertices of \(S\) are connected with an edge.\(^{\text{†}}\)For a graph \(G\), a subset \(S\) of vertices is called a clique if every vertex of \(S\) is connected to every other vertex of \(S\) with an edge.\(^{\text{‡}}\)A graph is a simple undirected graph if its edges are undirected and there are no self-loops or multiple edges between the same pair of vertices.
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(k\) (\(1\leq n\leq 300, 1\leq k\leq 10\)).Then, there are \(k\) graphs described. The first line of each graph description contains a single integer \(m\) (\(0\leq m\leq \frac{n\cdot(n-1)}{2} \)).Next \(m\) lines each contain two space-separated integers \(u\) and \(v\) (\(1\leq u, v\leq n, u\neq v\)), denoting that an edge connects vertices \(u\) and \(v\).It is guaranteed that the sum of \(m\) over all graphs over all test cases does not exceed \(2\cdot 10^5\), and the sum of \(n\) over all test cases does not exceed \(300\).
|
For each testcase, print ""Yes"" if there exists \(k\) graphs satisfying the conditions; otherwise, ""No"".You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
|
For the first test case, the following are the graphs of \(G_1, H_1\) and \(G_2, H_2\) such that \(G_1\) is superb graph of \(H_1\) and \(G_2\) is superb graph of \(H_2\). In each graph, vertex \(2\) of \(G_i\) corresonds to independent set \(\{2\_1, 2\_2\}\) of corresponding \(H_i\) and remaining vertices \(v\in\{1,3,4,5\}\) of \(G_i\) correspond to independent set/clique \(\{v\}\) in corresponding \(H_i\)(a single vertex set can be considered both an independent set and a clique).In the third test case, it can be proven that the answer is ""No"".
|
Input: 35 233 45 35 163 53 41 41 22 34 24 3033 11 41 244 24 31 22 33 2033 13 21 2 | Output: Yes Yes No
|
Expert
| 2 | 2,258 | 761 | 268 | 21 |
1,850 |
B
|
1850B
|
B. Ten Words of Wisdom
| 800 |
implementation; sortings
|
In the game show ""Ten Words of Wisdom"", there are \(n\) participants numbered from \(1\) to \(n\), each of whom submits one response. The \(i\)-th response is \(a_i\) words long and has quality \(b_i\). No two responses have the same quality, and at least one response has length at most \(10\).The winner of the show is the response which has the highest quality out of all responses that are not longer than \(10\) words. Which response is the winner?
|
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 50\)) — the number of responses.Then \(n\) lines follow, the \(i\)-th of which contains two integers \(a_i\) and \(b_i\) (\(1 \leq a_i, b_i \leq 50\)) — the number of words and the quality of the \(i\)-th response, respectively. Additional constraints on the input: in each test case, at least one value of \(i\) satisfies \(a_i \leq 10\), and all values of \(b_i\) are distinct.
|
For each test case, output a single line containing one integer \(x\) (\(1 \leq x \leq n\)) — the winner of the show, according to the rules given in the statement.It can be shown that, according to the constraints in the statement, exactly one winner exists for each test case.
|
In the first test case, the responses provided are as follows: Response 1: \(7\) words, quality \(2\) Response 2: \(12\) words, quality \(5\) Response 3: \(9\) words, quality \(3\) Response 4: \(9\) words, quality \(4\) Response 5: \(10\) words, quality \(1\) We can see that the responses with indices \(1\), \(3\), \(4\), and \(5\) have lengths not exceeding \(10\) words. Out of these responses, the winner is the one with the highest quality.Comparing the qualities, we find that: Response 1 has quality \(2\). Response 3 has quality \(3\). Response 4 has quality \(4\). Response 5 has quality \(1\). Among these responses, Response 4 has the highest quality.
|
Input: 357 212 59 39 410 131 23 45 611 43 | Output: 4 3 1
|
Beginner
| 2 | 455 | 559 | 278 | 18 |
116 |
B
|
116B
|
B. Little Pigs and Wolves
| 1,100 |
greedy; implementation
|
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.What is the maximum number of little pigs that may be eaten by the wolves?
|
The first line contains integers n and m (1 ≤ n, m ≤ 10) which denotes the number of rows and columns in our two-dimensional grid, respectively. Then follow n lines containing m characters each — that is the grid description. ""."" means that this cell is empty. ""P"" means that this cell contains a little pig. ""W"" means that this cell contains a wolf. It is guaranteed that there will be at most one wolf adjacent to any little pig.
|
Print a single number — the maximal number of little pigs that may be eaten by the wolves.
|
In the first example, one possible scenario in which two little pigs get eaten by the wolves is as follows.
|
Input: 2 3PPWW.P | Output: 2
|
Easy
| 2 | 890 | 437 | 90 | 1 |
894 |
E
|
894E
|
E. Ralph and Mushrooms
| 2,100 |
dp; graphs
|
Ralph is going to collect mushrooms in the Mushroom Forest. There are m directed paths connecting n trees in the Mushroom Forest. On each path grow some mushrooms. When Ralph passes a path, he collects all the mushrooms on the path. The Mushroom Forest has a magical fertile ground where mushrooms grow at a fantastic speed. New mushrooms regrow as soon as Ralph finishes mushroom collection on a path. More specifically, after Ralph passes a path the i-th time, there regrow i mushrooms less than there was before this pass. That is, if there is initially x mushrooms on a path, then Ralph will collect x mushrooms for the first time, x - 1 mushrooms the second time, x - 1 - 2 mushrooms the third time, and so on. However, the number of mushrooms can never be less than 0.For example, let there be 9 mushrooms on a path initially. The number of mushrooms that can be collected from the path is 9, 8, 6 and 3 when Ralph passes by from first to fourth time. From the fifth time and later Ralph can't collect any mushrooms from the path (but still can pass it).Ralph decided to start from the tree s. How many mushrooms can he collect using only described paths?
|
The first line contains two integers n and m (1 ≤ n ≤ 106, 0 ≤ m ≤ 106), representing the number of trees and the number of directed paths in the Mushroom Forest, respectively.Each of the following m lines contains three integers x, y and w (1 ≤ x, y ≤ n, 0 ≤ w ≤ 108), denoting a path that leads from tree x to tree y with w mushrooms initially. There can be paths that lead from a tree to itself, and multiple paths between the same pair of trees.The last line contains a single integer s (1 ≤ s ≤ n) — the starting position of Ralph.
|
Print an integer denoting the maximum number of the mushrooms Ralph can collect during his route.
|
In the first sample Ralph can pass three times on the circle and collect 4 + 4 + 3 + 3 + 1 + 1 = 16 mushrooms. After that there will be no mushrooms for Ralph to collect.In the second sample, Ralph can go to tree 3 and collect 8 mushrooms on the path from tree 1 to tree 3.
|
Input: 2 21 2 42 1 41 | Output: 16
|
Hard
| 2 | 1,161 | 536 | 97 | 8 |
1,029 |
A
|
1029A
|
A. Many Equal Substrings
| 1,300 |
implementation; strings
|
You are given a string \(t\) consisting of \(n\) lowercase Latin letters and an integer number \(k\).Let's define a substring of some string \(s\) with indices from \(l\) to \(r\) as \(s[l \dots r]\).Your task is to construct such string \(s\) of minimum possible length that there are exactly \(k\) positions \(i\) such that \(s[i \dots i + n - 1] = t\). In other words, your task is to construct such string \(s\) of minimum possible length that there are exactly \(k\) substrings of \(s\) equal to \(t\).It is guaranteed that the answer is always unique.
|
The first line of the input contains two integers \(n\) and \(k\) (\(1 \le n, k \le 50\)) — the length of the string \(t\) and the number of substrings.The second line of the input contains the string \(t\) consisting of exactly \(n\) lowercase Latin letters.
|
Print such string \(s\) of minimum possible length that there are exactly \(k\) substrings of \(s\) equal to \(t\).It is guaranteed that the answer is always unique.
|
Input: 3 4aba | Output: ababababa
|
Easy
| 2 | 557 | 259 | 165 | 10 |
|
1,736 |
A
|
1736A
|
A. Make A Equal to B
| 800 |
brute force; greedy; sortings
|
You are given two arrays \(a\) and \(b\) of \(n\) elements, each element is either \(0\) or \(1\).You can make operations of \(2\) kinds. Pick an index \(i\) and change \(a_i\) to \(1-a_i\). Rearrange the array \(a\) however you want. Find the minimum number of operations required to make \(a\) equal to \(b\).
|
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 400\)) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 100\)) — the length of the arrays \(a\) and \(b\).The second line of each test case contains \(n\) space-separated integers \(a_1,a_2,\ldots,a_n\) (\(a_i\) is \(0\) or \(1\)), representing the array \(a\).The third line of each test case contains \(n\) space-separated integers \(b_1,b_2,\ldots,b_n\) (\(b_i\) is \(0\) or \(1\)), representing the array \(b\).
|
For each test case, print the minimum number of operations required to make \(a\) equal to \(b\).
|
In the first case, we need only one operation: change \(a_1\) to \(1-a_i\). Now \(a = [0, 0]\) which is equal to \(b\).In the second case, the optimal way is to rearrange \(a\) to get the array \([0, 1, 11\). Now \(a = [0, 0, 1]\) which is equal to \(b\).In the second case, one of optimal ways would be to first change \(a_3\) to \(1 - a_3\), then rearrange \(a\).In the third case, no operation is needed.In the fourth case, the optimal way is to rearrange \(a\) to get the array \([0, 1, 1, 0]\).
|
Input: 531 0 10 0 141 1 0 00 1 1 121 11 141 0 0 10 1 1 0101 | Output: 1 2 0 1 1
|
Beginner
| 3 | 311 | 618 | 97 | 17 |
833 |
B
|
833B
|
B. The Bakery
| 2,200 |
binary search; data structures; divide and conquer; dp; two pointers
|
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
|
The first line contains two integers n and k (1 ≤ n ≤ 35000, 1 ≤ k ≤ min(n, 50)) – the number of cakes and the number of boxes, respectively.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) – the types of cakes in the order the oven bakes them.
|
Print the only integer – the maximum total value of all boxes with cakes.
|
In the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.
|
Input: 4 11 2 2 1 | Output: 2
|
Hard
| 5 | 1,037 | 260 | 73 | 8 |
1,584 |
D
|
1584D
|
D. Guess the Permutation
| 2,000 |
binary search; combinatorics; interactive; math
|
This is an interactive problem.Jury initially had a sequence \(a\) of length \(n\), such that \(a_i = i\).The jury chose three integers \(i\), \(j\), \(k\), such that \(1 \leq i < j < k \leq n\), \(j - i > 1\). After that, Jury reversed subsegments \([i, j - 1]\) and \([j, k]\) of the sequence \(a\).Reversing a subsegment \([l, r]\) of the sequence \(a\) means reversing the order of elements \(a_l, a_{l+1}, \ldots, a_r\) in the sequence, i. e. \(a_l\) is swapped with \(a_r\), \(a_{l+1}\) is swapped with \(a_{r-1}\), etc.You are given the number \(n\) and you should find \(i\), \(j\), \(k\) after asking some questions.In one question you can choose two integers \(l\) and \(r\) (\(1 \leq l \leq r \leq n\)) and ask the number of inversions on the subsegment \([l, r]\) of the sequence \(a\). You will be given the number of pairs \((i, j)\) such that \(l \leq i < j \leq r\), and \(a_i > a_j\).Find the chosen numbers \(i\), \(j\), \(k\) after at most \(40\) questions.The numbers \(i\), \(j\), and \(k\) are fixed before the start of your program and do not depend on your queries.
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) — the number of test cases. Description of the test cases follows.The single line of each test case contains a single integer \(n\) (\(4 \leq n \leq 10^9\)). After reading it you should start an interaction process by asking questions for that test case. After giving an answer you should: Terminate your program if that is the last test case. Proceed to the next test case otherwise.
|
In the first test case, \(i = 1\), \(j = 3\), \(k = 5\), so the sequence \(a\) is \([2, 1, 5, 4, 3]\).In the second test case, \(i = 2\), \(j = 4\), \(k = 5\), so the sequence \(a\) is \([1, 3, 2, 5, 4]\).
|
Input: 2 5 4 3 3 5 2 2 1 | Output: ? 1 5 ? 2 5 ? 3 5 ! 1 3 5 ? 1 5 ? 2 5 ? 3 5 ! 2 4 5
|
Hard
| 4 | 1,089 | 498 | 0 | 15 |
|
66 |
D
|
66D
|
D. Petya and His Friends
| 1,700 |
constructive algorithms; math; number theory
|
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is evenly divisible by d. At that, we assume that all ai's are greater than zero.Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives a1 sweets, the 2-nd one gives a2 sweets, ..., the n-th one gives an sweets. At the same time, for any i and j (1 ≤ i, j ≤ n) they want the GCD(ai, aj) not to be equal to 1. However, they also want the following condition to be satisfied: GCD(a1, a2, ..., an) = 1. One more: all the ai should be distinct.Help the friends to choose the suitable numbers a1, ..., an.
|
The first line contains an integer n (2 ≤ n ≤ 50).
|
If there is no answer, print ""-1"" without quotes. Otherwise print a set of n distinct positive numbers a1, a2, ..., an. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them.Do not forget, please, that all of the following conditions must be true: For every i and j (1 ≤ i, j ≤ n): GCD(ai, aj) ≠ 1 GCD(a1, a2, ..., an) = 1 For every i and j (1 ≤ i, j ≤ n, i ≠ j): ai ≠ aj Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
|
Input: 3 | Output: 995511115
|
Medium
| 3 | 863 | 50 | 646 | 0 |
|
1,068 |
A
|
1068A
|
A. Birthday
| 1,400 |
math
|
Ivan is collecting coins. There are only \(N\) different collectible coins, Ivan has \(K\) of them. He will be celebrating his birthday soon, so all his \(M\) freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than \(L\) coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.
|
The only line of input contains 4 integers \(N\), \(M\), \(K\), \(L\) (\(1 \le K \le N \le 10^{18}\); \(1 \le M, \,\, L \le 10^{18}\)) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.
|
Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print ""-1"" (without quotes).
|
In the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.
|
Input: 20 15 2 3 | Output: 1
|
Easy
| 1 | 713 | 279 | 176 | 10 |
1,352 |
A
|
1352A
|
A. Sum of Round Numbers
| 800 |
implementation; math
|
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from \(1\) to \(9\) (inclusive) are round.For example, the following numbers are round: \(4000\), \(1\), \(9\), \(800\), \(90\). The following numbers are not round: \(110\), \(707\), \(222\), \(1001\).You are given a positive integer \(n\) (\(1 \le n \le 10^4\)). Represent the number \(n\) as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number \(n\) as a sum of the least number of terms, each of which is a round number.
|
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases in the input. Then \(t\) test cases follow.Each test case is a line containing an integer \(n\) (\(1 \le n \le 10^4\)).
|
Print \(t\) answers to the test cases. Each answer must begin with an integer \(k\) — the minimum number of summands. Next, \(k\) terms must follow, each of which is a round number, and their sum is \(n\). The terms can be printed in any order. If there are several answers, print any of them.
|
Input: 5 5009 7 9876 10000 10 | Output: 2 5000 9 1 7 4 800 70 6 9000 1 10000 1 10
|
Beginner
| 2 | 739 | 210 | 293 | 13 |
|
6 |
B
|
6B
|
B. President's Office
| 1,100 |
implementation
|
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
|
The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
|
Print the only number — the amount of President's deputies.
|
Input: 3 4 RG.B..RR.TTT. | Output: 2
|
Easy
| 1 | 856 | 439 | 59 | 0 |
|
66 |
E
|
66E
|
E. Petya and Post
| 2,000 |
data structures; dp
|
Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations. The total number of stations equals to n. One can fuel the car at the i-th station with no more than ai liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the 1-st and the 2-nd station is b1 kilometers, the distance between the 2-nd and the 3-rd one is b2 kilometers, ..., between the (n - 1)-th and the n-th ones the distance is bn - 1 kilometers and between the n-th and the 1-st one the distance is bn kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all ai is equal to the sum of all bi. The i-th gas station and i-th post office are very close, so the distance between them is 0 kilometers.Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.
|
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers ai — amount of gasoline on the i-th station. The third line contains n integers b1, b2, ..., bn. They are the distances between the 1-st and the 2-nd gas stations, between the 2-nd and the 3-rd ones, ..., between the n-th and the 1-st ones, respectively. The sum of all bi equals to the sum of all ai and is no more than 109. Each of the numbers ai, bi is no less than 1 and no more than 109.
|
Print on the first line the number k — the number of possible post offices, from which the car can drive one circle along a circular road. Print on the second line k numbers in the ascending order — the numbers of offices, from which the car can start.
|
Input: 41 7 2 38 1 1 3 | Output: 22 4
|
Hard
| 2 | 1,934 | 477 | 252 | 0 |
|
913 |
C
|
913C
|
C. Party Lemonade
| 1,600 |
bitmasks; dp; greedy
|
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci roubles. The number of bottles of each type in the store can be considered infinite.You want to buy at least L liters of lemonade. How many roubles do you have to spend?
|
The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 109) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively.The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 109) — the costs of bottles of different types.
|
Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.
|
In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.
|
Input: 4 1220 30 70 90 | Output: 150
|
Medium
| 3 | 486 | 286 | 119 | 9 |
1,917 |
C
|
1917C
|
C. Watering an Array
| 1,600 |
brute force; greedy; implementation; math
|
You have an array of integers \(a_1, a_2, \ldots, a_n\) of length \(n\). On the \(i\)-th of the next \(d\) days you are going to do exactly one of the following two actions: Add \(1\) to each of the first \(b_i\) elements of the array \(a\) (i.e., set \(a_j := a_j + 1\) for each \(1 \le j \le b_i\)). Count the elements which are equal to their position (i.e., the \(a_j = j\)). Denote the number of such elements as \(c\). Then, you add \(c\) to your score, and reset the entire array \(a\) to a \(0\)-array of length \(n\) (i.e., set \([a_1, a_2, \ldots, a_n] := [0, 0, \ldots, 0]\)). Your score is equal to \(0\) in the beginning. Note that on each day you should perform exactly one of the actions above: you cannot skip a day or perform both actions on the same day.What is the maximum score you can achieve at the end?Since \(d\) can be quite large, the sequence \(b\) is given to you in the compressed format: You are given a sequence of integers \(v_1, v_2, \ldots, v_k\). The sequence \(b\) is a concatenation of infinitely many copies of \(v\): \(b = [v_1, v_2, \ldots, v_k, v_1, v_2, \ldots, v_k, \ldots]\).
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^3\)) — the number of test cases.The first line of each test case contains three integers \(n\), \(k\) and \(d\) (\(1 \le n \le 2000\), \(1 \le k \le 10^5\), \(k \le d \le 10^9\)) — the length of the array \(a\), the length of the sequence \(v\) and the number of days you are going to perform operations on.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le n\)) — the array \(a\).The third line of each test case contains \(k\) integers \(v_1, v_2, \ldots, v_k\) (\(1 \le v_i \le n\)) — the sequence \(v\).It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2000\) and the sum of \(k\) over all test cases doesn't exceed \(10^5\).
|
For each test case, output one integer: the maximum score you can achieve at the end of the \(d\)-th day.
|
In the first test case, the sequence \(b\) is equal to \([1, 3, 2, 3, 1, 3, 2, 3, \ldots]\) and one of the optimal solutions for this case is as follows: Perform the operation of the second type on the \(1\)-st day: your score increases by \(3\) and array \(a\) becomes equal to \([0, 0, 0]\). Perform the operation of the first type on the \(2\)-nd day: array \(a\) becomes equal to \([1, 1, 1]\). Perform the operation of the first type on the \(3\)-rd day: array \(a\) becomes equal to \([2, 2, 1]\). Perform the operation of the second type on the \(4\)-th day: your score increases by \(1\) and array \(a\) becomes equal to \([0, 0, 0]\). It can be shown that it is impossible to score more than \(4\), so the answer is \(4\).In the second test case, the sequence \(b\) is equal to \([6, 6, 6, 6, \ldots]\). One of the ways to score \(3\) is to perform operations of the first type on the \(1\)-st and the \(3\)-rd days and to perform an operation of the second type on the \(2\)-nd day.
|
Input: 53 4 41 2 31 3 2 36 2 36 1 2 4 1 56 65 1 10 5 0 5 051 1 1113 4 61 2 31 3 2 3 | Output: 4 3 0 1 5
|
Medium
| 4 | 1,119 | 770 | 105 | 19 |
1,469 |
C
|
1469C
|
C. Building a Fence
| 1,600 |
dp; greedy; implementation; two pointers
|
You want to build a fence that will consist of \(n\) equal sections. All sections have a width equal to \(1\) and height equal to \(k\). You will place all sections in one line side by side.Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the \(i\)-th section is equal to \(h_i\). You should follow several rules to build the fence: the consecutive sections should have a common side of length at least \(1\); the first and the last sections should stand on the corresponding ground levels; the sections between may be either on the ground level or higher, but not higher than \(k - 1\) from the ground level \(h_i\) (the height should be an integer); One of possible fences (blue color) for the first test case Is it possible to build a fence that meets all rules?
|
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(2 \le n \le 2 \cdot 10^5\); \(2 \le k \le 10^8\)) — the number of sections in the fence and the height of each section.The second line of each test case contains \(n\) integers \(h_1, h_2, \dots, h_n\) (\(0 \le h_i \le 10^8\)), where \(h_i\) is the ground level beneath the \(i\)-th section.It's guaranteed that the sum of \(n\) over test cases doesn't exceed \(2 \cdot 10^5\).
|
For each test case print YES if it's possible to build the fence that meets all rules. Otherwise, print NO.You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).
|
In the first test case, one of the possible fences is shown in the picture.In the second test case, according to the second rule, you should build both sections on the corresponding ground levels, and since \(k = 3\), \(h_1 = 0\), and \(h_2 = 2\) the first rule is also fulfilled.In the third test case, according to the second rule, you should build the first section on height \(3\) and the third section on height \(2\). According to the first rule, the second section should be on the height of at least \(2\) (to have a common side with the first section), but according to the third rule, the second section can be built on the height of at most \(h_2 + k - 1 = 1\).
|
Input: 3 6 3 0 0 2 5 1 1 2 3 0 2 3 2 3 0 2 | Output: YES YES NO
|
Medium
| 4 | 831 | 548 | 221 | 14 |
234 |
A
|
234A
|
A. Lefthanders and Righthanders
| 1,200 |
implementation
|
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
|
The first input line contains a single even integer n (4 ≤ n ≤ 100) — the number of students in the class. The second line contains exactly n capital English letters ""L"" and ""R"". If the i-th letter at the second line equals ""L"", then the student number i is a lefthander, otherwise he is a righthander.
|
Print integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.
|
Input: 6LLRLLL | Output: 1 42 56 3
|
Easy
| 1 | 1,112 | 308 | 369 | 2 |
|
520 |
E
|
520E
|
E. Pluses everywhere
| 2,200 |
combinatorics; dp; math; number theory
|
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses (""+"") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109 + 7. Help him!
|
The first line contains two integers, n and k (0 ≤ k < n ≤ 105).The second line contains a string consisting of n digits.
|
Print the answer to the problem modulo 109 + 7.
|
In the first sample the result equals (1 + 08) + (10 + 8) = 27.In the second sample the result equals 1 + 0 + 8 = 9.
|
Input: 3 1108 | Output: 27
|
Hard
| 4 | 1,116 | 121 | 47 | 5 |
1,249 |
B1
|
1249B1
|
B1. Books Exchange (easy version)
| 1,000 |
dsu; math
|
The only difference between easy and hard versions is constraints.There are \(n\) kids, each of them is reading a unique book. At the end of any day, the \(i\)-th kid will give his book to the \(p_i\)-th kid (in case of \(i = p_i\) the kid will give his book to himself). It is guaranteed that all values of \(p_i\) are distinct integers from \(1\) to \(n\) (i.e. \(p\) is a permutation). The sequence \(p\) doesn't change from day to day, it is fixed.For example, if \(n=6\) and \(p=[4, 6, 1, 3, 5, 2]\) then at the end of the first day the book of the \(1\)-st kid will belong to the \(4\)-th kid, the \(2\)-nd kid will belong to the \(6\)-th kid and so on. At the end of the second day the book of the \(1\)-st kid will belong to the \(3\)-th kid, the \(2\)-nd kid will belong to the \(2\)-th kid and so on.Your task is to determine the number of the day the book of the \(i\)-th child is returned back to him for the first time for every \(i\) from \(1\) to \(n\).Consider the following example: \(p = [5, 1, 2, 4, 3]\). The book of the \(1\)-st kid will be passed to the following kids: after the \(1\)-st day it will belong to the \(5\)-th kid, after the \(2\)-nd day it will belong to the \(3\)-rd kid, after the \(3\)-rd day it will belong to the \(2\)-nd kid, after the \(4\)-th day it will belong to the \(1\)-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer \(q\) independent queries.
|
The first line of the input contains one integer \(q\) (\(1 \le q \le 200\)) — the number of queries. Then \(q\) queries follow.The first line of the query contains one integer \(n\) (\(1 \le n \le 200\)) — the number of kids in the query. The second line of the query contains \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\), all \(p_i\) are distinct, i.e. \(p\) is a permutation), where \(p_i\) is the kid which will get the book of the \(i\)-th kid.
|
For each query, print the answer on it: \(n\) integers \(a_1, a_2, \dots, a_n\), where \(a_i\) is the number of the day the book of the \(i\)-th child is returned back to him for the first time in this query.
|
Input: 6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3 | Output: 1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 4
|
Beginner
| 2 | 1,537 | 465 | 208 | 12 |
|
162 |
G
|
162G
|
G. Non-decimal sum
| 2,000 |
*special
|
You are given an array of integers written in base radix. Calculate their sum and output it written in the same base.
|
The first line of the input contains an integer n (1 ≤ n ≤ 10) — the size of the array. The second line contains an integer radix (2 ≤ radix ≤ 36) — the base of the numeral system used. Next n lines contain the elements of the array, one per line. Each element is a non-negative integer written in radix-based notation, possibly with leading zeros, which contains between 1 and 5 digits, inclusive. The digits of the notation will be 0, 1, ..., 9, A, B, ..., Z in the given order.
|
Output the sum of array elements in radix-based notation. Use the same format as in the input.
|
Input: 316F020B004 | Output: 2FF
|
Hard
| 1 | 117 | 480 | 94 | 1 |
|
288 |
A
|
288A
|
A. Polo the Penguin and Strings
| 1,300 |
greedy
|
Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.
|
A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.
|
In a single line print the required string. If there isn't such string, print ""-1"" (without the quotes).
|
Input: 7 4 | Output: ababacd
|
Easy
| 1 | 905 | 136 | 106 | 2 |
|
360 |
D
|
360D
|
D. Levko and Sets
| 2,600 |
number theory
|
Levko loves all sorts of sets very much.Levko has two arrays of integers a1, a2, ... , an and b1, b2, ... , bm and a prime number p. Today he generates n sets. Let's describe the generation process for the i-th set: First it has a single number 1. Let's take any element c from this set. For all j (1 ≤ j ≤ m) if number (c·aibj) mod p doesn't occur in the set, then add it to the set. Repeat step 2 as long as we can add at least one element to our set. Levko wonders, how many numbers belong to at least one set. That is, he wants to know what size is the union of n generated sets.
|
The first line contains three integers n, m and p (1 ≤ n ≤ 104, 1 ≤ m ≤ 105, 2 ≤ p ≤ 109), p is prime. The second line contains space-separated integers a1, a2, ... , an (1 ≤ ai < p). The third line contains space-separated integers b1, b2, ... , bm (1 ≤ bi ≤ 109).
|
The single number — the size of the union of the sets.
|
Input: 1 1 725 | Output: 3
|
Expert
| 1 | 583 | 265 | 54 | 3 |
|
268 |
E
|
268E
|
E. Playlist
| 2,100 |
math; probabilities; sortings
|
Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist: If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song. If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song. For example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following: Manao listens to A, he likes it, he remembers it. Manao listens to B, he does not like it, so he listens to A, again. Manao listens to C, he likes the song and he remembers it, too. Manao listens to D, but does not enjoy it and re-listens to songs A and C. That is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening.Manao has received n songs: the i-th of them is li seconds long and Manao may like it with a probability of pi percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist.
|
The first line contains a single integer n (1 ≤ n ≤ 50000). The i-th of the following n lines contains two integers, separated by a single space — li and pi (15 ≤ li ≤ 1000, 0 ≤ pi ≤ 100) — the length of the i-th song in seconds and the probability that Manao will like the song, in percents.
|
In a single line print a single real number — the maximum expected listening time over all permutations of songs. The answer will be considered valid if the absolute or relative error does not exceed 10 - 9.
|
Consider the first test case. If Manao listens to the songs in the order in which they were originally compiled, the mathematical expectation will be equal to 467.5 seconds. The maximum expected value is obtained by putting the first song at the end of the playlist.Consider the second test case. The song which is 360 seconds long should be listened to first. The song 300 seconds long which Manao will dislike for sure should be put in the end.
|
Input: 3150 20150 50100 50 | Output: 537.500000000
|
Hard
| 3 | 1,717 | 292 | 207 | 2 |
1,007 |
C
|
1007C
|
C. Guess two numbers
| 3,000 |
binary search; interactive
|
This is an interactive problem.Vasya and Vitya play a game. Vasya thought of two integers \(a\) and \(b\) from \(1\) to \(n\) and Vitya tries to guess them. Each round he tells Vasya two numbers \(x\) and \(y\) from \(1\) to \(n\). If both \(x=a\) and \(y=b\) then Vitya wins. Else Vasya must say one of the three phrases: \(x\) is less than \(a\); \(y\) is less than \(b\); \(x\) is greater than \(a\) or \(y\) is greater than \(b\). Vasya can't lie, but if multiple phrases are true, he may choose any of them. For example, if Vasya thought of numbers \(2\) and \(4\), then he answers with the phrase \(3\) to a query \((3, 4)\), and he can answer with the phrase \(1\) or phrase \(3\) to a query \((1, 5)\).Help Vitya win in no more than \(600\) rounds.
|
The first line contains a single integer \(n\) (\(1 \leq n \leq 10^{18}\)) — the upper limit of the numbers.
|
Let's analyze the sample test. The chosen numbers are \(2\) and \(4\). The interactor was given two instructions.For the query \((4, 3)\), it can return \(2\) or \(3\). Out of the two instructions the second one is chosen, so the interactor returns \(a^{23}_2=3\).For the query \((3, 4)\), it can return only \(3\).For the query \((3, 3)\), it can return \(2\) or \(3\). Out of the two instructions the first one is chosen (since in case of equal values, the least number is preferred), so the interactor returns \(a^{23}_1=2\).For the query \((1, 5)\), it can return \(1\) or \(3\). Out of the two instructions the first one is chosen, so the interactor returns \(a^{13}_1=1\).In the fifth query \((2, 4)\), the numbers are guessed correctly, the player wins.
|
Input: 533210 | Output: 4 33 43 31 52 4
|
Master
| 2 | 756 | 108 | 0 | 10 |
|
2,063 |
F1
|
2063F1
|
F1. Counting Is Not Fun (Easy Version)
| 2,400 |
combinatorics; data structures; dfs and similar; dp; dsu; graphs; hashing; implementation; math; trees
|
This is the easy version of the problem. The difference between the versions is that in this version, the limits on \(t\) and \(n\) are smaller. You can hack only if you solved all versions of this problem. Now Little John is rich, and so he finally buys a house big enough to fit himself and his favorite bracket sequence. But somehow, he ended up with a lot of brackets! Frustrated, he penetrates through the ceiling with the ""buddha palm"". A bracket sequence is called balanced if it can be constructed by the following formal grammar. The empty sequence \(\varnothing\) is balanced. If the bracket sequence \(A\) is balanced, then \(\mathtt{(}A\mathtt{)}\) is also balanced. If the bracket sequences \(A\) and \(B\) are balanced, then the concatenated sequence \(A B\) is also balanced. For example, the sequences ""(())()"", ""()"", ""(()(()))"", and the empty sequence are balanced, while ""(()"" and ""(()))("" are not.Given a balanced bracket sequence \(s\), a pair of indices \((i,j)\) (\(i<j\)) is called a good pair if \(s_i\) is '(', \(s_j\) is ')', and the two brackets are added simultaneously with respect to Rule 2 while constructing the sequence \(s\). For example, the sequence ""(())()"" has three different good pairs, which are \((1,4)\), \((2,3)\), and \((5,6)\). One can show that any balanced bracket sequence of \(2n\) brackets contains exactly \(n\) different good pairs, and using any order of rules to construct the same bracket sequence will yield the same set of good pairs.Emily will play a bracket guessing game with John. The game is played as follows.Initially, John has a balanced bracket sequence \(s\) containing \(n\) different good pairs, which is not known to Emily. John tells Emily the value of \(n\) and asks Emily to guess the sequence.Throughout \(n\) turns, John gives Emily the following kind of clue on each turn. \(l\;r\): The sequence \(s\) contains a good pair \((l,r)\). The clues that John gives Emily are pairwise distinct and do not contradict each other.At a certain point, Emily can be certain that the balanced bracket sequence satisfying the clues given so far is unique. For example, assume Emily knows that \(s\) has \(3\) good pairs, and it contains the good pair \((2,5)\). Out of \(5\) balanced bracket sequences with \(3\) good pairs, there exists only one such sequence ""((()))"" with the good pair \((2,5)\). Therefore, one can see that Emily does not always need \(n\) turns to guess \(s\).To find out the content of \(s\) as early as possible, Emily wants to know the number of different balanced bracket sequences that match the clues after each turn. Surely, this is not an easy job for Emily, especially when she is given so many good pairs. Now it is your turn to help Emily. Given the clues, you must find the answer before and after each turn. As the answers may be huge, you need to find them modulo \(998\,244\,353\).
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)). The description of the test cases follows. The first line of each test case contains one integer \(n\) (\(2 \le n \le 5000\)) — the number of good pairs.Then, each of the \(n\) following lines contains two integers \(l_i\) and \(r_i\) representing the \(i\)-th clue (\(1 \le l_i < r_i \le 2n\)).The clues in one test case are pairwise distinct and do not contradict each other.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5000\).
|
For each test case, output \(n+1\) integers on a separate line: The first integer is the answer before all clues, modulo \(998\,244\,353\). For all \(i \ge 1\), the \(i+1\)-th integer is the answer after the \(i\)-th clue, modulo \(998\,244\,353\).
|
The first test case of the example is explained in the problem description.The third test case of the example is explained as follows. It can be shown that there are \(132\) balanced bracket sequences with \(6\) good pairs. The answers after each clue are given as follows: You are given the good pair \((2,3)\). There are \(42\) balanced bracket sequences having the good pair \((2,3)\). You are given the good pair \((1,6)\). There are \(5\) balanced bracket sequences having good pairs \((2,3)\), \((1,6)\). You are given the good pair \((7,8)\). There are \(2\) balanced bracket sequences having the three good pairs. The strings are ""(()())()(())"" and ""(()())()()()"", respectively. You are given the good pair \((9,12)\). There is only one balanced bracket sequence having the four good pairs. The content of \(s\) is therefore the only string, which is ""(()())()(())"". Then, the number of bracket sequences after the fifth and the sixth clue are both \(1\) as you already know the content of \(s\).
|
Input: 332 51 63 441 67 82 34 562 31 67 89 1210 114 5 | Output: 5 1 1 1 14 2 2 1 1 132 42 5 2 1 1 1
|
Expert
| 10 | 2,897 | 580 | 248 | 20 |
1,403 |
B
|
1403B
|
B. Spring cleaning
| 2,300 |
*special; data structures; dfs and similar; graphs; trees
|
Spring cleanings are probably the most boring parts of our lives, except this year, when Flóra and her mother found a dusty old tree graph under the carpet.This tree has \(N\) nodes (numbered from \(1\) to \(N\)), connected by \(N-1\) edges. The edges gathered too much dust, so Flóra's mom decided to clean them. Cleaning the edges of an arbitrary tree is done by repeating the following process: She chooses 2 different leaves (a node is a leaf if it is connected to exactly one other node by an edge), and cleans every edge lying on the shortest path between them. If this path has \(d\) edges, then the cost of cleaning this path is \(d\).She doesn't want to harm the leaves of the tree, so she chooses every one of them at most once. A tree is cleaned when all of its edges are cleaned. The cost of this is the sum of costs for all cleaned paths.Flóra thinks the tree they found is too small and simple, so she imagines \(Q\) variations of it. In the \(i\)-th variation, she adds a total of \(D_i\) extra leaves to the original tree: for each new leaf, she chooses a node from the original tree, and connects that node with the new leaf by an edge. Note that some nodes may stop being leaves during this step.For all these \(Q\) variations, we are interested in the minimum cost that is required to clean the tree.
|
The first line contains two space-separated integer, \(N\) and \(Q\) (\(3 \leq N \leq 10^{5}\), \(1 \leq Q \leq 10^{5}\)) – the number of nodes the tree has and the number of variations. Each of the next \(N-1\) lines contains two space-separated integers \(u\) and \(v\) denoting that nodes \(u\) and \(v\) are connected by an edge (\(1 \leq u, v \leq N\)). The next \(Q\) lines describe the variations. The first integer in the \(i\)th line is \(D_i\) (\(1 \leq D_i \leq 10^{5}\)). Then \(D_i\) space-separated integers follow: if the \(j\)th number is \(a_j\), it means that Flóra adds a new leaf to node \(a_j\) (\(1 \leq a_j \leq N\)). We may add more than one leaf to the same node. \(\sum_{1}^{Q} D_i \leq 10^{5}\) i.e. the sum of \(D_i\) in all varations is at most \(10^5\).After each variation, Flóra restarts and adds extra leaves to the original tree.
|
You should print \(Q\) lines. In the \(i\)-th line, print a single integer: the minimum cost required to clean the \(i\)-th variation of the tree. If the tree cannot be cleaned, print \(-1\).
|
The following picture shows the second variation. A possible solution is to clean the path between leaves \(1 - 6\), \(A - 7\) and \( B - 3\).You can download the above example and an additional (bigger) sample input here: https://gofile.io/d/8QlbsS
|
Input: 7 3 1 2 2 4 4 5 5 6 5 7 3 4 1 4 2 2 4 1 1 | Output: -1 10 8
|
Expert
| 5 | 1,319 | 863 | 191 | 14 |
1,200 |
A
|
1200A
|
A. Hotelier
| 800 |
brute force; data structures; implementation
|
Amugae has a hotel consisting of \(10\) rooms. The rooms are numbered from \(0\) to \(9\) from left to right.The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.
|
The first line consists of an integer \(n\) (\(1 \le n \le 10^5\)), the number of events in Amugae's memory.The second line consists of a string of length \(n\) describing the events in chronological order. Each character represents: 'L': A customer arrives from the left entrance. 'R': A customer arrives from the right entrance. '0', '1', ..., '9': The customer in room \(x\) (\(0\), \(1\), ..., \(9\) respectively) leaves. It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room \(x\) when \(x\) (\(0\), \(1\), ..., \(9\)) is given. Also, all the rooms are initially empty.
|
In the only line, output the hotel room's assignment status, from room \(0\) to room \(9\). Represent an empty room as '0', and an occupied room as '1', without spaces.
|
In the first example, hotel room's assignment status after each action is as follows. First of all, all rooms are empty. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. L: one more customer from the left entrance. Assignment status is 1110000001. 1: the customer in room \(1\) leaves. Assignment status is 1010000001. R: one more customer from the right entrance. Assignment status is 1010000011. L: one more customer from the left entrance. Assignment status is 1110000011. 1: the customer in room \(1\) leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011.In the second example, hotel room's assignment status after each action is as follows. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. 0: the customer in room \(0\) leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again. 0: the customer in room \(0\) leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. R: one more customer from the right entrance. Assignment status is 1100000011. 9: the customer in room \(9\) leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010.
|
Input: 8 LLRL1RL1 | Output: 1010000011
|
Beginner
| 3 | 772 | 636 | 168 | 12 |
585 |
F
|
585F
|
F. Digits of Number Pi
| 3,200 |
dp; implementation; strings
|
Vasily has recently learned about the amazing properties of number π. In one of the articles it has been hypothesized that, whatever the sequence of numbers we have, in some position, this sequence is found among the digits of number π. Thus, if you take, for example, the epic novel ""War and Peace"" of famous Russian author Leo Tolstoy, and encode it with numbers, then we will find the novel among the characters of number π.Vasily was absolutely delighted with this, because it means that all the books, songs and programs have already been written and encoded in the digits of π. Vasily is, of course, a bit wary that this is only a hypothesis and it hasn't been proved, so he decided to check it out.To do this, Vasily downloaded from the Internet the archive with the sequence of digits of number π, starting with a certain position, and began to check the different strings of digits on the presence in the downloaded archive. Vasily quickly found short strings of digits, but each time he took a longer string, it turned out that it is not in the archive. Vasily came up with a definition that a string of length d is a half-occurrence if it contains a substring of length of at least , which occurs in the archive.To complete the investigation, Vasily took 2 large numbers x, y (x ≤ y) with the same number of digits and now he wants to find the number of numbers in the interval from x to y, which are half-occurrences in the archive. Help Vasily calculate this value modulo 109 + 7.
|
The first line contains string s consisting of decimal digits (1 ≤ |s| ≤ 1000) that Vasily will use to search substrings in. According to hypothesis, this sequence of digis indeed occurs in the decimal representation of π, although we can't guarantee that.The second and third lines contain two positive integers x, y of the same length d (x ≤ y, 2 ≤ d ≤ 50). Numbers x, y do not contain leading zeroes.
|
Print how many numbers in the segment from x to y that are half-occurrences in s modulo 109 + 7.
|
Input: 021019 | Output: 2
|
Master
| 3 | 1,495 | 403 | 96 | 5 |
|
1,208 |
B
|
1208B
|
B. Uniqueness
| 1,500 |
binary search; brute force; implementation; two pointers
|
You are given an array \(a_{1}, a_{2}, \ldots, a_{n}\). You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers \(l\) and \(r\) (\(1 \leq l \leq r \leq n\)) and delete integers \(a_l, a_{l+1}, \ldots, a_r\) from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.
|
The first line of the input contains a single integer \(n\) (\(1 \le n \le 2000\)) — the number of elements in the given array.The next line contains \(n\) spaced integers \(a_{1}, a_{2}, \ldots, a_{n}\) (\(1 \le a_{i} \le 10^{9}\)) — the elements of the array.
|
Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print \(0\).
|
In the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index \(2\) to \(3\).In the third example you can remove the subsegments from index \(1\) to \(2\), or from index \(2\) to \(3\), or from index \(3\) to \(4\).
|
Input: 3 1 2 3 | Output: 0
|
Medium
| 4 | 473 | 261 | 182 | 12 |
808 |
F
|
808F
|
F. Card Game
| 2,400 |
binary search; flows; graphs
|
Digital collectible card games have become very popular recently. So Vova decided to try one of these.Vova has n cards in his collection. Each of these cards is characterised by its power pi, magic number ci and level li. Vova wants to build a deck with total power not less than k, but magic numbers may not allow him to do so — Vova can't place two cards in a deck if the sum of the magic numbers written on these cards is a prime number. Also Vova cannot use a card if its level is greater than the level of Vova's character.At the moment Vova's character's level is 1. Help Vova to determine the minimum level he needs to reach in order to build a deck with the required total power.
|
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 100000).Then n lines follow, each of these lines contains three numbers that represent the corresponding card: pi, ci and li (1 ≤ pi ≤ 1000, 1 ≤ ci ≤ 100000, 1 ≤ li ≤ n).
|
If Vova won't be able to build a deck with required power, print - 1. Otherwise print the minimum level Vova has to reach in order to build a deck.
|
Input: 5 85 5 11 5 44 6 31 12 43 12 1 | Output: 4
|
Expert
| 3 | 687 | 237 | 147 | 8 |
|
3 |
C
|
3C
|
C. Tic-tac-toe
| 1,800 |
brute force; games; implementation
|
Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below: illegal — if the given board layout can't appear during a valid game; the first player won — if in the given board layout the first player has just won; the second player won — if in the given board layout the second player has just won; draw — if the given board layout has just let to a draw.
|
The input consists of three lines, each of the lines contains characters ""."", ""X"" or ""0"" (a period, a capital letter X, or a digit zero).
|
Print one of the six verdicts: first, second, illegal, the first player won, the second player won or draw.
|
Input: X0X.0..X. | Output: second
|
Medium
| 3 | 954 | 143 | 107 | 0 |
|
207 |
D10
|
207D10
|
D10. The Beaver's Problem - 3
| 2,100 |
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:You've got some training set of documents. For each document you know its subject. The subject in this problem is an integer from 1 to 3. Each of these numbers has a physical meaning. For instance, all documents with subject 3 are about trade.You can download the training set of documents at the following link: http://download4.abbyy.com/a2/X2RZ2ZWXBG5VYWAL61H76ZQM/train.zip. The archive contains three directories with names ""1"", ""2"", ""3"". Directory named ""1"" contains documents on the 1-st subject, directory ""2"" contains documents on the 2-nd subject, and directory ""3"" contains documents on the 3-rd subject. Each document corresponds to exactly one file from some directory.All documents have the following format: the first line contains the document identifier, the second line contains the name of the document, all subsequent lines contain the text of the document. The document identifier is used to make installing the problem more convenient and has no useful information for the participants.You need to write a program that should indicate the subject for a given document. It is guaranteed that all documents given as input to your program correspond to one of the three subjects of the training set.
|
The first line contains integer id (0 ≤ id ≤ 106) — the document identifier. The second line contains the name of the document. The third and the subsequent lines contain the text of the document. It is guaranteed that the size of any given document will not exceed 10 kilobytes.The tests for this problem are divided into 10 groups. Documents of groups 1 and 2 are taken from the training set, but their identifiers will not match the identifiers specified in the training set. Groups from the 3-rd to the 10-th are roughly sorted by the author in ascending order of difficulty (these groups contain documents which aren't present in the training set).
|
Print an integer from 1 to 3, inclusive — the number of the subject the given document corresponds to.
|
Hard
| 0 | 1,472 | 653 | 102 | 2 |
|||
497 |
D
|
497D
| 2,900 |
brute force; geometry; math
|
Master
| 3 | 0 | 0 | 0 | 4 |
||||||
1,093 |
G
|
1093G
|
G. Multidimensional Queries
| 2,300 |
bitmasks; data structures
|
You are given an array \(a\) of \(n\) points in \(k\)-dimensional space. Let the distance between two points \(a_x\) and \(a_y\) be \(\sum \limits_{i = 1}^{k} |a_{x, i} - a_{y, i}|\) (it is also known as Manhattan distance).You have to process \(q\) queries of the following two types: \(1\) \(i\) \(b_1\) \(b_2\) ... \(b_k\) — set \(i\)-th element of \(a\) to the point \((b_1, b_2, \dots, b_k)\); \(2\) \(l\) \(r\) — find the maximum distance between two points \(a_i\) and \(a_j\), where \(l \le i, j \le r\).
|
The first line contains two numbers \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5\), \(1 \le k \le 5\)) — the number of elements in \(a\) and the number of dimensions of the space, respectively.Then \(n\) lines follow, each containing \(k\) integers \(a_{i, 1}\), \(a_{i, 2}\), ..., \(a_{i, k}\) (\(-10^6 \le a_{i, j} \le 10^6\)) — the coordinates of \(i\)-th point.The next line contains one integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) — the number of queries.Then \(q\) lines follow, each denoting a query. There are two types of queries: \(1\) \(i\) \(b_1\) \(b_2\) ... \(b_k\) (\(1 \le i \le n\), \(-10^6 \le b_j \le 10^6\)) — set \(i\)-th element of \(a\) to the point \((b_1, b_2, \dots, b_k)\); \(2\) \(l\) \(r\) (\(1 \le l \le r \le n\)) — find the maximum distance between two points \(a_i\) and \(a_j\), where \(l \le i, j \le r\).There is at least one query of the second type.
|
Print the answer for each query of the second type.
|
Input: 5 2 1 2 2 3 3 4 4 5 5 6 7 2 1 5 2 1 3 2 3 5 1 5 -1 -2 2 1 5 1 4 -1 -2 2 1 5 | Output: 8 4 4 12 10
|
Expert
| 2 | 512 | 887 | 51 | 10 |
|
348 |
A
|
348A
|
A. Mafia
| 1,600 |
binary search; math; sortings
|
One day n friends gathered together to play ""Mafia"". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the ""Mafia"" game they need to play to let each person play at least as many rounds as they want?
|
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
|
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds.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.
|
You don't need to know the rules of ""Mafia"" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
|
Input: 33 2 2 | Output: 4
|
Medium
| 3 | 433 | 216 | 287 | 3 |
1,286 |
C1
|
1286C1
|
C1. Madhouse (Easy version)
| 2,400 |
brute force; constructive algorithms; interactive; math
|
This problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string \(s\) of length \(n\), consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of \(s[l..r]\). Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than \(3\) queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed \((n+1)^2\).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.
|
First line contains number \(n\) (\(1 \le n \le 100\)) — the length of the picked string.
|
Input: 4 a aa a cb b c c | Output: ? 1 2 ? 3 4 ? 4 4 ! aabc
|
Expert
| 4 | 1,441 | 89 | 0 | 12 |
||
2,064 |
A
|
2064A
|
A. Brogramming Contest
| 800 |
greedy; strings
|
One day after waking up, your friend challenged you to a brogramming contest. In a brogramming contest, you are given a binary string\(^{\text{∗}}\) \(s\) of length \(n\) and an initially empty binary string \(t\). During a brogramming contest, you can make either of the following moves any number of times: remove some suffix\(^{\text{†}}\) from \(s\) and place it at the end of \(t\), or remove some suffix from \(t\) and place it at the end of \(s\). To win the brogramming contest, you must make the minimum number of moves required to make \(s\) contain only the character \(\texttt{0}\) and \(t\) contain only the character \(\texttt{1}\). Find the minimum number of moves required.\(^{\text{∗}}\)A binary string is a string consisting of characters \(\texttt{0}\) and \(\texttt{1}\).\(^{\text{†}}\)A string \(a\) is a suffix of a string \(b\) if \(a\) can be obtained from deletion of several (possibly, zero or all) elements from the beginning of \(b\).
|
The first line contains an integer \(t\) (\(1 \le t \le 100\)) — the number of test cases.The first line of each test case is an integer \(n\) (\(1 \le n \le 1000\)) — the length of the string \(s\).The second line of each test case contains the binary string \(s\).The sum of \(n\) across all test cases does not exceed \(1000\).
|
For each testcase, output the minimum number of moves required.
|
An optimal solution to the first test case is as follows: \(s = \texttt{00}\color{red}{\texttt{110}}\), \(t =\) empty string. \(s = \texttt{00}\), \(t = \texttt{11}\color{red}{\texttt{0}}\). \(s = \texttt{000}\), \(t = \texttt{11}\). It can be proven that there is no solution using less than \(2\) moves.In the second test case, you have to move the whole string from \(s\) to \(t\) in one move.In the fourth test case, you don't have to do any moves.
|
Input: 55001104111130015000003101 | Output: 2 1 1 0 3
|
Beginner
| 2 | 962 | 330 | 63 | 20 |
896 |
E
|
896E
|
E. Welcome home, Chtholly
| 3,100 |
data structures; dsu
|
— I... I survived.— Welcome home, Chtholly.— I kept my promise...— I made it... I really made it!After several days of fighting, Chtholly Nota Seniorious miraculously returned from the fierce battle.As promised, Willem is now baking butter cake for her.However, although Willem is skilled in making dessert, he rarely bakes butter cake.This time, Willem made a big mistake — he accidentally broke the oven!Fortunately, Chtholly decided to help him.Willem puts n cakes on a roll, cakes are numbered from 1 to n, the i-th cake needs ai seconds of baking.Willem needs Chtholly to do m operations to bake the cakes.Operation 1: 1 l r xWillem asks Chtholly to check each cake in the range [l, r], if the cake needs to be baked for more than x seconds, he would bake it for x seconds and put it back in its place. More precisely, for every i in range [l, r], if ai is strictly more than x, ai becomes equal ai - x.Operation 2: 2 l r xWillem asks Chtholly to count the number of cakes in the range [l, r] that needs to be cooked for exactly x seconds. More formally you should find number of such i in range [l, r], that ai = x.
|
The first line contains two integers n and m (1 ≤ n, m ≤ 105).The second line contains n integers, i-th of them is ai (1 ≤ ai ≤ 105).The next m lines are the m operations described above. It is guaranteed that 1 ≤ l ≤ r ≤ n and 1 ≤ x ≤ 105.
|
For each operation of the second type, print the answer.
|
Input: 5 61 5 5 5 82 2 5 51 2 4 32 2 5 22 2 5 51 3 5 12 1 5 1 | Output: 3303
|
Master
| 2 | 1,121 | 240 | 56 | 8 |
|
1,660 |
F2
|
1660F2
|
F2. Promising String (hard version)
| 2,100 |
data structures; implementation; math; strings
|
This is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings ""+--+"" and ""++-+--"" are balanced, and strings ""+--"", ""--"" and """" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string ""-+---"" is promising, because you can replace two adjacent minuses with plus and get a balanced string ""-++-"", or get another balanced string ""-+-+"".How many non-empty substrings of the given string \(s\) are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string \(s\).Recall that a substring is a sequence of consecutive characters of the string. For example, for string ""+-+"" its substring are: ""+-"", ""-+"", ""+"", ""+-+"" (the string is a substring of itself) and some others. But the following strings are not its substring: ""--"", ""++"", ""-++"".
|
The first line of the input contains an integer \(t\) (\(1 \le t \le 10^4\)) —the number of test cases in the test.Then the descriptions of test cases follow.Each test case of input data consists of two lines. The first line consists of the number \(n\) (\(1 \le n \le 2 \cdot 10^5\)): the length of \(s\).The second line of the test case contains the string \(s\) of length \(n\), consisting only of characters ""+"" and ""-"".It is guaranteed that the sum of values \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, print a single number: the number of the promising non-empty substrings of string \(s\). Each non-empty promising substring must be counted in the answer as many times as it occurs in string \(s\).
|
The following are the promising substrings for the first three test cases in the example: \(s[1 \dots 2]\)=""+-"", \(s[2 \dots 3]\)=""-+""; \(s[1 \dots 2]\)=""-+"", \(s[2 \dots 3]\)=""+-"", \(s[1 \dots 5]\)=""-+---"", \(s[3 \dots 5]\)=""---""; \(s[1 \dots 3]\)=""---"", \(s[2 \dots 4]\)=""---"".
|
Input: 53+-+5-+---4----7--+---+6+++--- | Output: 2 4 2 7 4
|
Hard
| 4 | 1,286 | 527 | 217 | 16 |
1,887 |
D
|
1887D
|
D. Split
| 2,700 |
binary search; data structures; divide and conquer; dsu; math; trees; two pointers
|
Let's call an array \(b_1, b_2, \ldots, b_m\) (\(m \ge 2\)) good if it can be split into two parts such that all elements in the left part are strictly smaller than all elements in the right part. In other words, there must exist an index \(1 \le i < m\) such that every element from \(b_1, \ldots, b_i\) is strictly smaller than every element from \(b_{i+1}, \ldots, b_m\).Given an array \(a_1, a_2, \ldots a_n\) consisting of distinct integers from \(1\) to \(n\). There are \(q\) queries. Each query consists of two numbers \(l\) and \(r\). For each query, determine whether the array \(a_l, a_{l+1}, \ldots, a_r\) is good.
|
The first line contains a single integer \(n\) (\(2 \le n \le 3 \cdot 10^5\)) — the size of the array.The second line contains \(n\) distinct integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_n \le n\)) — the elements of the array \(a\).The third line contains a single integer \(q\) (\(1 \le q \le 3 \cdot 10^5\)) — the number of queries.Each of the next \(q\) lines contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i < r_i \le n\)) — the description of the \(i\)-th query.
|
For each query, output ""Yes"" (without quotes) if the array \(a_l, a_{l+1}, \ldots, a_r\) is good, and ""No"" (without quotes) otherwise.You can output ""Yes"" and ""No"" in any case (for example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as a positive answer).
|
In the first example: The array \([3,2,1,4,5]\) can be split into two parts: \([3,2,1]\) and \([4,5]\). The array \([3,2,1]\) cannot be split into two parts such that all elements in the left part are smaller than all elements in the right part. The array \([3,2,1,4]\) can be split into two parts: \([3,2,1]\) and \([4]\). The array \([3,2]\) cannot be split into two parts such that all elements in the left part are smaller than all elements in the right part. The array \([2,1,4,5]\) can be split into two parts: \([2,1]\) and \([4,5]\).In the second example: The array \([2,4,3]\) can be split into two parts: \([2]\) and \([4,3]\). The array \([6,2,4,3,5]\) cannot be split into two parts such that all elements in the left part are smaller than all elements in the right part. The array \([4,3,5]\) can be split into two parts: \([4,3]\) and \([5]\).
|
Input: 5 3 2 1 4 5 5 1 5 1 3 1 4 1 2 2 5 | Output: Yes No Yes No Yes
|
Master
| 7 | 626 | 474 | 290 | 18 |
1,426 |
E
|
1426E
|
E. Rock, Paper, Scissors
| 1,800 |
brute force; constructive algorithms; flows; greedy; math
|
Alice and Bob have decided to play the game ""Rock, Paper, Scissors"". The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a draw. Otherwise, the following rules applied: if one player showed rock and the other one showed scissors, then the player who showed rock is considered the winner and the other one is considered the loser; if one player showed scissors and the other one showed paper, then the player who showed scissors is considered the winner and the other one is considered the loser; if one player showed paper and the other one showed rock, then the player who showed paper is considered the winner and the other one is considered the loser. Alice and Bob decided to play exactly \(n\) rounds of the game described above. Alice decided to show rock \(a_1\) times, show scissors \(a_2\) times and show paper \(a_3\) times. Bob decided to show rock \(b_1\) times, show scissors \(b_2\) times and show paper \(b_3\) times. Though, both Alice and Bob did not choose the sequence in which they show things. It is guaranteed that \(a_1 + a_2 + a_3 = n\) and \(b_1 + b_2 + b_3 = n\).Your task is to find two numbers: the minimum number of round Alice can win; the maximum number of rounds Alice can win.
|
The first line of the input contains one integer \(n\) (\(1 \le n \le 10^{9}\)) — the number of rounds.The second line of the input contains three integers \(a_1, a_2, a_3\) (\(0 \le a_i \le n\)) — the number of times Alice will show rock, scissors and paper, respectively. It is guaranteed that \(a_1 + a_2 + a_3 = n\).The third line of the input contains three integers \(b_1, b_2, b_3\) (\(0 \le b_j \le n\)) — the number of times Bob will show rock, scissors and paper, respectively. It is guaranteed that \(b_1 + b_2 + b_3 = n\).
|
Print two integers: the minimum and the maximum number of rounds Alice can win.
|
In the first example, Alice will not win any rounds if she shows scissors and then paper and Bob shows rock and then scissors. In the best outcome, Alice will win one round if she shows paper and then scissors, and Bob shows rock and then scissors.In the second example, Alice will not win any rounds if Bob shows the same things as Alice each round.In the third example, Alice always shows paper and Bob always shows rock so Alice will win all three rounds anyway.
|
Input: 2 0 1 1 1 1 0 | Output: 0 1
|
Medium
| 5 | 1,406 | 534 | 79 | 14 |
182 |
A
|
182A
|
A. Battlefield
| 2,200 |
geometry; graphs; implementation; shortest paths
|
Vasya lagged behind at the University and got to the battlefield. Just joking! He's simply playing some computer game. The field is a flat platform with n trenches dug on it. The trenches are segments on a plane parallel to the coordinate axes. No two trenches intersect.There is a huge enemy laser far away from Vasya. The laser charges for a seconds, and then shoots continuously for b seconds. Then, it charges for a seconds again. Then it shoots continuously for b seconds again and so on. Vasya knows numbers a and b. He also knows that while the laser is shooting, Vasya must be in the trench, but while the laser is charging, Vasya can safely move around the field. The main thing is to have time to hide in the trench before the shot. If Vasya reaches the trench exactly at the moment when the laser starts shooting, we believe that Vasya managed to hide. Coincidentally, the length of any trench in meters numerically does not exceed b.Initially, Vasya is at point A. He needs to get to point B. Vasya moves at speed 1 meter per second in either direction. You can get in or out of the trench at any its point. Getting in or out of the trench takes no time. It is also possible to move in the trench, without leaving it.What is the minimum time Vasya needs to get from point A to point B, if at the initial time the laser has just started charging? If Vasya cannot get from point A to point B, print -1. If Vasya reaches point B at the moment when the laser begins to shoot, it is believed that Vasya managed to reach point B.
|
The first line contains two space-separated integers: a and b (1 ≤ a, b ≤ 1000), — the duration of charging and the duration of shooting, in seconds.The second line contains four space-separated integers: Ax, Ay, Bx, By ( - 104 ≤ Ax, Ay, Bx, By ≤ 104) — the coordinates of points А and B. It is guaranteed that points A and B do not belong to any trench.The third line contains a single integer: n (1 ≤ n ≤ 1000), — the number of trenches. Each of the following n lines contains four space-separated integers: x1, y1, x2, y2 ( - 104 ≤ xi, yi ≤ 104) — the coordinates of ends of the corresponding trench.All coordinates are given in meters. It is guaranteed that for any trench either x1 = x2, or y1 = y2. No two trenches intersect. The length of any trench in meters doesn't exceed b numerically.
|
If Vasya can get from point A to point B, print the minimum time he will need for it. Otherwise, print number -1.The answer will be considered correct if the absolute or relative error does not exceed 10 - 4
|
Input: 2 40 5 6 530 0 0 41 1 4 16 0 6 4 | Output: 19.0000000000
|
Hard
| 4 | 1,535 | 796 | 207 | 1 |
|
2,106 |
A
|
2106A
|
A. Dr. TC
| 800 |
brute force; math
|
In order to test his patients' intelligence, Dr. TC created the following test.First, he creates a binary string\(^{\text{∗}}\) \(s\) having \(n\) characters. Then, he creates \(n\) binary strings \(a_1, a_2, \ldots, a_n\). It is known that \(a_i\) is created by first copying \(s\), then flipping the \(i\)'th character (\(\texttt{1}\) becomes \(\texttt{0}\) and vice versa). After creating all \(n\) strings, he arranges them into a grid where the \(i\)'th row is \(a_i\). For example, If \(s = \texttt{101}\), \(a = [\texttt{001}, \texttt{111}, \texttt{100}]\). If \(s = \texttt{0000}\), \(a = [\texttt{1000}, \texttt{0100}, \texttt{0010}, \texttt{0001}]\). The patient needs to count the number of \(1\)s written on the board in less than a second. Can you pass the test?\(^{\text{∗}}\)A binary string is a string that only consists of characters \(\texttt{1}\) and \(\texttt{0}\).
|
The first line of the input consists of a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10\)) — the length of the binary string \(s\).The second line of each test case contains a single binary string \(s\) of size \(n\).
|
For each test case, output a single integer, the number of \(\texttt{1}\)s on the board.
|
The first example is explained in the statement.For the second example, the only string written on the board will be the string \(\texttt{0}\); therefore, the answer is \(0\).In the third example, the following strings will be written on the board: \([\texttt{10000}, \texttt{01000}, \texttt{00100}, \texttt{00010}, \texttt{00001}]\); so there are five \(\texttt{1}\)s written on the board.
|
Input: 53101115000002113010 | Output: 5 0 5 2 4
|
Beginner
| 2 | 885 | 325 | 88 | 21 |
306 |
A
|
306A
|
A. Candies
| 800 |
implementation
|
Polycarpus has got n candies and m friends (n ≥ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such ai, where ai is the number of candies in the i-th friend's present, that the maximum ai differs from the least ai as little as possible.For example, if n is divisible by m, then he is going to present the same number of candies to all his friends, that is, the maximum ai won't differ from the minimum one.
|
The single line of the input contains a pair of space-separated positive integers n, m (1 ≤ n, m ≤ 100;n ≥ m) — the number of candies and the number of Polycarpus's friends.
|
Print the required sequence a1, a2, ..., am, where ai is the number of candies in the i-th friend's present. All numbers ai must be positive integers, total up to n, the maximum one should differ from the minimum one by the smallest possible value.
|
Print ai in any order, separate the numbers by spaces.
|
Input: 12 3 | Output: 4 4 4
|
Beginner
| 1 | 562 | 173 | 248 | 3 |
1,186 |
F
|
1186F
|
F. Vus the Cossack and a Graph
| 2,400 |
dfs and similar; graphs; greedy; implementation
|
Vus the Cossack has a simple graph with \(n\) vertices and \(m\) edges. Let \(d_i\) be a degree of the \(i\)-th vertex. Recall that a degree of the \(i\)-th vertex is the number of conected edges to the \(i\)-th vertex.He needs to remain not more than \(\lceil \frac{n+m}{2} \rceil\) edges. Let \(f_i\) be the degree of the \(i\)-th vertex after removing. He needs to delete them in such way so that \(\lceil \frac{d_i}{2} \rceil \leq f_i\) for each \(i\). In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges!
|
The first line contains two integers \(n\) and \(m\) (\(1 \leq n \leq 10^6\), \(0 \leq m \leq 10^6\)) — the number of vertices and edges respectively.Each of the next \(m\) lines contains two integers \(u_i\) and \(v_i\) (\(1 \leq u_i, v_i \leq n\)) — vertices between which there is an edge.It is guaranteed that the graph does not have loops and multiple edges.It is possible to show that the answer always exists.
|
In the first line, print one integer \(k\) (\(0 \leq k \leq \lceil \frac{n+m}{2} \rceil\)) — the number of edges which you need to remain.In each of the next \(k\) lines, print two integers \(u_i\) and \(v_i\) (\(1 \leq u_i, v_i \leq n\)) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once.
|
Input: 6 6 1 2 2 3 3 4 4 5 5 3 6 5 | Output: 5 2 1 3 2 5 3 5 4 6 5
|
Expert
| 4 | 574 | 416 | 346 | 11 |
|
106 |
A
|
106A
|
A. Card Game
| 1,000 |
implementation
|
There is a card game called ""Durak"", which means ""Fool"" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly — you can find them later yourselves if you want.To play durak you need a pack of 36 cards. Each card has a suit (""S"", ""H"", ""D"" and ""C"") and a rank (in the increasing order ""6"", ""7"", ""8"", ""9"", ""T"", ""J"", ""Q"", ""K"" and ""A""). At the beginning of the game one suit is arbitrarily chosen as trump. The players move like that: one player puts one or several of his cards on the table and the other one should beat each of them with his cards.A card beats another one if both cards have similar suits and the first card has a higher rank then the second one. Besides, a trump card can beat any non-trump card whatever the cards’ ranks are. In all other cases you can not beat the second card with the first one.You are given the trump suit and two different cards. Determine whether the first one beats the second one or not.
|
The first line contains the tramp suit. It is ""S"", ""H"", ""D"" or ""C"".The second line contains the description of the two different cards. Each card is described by one word consisting of two symbols. The first symbol stands for the rank (""6"", ""7"", ""8"", ""9"", ""T"", ""J"", ""Q"", ""K"" and ""A""), and the second one stands for the suit (""S"", ""H"", ""D"" and ""C"").
|
Print ""YES"" (without the quotes) if the first cards beats the second one. Otherwise, print ""NO"" (also without the quotes).
|
Input: HQH 9S | Output: YES
|
Beginner
| 1 | 1,041 | 382 | 126 | 1 |
|
1,819 |
D
|
1819D
|
D. Misha and Apples
| 2,800 |
brute force; data structures; dp; two pointers
|
Schoolboy Misha got tired of doing sports programming, so he decided to quit everything and go to the magical forest to sell magic apples.His friend Danya came to the magical forest to visit Misha. What was his surprise when he found out that Misha found a lot of friends there, the same former sports programmers. And all of them, like Misha, have their own shop where they sell magic apples. To support his friends, who have changed their lives so drastically, he decided to buy up their entire assortment.The buying process works as follows: in total there are \(n\) stalls, numbered with integers from \(1\) to \(n\), and \(m\) kinds of magic apples, numbered with integers from \(1\) to \(m\). Each shop sells some number of kinds of apples. Danya visits all the shops in order of increasing number, starting with the first one. Upon entering the shop he buys one magic apple of each kind sold in that shop and puts them in his backpack.However, magical apples wouldn't be magical if they were all right. The point is that when two apples of the same type end up together in the backpack, all of the apples in it magically disappear. Importantly, the disappearance happens after Danya has put the apples in the backpack and left the shop.Upon returning home, Danya realized that somewhere in the forest he had managed to lose his backpack. Unfortunately, for some shops Danya had forgotten what assortment of apples there was. Remembering only for some shops, what kinds of magical apples were sold in them, he wants to know what is the maximum number of apples he could have in his backpack after all his purchases at best.
|
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 2 \cdot 10^5\)) —the number of test cases. The description of test cases follows.The first line contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 2 \cdot 10^5\)) —the number of stalls and kinds of apples.Each of the following \(n\) lines describes the assortment of the next stall in the format described below.Each line starts with an integer \(k_i\) (\(0 \le k_i \le 2 \cdot 10^5\)). This is followed by \(k_i\) of different integers \(a_{ij}\) (\(1 \le a_{ij} \le m\)) —the kinds of apples sold in the \(i\)-th stall. If \(k_i = 0\), then Danya does not remember what assortment was in that shop, and the set of apple kinds can be anything (including empty).It is guaranteed that the sum of all \(k_i\) over all test cases does not exceed \(2 \cdot 10^5\) and the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\)
|
For each test case, output a single integer — the maximum number of apples that could be in Dani's backpack after visiting all the shops at best.
|
In the first test case, Danya remembers all the shops, so the process will be deterministic. He will take two apples at the first shop and two more at the second, but after he puts them in his backpack, they will disappear. So at the end there will only be \(2\) apples left, which he will take at the third shop.In the second test case, if the third shop is empty, then after visiting the fourth shop all the apples will disappear. In any other case the apples will disappear after the third shop, and in the fourth shop Dan can take one apple, so the answer is \(1\).In the third test case, the first shop may sell all kinds of apples, and the second shop may sell nothing. Then all \(5\) apples will be left at the end.
|
Input: 43 42 1 22 4 12 1 24 42 1 22 3 401 12 5005 303 1 2 32 3 101 3 | Output: 2 1 5 3
|
Master
| 4 | 1,629 | 945 | 145 | 18 |
367 |
C
|
367C
|
C. Sereja and the Arrangement of Numbers
| 2,000 |
graphs; greedy; sortings
|
Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property: consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a; for each pair x, y must exist some position j (1 ≤ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x. Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.Help Sereja, find the maximum amount of money he can pay to Dima.
|
The first line contains two integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 105). Next m lines contain pairs of integers. The i-th line contains numbers qi, wi (1 ≤ qi, wi ≤ 105).It is guaranteed that all qi are distinct.
|
In a single line print maximum amount of money (in rubles) Sereja can pay.Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
|
In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].
|
Input: 5 21 22 3 | Output: 5
|
Hard
| 3 | 1,092 | 214 | 221 | 3 |
1,641 |
A
|
1641A
|
A. Great Sequence
| 1,200 |
brute force; greedy; sortings
|
A sequence of positive integers is called great for a positive integer \(x\), if we can split it into pairs in such a way that in each pair the first number multiplied by \(x\) is equal to the second number. More formally, a sequence \(a\) of size \(n\) is great for a positive integer \(x\), if \(n\) is even and there exists a permutation \(p\) of size \(n\), such that for each \(i\) (\(1 \le i \le \frac{n}{2}\)) \(a_{p_{2i-1}} \cdot x = a_{p_{2i}}\). Sam has a sequence \(a\) and a positive integer \(x\). Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence \(a\) to make it great for the number \(x\).
|
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 20\,000\)) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers \(n\), \(x\) (\(1 \le n \le 2 \cdot 10^5\), \(2 \le x \le 10^6\)).The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case print a single integer — the minimum number of integers that can be added to the end of \(a\) to make it a great sequence for the number \(x\).
|
In the first test case, Sam got lucky and the sequence is already great for the number \(4\) because you can divide it into such pairs: \((1, 4)\), \((4, 16)\). Thus we can add \(0\) numbers.In the second test case, you can add numbers \(1\) and \(14\) to the sequence, then you can divide all \(8\) integers into such pairs: \((1, 2)\), \((1, 2)\), \((2, 4)\), \((7, 14)\). It is impossible to add less than \(2\) integers to fix the sequence.
|
Input: 44 41 16 4 46 21 2 2 2 4 75 35 2 3 5 159 1010 10 10 20 1 100 200 2000 3 | Output: 0 2 3 3
|
Easy
| 3 | 683 | 481 | 162 | 16 |
1,158 |
A
|
1158A
|
A. The Party and Sweets
| 1,500 |
binary search; constructive algorithms; greedy; implementation; math; sortings; two pointers
|
\(n\) boys and \(m\) girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from \(1\) to \(n\) and all girls are numbered with integers from \(1\) to \(m\). For all \(1 \leq i \leq n\) the minimal number of sweets, which \(i\)-th boy presented to some girl is equal to \(b_i\) and for all \(1 \leq j \leq m\) the maximal number of sweets, which \(j\)-th girl received from some boy is equal to \(g_j\).More formally, let \(a_{i,j}\) be the number of sweets which the \(i\)-th boy give to the \(j\)-th girl. Then \(b_i\) is equal exactly to the minimum among values \(a_{i,1}, a_{i,2}, \ldots, a_{i,m}\) and \(g_j\) is equal exactly to the maximum among values \(b_{1,j}, b_{2,j}, \ldots, b_{n,j}\).You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of \(a_{i,j}\) for all \((i,j)\) such that \(1 \leq i \leq n\) and \(1 \leq j \leq m\). You are given the numbers \(b_1, \ldots, b_n\) and \(g_1, \ldots, g_m\), determine this number.
|
The first line contains two integers \(n\) and \(m\), separated with space — the number of boys and girls, respectively (\(2 \leq n, m \leq 100\,000\)). The second line contains \(n\) integers \(b_1, \ldots, b_n\), separated by spaces — \(b_i\) is equal to the minimal number of sweets, which \(i\)-th boy presented to some girl (\(0 \leq b_i \leq 10^8\)). The third line contains \(m\) integers \(g_1, \ldots, g_m\), separated by spaces — \(g_j\) is equal to the maximal number of sweets, which \(j\)-th girl received from some boy (\(0 \leq g_j \leq 10^8\)).
|
If the described situation is impossible, print \(-1\). In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
|
In the first test, the minimal total number of sweets, which boys could have presented is equal to \(12\). This can be possible, for example, if the first boy presented \(1\) and \(4\) sweets, the second boy presented \(3\) and \(2\) sweets and the third boy presented \(1\) and \(1\) sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to \(12\).In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to \(4\). This can be possible, for example, if the first boy presented \(1\), \(1\), \(2\) sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to \(4\).
|
Input: 3 2 1 2 1 3 4 | Output: 12
|
Medium
| 7 | 1,078 | 560 | 187 | 11 |
1,705 |
D
|
1705D
|
D. Mark and Lightbulbs
| 1,800 |
combinatorics; constructive algorithms; greedy; math; sortings
|
Mark has just purchased a rack of \(n\) lightbulbs. The state of the lightbulbs can be described with binary string \(s = s_1s_2\dots s_n\), where \(s_i=\texttt{1}\) means that the \(i\)-th lightbulb is turned on, while \(s_i=\texttt{0}\) means that the \(i\)-th lightbulb is turned off.Unfortunately, the lightbulbs are broken, and the only operation he can perform to change the state of the lightbulbs is the following: Select an index \(i\) from \(2,3,\dots,n-1\) such that \(s_{i-1}\ne s_{i+1}\). Toggle \(s_i\). Namely, if \(s_i\) is \(\texttt{0}\), set \(s_i\) to \(\texttt{1}\) or vice versa. Mark wants the state of the lightbulbs to be another binary string \(t\). Help Mark determine the minimum number of operations to do so.
|
The first line of the input contains a single integer \(q\) (\(1\leq q\leq 10^4\)) — the number of test cases.The first line of each test case contains a single integer \(n\) (\(3\leq n\leq 2\cdot 10^5\)) — the number of lightbulbs.The second line of each test case contains a binary string \(s\) of length \(n\) — the initial state of the lightbulbs.The third line of each test case contains a binary string \(t\) of length \(n\) — the final state of the lightbulbs.It is guaranteed that the sum of \(n\) across all test cases does not exceed \(2\cdot 10^5\).
|
For each test case, print a line containing the minimum number of operations Mark needs to perform to transform \(s\) to \(t\). If there is no such sequence of operations, print \(-1\).
|
In the first test case, one sequence of operations that achieves the minimum number of operations is the following. Select \(i=3\), changing \(\texttt{01}\color{red}{\texttt{0}}\texttt{0}\) to \(\texttt{01}\color{red}{\texttt{1}}\texttt{0}\). Select \(i=2\), changing \(\texttt{0}\color{red}{\texttt{1}}\texttt{10}\) to \(\texttt{0}\color{red}{\texttt{0}}\texttt{10}\). In the second test case, there is no sequence of operations because one cannot change the first digit or the last digit of \(s\).In the third test case, even though the first digits of \(s\) and \(t\) are the same and the last digits of \(s\) and \(t\) are the same, it can be shown that there is no sequence of operations that satisfies the condition.In the fourth test case, one sequence that achieves the minimum number of operations is the following: Select \(i=3\), changing \(\texttt{00}\color{red}{\texttt{0}}\texttt{101}\) to \(\texttt{00}\color{red}{\texttt{1}}\texttt{101}\). Select \(i=2\), changing \(\texttt{0}\color{red}{\texttt{0}}\texttt{1101}\) to \(\texttt{0}\color{red}{\texttt{1}}\texttt{1101}\). Select \(i=4\), changing \(\texttt{011}\color{red}{\texttt{1}}\texttt{01}\) to \(\texttt{011}\color{red}{\texttt{0}}\texttt{01}\). Select \(i=5\), changing \(\texttt{0110}\color{red}{\texttt{0}}\texttt{1}\) to \(\texttt{0110}\color{red}{\texttt{1}}\texttt{1}\). Select \(i=3\), changing \(\texttt{01}\color{red}{\texttt{1}}\texttt{011}\) to \(\texttt{01}\color{red}{\texttt{0}}\texttt{011}\).
|
Input: 4401000010410100100501001000116000101010011 | Output: 2 -1 -1 5
|
Medium
| 5 | 737 | 560 | 185 | 17 |
1,844 |
C
|
1844C
|
C. Particles
| 1,300 |
dp; greedy; implementation; math
|
You have discovered \(n\) mysterious particles on a line with integer charges of \(c_1,\dots,c_n\). You have a device that allows you to perform the following operation: Choose a particle and remove it from the line. The remaining particles will shift to fill in the gap that is created. If there were particles with charges \(x\) and \(y\) directly to the left and right of the removed particle, they combine into a single particle of charge \(x+y\). For example, if the line of particles had charges of \([-3,1,4,-1,5,-9]\), performing the operation on the \(4\)th particle will transform the line into \([-3,1,9,-9]\). If we then use the device on the \(1\)st particle in this new line, the line will turn into \([1,9,-9]\). You will perform operations until there is only one particle left. What is the maximum charge of this remaining particle that you can obtain?
|
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)).The second line of each test case contains \(n\) integers \(c_1,\dots,c_n\) (\(-10^9 \le c_i \le 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
|
For each test case, output one integer, the maximum charge of the remaining particle.
|
In the first test case, the best strategy is to use the device on the \(4\)th particle, then on the \(1\)st particle (as described in the statement), and finally use the device on the new \(3\)rd particle followed by the \(1\)st particle.In the second test case, the best strategy is to use the device on the \(4\)th particle to transform the line into \([998244353,998244353,1996488706]\), then on the \(2\)nd particle to transform the line into \([2994733059]\). Be wary of integer overflow.In the third test case, there is only one particle, so no operations can be performed.
|
Input: 36-3 1 4 -1 5 -95998244353 998244353 998244353 998244353 9982443531-2718 | Output: 9 2994733059 -2718
|
Easy
| 4 | 869 | 454 | 85 | 18 |
593 |
C
|
593C
|
C. Beautiful Function
| 2,200 |
constructive algorithms; math
|
Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.Yesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as (xt = f(t), yt = g(t)), where argument t takes all integer values from 0 to 50. Moreover, f(t) and g(t) should be correct functions.Assume that w(t) and h(t) are some correct functions, and c is an integer ranging from 0 to 50. The function s(t) is correct if it's obtained by one of the following rules: s(t) = abs(w(t)), where abs(x) means taking the absolute value of a number x, i.e. |x|; s(t) = (w(t) + h(t)); s(t) = (w(t) - h(t)); s(t) = (w(t) * h(t)), where * means multiplication, i.e. (w(t)·h(t)); s(t) = c; s(t) = t;Yesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate f(t) and g(t) for any set of at most 50 circles.In each of the functions f(t) and g(t) you are allowed to use no more than 50 multiplications. The length of any function should not exceed 100·n characters. The function should not contain spaces.Ruslan can't keep big numbers in his memory, so you should choose f(t) and g(t), such that for all integer t from 0 to 50 value of f(t) and g(t) and all the intermediate calculations won't exceed 109 by their absolute value.
|
The first line of the input contains number n (1 ≤ n ≤ 50) — the number of circles Ruslan thinks of. Next follow n lines, each of them containing three integers xi, yi and ri (0 ≤ xi, yi ≤ 50, 2 ≤ ri ≤ 50) — the coordinates of the center and the raduis of the i-th circle.
|
In the first line print a correct function f(t). In the second line print a correct function g(t). The set of the points (xt = f(t), yt = g(t)) (0 ≤ t ≤ 50) must satisfy the condition, that there is at least one point inside or on the border of each of the circles, Ruslan thinks of at the beginning.
|
Correct functions: 10 (1+2) ((t-3)+(t*4)) abs((t-10)) (abs((((23-t)*(t*t))+((45+12)*(t*t))))*((5*t)+((12*t)-13))) abs((t-(abs((t*31))+14))))Incorrect functions: 3+5+7 (not enough brackets, it should be ((3+5)+7) or (3+(5+7))) abs(t-3) (not enough brackets, it should be abs((t-3)) 2+(2-3 (one bracket too many) 1(t+5) (no arithmetic operation between 1 and the bracket) 5000*5000 (the number exceeds the maximum) The picture shows one of the possible solutions
|
Input: 30 10 410 0 420 10 4 | Output: t abs((t-10))
|
Hard
| 2 | 1,592 | 272 | 300 | 5 |
1,840 |
B
|
1840B
|
B. Binary Cafe
| 1,100 |
bitmasks; combinatorics; math
|
Once upon a time, Toma found himself in a binary cafe. It is a very popular and unusual place.The cafe offers visitors \(k\) different delicious desserts. The desserts are numbered from \(0\) to \(k-1\). The cost of the \(i\)-th dessert is \(2^i\) coins, because it is a binary cafe! Toma is willing to spend no more than \(n\) coins on tasting desserts. At the same time, he is not interested in buying any dessert more than once, because one is enough to evaluate the taste.In how many different ways can he buy several desserts (possibly zero) for tasting?
|
The first line of the input contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases.Then follows \(t\) lines, each of which describes one test case.Each test case is given on a single line and consists of two integers \(n\) and \(k\) (\(1 \le n, k \le 10^9\)) — the number of coins Toma is willing to spend and the number of desserts in the binary cafe.
|
Output \(t\) integers, the \(i\)-th of which should be equal to the answer for the \(i\)-th test case — the number of ways to buy desserts for tasting.
|
Variants for 1st sample: {}, {1}Variants for 2nd sample: {}, {1}Variants for 3rd sample: {}, {1}, {2}Variants for 4th sample: {}, {1}, {2}, {1, 2}
|
Input: 51 22 12 210 2179 100 | Output: 2 2 3 4 180
|
Easy
| 3 | 559 | 379 | 151 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.