Problem A. Bonus points

Author:Антон Карабанов   Time limit:1 sec
Input file:Standard input   Memory limit:512 Mb
Output file:Standard output  

Statement

Oh, those math lessons! Today, for example was the fourth test on the subject. To those who finished ahead of time the teacher offered an extra task for bonus points.

Two n-digit numbers are written on the blackboard, first composed of only the digit d1, second — of only the digit d2. Determine which digit occupies position k in the sum of those numbers. Positions are numbered left to right starting from 1.

You want bonus points, don't you?

Input format

Four lines of input contain four integers: n, d1, d2 and k. It is guaranteed that k is correct.

Output format

Output a single decimal digit — answer to the problem.

Constraints

1 ≤ n ≤ 109

1 ≤ k ≤ n + 1

1 ≤ d1, d2 ≤ 9

Notes on sample

Sample has n = 2 (adding two-digit numbers), d1 = 5 (first number is 55), d2 = 8 (second number is 88). Sum is 55 + 88 = 143. k = 1 (teacher asks the first digit of the result). The digit at first position of the number 143 is 1.

Sample tests

No. Standard input Standard output
1
2
5
8
1
1

Problem B. Amazon

Author:Антон Карабанов   Time limit:1 sec
Input file:Standard input   Memory limit:512 Mb
Output file:Standard output  

Statement

Fantasy chess is a variant of chess composition. Puzzles of this variant contain changes to some of the accepted rules of the game or utilize unusual pieces or boards.

Amazon is a fantasy chess piece which can move as either a queen or a knight. It is usually represented on diagrams as a horse with the crown. You can see all possible moves of this piece on a picture below. Amazon is so strong and independent that it can checkmate the enemy king without the help of another friendly piece.

White amazon and black king are positioned on a normal chess board. Determine whether the king is checkmated.

Input format

First line of input contains two integers separated by space: x1 and y1 — coordinates of the white amazon. Second line contains coordinates of the black king x2 and y2 in the same format. Piece positions are guaranteed to be different.

Output format

Output Yes or No — answer to the problem's question.

Constraints

1 ≤ x1, x2, y1, y2 ≤ 8

Notes on the samples

See the picture. In the second sample the king can capture the amazon.

Sample tests

No. Standard input Standard output
1
7 6
7 8
Yes
2
6 7
7 8
No

Problem C. Karousel

Author:Антон Карабанов   Time limit:1 sec
Input file:Standard input   Memory limit:512 Mb
Output file:Standard output  

Statement

Children theme park has opened a new attraction "Karousel" for n persons. According to safety regulations, when the attraction is running, children must be seated so that the center of mass of all riders coincides with the center of carousel and the distances between them alongside the circumference is equal. For example, for n = 6, 2, 3 or 6 children may ride simultaneously, while for n = 5 — only exactly 5. In other words, attraction is allowed to start if it has k children, where k — is a divisor of n and k ≠ 1.

There are d children waiting in the queue for the carousel. After finishing the ride children leave to other attractions. What is the minimum number of runs to let all children ride the carousel once each?

Input format

Two lines of input contain integers n and d.

Output format

Output a single integer — answer to the problem. If it is impossible for all children to get a ride, output -1.

Constraints

1 ≤ (d, n) ≤ 105

Notes on sample

In the first sample n = 16 and d = 14 (16 seats on carousel, 14 children in the queue). It is enough to run carousel 3 times: first time for 8 children, second — for 4, third — for 2.

In the first sample n = 15 and d = 7. It is impossible to let all children ride since according to regulations only 3, 5 or 15 are allowed to ride at a time.

Sample tests

No. Standard input Standard output
1
16
14
3
2
15
7
-1

Problem D. Jolly evening

Author:Антон Карабанов   Time limit:1 sec
Input file:Standard input   Memory limit:512 Mb
Output file:Standard output  

Statement

Marina Tsvetaeva, Andrej Belyj and Sasha Chernyj are spending the evening playing chess. For each game two of them are playing and the third person is waiting to take the place of the loser. The winner of each game plays next game with white pieces.

After playing n games silver age poets were surprised to find out that white side had been repeatedly winning k times in a row, followed by a black victory every time.

Andrej Belyj likes to play with white pieces, Sasha Chernyj — with black, Marina Tsvetaeva likes either of the colors. Determine the number of games where both players played with the color they like. First game was between Andrej Belyj (played with white) and Sasha Chernyj (played with black). No game was a draw.

Input format

Two lines of input contain two integers n and k.

Output format

Output a single integer — problem answer.

Constraints

1 ≤ n ≤ 109

1 ≤ k ≤ 100

Notes on sample

4 games were played. White player had been winning one game, and then losing the next one.

In the first game Belyj — Chernyj both play the color they like. Andrej wins, playing with white.

In the second game Belyj — Tsvetaeva both play the color they like. Andrej loses, playing with white.

In the third game Tsvetaeva — Chernyj both play the color they like. Marina wins, playing with white.

In the final game Tsvetaeva — Belyj only Marina plays the color she likes. So the answer is 3 games.

Sample tests

No. Standard input Standard output
1
4
1
3

Problem E. Health and light

Author:Антон Карабанов   Time limit:1 sec
Input file:Standard input   Memory limit:512 Mb
Output file:Standard output  

Statement

The city of N has a happy event! On the single street of the city, new street lamp will be installed and the new pharmacy will open. Help the city governor to find optimal places for these objects.

The street is represented by a segment of coordinate axis, where the leftmost house has coordinate 0. Let's assume house sizes to be negligibly small compared to the street length and represent houses as points on the axis.

The lamp has "brightness" parameter expressing the largest distance from the lamp where the light reaches. For example when brightness is equal to 10, lamp installed at the point x = 25 will light the street on the segment from 15 to 35 inclusive.

The pharmacy has "remoteness" parameter expressing the largest distance from it to the house such that people from that house will still visit. For example when remoteness is equal to 100, pharmacy located at point x = 25, will be visited by people living in houses with coordinates from 0 to 125 inclusive (there are no houses with negative coordinates).

Input format

First line of input contains three integers separated by spaces: n — number of houses, a — brightness и b — remoteness. Next n lines contain two space-separated integers each: xi, qi — coordinate of the house and number of people living in it (houses may be empty).

Output format

Output two integers — maximum number of houses illuminated by the lamp and maximum number of people who will visit the pharmacy. Both lamp and pharmacy may be located between the houses as well as at points with the coordinate of some house.

Constraints

1 ≤ n, a, b ≤ 105

0 ≤ xi, qi ≤ 109

Notes on sample

Sample contains five houses, lamp brightness 15 and pharmacy remoteness 20. Lamp can be installed at either point 15, or point 25, in both cases 4 houses will be illuminated. Pharmacy may be located at point 20, in which case all city inhabitants will be able to visit.

Sample tests

No. Standard input Standard output
1
5 15 20
0 6
10 5
20 0
30 7
40 10
4 28

Problem F. Identical digits

Author:Антон Карабанов   Time limit:1 sec
Input file:Standard input   Memory limit:512 Mb
Output file:Standard output  

Statement

Zhenya Slavin is a first human born on Mars. He is yet a little boy and likes to look at the digital clock hanging opposite of his bed. Most of all he likes the moments when all digits on the clock become identical. In those moments he always claps joyfully.

Since the period of rotation of Mars around its axis is different from that of the Earth, Martian colonists decided that:

Current time on Mars is hM hours, mM minutes and sM seconds. After how many seconds will Zhenya clap? Time on the Martian digital clocks is displayed with leading zeroes in all positions. Extra positions are not used.

Input format

Input contains six integers, one per line: h, m and s — description of Martian day subdivision, followed by hM, mM and sM — current time.

Output format

Output a single integer — number of seconds until the moment when all digits on the clock become identical.

Constraints

0 ≤ hM < h ≤ 106

0 ≤ mM < m ≤ 106

0 ≤ sM < s ≤ 106

Notes on samples

It the first sample Martian days are no different from Earth ones (24 hours of 60 minutes of 60 seconds). Now it is 23 hours 50 minutes exactly (clock displays digits 23:50:00). After 10 minutes (or 600 seconds) the clock will display zeroes in all positions.

It the second sample Martian days contain 627 hours of 5 minutes of 777 seconds. Now it is 49 hours 3 minutes and 2 seconds (clock displays digits 049:3:002). After 61 hours 3 minutes and 109 seconds (or 239425 Martian seconds) the clock will display ones in all positions.

Sample tests

No. Standard input Standard output
1
24
60
60
23
50
0
600
2
627
5
777
49
3
2
239425

Задача G. Характеристика последовательности

Входной файл:Стандартный вход   Ограничение времени:1 сек
Выходной файл:Стандартный выход   Ограничение памяти:512 Мб

Условие

Утенок Даки заинтерисовался последовательностями. Немного изучив данную тему, Даки решил ввести свою характеристику для последовательностей из целых чисел, под названием d-харктеристика.

Для вычисления d-характеристики требуется определить всех чисел последовательности. Если таких элементов в последовательности нет, то d-харктеристика равна 0.

Например, если дана последовательность  − 1 5 3 2, то значение будет .

Формат входных данных

Дана последовательность из N целых чисел a1, a2, …, aN

Первая строка входных данных содержит целое число N.

Вторая строка содержит N целых чисел ai, разделённых пробелами.

Формат выходных данных

Выходные данные должны содержать единственное целое число — значение d-характеристики.

Ограничения

1 ≤ N ≤ 20

 − 1000 ≤ ai ≤ 1000


Задача H. Среднее арифметическое 2

Входной файл:Стандартный вход   Ограничение времени:1 сек
Выходной файл:Стандартный выход   Ограничение памяти:512 Мб

Условие

Дана последовательность из N целых чисел a1, a2, …, aN

Требуется определить всех чисел последовательности. Если таких элементов в последовательности нет, вывести число 0.

Например, если дана последовательность  − 1 5 3 2, то ответ будет .

Формат входных данных

Первая строка входных данных содержит целое число N.

Вторая строка содержит N целых чисел ai, разделённых пробелами.

Формат выходных данных

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

Ограничения

1 ≤ N ≤ 20

 − 1000 ≤ ai ≤ 1000


Задача I. Максимум в скользящем окне

Автор:Известная   Ограничение времени:2 сек
Входной файл:input.txt   Ограничение памяти:256 Мб
Выходной файл:output.txt  

Условие

Пусть задан массив из n целых чисел. По этому массиву будут ходить два указателя l и r. Изначально оба они указывают на первый элемент массива. Оба указателя могут двигаться только вправо, на одну позицию за раз. При этом указатель l никогда не оказывается правее указателя r, и ни один из них не выходит за пределы массива. Вам нужно после каждого перемещения указателя определить максимум всех элементов от указателя l вправо до указателя r (включая позиции, на которые указывают l и r).

Формат входного файла

Первая строка входного файла содержит целое число n - размер массива. Во второй строке содержится строке n целых чисел ai - сам массив.

В третьей строке указано число m — количество перемещений. В четвертой строке — m символов 'L' или 'R', разделенных пробелами. 'L' означает, что нужно сдвинуть l вправо, 'R' — что нужно сдвинуть r вправо.

Формат выходного файла

В выходной файл выведите в одну строку ровно m чисел, где i-е число — максимальное значение на отрезке от l до r после выполнения i-й операции.

Ограничения

1 ≤ n ≤ 105

|ai| ≤ 109

0 ≤ m ≤ 2n − 2

Примеры тестов

Входной файл (input.txt) Выходной файл (output.txt)
1
4
-3 -2 -1 0
6
RRRLLL
-2 -1 0 0 0 0
2
10
1 4 2 3 5 8 6 7 9 10
12
RRLRRRLLLRLL
4 4 4 4 5 8 8 8 8 8 8 6

Задача J. Поиск в массиве

Автор:Известная   Ограничение времени:1 сек
Входной файл:Стандартный вход   Ограничение памяти:256 Мб
Выходной файл:Стандартный выход  

Условие

В первой строке входных данных содержатся натуральные числа n и m.

Во второй строке задаются n элементов первого массива, отсортированные по возрастанию, а в третьей строке – m элементов второго массива.

Элементы обоих массивов - целые числа, каждое из которых по модулю не превосходит 109

Формат входных данных

Первая строка входных данных содержит числа n и m - количество чисел в первом и втором массиве.

В следующей строке идут n чисел ai.

В третьей строке идут m чисел bi.

Формат выходных данных

Требуется для каждого из m чисел вывести в отдельную строку "YES", если это число встречается в первом массиве, и "NO" в противном случае.

Ограничения

0 < n,m ≤ 105

 − 109 < ai, bi ≤ 109

Примеры тестов

Стандартный вход Стандартный выход
1
3 3
2 3 5
1 2 3
NO
YES
YES
2
3 4
1 2 2
1 2 4 5
YES
YES
NO
NO

0.571s 0.015s 37