Problem A. Alphabetic replacement

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

Statement

You are given two strings of small Latin letters, S and T. Some letters of string S may be replaced by letters of T according to the following rules:

  1. Each letter from T may be used only once or not used at all.
  2. Letters from T must be used in order from left to right. In other words, if letter Si is replaced by letter Tp, letter Sj is replaced by letter Tq, and i < j, then p < q.

You program must modify string S according to the rules above to get lexicographically smallest string.

Input file format

First line of input file contains string S. Second line of input file contains string T.

Output file format

Output file must contain optimally modified string S.

Constraints

0 < |S|, |T| ≤ 105

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
aaa
abacaba
aaa
2
ababcaba
abca
aaaacaba

Problem B. Biota

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

Statement

Young marine biologist Masha spent her summer in Primorye, diving and taking notes of what she saw on the seafloor. Later she found her records for one of the bays where she has been. These records were:

Help Masha to figure the minimum possible percentage of the seafloor inhabited by all three species simultaneously.

In the first example, shellfish live everywhere. Starfish and sea urchins each take 3/4 of the seafloor, which means that at least half of the seafloor is inhabited by shellfish, starfish and sea urchins simultaneously.

In the second example, there are areas where 2 out of 3 species live. But it's possible that there are no areas where all 3 species live.

Input file format

Input file contains integers A, B and C.

Output file format

Output file must contain a single integer from 0 to 100 — the answer, in percents.

Constraints

0 ≤ A, B, C ≤ 100

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
75 75 100
50
2
30 45 40
0
3
70 80 90
40

Problem C. Cyclic state machine

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

Statement

Vasya invented a device working similarly to finite automaton. Device accepts as input a cyclic string of characters, and has a pointer to one of characters. On each step the device reads the character at the current pointer position and executes an action according to a given table.

Action in the table is represented by four values S C Q H, where

The device will stop if:

Your program must, given input sting and a table, determine starting position and state which will cause device to execute maximum possible number of steps until stopping.

Input file format

First line of input file contains input string T, consisting of small Latin letters and digits. Second line contains integer M — number of commands. Following M lines contain commands in the format described above.

Output file format

Output file must contain two integers — numbers of staring position and starting state. Positions are numbered from zero. If there are several optimal solutions, output any of them.

Constraints

Action table contains no more than one action for each pair (position, state).

0 ≤ S, Q < 1000,

0 ≤ |H| ≤ |T|,

0 < |T| ≤ 500, 0 < M ≤ 36 ⋅ 1000

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
acabcbabac
4
1 c 2 -1
1 b 1 1
3 a 1 1
2 b 1 -1
2 3
2
9696969676
4
1 9 2 -3
1 6 2 2
3 7 1 1
2 6 1 -3
3 1

Problem D. Dense schedule

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

Statement

One famous university has failed to create a proper schedule of classes before the beginning of the academic year. Teachers decided to fix this. They created a list of classes that teachers have to give to some of the groups of students according to the academic plan. However, coming up with an actual schedule is difficult and feels like something that a computer can do. They came to computer science department and asked you to write a program that will generate the best schedule.

There are N teachers numbered from 1 to N. There are M groups of students numbered from 1 to M. Teachers created a list of K pairs (t, g), meaning that teacher t needs to give a class to a group g. Some pairs may repeat in the list — this is because there might be several classes per day for the same subject (e.g., Calculus).

For simplicity, suppose that all these classes should happen in one day. The length of each class is the same and equal to the length of academic "pair" — a time slot. Of course, a teacher can not give two classes at the same time, as well as a group can not attend two classes simultaneously.

The best schedule is the one that fits into the minimum number of time slots. In other words, the schedule should ensure that the last teacher and the last group of students will leave the university as soon as possible.

Input file format

Input file contains integers N, M, K, followed by K pairs of integers ti and gi.

Output file format

Output file must start with an integer — the number of time slots in the schedule, followed by time slots description. Each description starts with li — the number of classes happening in this time slot, followed by (t, g) pairs from the original list.

The output must list all pairs from the input (li = K).

Constraints

1 ≤ N, M ≤ 100; 1 ≤ K ≤ 1000

1 ≤ ti ≤ N; 1 ≤ gi ≤ M

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
1 3 2
1 1
1 2
2
1
1 1
1
1 2
2
2 2 4
1 1
1 2
2 1
2 2
2
2
1 1
2 2
2
1 2
2 1

Problem E. Easy patrol

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

Statement

Young programmer Vasya tinkered with robots, and decided to create a new startup Easy Patrol with the goal of producing robot guardian to replace human guards.

As a first step, he considered a single wall of N meters in length and two patrolling robots moving back and forth along it.

First robot starts patrolling at the point located x meters from the left edge of the wall, moving to the right. Second robot starts patrolling at the point located y meters from the left edge of the wall, moving to the left.

Each second, events happen in the following order:

  1. if robots are about to collide (that is, are facing each other at the distance 0 or 1 meters), both reverse direction.
  2. each robot checks whether it has reached the edge and reverses direction if it is so.
  3. both robots move simultaneously, each for exactly 1 meter in its current direction.

Your program must determine maximum possible distance between two robots.

Input file format

Input file contains integers N, x, y.

Output file format

Output file must contain a single integer — maximum distance between robots in meters.

Constraints

4 ≤ N ≤ 106

0 ≤ x, y ≤ N

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
5 1 3
4
2
8 3 1
4

Problem F. Fancy substring

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

Statement

String T consists of small Latin letters. String P consists of small Latin letters and star symbols '*'.

Your program must find all positions in T where some cyclic shift of P occurs (that is, indexes s, for which there exists d such that P(i + dmod |P| = Ts + i, i = 0, |P| − 1).

Additionally, star in P may correspond to an arbitrary single character in T.

Input file format

First line of input file contains string T. Second line of input file contains string P.

Output file format

Output file must contain an integer K — number of positions, followed by K integers ai — position indexes in ascending order. Positions are indexed from zero.

Constraints

1 ≤ |T| ≤ 105

1 ≤ |P| ≤ 400

|P| ≤ |T|

Number of star symbols in P doesn't exceed 3.

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
abacaba
bca
1
3
2
abacaba
a*a
3
0 2 4

Problem G. Great triangle

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

Statement

Consider a set of n points on a plane, described by their coordinates: M = {(xi, yi): i = 0, 1, …, n − 1}.

Your program must, given two points A and B, find a point C from set M, such that triangle {A, B, C} contains maximum possible number of points from M. Points both inside and on the edges of the triangle are counted.

Input file format

Input file contains integer n, followed by n pairs of integers — point coordinates (xi, yi). Next, four integers follow — coordinates of points A and B.

Output file format

Output file must contain a single integer — index of point C. Indexes start from zero. If there are several solutions, output any of them.

Constraints

Points A and B are different.

 − 104 ≤ (xi, yi) ≤ 104, 0 < n ≤ 105

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
10
-7683 -1465
 1000  6970
-1096 -1613
 7052  3877
-8237  2965
 5089  6152
-7697  5970
 1340 -7370
 2068  1467
 4499 -3269

 1990 -5786
-6140 -5000
5
2
10
-4036  1190
 4691 -1023
 7809 -1023
 7021 -6507
 4691 -1023
-1000 -5000
 3096 -1023
 1570 -4210
 7809 -1023
 7809 -1023

-7500 -5103
-1059 -1023
9

Problem H. Highway cycle

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

Statement

Young programmer Vasya lives in a city where streets can be represented by a tree. Each vertex of a tree correspond to an intersection, each edge — to a street. So number of streets in the city is 1 less than a number of intersections. It is possible to get from from each intersection to every other one by streets.

There are two kinds of streets — residential and office ones.

City administration wants to create a looping road, represented by a cycle of streets. To minimize spending, only a single road of either kind must be built, creating a cycle. To satisfy zoning regulations, cycle must consist of at least 4 streets and number of residential streets in the cycle must be equal to the number of office streets.

Young programmer Vasya is preparing a presentation for city mayor and wants to add a slide with the total number of ways to add a street to the city road system, while satisfying all requirements. Your program must calculate that number.

Input file format

Input file contains integer N — number of intersections in the city, followed by N − 1 triplets of integers u, v, c — numbers of intersections connected by street (u, v) and the kind of the street. c = 0 — residential street, c = 1 — office street.

Output file format

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

Constraints

3 ≤ N ≤ 3000

0 ≤ u, v < N

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
4
0 1 0
1 2 1
2 3 1
1
2
5
0 1 0
1 2 1
2 3 1
3 4 0
2

Задача I. Interactive increment

Автор:A. Usmanov   Ограничение времени:1 сек
Ввод / вывод:интерактивный   Ограничение памяти:256 Мб

Условие

Данная задача является интерактивной.

Жюри загадало секретное целое число X, состоящее из ровно N бит. Известно, что в этом числе есть K единичных бит (и N − K нулевых бит). Ваша программа может делать запросы вида "+ Y", которые к текущему значению числа X будет прибавляют целое число Y. При этом биты старше N-о отбрасываются, то есть выполняется операция вида X = (X + Ymod 2N.

На каждый запрос программа жюри отвечает количеством единичных бит в текущем значении X. Требуется определить текущее значение числа X, сделав не более ⌊ N2 запросов.

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

В первой строке входных данных записано два целых числа N и K — общее количество бит в числе и количество единичных бит в начальном значении соответственно.

Протокол взаимодействия

Чтобы сделать запрос, ваша программа должна вывести "+ Y", где Y — целое число, которое нужно прибавить к X. На каждый запрос программа жюри ответит целым числом — количеством единичных бит в числе X после выполнения запроса.

Когда ваша программа определит текущее значение X, она должна вывести "! X" и завершиться.

Если ваша программа сделает недопустимый запрос, то она получит вердикт "Presentation error". Если ваша программа превысит допустимое количество запросов, то она получит вердикт "Wrong answer".

Каждый запрос и вывод окончательного результата должен быть одиночной строкой заканчивающейся одиночным переводом строки (\n). Буфер вывода необходимо сбрасывать после каждой строки:

Язык C++ Pascal Java Python
Код cout.flush() flush(output) System.out.flush() stdout.flush()

Ограничения

1 ≤ N ≤ 60

0 ≤ K ≤ N

0 ≤ X, Y < 2N

Пояснение к примерам

В первом примере было загадано число 13 (1101 в двоичной системе счисления). После выполнения первого запроса получилось (13 + 9mod 16 = 6 (01102). После выполнения второго запроса получилось (6 + 9mod 16 = 15 (11112).

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

Стандартный вход Стандартный выход
1
4 3 

2

4

+ 9

+ 9

! 15
2
2 2

! 3

Problem J. Jigsaw separation

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

Statement

Rectangular jigsaw puzzle consists of two pieces. Each piece is a 4-connected set of square cells, each cell represented by character 'X' or 'O'.

Your program must determine whether it is possible to separate puzzle pieces by moving either of them in vertical or horizontal direction.

In the first sample it is possible to separate pieces by moving 'X' piece up and/or 'O' piece down.

Input file format

First line of input contains two integers W H. Following H lines contain W characters each — puzzle representation.

Output file format

Output must contain a single string YES or NO.

Constraints

1 ≤ W, H ≤ 100. Each piece contains at least one cell.

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
4 3
XXXX
XOXO
OOOO
YES
2
3 3
XXX
XOX
XXX
NO

0.898s 0.019s 31