Problem A1. Митинг (две характеристики) ≡

Author:mesenev   Time limit:2 sec
Input file:input.txt   Memory limit:256 Mb
Output file:output.txt  

Statement

The virtual student council has decided to hold a rally against freedom of speech. This raised the question of choosing a chairperson. The student council is full of people, yet there is no one to choose from. After deliberating, the virtual characters numbered themselves, and for the character numbered i defined the following numbers:

The larger the number, the higher the character's skill level in the corresponding field.

Character i is considered a candidate for chairperson if and only if there is no character j such that simultaneously mj > mi and pj > pi.

Write a program that compiles the list of candidates for chairperson.

Input file format

The input file contains a natural number n  — the number of characters. It is followed by n pairs of natural numbers mi pi.

Output file format

Output to the output file the numbers of the selected characters in increasing order.

Constraints

1 ≤ n ≤ 105

1 ≤ mi, pi ≤ 109

Sample tests

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

Problem A2. Митинг ≡

Author:Виртуальная реальность   Time limit:2 sec
Input file:input.txt   Memory limit:256 Mb
Output file:output.txt  

Statement

The virtual student council has decided to hold a rally against freedom of speech. This raised the question of choosing a chairperson. The student council is full of people, yet there is no one to choose from. After deliberating, the virtual characters numbered themselves, and for the character numbered i defined the following numbers:

The larger the number, the higher the character's skill level in the corresponding field.

Character i is considered a candidate for chairperson if and only if there is no character j such that simultaneously mj > mi, pj > pi and tj > ti.

Write a program that compiles the list of candidates for chairperson.

Input file format

The input file contains a natural number n  — the number of characters. It is followed by n triples of natural numbers mi pi ti.

Output file format

Output to the output file the numbers of the selected characters in increasing order.

Constraints

1 ≤ n ≤ 105

1 ≤ mi, pi, ti ≤ 109

Sample tests

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

Problem B1. Кабинет мыслей Гарри Дюбуа (Online) ≡

Author:mesenev   Time limit:2 sec
Input file:input.txt   Memory limit:512 Mb
Output file:output.txt  

Statement

Your consciousness is branching. The initial state of complete amnesia is version 0. In total, Q mental acts will take place during the investigation. Each act gives birth to a new version of your "self" (versions are numbered strictly from 1 to Q). Your consciousness is in a state of permanent psychosis, so you cannot predict the future: each next request is encrypted using the answer to the previous request that required output.

Mental acts are of three types:

Decryption mechanism (Online). Let last_ans be the answer to the last output query of the third type (initially last_ans = 0). Each string s or p in the input is encrypted with a cyclic shift: to decrypt a string, every character must be shifted backward through the alphabet by last_ans positions: cdecrypted = ((c − 'a' − last_ans) mod 26 + 26) mod 26 + 'a'. The base version number v is always given in the input in unencrypted form.

Input file format

The first line of the input file contains a single integer Q  — the number of mental acts.

The next Q lines describe the acts in chronological order. Each line starts with the act type type (1 ≤ type ≤ 3) and the base version number v (0 ≤ v < i, where i is the index of the current query, from 1 to Q). If type = 1 or type = 2, an encrypted string s follows. If type = 3, an encrypted string p follows.

The total length of all strings in the input does not exceed 106. All decrypted strings consist of lowercase Latin letters and are non-empty.

Output file format

For each query of the third type, output a single integer  — the answer. Output each answer on its own line.

Constraints

1 ≤ Q ≤ 2 ⋅ 105

Sample tests

No. Input file (input.txt) Output file (output.txt)
1
8
1 0 abc
1 1 abd
3 2 a
2 2 cde
3 3 c
3 4 c
3 4 bc
3 1 b
2
2
1
1
1

Задача C1. Грузовики ≡

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

Условие

Порт отправляет грузовики на склад по сети дорог с односторонним движением. В сети n перекрёстков, пронумерованных от 1 до n; порт находится на перекрёстке 1, склад — на перекрёстке n. Дорога номер i ведёт с перекрёстка ui на перекрёсток vi и пропускает не больше ci грузовиков в час.

Между одними и теми же перекрёстками может быть несколько дорог, в том числе встречных. Грузовики не появляются и не исчезают на перекрёстках: сколько въехало на перекрёсток (кроме порта и склада), столько с него и выехало.

Сеть из первого примера

Какое наибольшее число грузовиков в час можно отправлять из порта на склад?

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

В первой строке — два целых числа n и m: число перекрёстков и число дорог. В каждой из следующих m строк — три целых числа ui, vi, ci.

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

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

Ограничения

2 ≤ n ≤ 100

1 ≤ m ≤ 1000

1 ≤ ui, vi ≤ n, ui ≠ vi

1 ≤ ci ≤ 100

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

№ Стандартный вход Стандартный выход
1
6 7
1 2 10
1 3 5
2 4 4
2 5 8
3 5 6
4 6 10
5 6 7
11
2
4 5
1 2 100
1 3 100
2 3 1
2 4 100
3 4 100
200

Задача C2. Нефтепровод ≡

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

Условие

Нефть перекачивают с промысла на терминал по сети труб. В сети n узлов, пронумерованных от 1 до n; промысел — узел 1, терминал — узел n. Труба номер i ведёт из узла ui в узел vi (нефть по ней течёт только в этом направлении) и пропускает не больше ci баррелей в сутки.

Между одними и теми же узлами может быть несколько труб, в том числе встречных. В узлах нефть не накапливается и не теряется: сколько втекло в узел (кроме промысла и терминала), столько из него и вытекло.

Какое наибольшее количество баррелей в сутки можно перекачивать с промысла на терминал?

На рисунке — сеть из первого примера: промысел 1, терминал 4, рядом с трубой — её пропускная способность.

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

В первой строке — два целых числа n и m: число узлов и число труб. В каждой из следующих m строк — три целых числа ui, vi, ci.

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

Выведите одно целое число — наибольшее количество баррелей в сутки.

Ограничения

2 ≤ n ≤ 300, 1 ≤ m ≤ 104

1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ ci ≤ 109

Тесты разбиты на три группы. Баллы за группу начисляются, только если пройдены все её тесты.

ГруппаБаллыДополнительные ограничения
120n ≤ 10, m ≤ 20, ci ≤ 100
230n ≤ 100, m ≤ 1000, ci ≤ 100
350без дополнительных ограничений

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

№ Стандартный вход Стандартный выход
1
4 5
1 2 10
1 3 5
2 4 4
3 4 8
2 3 2
11
2
4 5
1 2 100
1 3 100
2 3 1
2 4 100
3 4 100
200

Задача D1. Доминошки ≡

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

Условие

Дана клетчатая доска из n строк и m столбцов; некоторые клетки вырезаны. Доминошка занимает две свободные клетки, соседние по стороне. Доминошки не должны перекрываться.

Положите на доску как можно больше доминошек.

На рисунке — доска из первого примера: слева положена одна доминошка, и больше не помещается; справа — две.

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

В первой строке — два целых числа n и m. В каждой из следующих n строк — m символов: . — свободная клетка, # — вырезанная.

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

В первой строке выведите k — наибольшее число доминошек. В каждой из следующих k строк — четыре числа r1, c1, r2, c2: строки и столбцы двух клеток очередной доминошки (нумерация с 1). Если оптимальных раскладок несколько, выведите любую.

Ограничения

1 ≤ n, m ≤ 100

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

№ Стандартный вход Стандартный выход
1
2 3
...
.##
2
1 1 2 1
1 3 1 2
2
3 4
..#.
....
.#..
5
3 1 2 1
1 1 1 2
2 4 1 4
2 2 2 3
3 3 3 4

Задача D2. Минимум автобусов ≡

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

Условие

Есть расписание из n рейсов. Рейс i отправляется из точки (xi, yi) в момент ti и идёт в точку (x′i, y′i). Город — прямоугольная сетка улиц: дорога из точки (a, b) в точку (c, d) занимает |a − c| + |b − d| минут, и с пассажирами, и порожняком.

Автобус может выполнить рейс j сразу после рейса i, если, закончив рейс i, он успевает доехать порожняком до начала рейса j к моменту tj (приехать ровно к tj можно). Перед первым рейсом автобус может стоять где угодно.

Каким наименьшим числом автобусов можно выполнить все рейсы? Предъявите расписание каждого автобуса.

На рисунке — первый пример. Если раздавать рейсы по одному, в порядке отправления, каждый раз первому автобусу, который успевает, понадобится три автобуса; на самом деле хватает двух.

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

В первой строке — число n. В каждой из следующих n строк — пять целых чисел xi, yi, x′i, y′i, ti.

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

В первой строке выведите k — наименьшее число автобусов. Затем k строк, по одной на автобус: сначала число его рейсов, затем номера рейсов в порядке выполнения (рейсы нумеруются с 1 в порядке входа). Каждый рейс должен встретиться ровно один раз. Если ответов несколько, выведите любой.

Ограничения

1 ≤ n ≤ 500

0 ≤ xi, yi, x′i, y′i ≤ 106, (xi, yi) ≠ (x′i, y′i), 0 ≤ ti ≤ 109

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

№ Стандартный вход Стандартный выход
1
4
10 0 2 0 6
2 0 3 0 18
10 0 3 0 23
8 0 1 0 8
2
2 1 3
2 4 2
2
5
0 0 5 5 0
5 5 0 0 10
5 0 0 5 3
0 5 5 0 12
2 2 3 3 25
3
3 1 2 5
1 3
1 4

Problem E01. Two-Direction Mechanism ≡

Author:Well-known   Time limit:1 sec
Input file:Standard input   Memory limit:64 Mb
Output file:Standard output  

Statement

An ancient mechanism contains gears that can be installed clockwise or counterclockwise. Each inscription states that gear i has direction di, gear j has direction dj, or both. The mechanism opens only when every inscription is true.

Formally, let xi = 1 mean clockwise and xi = 0 mean counterclockwise. Each inscription is a disjunction of two literals (li ∧ lj). Find an assignment satisfying every clause, or report that none exists.

Input format

The first line contains n, the number of clauses. Each of the next n lines contains at most two integers. A positive integer i denotes xi, and a negative integer  − i denotes ¬ xi.

For example, (X ∧ Y) ∨ (¬ X ∧ Z) is represented as:

2 1 2 -1 3

Output format

Print any satisfying sequence of zeros and ones separated by spaces. Position i describes gear i. Its length must equal the largest gear index in the input. If the formula is unsatisfiable, print  − 1.

Sample tests

No. Standard input Standard output
1
2
1 2
-1
0 1
2
3
1 2
-1
-2
-1

Задача E11. Сапёр ≡

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

Условие

Петя изучает теорию сложности вычислений и узнал, что задача "Сапёр" является NP-полной. Так как эта задача принадлежит классу NP, её можно свести к задаче выполнимости булевых формул (SAT).

Игровое поле состоит из клеток, некоторые из которых содержат мины. Число в клетке (подсказка) показывает, сколько мин находится в соседних 8 клетках. Если в клетке число 0 - все соседние клетки безопасны.

Необходимо реализовать это сведение - преобразовать игровое поле Сапёра в булеву формулу в формате DIMACS CNF.

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

Первая строка содержит два целых числа через пробел: n m, где:

Последующие n строк содержат по m целых чисел через пробел, где:

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

Программа должна выводить SAT-формулу в формате DIMACS CNF:

p cnf variables clauses
clause1 0
clause2 0
...

Требования к структуре формулы

Для прохождения тестов формула должна быть детерминированной. Соблюдайте следующие правила:

  1. Приоритет подсказок: генерация ограничений происходит в цикле по значению числа в клетке K от 0 до 8. Сначала обрабатываются все клетки с цифрой 0, затем с цифрой 1, и так далее до 8. Внутри группы с одинаковыми цифрами клетки обрабатываются в естественном порядке (построчно: сверху-вниз, слева-направо).
  2. Нумерация переменных: переменная для закрытой клетки получает свой ID (1, 2, 3...) в тот момент, когда она впервые упоминается как сосед при формировании ограничений согласно порядку из п.1.
  3. Порядок соседей: при перечислении соседей (для формирования клоуза или присвоения ID) используется геометрический порядок: от верхнего левого (-1, -1) к нижнему правому (1, 1).
  4. Порядок ограничений для одной клетки:
    • Сначала выводятся условия, запрещающие ситуацию "мин больше K" (комбинации отрицательных литералов).
    • Следом выводятся условия, запрещающие ситуацию "мин меньше K" (комбинации положительных литералов).
  5. Уникальность: В итоговом файле не должно быть дублирующихся строк (клоузов). Дубликаты должны быть удалены, при этом сохраняется порядок первого появления клоуза.

Ограничения

1 ≤ n, m ≤ 10

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

№ Стандартный вход Стандартный выход
1
3 3
0 1 -1
1 2 -1
-1 -1 -1
p cnf 5 19
-1 -2 0
1 2 0
-3 -4 0
3 4 0
-1 -2 -3 0
-1 -2 -4 0
-1 -2 -5 0
-1 -3 -4 0
-1 -3 -5 0
-1 -4 -5 0
-2 -3 -4 0
-2 -3 -5 0
-2 -4 -5 0
-3 -4 -5 0
1 2 3 4 0
1 2 3 5 0
1 2 4 5 0
1 3 4 5 0
2 3 4 5 0
2
3 4
0 1 -1 -1
1 3 -1 -1
-1 -1 -1 -1
p cnf 5 19
-1 -2 0
1 2 0
-3 -4 0
3 4 0
-1 -2 -3 -4 0
-1 -2 -3 -5 0
-1 -2 -4 -5 0
-1 -3 -4 -5 0
-2 -3 -4 -5 0
1 2 3 0
1 2 4 0
1 2 5 0
1 3 4 0
1 3 5 0
1 4 5 0
2 3 4 0
2 3 5 0
2 4 5 0
3 4 5 0

Problem E12. Sudoku Through an Oracle ≡

Author:Course Instructor   Time limit:10 sec
Input / output:interactive   Memory limit:512 Mb

Statement

Fill a Sudoku of box size k: a grid of n × n cells, n = k2, split into n boxes of k × k cells. Every row, every column and every box must contain each of the numbers 1,…,n exactly once. Some cells are given.

You do not have to search for the answer yourself. The judge owns a SAT solver (an oracle) and lets your program use it: you send a formula in conjunctive normal form, the oracle says whether it is satisfiable and, in MODEL mode, returns a satisfying assignment. Translate the puzzle into a formula, ask the oracle, and translate its answer back into a filled grid. The large tests are out of reach of hand-written backtracking within the time limit; a correct encoding makes them easy for the oracle.

This is an interactive problem. After reading the test, your program prints commands (tokens separated by whitespace; a command may span several lines):

In DECISION mode the oracle answers only SAT or UNSAT, without a model, and you must still output a filled grid. Hint: forcing one more literal that keeps the formula satisfiable keeps a solution.

Clauses stay in the oracle between queries: you may add clauses after a reply and ask again.

Example (fragment, MODEL mode): two clauses over variables 1 and 2, one query, the model says x1 = 0, x2 = 1.

you:    a 1 2 0
you:    a -1 0
you:    s 0
oracle: SAT
oracle: 01
you:    ans ...

Input format

Line 1: the mode (MODEL or DECISION), the conflict budget of one query C and the maximum number of queries Q. Line 2: k. Then n lines of n integers, the grid; 0 marks an empty cell.

Output format

The commands described above, ending with ans and the filled grid. Any valid filling that keeps the given cells is accepted.

Constraints

3 ≤ k ≤ 6; every test has a solution.

At most Q queries per test and at most 3 ⋅ 107 literals in all clauses together.

Groups: warm-up (n ≤ 16, MODEL), large (n = 25,36, MODEL), decision (n ≤ 16, DECISION), decision large (n = 25, DECISION).


Problem E13. Numberlink Through an Oracle ≡

Author:Course Instructor   Time limit:10 sec
Input / output:interactive   Memory limit:512 Mb

Statement

A grid of h × w cells contains pairs of numbered endpoints. Connect every pair of equal numbers by a pipe so that a pipe runs through side-adjacent cells; pipes never cross or branch (an endpoint has exactly one connection, every other cell exactly two); every cell is used; and there are no closed loops: every pipe joins two endpoints with the same number.

As in "Sudoku Through an Oracle", the judge owns a SAT solver and your program may use it: encode the rules as a formula, ask the oracle, decode the answer. The catch: the local rules allow closed loops that touch no endpoint, and a compact formula cannot easily forbid all of them at once. When a model contains a loop, add a clause that forbids it and ask again; the oracle keeps all clauses between queries, so this loop of queries is cheap.

The protocol is that of "Sudoku Through an Oracle": a l1 ... 0 adds a clause; s a1 ... 0 solves under assumptions (flush, then read SAT with a model line in MODEL mode, UNSAT with the failed assumptions if there were any, or UNKNOWN); ans followed by the answer ends the dialogue. In DECISION mode the oracle answers only SAT or UNSAT.

Example: a puzzle with 3 rows and 4 columns, one solution, and its answer (cell (2,2) connects left and down: 4 + 2 = 6).

1 0 0 1      1 - 1 - 1 - 1       ans
2 0 0 3      2 - 2   3 - 3       8 12 12 4
2 0 0 3          |   |           8 6 10 4
             2 - 2   3 - 3       8 5 9 4

Input format

Line 1: the mode (MODEL or DECISION), the conflict budget of one query C and the maximum number of queries Q. Line 2: h and w. Then h lines of w integers: 0 for an empty cell, c > 0 for an endpoint of colour c; colours are 1,…,K and each appears exactly twice.

Output format

Oracle commands, then ans and h lines of w integers: the pipe mask of each cell, the sum of 1 (up), 2 (down), 4 (left) and 8 (right) over the sides through which the pipe leaves the cell. Connections must agree between neighbours. Any valid solution is accepted.

Constraints

6 ≤ h,w ≤ 30; every test has a solution. At most Q queries per test and at most 3 ⋅ 107 literals in all clauses together.

Groups: small (up to 10 × 10, MODEL), medium (12 × 12 to 15 × 15, MODEL), decision (up to 10 × 10, DECISION), large (17 × 17 to 20 × 20, MODEL), boss (25 × 25, 30 × 30, MODEL). As in other problems of the course, the boss group is out of reach of the authors' reference solution.


0.243s 0.008s 44