| Author: | mesenev | Time limit: | 2 sec | |
| Input file: | input.txt | Memory limit: | 256 Mb | |
| Output file: | output.txt |
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:
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.
The input file contains a natural number n — the number of characters. It is followed by n pairs of natural numbers mi pi.
Output to the output file the numbers of the selected characters in increasing order.
1 ≤ n ≤ 105
1 ≤ mi, pi ≤ 109
| No. | Input file (input.txt) |
Output file (output.txt) |
|---|---|---|
| 1 |
|
|
| Author: | Виртуальная реальность | Time limit: | 2 sec | |
| Input file: | input.txt | Memory limit: | 256 Mb | |
| Output file: | output.txt |
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:
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.
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 to the output file the numbers of the selected characters in increasing order.
1 ≤ n ≤ 105
1 ≤ mi, pi, ti ≤ 109
| No. | Input file (input.txt) |
Output file (output.txt) |
|---|---|---|
| 1 |
|
|
| Author: | mesenev | Time limit: | 2 sec | |
| Input file: | input.txt | Memory limit: | 512 Mb | |
| Output file: | output.txt |
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.
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.
For each query of the third type, output a single integer — the answer. Output each answer on its own line.
1 ≤ Q ≤ 2 ⋅ 105
| No. | Input file (input.txt) |
Output file (output.txt) |
|---|---|---|
| 1 |
|
|
| Автор: | 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 |
|
|
| 2 |
|
|
| Автор: | 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
Тесты разбиты на три группы. Баллы за группу начисляются, только если пройдены все её тесты.
| Группа | Баллы | Дополнительные ограничения |
|---|---|---|
| 1 | 20 | n ≤ 10, m ≤ 20, ci ≤ 100 |
| 2 | 30 | n ≤ 100, m ≤ 1000, ci ≤ 100 |
| 3 | 50 | без дополнительных ограничений |
| № | Стандартный вход | Стандартный выход |
|---|---|---|
| 1 |
|
|
| 2 |
|
|
| Автор: | Pavel Mesenev | Ограничение времени: | 2 сек | |
| Входной файл: | Стандартный вход | Ограничение памяти: | 256 Мб | |
| Выходной файл: | Стандартный выход |
Дана клетчатая доска из n строк и m столбцов; некоторые клетки вырезаны. Доминошка занимает две свободные клетки, соседние по стороне. Доминошки не должны перекрываться.
Положите на доску как можно больше доминошек.

На рисунке — доска из первого примера: слева положена одна доминошка, и больше не помещается; справа — две.
В первой строке — два целых числа n и m. В каждой из следующих n строк —
m символов: . — свободная клетка, # — вырезанная.
В первой строке выведите k — наибольшее число доминошек. В каждой из следующих k строк — четыре числа r1, c1, r2, c2: строки и столбцы двух клеток очередной доминошки (нумерация с 1). Если оптимальных раскладок несколько, выведите любую.
1 ≤ n, m ≤ 100
| № | Стандартный вход | Стандартный выход |
|---|---|---|
| 1 |
|
|
| 2 |
|
|
| Автор: | 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 |
|
|
| 2 |
|
|
| Author: | Well-known | Time limit: | 1 sec | |
| Input file: | Standard input | Memory limit: | 64 Mb | |
| Output file: | Standard output |
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.
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
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.
| No. | Standard input | Standard output |
|---|---|---|
| 1 |
|
|
| 2 |
|
|
| Автор: | Егорова Ирина, Котляренко Анастасия, Сафонов Никита, Константинов Иван | Ограничение времени: | 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 ≤ n, m ≤ 10
| № | Стандартный вход | Стандартный выход |
|---|---|---|
| 1 |
|
|
| 2 |
|
|
| Author: | Course Instructor | Time limit: | 10 sec | |
| Input / output: | interactive | Memory limit: | 512 Mb |
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):
a l1 l2 ... 0 adds the clause (l1 ∨ l2 ∨ …). Variables are positive integers up to 5 ⋅ 106, literal − v is the negation of v; you choose the numbering.s a1 a2 ... 0 solves the formula of all clauses added so far under the temporary assumptions a1,a2,… (literals forced true for this query only; the list may be empty: s 0). Flush the output, then read the reply:
SAT; in MODEL mode it is followed by a line of V characters 0/1, where V is the largest variable used so far: the i-th character is the value of variable i;UNSAT; if the query had assumptions, it is followed by a line listing the assumptions used by the refutation, ending with 0;UNKNOWN: the query exceeded C conflicts.ans followed by the filled grid (n lines of n integers) ends the dialogue. Flush the output.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 ...
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.
The commands described above, ending with ans and the filled grid. Any valid filling that keeps the given cells is accepted.
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).
| Author: | Course Instructor | Time limit: | 10 sec | |
| Input / output: | interactive | Memory limit: | 512 Mb |
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
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.
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.
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.