Задача A. Binary king

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

Условие

Юная разработчица компьютерных игр Алиса создала новую игру и разослала её друзьям на бета-тестирование.

Юный геймер Вася хочет произвести впечатление на Алису, пройдя игру полностью.

На последнем уровне Вася столкнулся с главным боссом — Бинарным королём. В начале боя Бинарный король игры генерирует последовательность K из N двоичных цифр. После этого Вася должен предоставить свою бинарную последовательность V такой же длины.

Васина последовательность оценивается следующим образом. Для каждой позиции i, если Vi = 1 и Ki = 0, Вася получает 1 балл; если Vi = 0 и Ki = 1, Вася теряет 2 балла.

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

Чтобы победить, Вася должен набрать наибольшее возможное количество баллов.

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

Входной файл содержит N символов 0 или 1 — последовательность Короля.

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

Выходной файл должен содержать N символов 0 или 1 — последовательность Васи, набирающую наибольшее количество баллов. Если существует несколько оптимальных решений, выведите любое из них.

Ограничения

1 ≤ N ≤ 105

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

Входной файл (input.txt) Выходной файл (output.txt)
1
111111111111
000000111111
2
111011001000
001011001011

Problem B. Document signing

Author:A. Baranov   Time limit:1 sec
Input file:input.txt   Memory limit:256 Mb
Output file:output.txt  

Statement

You have a document that needs to be signed by university president. It's hard to get president's time, but luckily you know his current location in the university campus. You also know that he is heading to his office now, so you can try to intercept him on the way and ask for a signature. Even more, everyone at university knows that president always takes fastest path wherever he goes. However, if there are several fastest paths, the president chooses any of them.

You need to write a program that determines whether you can guarantee meeting the president no matter which of the fastest path he picks, if you start moving from your room at the same time as the president.

More formally, university campus map is given as an undirected graph. i-th edge is given by its vertices (ai, bi) and traversal time ti (this is a traversal time for any human, either you or the president). Initially, the president is located at vertex p1 and is taking one of the fastest paths to his office located at vertex f. You are initially located at vertex p2. You can get the signature if you meet the president at vertex v such that:

Input file format

Input file starts with two integers: n — the number of vertices and m — the number of edges.

Then m edges are given by integers ai, bi, ti. Vertices are numbered starting from 0.

Finally, there are three integers f, p1, and p2.

Output file format

Output file must contain the number of vertices where it is possible to get the signature, followed by the list of vertex numbers in ascending order.

Constraints

It is guaranteed that the graph is connected, i.e. it's possible to get from any vertex to any other vertex.

There is no more than one edge between each pair of vertices (ai, bi).

2 ≤ n ≤ 1000, 1 ≤ m ≤ n(n − 1) / 2

0 ≤ ai, bi, p1, p2, f < n

ai ≠ bi, p1 ≠ p2

0 < ti ≤ 1000

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
8 9

0 1 1
5 1 1
5 6 2
6 4 3
5 4 7
1 2 2
2 4 4
3 7 5
7 4 6

3
0
5
4
1 3 4 7
2
8 9

5 6 1
6 4 4
0 1 2
1 7 1
7 2 2
1 4 4
1 2 4
4 2 1
2 3 7

3
0
5
0

Задача C. Emitting light

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

Условие

Юный физик Маша изучает лазеры. Маша хочет построить простой двумерный волновод, состоящий из двух очень длинных параллельных зеркал. Первое зеркало совпадает с осью Ox, а второе зеркало расположено на расстоянии h от первого.

Маша расположила лазер в точке с координатами (0,y) и направила лазерный луч в направлении (1,  − 1). Маша хочет подобрать расстояние между зеркалами h так, чтобы луч прошёл через точку с координатами (xt,yt). Сам лазер при этом должен находиться внутри волновода, то есть h≥ y. Лазерный луч всегда отражается от зеркал под углом в 45 градусов.

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

Входной файл содержит три целых числа: y, xt, yt — координаты лазера и цели.

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

Программа должна вывести единственное целое число — значение h, при котором лазерный луч пройдёт через цель. Если есть несколько решений, выведите минимальное возможное значение h. Если решений нет, выведите одно число  − 1.

Ограничения

1 ≤ y, xt, yt ≤ 109

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

Входной файл (input.txt) Выходной файл (output.txt)
1
5 2 2
-1
2
5 6 1
5
3
2 16 2
2

Problem D. Fixing lottery

Author:A. Klenin   Time limit:1 sec
Input file:input.txt   Memory limit:256 Mb
Output file:output.txt  

Statement

Well-known store chain "Three cats" decided to create a marketing lottery. Customers were given tickets with sequential integer numbers, and each month a single ticket number was selected as a winner.

To promote company image, it was decided that winning number must be divisible by 3.

For the first month of the lottery, company selected a ticket and printed it on a large banner to hang inside the store. Unfortunately, a person from marketing who selected a ticket did not know math, and selected ticket number which is not divisible by 3.

To quickly fix the banner, your program must change exactly one digit in the number so that:

  1. Result is divisible by 3.
  2. Result is less than original number.
  3. Result has no leading zeroes.

Input file format

Input file contains a string of N decimal digits. First digit is non-zero.

Output file format

Output file must contain a string of N decimal digits — fixed ticket number. If there is more than one solution, output numerically smallest of them. If there is no solution, output string IMPOSSIBLE.

Constraints

2 ≤ N ≤ 100

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
13
12
2
200
IMPOSSIBLE
3
55
15

Задача E. Implicit array

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

Условие

Отсортированный массив целых чисел задан неявным образом. Вместо каждого элемента известно множество, состоящее из данного элемента и его соседей справа и слева. У первого и последнего элемента есть не более одного соседа. Заметим, что множество не сохраняет ни порядок элементов, ни наличие дубликатов.

Напишите программу, которая восстановит массив в явном виде (все элементы по порядку).

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

Первая строка входного файла содержит целое число N — количество элементов в массиве.

Следующие N строк содержат неявные описания элементов массива: размер множества si и si различных целых чисел aij — множество, состоящее из i-го элемента массива и его соседей.

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

Выходной файл должен содержать N целых чисел — элементы исходного отсортированного массива.

Ограничения

1 ≤ N ≤ 105

 − 109 ≤ aij ≤ 109

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

Входной файл (input.txt) Выходной файл (output.txt)
1
7
1 1
1 1
2 1 2
2 1 2
2 2 3
2 2 3
1 3
1 1 1 2 2 3 3
2
1
1 7
7

Problem F. Jubilees

Author:A. Klenin   Time limit:1 sec
Input file:input.txt   Memory limit:256 Mb
Output file:output.txt  

Statement

Let's define that a positive integer is a jubilee if it is divisible by 5 and is no less than 10. (i.e. 10, 15, 20, …).

Your program must, given a sequence of N decimal digits, find maximum number of jubilees which can be made by splitting this sequence into disjoint subsequences. In other words, every digit of sequence must be used no more than once and original order of digits must be preserved.

In the first sample, sequence 2535 can be split into 25 and 35.

In the second sample, sequence 1115005000 can be split into 10, 10, 10, 50 and 50.

Input file format

Input file contains a string of N decimal digits. First digit is non-zero.

Output file format

Output file must contain a single integer — number of jubilees.

Constraints

1 ≤ N ≤ 100

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
2535
2
2
1115005000
5

Problem G. K

Author:A. Klenin   Time limit:1 sec
Input file:input.txt   Memory limit:256 Mb
Output file:output.txt  

Statement

Your program must output large letter 'K'.

Letter is drawn using '#' (ASCII 35) characters and is composed of vertical line of V characters, upper diagonal of H characters, and lower diagonal of L characters.

Diagonals must connect in the middle of the vertical line. If vertical line has even length, diagonals must connect on the character above the middle.

Letter image must be the smallest possible rectangle including the letter. Parts of rectangle not occupied by the letter must be filled with '.' (ASCII 46) character.

Input file format

Input file contains three integers V H L.

Output file format

Output file must contain letter image.

Constraints

3 ≤ V ≤ 20

1 ≤ H, L ≤ 20

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
6 3 2
...#
#.#.
##..
#...
##..
#.#.
#...
2
7 1 2
#..
#..
##.
#..
##.
#.#
#..

0.503s 0.019s 25