There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.

For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).

NoteIn the first test case of the example, the optimal sequence of moves can be as follows:  before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$;  choose $$$c=6$$$;  now $$$a=[40, 3, 40, 3, 20, 1]$$$;  choose $$$c=40$$$;  now $$$a=[20, 3, 20, 3, 20, 1]$$$;  choose $$$c=20$$$;  now $$$a=[10, 3, 10, 3, 10, 1]$$$;  choose $$$c=10$$$;  now $$$a=[5, 3, 5, 3, 5, 1]$$$ — all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.


Вася купил стол, у которого n ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке.Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей. Во второй строке следует последовательность из 2n целых положительных чисел a1, a2, ..., a2n (1 ≤ ai ≤ 100 000) — длины частей ножек стола в произвольном порядке.

Выведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.


Память компьютера состоит из n ячеек, которые выстроены в ряд. Пронумеруем ячейки от 1 до n слева направо. Про каждую ячейку известно, свободна она или принадлежит какому-либо процессу (в таком случае известен процесс, которому она принадлежит).Для каждого процесса известно, что принадлежащие ему ячейки занимают в памяти непрерывный участок. С помощью операций вида «переписать данные из занятой ячейки в свободную, а занятую теперь считать свободной» требуется расположить все принадлежащие процессам ячейки в начале памяти компьютера. Другими словами, любая свободная ячейка должна располагаться правее (иметь больший номер) любой занятой.Вам необходимо найти минимальное количество операций переписывания данных из одной ячейки в другую, с помощью которых можно достичь описанных условий. Допустимо, что относительный порядок ячеек в памяти для каждого из процессов изменится после дефрагментации, но относительный порядок самих процессов должен остаться без изменений. Это значит, что если все ячейки, принадлежащие процессу i, находились в памяти раньше всех ячеек процесса j, то и после перемещений это условие должно выполняться.Считайте, что номера всех процессов уникальны, хотя бы одна ячейка памяти занята каким-либо процессом.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных записано число n (1 ≤ n ≤ 200 000) — количество ячеек в памяти компьютера. Во второй строке входных данных следуют n целых чисел a1, a2, ..., an (1 ≤ ai ≤ n), где ai равно либо 0 (это означает, что i-я ячейка памяти свободна), либо номеру процесса, которому принадлежит i-я ячейка памяти. Гарантируется, что хотя бы одно значение ai не равно 0. Процессы пронумерованы целыми числами от 1 до n в произвольном порядке. При этом процессы не обязательно пронумерованы последовательными числами.

Выведите одно целое число — минимальное количество операций, которое нужно сделать для дефрагментации памяти.

ПримечаниеВ первом тестовом примере достаточно двух операций:  Переписать данные из третьей ячейки в первую. После этого память компьютера примет вид: 2 2 0 1.  Переписать данные из четвертой ячейки в третью. После этого память компьютера примет вид: 2 2 1 0.


A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.

Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes).

NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.


You are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.What is the minimum number of removals necessary to remove all vertices from the tree?

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100\,000$$$), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 200\,000$$$): the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_v$$$ ($$$0 \le a_v \le 2$$$): colours of vertices. Gray vertices have $$$a_v=0$$$, white have $$$a_v=1$$$, black have $$$a_v=2$$$. Each of the next $$$n-1$$$ lines contains two integers $$$u, v$$$ ($$$1 \le u, v \le n$$$): tree edges. The sum of all $$$n$$$ throughout the test is guaranteed to not exceed $$$200\,000$$$.

For each test case, print one integer: the minimum number of operations to solve the problem.

NoteIn the first test case, both vertices are white, so you can remove them at the same time.In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.


Polycarp is preparing the first programming contest for robots. There are $$$n$$$ problems in it, and a lot of robots are going to participate in it. Each robot solving the problem $$$i$$$ gets $$$p_i$$$ points, and the score of each robot in the competition is calculated as the sum of $$$p_i$$$ over all problems $$$i$$$ solved by it. For each problem, $$$p_i$$$ is an integer not less than $$$1$$$.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of $$$p_i$$$ in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of $$$p_i$$$ will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of $$$p_i$$$ over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of problems. The second line contains $$$n$$$ integers $$$r_1$$$, $$$r_2$$$, ..., $$$r_n$$$ ($$$0 \le r_i \le 1$$$). $$$r_i = 1$$$ means that the "Robo-Coder Inc." robot will solve the $$$i$$$-th problem, $$$r_i = 0$$$ means that it won't solve the $$$i$$$-th problem. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$0 \le b_i \le 1$$$). $$$b_i = 1$$$ means that the "BionicSolver Industries" robot will solve the $$$i$$$-th problem, $$$b_i = 0$$$ means that it won't solve the $$$i$$$-th problem.

If "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer $$$-1$$$. Otherwise, print the minimum possible value of $$$\max \limits_{i = 1}^{n} p_i$$$, if all values of $$$p_i$$$ are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.

NoteIn the first example, one of the valid score assignments is $$$p = [3, 1, 3, 1, 1]$$$. Then the "Robo-Coder" gets $$$7$$$ points, the "BionicSolver" — $$$6$$$ points.In the second example, both robots get $$$0$$$ points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.


You are given a string $$$s$$$ consisting of lowercase Latin letters. Let the length of $$$s$$$ be $$$|s|$$$. You may perform several operations on this string.In one operation, you can choose some index $$$i$$$ and remove the $$$i$$$-th character of $$$s$$$ ($$$s_i$$$) if at least one of its adjacent characters is the previous letter in the Latin alphabet for $$$s_i$$$. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index $$$i$$$ should satisfy the condition $$$1 \le i \le |s|$$$ during each operation.For the character $$$s_i$$$ adjacent characters are $$$s_{i-1}$$$ and $$$s_{i+1}$$$. The first and the last characters of $$$s$$$ both have only one adjacent character (unless $$$|s| = 1$$$).Consider the following example. Let $$$s=$$$ bacabcab.  During the first move, you can remove the first character $$$s_1=$$$ b because $$$s_2=$$$ a. Then the string becomes $$$s=$$$ acabcab.  During the second move, you can remove the fifth character $$$s_5=$$$ c because $$$s_4=$$$ b. Then the string becomes $$$s=$$$ acabab.  During the third move, you can remove the sixth character $$$s_6=$$$'b' because $$$s_5=$$$ a. Then the string becomes $$$s=$$$ acaba.  During the fourth move, the only character you can remove is $$$s_4=$$$ b, because $$$s_3=$$$ a (or $$$s_5=$$$ a). The string becomes $$$s=$$$ acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.

The only line of the input contains one integer $$$|s|$$$ ($$$1 \le |s| \le 100$$$) — the length of $$$s$$$. The second line of the input contains one string $$$s$$$ consisting of $$$|s|$$$ lowercase Latin letters.

Print one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.

NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only, but it can be shown that the maximum possible answer to this test is $$$4$$$.In the second example, you can remove all but one character of $$$s$$$. The only possible answer follows.  During the first move, remove the third character $$$s_3=$$$ d, $$$s$$$ becomes bca.  During the second move, remove the second character $$$s_2=$$$ c, $$$s$$$ becomes ba.  And during the third move, remove the first character $$$s_1=$$$ b, $$$s$$$ becomes a.


Everybody knows that the $$$m$$$-coder Tournament will happen soon. $$$m$$$ schools participate in the tournament, and only one student from each school participates.There are a total of $$$n$$$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $$$k$$$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le m, k \le n$$$) — the total number of students, the number of schools and the number of the Chosen Ones. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ denotes the power of $$$i$$$-th student. The bigger the power, the stronger the student. The third line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le m$$$), where $$$s_i$$$ denotes the school the $$$i$$$-th student goes to. At least one student studies in each of the schools.  The fourth line contains $$$k$$$ different integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \le c_i \le n$$$)  — the id's of the Chosen Ones.

Output a single integer  — the minimal number of schools to be made up by Arkady so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

NoteIn the first example there's just a single Chosen One with id $$$3$$$. His power is equal to $$$3$$$, but in the same school $$$1$$$, there's a student with id $$$5$$$ and power $$$6$$$, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be $$$4$$$) for the Chosen One, Technogoblet would select students with ids $$$2$$$ (strongest in $$$3$$$), $$$5$$$ (strongest in $$$1$$$), $$$6$$$ (strongest in $$$2$$$) and $$$3$$$ (strongest in $$$4$$$).In the second example, you can change the school of student $$$3$$$ to the made-up $$$5$$$ and the school of student $$$4$$$ to the made-up $$$6$$$. It will cause the Technogoblet to choose students $$$8$$$, $$$7$$$, $$$6$$$, $$$5$$$, $$$3$$$ and $$$4$$$.


Hooray! Polycarp turned $$$n$$$ years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his $$$n$$$ birthdays: from the $$$1$$$-th to the $$$n$$$-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $$$1$$$, $$$77$$$, $$$777$$$, $$$44$$$ and $$$999999$$$. The following numbers are not beautiful: $$$12$$$, $$$11110$$$, $$$6969$$$ and $$$987654321$$$.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from $$$1$$$ to $$$n$$$ (inclusive) that are beautiful.

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 consists of one line, which contains a positive integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — how many years Polycarp has turned.

Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $$$1$$$ and $$$n$$$, inclusive.


Карта звёздного неба представляет собой прямоугольное поле, состоящее из n строк по m символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда). Новое издание карты звёздного неба будет напечатано на квадратных листах, поэтому требуется найти минимально возможную сторону квадрата, в который могут поместиться все звезды. Границы искомого квадрата должны быть параллельны сторонам заданного прямоугольного поля.

256 мегабайт

В первой строке входных данных записаны два числа n и m (1 ≤ n, m ≤ 1000) — количество строк и столбцов на карте звездного неба. В следующих n строках задано по m символов. Каждый символ — это либо «.» (пустой участок неба), либо «*» (звезда). Гарантируется, что на небе есть хотя бы одна звезда.

Выведите одно число — минимально возможную сторону квадрата, которым можно накрыть все звезды.

ПримечаниеОдин из возможных ответов на первый тестовый пример:  Один из возможных ответов на второй тестовый пример (обратите внимание, что покрывающий квадрат выходит за пределы карты звездного неба):  Ответ на третий тестовый пример:


One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company.To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer ai, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.

The first line contains integer n (1 ≤ n ≤ 2·105) — the number of workers of the Big Software Company.  Then n lines follow, describing the company employees. The i-th line contains two integers pi, ai (1 ≤ ai ≤ 105) — the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p1 =  - 1, for all other people the condition 1 ≤ pi < i is fulfilled.

Print a single integer — the maximum possible efficiency of the workgroup.

NoteIn the sample test the most effective way is to make a workgroup from employees number 1, 2, 4, 5, 6.


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \le |p_i - p_{i+1}| \le 4$$$ for each $$$i$$$ ($$$1 \le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \le n \le 1000$$$).

Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.


Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices.Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.    The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.

The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes.

If it is impossible to obtain a chain from the given graph, print  - 1. Otherwise, print the maximum possible number of edges in the resulting chain.

NoteIn the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3.In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result.In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.


В Берляндском государственном университете локальная сеть между серверами не всегда работает без ошибок. При передаче двух одинаковых сообщений подряд возможна ошибка, в результате которой эти два сообщения сливаются в одно. При таком слиянии конец первого сообщения совмещается с началом второго. Конечно, совмещение может происходить только по одинаковым символам. Длина совмещения должна быть положительным числом, меньшим длины текста сообщения. Например, при передаче двух сообщений «abrakadabra» подряд возможно, что оно будет передано с ошибкой описанного вида, и тогда будет получено сообщение вида «abrakadabrabrakadabra» или «abrakadabrakadabra» (в первом случае совмещение произошло по одному символу, а во втором — по четырем).По полученному сообщению t определите, возможно ли, что это результат ошибки описанного вида работы локальной сети, и если возможно, определите возможное значение s. Не следует считать ошибкой ситуацию полного наложения друга на друга двух сообщений. К примеру, если получено сообщение «abcd», следует считать, что в нём ошибки нет. Аналогично, простое дописывание одного сообщения вслед за другим не является признаком ошибки. Например, если получено сообщение «abcabc», следует считать, что в нём ошибки нет.

стандартный ввод

стандартный вывод

256 мегабайт

В единственной строке выходных данных следует непустая строка t, состоящая из строчных букв латинского алфавита. Длина строки t не превосходит 100 символов.

Если сообщение t не может содержать ошибки, выведите «NO» (без кавычек) в единственную строку выходных данных. В противном случае в первой строке выведите «YES» (без кавычек), а в следующей строке выведите строку s — возможное сообщение, которое могло привести к ошибке. Если возможных ответов несколько, разрешается вывести любой из них.

ПримечаниеВо втором примере подходящим ответом также является строка acacaca.

abrakadabrabrakadabra acacacaca abcabc abababab tatbt


Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move. There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0). You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.

The first line contains four integers: xp, yp, xv, yv (0 ≤ xp, yp, xv, yv ≤ 105) — Polycarp's and Vasiliy's starting coordinates. It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).

Output the name of the winner: "Polycarp" or "Vasiliy".

NoteIn the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn.


Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.There are $$$n$$$ solutions, the $$$i$$$-th of them should be tested on $$$a_i$$$ tests, testing one solution on one test takes $$$1$$$ second. The solutions are judged in the order from $$$1$$$ to $$$n$$$. There are $$$k$$$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.At any time moment $$$t$$$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $$$i$$$, then it is being tested on the first test from time moment $$$t$$$ till time moment $$$t + 1$$$, then on the second test till time moment $$$t + 2$$$ and so on. This solution is fully tested at time moment $$$t + a_i$$$, and after that the testing process immediately starts testing another solution.Consider some time moment, let there be exactly $$$m$$$ fully tested solutions by this moment. There is a caption "System testing: $$$d$$$%" on the page with solutions, where $$$d$$$ is calculated as$$$$$$d = round\left(100\cdot\frac{m}{n}\right),$$$$$$where $$$round(x) = \lfloor{x + 0.5}\rfloor$$$ is a function which maps every real to the nearest integer.Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $$$q$$$, and the caption says "System testing: $$$q$$$%". Find the number of interesting solutions.Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.

The first line contains two positive integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1000$$$, $$$1 \le k \le 100$$$) standing for the number of submissions and the number of testing processes respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 150$$$), where $$$a_i$$$ is equal to the number of tests the $$$i$$$-th submission is to be run on.

Output the only integer — the number of interesting submissions.

NoteConsider the first example. At time moment $$$0$$$ both solutions start testing. At time moment $$$49$$$ the first solution is fully tested, so at time moment $$$49.5$$$ the second solution is being tested on the test $$$50$$$, and the caption says "System testing: $$$50$$$%" (because there is one fully tested solution out of two). So, the second solution is interesting.Consider the second example. At time moment $$$0$$$ the first and the second solutions start testing. At time moment $$$32$$$ the first solution is fully tested, the third solution starts testing, the caption says "System testing: $$$25$$$%". At time moment $$$32 + 24.5 = 56.5$$$ the third solutions is being tested on test $$$25$$$, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment $$$32 + 33 = 65$$$, the fourth solution is fully tested at time moment $$$65 + 1 = 66$$$. The captions becomes "System testing: $$$75$$$%", and at time moment $$$74.5$$$ the second solution is being tested on test $$$75$$$. So, this solution is also interesting. Overall, there are two interesting solutions.


Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.The game is played on the following field.  Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (xl, yl) in some small field, the next move should be done in one of the cells of the small field with coordinates (xl, yl). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.

First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell. The line after the table contains two integers x and y (1 ≤ x, y ≤ 9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right. It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.

Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.

NoteIn the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable.


Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds:   divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$);  multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.

The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.

NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$.


Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and pi — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.Unfortunately, there only are k tables in the restaurant. For each table, we know ri — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of requests from visitors. Then n lines follow. Each line contains two integers: ci, pi (1 ≤ ci, pi ≤ 1000) — the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly. The next line contains integer k (1 ≤ k ≤ 1000) — the number of tables in the restaurant. The last line contains k space-separated integers: r1, r2, ..., rk (1 ≤ ri ≤ 1000) — the maximum number of people that can sit at each table.

In the first line print two integers: m, s — the number of accepted requests and the total money you get from these requests, correspondingly. Then print m lines — each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input. If there are multiple optimal answers, print any of them.


Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:  if the last digit of the number is non-zero, she decreases the number by one;  if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number $$$n$$$. Tanya will subtract one from it $$$k$$$ times. Your task is to print the result after all $$$k$$$ subtractions.It is guaranteed that the result will be positive integer number.

The first line of the input contains two integer numbers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le k \le 50$$$) — the number from which Tanya will subtract and the number of subtractions correspondingly.

Print one integer number — the result of the decreasing $$$n$$$ by one $$$k$$$ times. It is guaranteed that the result will be positive integer number.

NoteThe first example corresponds to the following sequence: $$$512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$$$.


Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.

The first line contains integers n and p (3 ≤ n ≤ 3·105; 0 ≤ p ≤ n) — the number of coders in the F company and the minimum number of agreed people. Each of the next n lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of coders named by the i-th coder. It is guaranteed that xi ≠ i,  yi ≠ i,  xi ≠ yi.

Print a single integer — the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) and (2, 1) are considered identical.


There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then:  move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$.  move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$.  move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$.  move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$.  move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$.  move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers:  $$$a$$$ — the total size of all sweets eaten by Alice during the game;  $$$b$$$ — the total size of all sweets eaten by Bob during the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\cdot10^5$$$.

For each set of input data print three integers — the number of moves in the game and the required values $$$a$$$ and $$$b$$$.


You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \le x \le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print "-1" (without quotes).

The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sequence itself.

Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print "-1" (without quotes).

NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number.


The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., an of n these beavers. Beavershave 5000 needs one session to shave beavers with ids from x to y (inclusive) if and only if there are such indices i1 < i2 < ... < ik, that ai1 = x, ai2 = x + 1, ..., aik - 1 = y - 1, aik = y. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1, 2, 3, ..., n.If we can't shave beavers from x to y in one session, then we can split these beavers into groups [x, p1], [p1 + 1, p2], ..., [pm + 1, y] (x ≤ p1 < p2 < ... < pm < y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs m + 1 working sessions to shave beavers from x to y.All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types:   what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive?  two beavers on positions x and y (the beavers ax and ay) swapped. You can assume that any beaver can be shaved any number of times.

The first line contains integer n — the total number of beavers, 2 ≤ n. The second line contains n space-separated integers — the initial beaver permutation. The third line contains integer q — the number of queries, 1 ≤ q ≤ 105. The next q lines contain the queries. Each query i looks as pi xi yi, where pi is the query type (1 is to shave beavers from xi to yi, inclusive, 2 is to swap beavers on positions xi and yi). All queries meet the condition: 1 ≤ xi < yi ≤ n.   to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem B1);  to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems B1+B2).  Note that the number of queries q is limited 1 ≤ q ≤ 105 in both subproblem B1 and subproblem B2.

For each query with pi = 1, print the minimum number of Beavershave 5000 sessions.


Родители Васи хотят, чтобы он как можно лучше учился. Поэтому если он получает подряд три положительные оценки («четвёрки» или «пятёрки»), они дарят ему подарок. Соответственно, оценки «единица», «двойка» и «тройка» родители Васи считают плохими. Когда Вася получает подряд три хорошие оценки, ему сразу вручают подарок, но для того, чтобы получить ещё один подарок, ему вновь надо получить подряд ещё три хорошие оценки.Например, если Вася получит подряд пять «четвёрок» оценок, а потом «двойку», то ему дадут только один подарок, а вот если бы «четвёрок» было уже шесть, то подарков было бы два. За месяц Вася получил n оценок. Вам предстоит посчитать количество подарков, которые получил Вася. Оценки будут даны именно в том порядке, в котором Вася их получал.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных следует целое положительное число n (3 ≤ n ≤ 1000) — количество оценок, полученных Васей. Во второй строке входных данных следует последовательность из n чисел a1, a2, ..., an (1 ≤ ai ≤ 5) — оценки, полученные Васей. Оценки заданы в том порядке, в котором Вася их получил.

Выведите одно целое число — количество подарков, полученных Васей.

ПримечаниеВ первом примере Вася получит два подарка — за первые три положительные оценки и за следующую тройку положительных оценок соответственно.


На тренировку по подготовке к соревнованиям по программированию пришли n команд. Тренер для каждой команды подобрал тренировку, комплект задач для i-й команды занимает ai страниц. В распоряжении тренера есть x листов бумаги, у которых обе стороны чистые, и y листов, у которых только одна сторона чистая. При печати условия на листе первого типа можно напечатать две страницы из условий задач, а при печати на листе второго типа — только одну. Конечно, на листе нельзя печатать условия из двух разных комплектов задач. Обратите внимание, что при использовании листов, у которых обе стороны чистые, не обязательно печатать условие на обеих сторонах, одна из них может остаться чистой.Вам предстоит определить максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных следуют три целых числа n, x и y (1 ≤ n ≤ 200 000, 0 ≤ x, y ≤ 109) — количество команд, количество листов бумаги с двумя чистыми сторонами и количество листов бумаги с одной чистой стороной. Во второй строке входных данных следует последовательность из n целых чисел a1, a2, ..., an (1 ≤ ai ≤ 10 000), где i-е число равно количеству страниц в комплекте задач для i-й команды.

Выведите единственное целое число — максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.

ПримечаниеВ первом тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать весь первый комплект задач на листах с одной чистой стороной (после этого останется 3 листа с двумя чистыми сторонами и 1 лист с одной чистой стороной), а второй комплект напечатать на трех листах с двумя чистыми сторонами.Во втором тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать первый комплект задач на двух листах с двумя чистыми сторонами (после этого останется 1 лист с двумя чистыми сторонами и 5 листов с одной чистой стороной), а второй комплект напечатать на одном листе с двумя чистыми сторонами и на пяти листах с одной чистой стороной. Таким образом, тренер использует все листы для печати.В третьем тестовом примере можно напечатать только один комплект задач (любой из трёх 11-страничных). Для печати 11-страничного комплекта задач будет израсходована вся бумага.


You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $$$1$$$. For example, if you delete the character in the position $$$2$$$ from the string "exxxii", then the resulting string is "exxii".

The first line contains integer $$$n$$$ $$$(3 \le n \le 100)$$$ — the length of the file name. The second line contains a string of length $$$n$$$ consisting of lowercase Latin letters only — the file name.

Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.

NoteIn the first example Polycarp tried to send a file with name contains number $$$33$$$, written in Roman numerals. But he can not just send the file, because it name contains three letters "x" in a row. To send the file he needs to remove any one of this letters.


Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He wants to remove duplicate (equal) elements.Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of elements in Petya's array. The following line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1\,000$$$) — the Petya's array.

In the first line print integer $$$x$$$ — the number of elements which will be left in Petya's array after he removed the duplicates. In the second line print $$$x$$$ integers separated with a space — Petya's array after he removed the duplicates. For each unique element only the rightmost entry should be left.

NoteIn the first example you should remove two integers $$$1$$$, which are in the positions $$$1$$$ and $$$4$$$. Also you should remove the integer $$$5$$$, which is in the position $$$2$$$.In the second example you should remove integer $$$2$$$, which is in the position $$$1$$$, and two integers $$$4$$$, which are in the positions $$$2$$$ and $$$4$$$.In the third example you should remove four integers $$$6$$$, which are in the positions $$$1$$$, $$$2$$$, $$$3$$$ and $$$4$$$.


Три брата договорились о встрече. Пронумеруем братьев следующим образом: пусть старший брат имеет номер 1, средний брат имеет номер 2, а младший брат — номер 3. Когда пришло время встречи, один из братьев опоздал. По заданным номерам двух братьев, которые пришли вовремя, вам предстоит определить номер опоздавшего брата.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных следуют два различных целых числа a и b (1 ≤ a, b ≤ 3, a ≠ b) — номера братьев, которые пришли на встречу вовремя. Номера даны в произвольном порядке.

Выведите единственное целое число — номер брата, который опоздал на встречу.


Вам задано прямоугольное клетчатое поле, состоящее из n строк и m столбцов. Поле содержит цикл из символов «*», такой что:  цикл можно обойти, посетив каждую его клетку ровно один раз, перемещаясь каждый раз вверх/вниз/вправо/влево на одну клетку;  цикл не содержит самопересечений и самокасаний, то есть две клетки цикла соседствуют по стороне тогда и только тогда, когда они соседние при перемещении вдоль цикла (самокасание по углу тоже запрещено). Ниже изображены несколько примеров допустимых циклов:  Все клетки поля, отличные от цикла, содержат символ «.». Цикл на поле ровно один. Посещать клетки, отличные от цикла, Роботу нельзя.В одной из клеток цикла находится Робот. Эта клетка помечена символом «S». Найдите последовательность команд для Робота, чтобы обойти цикл. Каждая из четырёх возможных команд кодируется буквой и обозначает перемещение Робота на одну клетку:  «U» — сдвинуться на клетку вверх,  «R» — сдвинуться на клетку вправо,  «D» — сдвинуться на клетку вниз,  «L» — сдвинуться на клетку влево. Робот должен обойти цикл, побывав в каждой его клетке ровно один раз (кроме стартовой точки — в ней он начинает и заканчивает свой путь).Найдите искомую последовательность команд, допускается любое направление обхода цикла.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных записаны два целых числа n и m (3 ≤ n, m ≤ 100) — количество строк и столбцов прямоугольного клетчатого поля соответственно. В следующих n строках записаны по m символов, каждый из которых — «.», «*» или «S». Гарантируется, что отличные от «.» символы образуют цикл без самопересечений и самокасаний. Также гарантируется, что на поле ровно одна клетка содержит «S» и что она принадлежит циклу. Робот не может посещать клетки, помеченные символом «.».

В первую строку выходных данных выведите искомую последовательность команд для Робота. Направление обхода цикла Роботом может быть любым.

ПримечаниеВ первом тестовом примере для обхода по часовой стрелке последовательность посещенных роботом клеток выглядит следующим образом:  клетка (3, 2);  клетка (3, 1);  клетка (2, 1);  клетка (1, 1);  клетка (1, 2);  клетка (1, 3);  клетка (2, 3);  клетка (3, 3);  клетка (3, 2).


Профиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».  ....................*..*.......*.**.......*.**..*...**.***********   Пример изображения горного хребта.  Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправо — в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце.Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины:  наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма),  наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска).

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных записаны два целых числа n и m (1 ≤ n, m ≤ 100) — количество строк и столбцов в схематичном изображении соответственно. Далее следуют n строк по m символов в каждой — схематичное изображение горного хребта. Каждый символ схематичного изображения — это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».

Выведите через пробел два целых числа:   величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма),  величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска).

ПримечаниеВ первом тестовом примере высоты гор равны: 3, 4, 1, 1, 2, 1, 1, 1, 2, 5, 1. Наибольший подъем равен 3 и находится между горой номер 9 (её высота равна 2) и горой номер 10 (её высота равна 5). Наибольший спуск равен 4 и находится между горой номер 10 (её высота равна 5) и горой номер 11 (её высота равна 1).Во втором тестовом примере высоты гор равны: 1, 2, 3, 4, 5. Наибольший подъём равен 1 и находится, например, между горой номер 2 (ее высота равна 2) и горой номер 3 (её высота равна 3). Так как в данном горном хребте нет спусков, то величина наибольшего спуска равна 0.В третьем тестовом примере высоты гор равны: 1, 7, 5, 3, 4, 2, 3. Наибольший подъём равен 6 и находится между горой номер 1 (её высота равна 1) и горой номер 2 (её высота равна 7). Наибольший спуск равен 2 и находится между горой номер 2 (её высота равна 7) и горой номер 3 (её высота равна 5). Такой же спуск находится между горой номер 5 (её высота равна 4) и горой номер 6 (её высота равна 2).


The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.If $$$x$$$ is the number of passengers in a bus just before the current bus stop and $$$y$$$ is the number of passengers in the bus just after current bus stop, the system records the number $$$y-x$$$. So the system records show how number of passengers changed.The test run was made for single bus and $$$n$$$ bus stops. Thus, the system recorded the sequence of integers $$$a_1, a_2, \dots, a_n$$$ (exactly one number for each bus stop), where $$$a_i$$$ is the record for the bus stop $$$i$$$. The bus stops are numbered from $$$1$$$ to $$$n$$$ in chronological order.Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$ (that is, at any time in the bus there should be from $$$0$$$ to $$$w$$$ passengers inclusive).

The first line contains two integers $$$n$$$ and $$$w$$$ $$$(1 \le n \le 1\,000, 1 \le w \le 10^{9})$$$ — the number of bus stops and the capacity of the bus. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(-10^{6} \le a_i \le 10^{6})$$$, where $$$a_i$$$ equals to the number, which has been recorded by the video system after the $$$i$$$-th bus stop.

Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $$$w$$$. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.

NoteIn the first example initially in the bus could be $$$0$$$, $$$1$$$ or $$$2$$$ passengers.In the second example initially in the bus could be $$$1$$$, $$$2$$$, $$$3$$$ or $$$4$$$ passengers.In the third example initially in the bus could be $$$0$$$ or $$$1$$$ passenger.


Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2. По заданной последовательности целых положительных чисел a1, a2, ..., an требуется найти r — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел ai, которые делятся на r.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке записано целое число n (1 ≤ n ≤ 100) — длина последовательности a. Во второй строке записана последовательность целых чисел a1, a2, ..., an (1 ≤ ai ≤ 109).

Выведите два числа:   r — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности,  количество элементов последовательности, которые делятся на r.

ПримечаниеВ первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 24, на неё делятся числа 80, 16 и 48.Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 20. Это и будет максимальной степенью двойки для данного примера.


На координатной прямой сидит n собачек, i-я собачка находится в точке xi. Кроме того, на прямой есть m мисок с едой, для каждой известна её координата на прямой uj и время tj, через которое еда в миске остынет и станет невкусной. Это значит, что если собачка прибежит к миске в момент времени, строго больший tj, то еда уже остынет, и собачка кушать её не станет.Считая, что каждая собачка бежит со скоростью 1, найдите максимальное количество собачек, которые смогут покушать. Считайте, что собачки побегут к тем мискам, на которые вы им укажете. Из одной миски не могут кушать две или более собачки.Собачки могут обгонять друг друга, то есть, если одна из них остановится покушать, другая может пройти мимо неё, чтобы попасть к другой миске.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке находится пара целых чисел n и m (1 ≤ n, m ≤ 200 000) — количество собачек и мисок соответственно. Во второй строке находятся n целых чисел xi ( - 109 ≤ xi ≤ 109) — координата i-й собачки. В следующих m строках находятся пары целых чисел uj и tj ( - 109 ≤ uj ≤ 109, 1 ≤ tj ≤ 109) — координата j-й миски и время, когда остынет еда в ней, соответственно. Гарантируется, что никакие две собачки не находятся в одной точке. Никакие две миски также не могут находиться в одной точке.

Выведите одно целое число a — максимальное количество собачек, которые смогут покушать.

ПримечаниеВ первом примере первая собачка побежит направо к первой миске, третья собачка сразу начнёт есть из второй миски, четвёртая собачка побежит влево к третьей миске, а пятая собачка побежит влево к четвёртой миске.


Есть n-подъездный дом, в каждом подъезде по m этажей, и на каждом этаже каждого подъезда ровно k квартир. Таким образом, в доме всего n·m·k квартир. Они пронумерованы естественным образом от 1 до n·m·k, то есть первая квартира на первом этаже в первом подъезде имеет номер 1, первая квартира на втором этаже первого подъезда имеет номер k + 1 и так далее. Особенность этого дома состоит в том, что он круглый. То есть если обходить его по часовой стрелке, то после подъезда номер 1 следует подъезд номер 2, затем подъезд номер 3 и так далее до подъезда номер n. После подъезда номер n снова идёт подъезд номер 1.Эдвард живёт в квартире номер a, а Наташа — в квартире номер b. Переход на 1 этаж вверх или вниз по лестнице занимает 5 секунд, переход от двери подъезда к двери соседнего подъезда — 15 секунд, а переход в пределах одного этажа одного подъезда происходит мгновенно. Также в каждом подъезде дома есть лифт. Он устроен следующим образом: он всегда приезжает ровно через 10 секунд после вызова, а чтобы переместить пассажира на один этаж вверх или вниз, лифт тратит ровно 1 секунду. Посадка и высадка происходят мгновенно.Помогите Эдварду найти минимальное время, за которое он сможет добраться до квартиры Наташи. Считайте, что Эдвард может выйти из подъезда только с первого этажа соответствующего подъезда (это происходит мгновенно). Если Эдвард стоит перед дверью какого-то подъезда, он может зайти в него и сразу окажется на первом этаже этого подъезда (это также происходит мгновенно). Эдвард может выбирать, в каком направлении идти вокруг дома.

стандартный ввод

стандартный вывод

256 мегабайт

В первой строке входных данных следуют три числа n, m, k (1 ≤ n, m, k ≤ 1000) — количество подъездов в доме, количество этажей в каждом подъезде и количество квартир на каждом этаже каждого подъезда соответственно. Во второй строке входных данных записаны два числа a и b (1 ≤ a, b ≤ n·m·k) — номера квартир, в которых живут Эдвард и Наташа, соответственно. Гарантируется, что эти номера различны.

Выведите единственное целое число — минимальное время (в секундах), за которое Эдвард сможет добраться от своей квартиры до квартиры Наташи.

ПримечаниеВ первом тестовом примере Эдвард находится в 4 подъезде на 10 этаже, а Наташа находится в 1 подъезде на 2 этаже. Поэтому Эдварду выгодно сначала спуститься на лифте на первый этаж (на это он потратит 19 секунд, из которых 10 — на ожидание и 9 — на поездку на лифте), затем обойти дом против часовой стрелки до подъезда номер 1 (на это он потратит 15 секунд), и наконец подняться по лестнице на этаж номер 2 (на это он потратит 5 секунд). Таким образом, ответ равен 19 + 15 + 5 = 39.Во втором тестовом примере Эдвард живёт в подъезде 2 на этаже 1, а Наташа находится в подъезде 1 на этаже 1. Поэтому Эдварду выгодно просто обойти дом по часовой стрелке до подъезда 1, на это он потратит 15 секунд.


In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.

Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.


A very tense moment: n cowboys stand in a circle and each one points his colt at a neighbor. Each cowboy can point the colt to the person who follows or precedes him in clockwise direction. Human life is worthless, just like in any real western.The picture changes each second! Every second the cowboys analyse the situation and, if a pair of cowboys realize that they aim at each other, they turn around. In a second all such pairs of neighboring cowboys aiming at each other turn around. All actions happen instantaneously and simultaneously in a second.We'll use character "A" to denote a cowboy who aims at his neighbour in the clockwise direction, and character "B" for a cowboy who aims at his neighbour in the counter clockwise direction. Then a string of letters "A" and "B" will denote the circle of cowboys, the record is made from the first of them in a clockwise direction.For example, a circle that looks like "ABBBABBBA" after a second transforms into "BABBBABBA" and a circle that looks like "BABBA" transforms into "ABABB".     This picture illustrates how the circle "BABBA" transforms into "ABABB"  A second passed and now the cowboys' position is described by string s. Your task is to determine the number of possible states that lead to s in a second. Two states are considered distinct if there is a cowboy who aims at his clockwise neighbor in one state and at his counter clockwise neighbor in the other state.

The input data consists of a single string s. Its length is from 3 to 100 characters, inclusive. Line s consists of letters "A" and "B".

NoteIn the first sample the possible initial states are "ABBBABBAB" and "ABBBABBBA".In the second sample the possible initial states are "AABBB" and "BABBA".


Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.

The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T. The second line contains word S. The third line contains word T. Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.

Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo.

NoteIn the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).In the second sample test the two given words couldn't be obtained from the same word by removing one letter.In the third sample test the two given words could be obtained from either word "tory" or word "troy".


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.


Ivan Anatolyevich's agency is starting to become famous in the town. They have already ordered and made n TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the i-th video can only be shown within the time range of [li, ri] (it is not necessary to use the whole segment but the broadcast time should be within this segment).Now it's time to choose a TV channel to broadcast the commercial. Overall, there are m TV channels broadcasting in the city, the j-th one has cj viewers, and is ready to sell time [aj, bj] to broadcast the commercial.Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video i and exactly one TV channel j to broadcast this video and also a time range to broadcast [x, y]. At that the time range should be chosen so that it is both within range [li, ri] and within range [aj, bj].Let's define the efficiency of the broadcast as value (y - x)·cj — the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!

The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of commercial videos and channels, respectively. Each of the following n lines contains two integers li, ri (0 ≤ li ≤ ri ≤ 109) — the segment of time when it is possible to show the corresponding video. Each of the following m lines contains three integers aj, bj, cj (0 ≤ aj ≤ bj ≤ 109, 1 ≤ cj ≤ 109), characterizing the TV channel.

In the first line print an integer — the maximum possible efficiency of the broadcast. If there is no correct way to get a strictly positive efficiency, print a zero. If the maximum efficiency is strictly positive, in the second line also print the number of the video i (1 ≤ i ≤ n) and the number of the TV channel j (1 ≤ j ≤ m) in the most effective broadcast. If there are multiple optimal answers, you can print any of them.

NoteIn the first sample test the most optimal solution is to show the second commercial using the first TV channel at time [2, 4]. The efficiency of such solution is equal to (4 - 2)·2 = 4.In the second sample test Ivan Anatolievich's wish does not meet the options of the TV channel, the segments do not intersect, so the answer is zero.


Recently, Berland faces federalization requests more and more often. The proponents propose to divide the country into separate states. Moreover, they demand that there is a state which includes exactly k towns.Currently, Berland has n towns, some pairs of them are connected by bilateral roads. Berland has only n - 1 roads. You can reach any city from the capital, that is, the road network forms a tree.The Ministry of Roads fears that after the reform those roads that will connect the towns of different states will bring a lot of trouble.Your task is to come up with a plan to divide the country into states such that:  each state is connected, i.e. for each state it is possible to get from any town to any other using its roads (that is, the roads that connect the state towns),  there is a state that consisted of exactly k cities,  the number of roads that connect different states is minimum.

The first line contains integers n, k (1 ≤ k ≤ n ≤ 400). Then follow n - 1 lines, each of them describes a road in Berland. The roads are given as pairs of integers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the numbers of towns connected by the road. Assume that the towns are numbered from 1 to n.

The the first line print the required minimum number of "problem" roads t. Then print a sequence of t integers — their indices in the found division. The roads are numbered starting from 1 in the order they follow in the input. If there are multiple possible solutions, print any of them. If the solution shows that there are no "problem" roads at all, print a single integer 0 and either leave the second line empty or do not print it at all.


You are given $$$n$$$ non-decreasing arrays of non-negative numbers. Vasya repeats the following operation $$$k$$$ times:   Selects a non-empty array.  Puts the first element of the selected array in his pocket.  Removes the first element from the selected array. Vasya wants to maximize the sum of the elements in his pocket.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 3\,000$$$): the number of arrays and operations. Each of the next $$$n$$$ lines contain an array. The first integer in each line is $$$t_i$$$ ($$$1 \le t_i \le 10^6$$$): the size of the $$$i$$$-th array. The following $$$t_i$$$ integers $$$a_{i, j}$$$ ($$$0 \le a_{i, 1} \le \ldots \le a_{i, t_i} \le 10^8$$$) are the elements of the $$$i$$$-th array. It is guaranteed that $$$k \le \sum\limits_{i=1}^n t_i \le 10^6$$$.

Print one integer: the maximum possible sum of all elements in Vasya's pocket after $$$k$$$ operations.


Polycarp invented a new way to encode strings. Let's assume that we have string T, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in T with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word "parallelogram" according to the given encoding principle transforms to word "qolorreraglom".Polycarpus already has two strings, S and T. He suspects that string T was obtained after applying the given encoding method from some substring of string S. Find all positions mi in S (1 ≤ mi ≤ |S| - |T| + 1), such that T can be obtained fro substring SmiSmi + 1... Smi + |T| - 1 by applying the described encoding operation by using some set of pairs of English alphabet letters

The first line of the input contains two integers, |S| and |T| (1 ≤ |T| ≤ |S| ≤ 2·105) — the lengths of string S and string T, respectively. The second and third line of the input contain strings S and T, respectively. Both strings consist only of lowercase English letters.

Print number k — the number of suitable positions in string S. In the next line print k integers m1, m2, ..., mk — the numbers of the suitable positions in the increasing order.

21 13
paraparallelogramgram
qolorreraglom


Сity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right — the road network forms an undirected tree.Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:  each junction must have at most one restaurant;  each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";  each network should build at least one restaurant;  there is no pair of junctions that are connected by a road and contains restaurants of different networks. The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.

The first input line contains integer n (3 ≤ n ≤ 5000) — the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the indexes of connected junctions. Consider the junctions indexed from 1 to n. It is guaranteed that the given road network is represented by an undirected tree with n vertexes.

Print on the first line integer z — the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.

NoteThe figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.


Polycarp has $$$n$$$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".Polycarp wants to offer his set of $$$n$$$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:  the final set of $$$n$$$ words still contains different words (i.e. all words are unique);  there is a way to put all words of the final set of words in the order so that the final sequence of $$$n$$$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of words in the Polycarp's set. Next $$$n$$$ lines contain these words. All of $$$n$$$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $$$4\cdot10^6$$$. All words are different. Guaranteed, that the sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $$$4\cdot10^6$$$.

Print answer for all of $$$t$$$ test cases in the order they appear. If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $$$k$$$ ($$$0 \le k \le n$$$) — the minimal number of words in the set which should be reversed. The second line of the output should contain $$$k$$$ distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from $$$1$$$ to $$$n$$$ in the order they appear. If $$$k=0$$$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them.


Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function , that for any  the formula g(g(x)) = g(x) holds.Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x)) for each k > 1.You are given some function . Your task is to find minimum positive integer k such that function f(k)(x) is idempotent.

In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain. In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function.

Output minimum k such that function f(k)(x) is idempotent.

NoteIn the first sample test function f(x) = f(1)(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4.In the second sample test:   function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(x) = f(2)(x) is idempotent since for any x it is true that f(2)(x) = 3, so it is also true that f(2)(f(2)(x)) = 3. In the third sample test:   function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(f(x)) = f(2)(x) isn't idempotent because f(2)(f(2)(1)) = 2 but f(2)(1) = 3;  function f(f(f(x))) = f(3)(x) is idempotent since it is identity function: f(3)(x) = x for any  meaning that the formula f(3)(f(3)(x)) = f(3)(x) also holds.


The Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better.The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered sequentially from 1 to m, where m is the number of vertices in the tree. Before describing the actual game, let's introduce some definitions.We'll assume that the sequence of vertices with numbers v1, v2, ..., vk (k ≥ 1) is a forward path, if for any integer i from 1 to k - 1 vertex vi is a direct ancestor of vertex vi + 1. If we sequentially write out all letters from the the edges of the given path from v1 to vk, we get some string (k = 1 gives us an empty string). We'll say that such string corresponds to forward path v1, v2, ..., vk.We'll assume that the sequence of tree vertices with numbers v1, v2, ..., vk (k ≥ 1) is a backward path if for any integer i from 1 to k - 1 vertex vi is the direct descendant of vertex vi + 1. If we sequentially write out all the letters from the edges of the given path from v1 to vk, we get some string (k = 1 gives us an empty string). We'll say that such string corresponds to backward path v1, v2, ..., vk.Now let's describe the game that the Smart Beaver from ABBYY has come up with. The game uses two rooted trees, each of which initially consists of one vertex with number 1. The player is given some sequence of operations. Each operation is characterized by three values (t, v, c) where:   t is the number of the tree on which the operation is executed (1 or 2);  v is the vertex index in this tree (it is guaranteed that the tree contains a vertex with this index);  c is a lowercase English letter. The actual operation is as follows: vertex v of tree t gets a new descendant with number m + 1 (where m is the current number of vertices in tree t), and there should be letter c put on the new edge from vertex v to vertex m + 1.We'll say that an ordered group of three integers (i, j, q) is a good combination if:   1 ≤ i ≤ m1, where m1 is the number of vertices in the first tree;  1 ≤ j, q ≤ m2, where m2 is the number of vertices in the second tree;  there exists a forward path v1, v2, ..., vk such that v1 = j and vk = q in the second tree;  the string that corresponds to the forward path in the second tree from vertex j to vertex q equals the string that corresponds to the backward path in the first tree from vertex i to vertex 1 (note that both paths are determined uniquely). Your task is to calculate the number of existing good combinations after each operation on the trees.

The first line contains integer n — the number of operations on the trees. Next n lines specify the operations in the order of their execution. Each line has form "t v c", where t is the number of the tree, v is the vertex index in this tree, and c is a lowercase English letter. To get the full points for the first group of tests it is sufficient to solve the problem with 1 ≤ n ≤ 700. To get the full points for the second group of tests it is sufficient to solve the problem with 1 ≤ n ≤ 7000. To get the full points for the third group of tests it is sufficient to solve the problem with 1 ≤ n ≤ 100000.

Print exactly n lines, each containing one integer — the number of existing good combinations after the corresponding operation from the input. 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.

NoteAfter the first operation the only good combination was (1, 1, 1). After the second operation new good combinations appeared, (2, 1, 2) and (1, 2, 2). The third operation didn't bring any good combinations. The fourth operation added good combination (1, 3, 3). Finally, the fifth operation resulted in as much as three new good combinations — (1, 4, 4), (2, 3, 4) and (3, 1, 4).


Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.

The first line of the input contains integer n (1 ≤ n < 1015).

Print expected minimal number of digits 1.


We'll call string s[a, b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|) a substring of string s = s1s2... s|s|, where |s| is the length of string s.The trace of a non-empty string t is a set of characters that the string consists of. For example, the trace of string "aab" equals {'a', 'b'}.Let's consider an arbitrary string s and the set of its substrings with trace equal to C. We will denote the number of substrings from this set that are maximal by inclusion by r(C, s). Substring s[a, b] of length n = b - a + 1 belonging to some set is called maximal by inclusion, if there is no substring s[x, y] in this set with length greater than n, such that 1 ≤ x ≤ a ≤ b ≤ y ≤ |s|. Two substrings of string s are considered different even if they are equal but they are located at different positions of s.Polycarpus got a challenging practical task on a stringology exam. He must do the following: given string s and non-empty sets of characters C1, C2, ..., Cm, find r(Ci, s) for each set Ci. Help Polycarpus to solve the problem as he really doesn't want to be expelled from the university and go to the army!

The first line contains a non-empty string s (1 ≤ |s| ≤ 106). The second line contains a single integer m (1 ≤ m ≤ 104). Next m lines contain descriptions of sets Ci. The i-th line contains string ci such that its trace equals Ci. It is guaranteed that all characters of each string ci are different. Note that Ci are not necessarily different. All given strings consist of lowercase English letters.

Print m integers — the i-th integer must equal r(Ci, s).


Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.

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 given in two lines. The first line contains two integers $$$a_1$$$ and $$$b_1$$$ ($$$1 \le a_1, b_1 \le 100$$$) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers $$$a_2$$$ and $$$b_2$$$ ($$$1 \le a_2, b_2 \le 100$$$) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).

Print $$$t$$$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).


You are given a rooted tree with $$$n$$$ vertices, the root of the tree is the vertex $$$1$$$. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree $$$1$$$.Arkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empty set of vertices of the tree. On the second stage Vasily puts some integers into all leaves of the tree. On the third stage Arkady can perform several (possibly none) operations of the following kind: choose some vertex $$$v$$$ he bought on the first stage and some integer $$$x$$$, and then add $$$x$$$ to all integers in the leaves in the subtree of $$$v$$$. The integer $$$x$$$ can be positive, negative of zero.A leaf $$$a$$$ is in the subtree of a vertex $$$b$$$ if and only if the simple path between $$$a$$$ and the root goes through $$$b$$$.Arkady's task is to make all integers in the leaves equal to zero. What is the minimum total cost $$$s$$$ he has to pay on the first stage to guarantee his own win independently of the integers Vasily puts on the second stage? Also, we ask you to find all such vertices that there is an optimal (i.e. with cost $$$s$$$) set of vertices containing this one such that Arkady can guarantee his own win buying this set on the first stage.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \le c_i \le 10^9$$$), where $$$c_i$$$ is the price of the $$$i$$$-th vertex. Each of the next $$$n - 1$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$), denoting an edge of the tree.

In the first line print two integers: the minimum possible cost $$$s$$$ Arkady has to pay to guarantee his own win, and the number of vertices $$$k$$$ that belong to at least one optimal set. In the second line print $$$k$$$ distinct integers in increasing order the indices of the vertices that belong to at least one optimal set.

NoteIn the second example all sets of two vertices are optimal. So, each vertex is in at least one optimal set.


You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 106). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ 2bi ≤ 109).

Print a single integer — the answer to the problem.

NoteIn the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8.In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them.


Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.You are given a string $$$s$$$ consisting of $$$n$$$ capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string $$$s$$$ = "BBAABBBA" the answer is two-gram "BB", which contained in $$$s$$$ three times. In other words, find any most frequent two-gram.Note that occurrences of the two-gram can overlap with each other.

The first line of the input contains integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of string $$$s$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ capital Latin letters.

Print the only line containing exactly two capital Latin letters — any two-gram contained in the given string $$$s$$$ as a substring (i.e. two consecutive characters of the string) maximal number of times.

NoteIn the first example "BA" is also valid answer.In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times.