Девочка Юля захотела написать песню, чтобы попасть в чарты и реки. Но, к сожалению, у неё нет музыкального таланта, зато есть идея.
Она взяла $$$n$$$ строк из песен своей любимой группы «ABACABA» и $$$n$$$ строк из репертуара Алёны Фин и хочет сделать из них свою песню. Для этого она будет чередовать строки разных исполнителей. Чтобы её не обвинили в плагиате, строки $$$1, 3, \ldots, 2n-1$$$ будут взяты из первого набора, а строки $$$2, 4, \ldots, 2n$$$ — из второго.
Назовём уровнем рифмы двух строк длину общего суффикса этих двух строк (то есть уровнем рифмы строк $$$a$$$ и $$$b$$$ называется максимальное число $$$r$$$ такое, что $$$r \le |a|, r \le |b|$$$ и для всех $$$0 \le i \le r - 1$$$ выполняется $$$a_{|a|-i} = b_{|b|-i}$$$). Музыкальностью песни называется сумма уровней рифмы пар строк $$$1$$$ и $$$2$$$, $$$3$$$ и $$$4$$$, $$$\ldots$$$, $$$2n-1$$$ и $$$2n$$$ (то есть каждая строка участвует ровно в одной паре).
Помогите Юле написать хит — песню с максимальной музыкальностью!
В первой строке находится одно число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длина наборов. В последующих $$$n$$$ строках содержатся элементы первого набора. В последующих $$$n$$$ строках содержатся элементы второго набора.
Все строки состоят из строчных латинских букв. Гарантируется, что сумма длин строк в каждом наборе не превосходит $$$2 \cdot 10^5$$$.
Выведите одно число — максимальную музыкальность песни, которую можно получить.
4 dca cba dcb bbb fea fea aba bbb
6
3 a bc bcaa aa aaa aaac
4
В первом примере можно разбить строки на пары так: «dcb» + «fea», «dca» + «fea», «cba» + «aba», «bbb» + «bbb» (общие суффиксы в каждой паре выделены жирным). Сумма длин общих суффиксов равна $$$0 + 1 + 2 + 3 = 6$$$.
$$$n$$$ джентльменов играют в очень интересную игру: На столе перед ними лежат $$$m$$$ карточек, на каждой по $$$n$$$ чисел. $$$j$$$-е число на $$$i$$$-й карточке равно $$$a_{i, j}$$$.
Джентльмены по очереди от $$$1$$$-го до $$$n$$$-го выбирают одну из оставшихся карточек и забирают её себе. После того как все закончили выбирать, $$$j$$$-й джентльмен получает столько очков, сколько написано на взятой им карточке на позиции $$$j$$$.
Джентльмен, набравший наибольшее количество очков, считается победителем и получает главный приз. Также каждый джентльмен, включая победителя, получает вторичный приз, равный количеству набранных им очков.
Таким образом каждый джентльмен в первую очередь желает получить главный приз, который гораздо ценнее любого вторичного приза, а во вторую очередь хочет максимизировать количество набранных очков.
Вам предстоит по данному набору карточек узнать, какой из джентльменов получит главный приз, если все джентльмены будут играть оптимально.
В первой строке даны два целых числа $$$n$$$, $$$m$$$ $$$(2 \le n \le m \le 2\,000)$$$ — количество играющих джентльменов и число карточек соответственно.
В следующих $$$m$$$ строках даны описания карточек. В каждой из них находятся $$$n$$$ целых чисел $$$a_{i, j}$$$ $$$(1 \le a_{i, j} \le n \cdot m)$$$ — числа на $$$i$$$-й карточке.
Гарантируется, что все числа $$$a_{i, j}$$$ попарно различны.
В единственной строке выведите ответ на задачу — номер джентльмена, который заберет себе главный приз, если все джентльмены будут играть оптимально.
2 3 4 1 3 6 5 2
1
3 3 3 9 8 2 4 7 1 6 5
3
3 4 2 7 1 9 12 5 4 3 8 11 6 10
2
В первом примере $$$1$$$-й джентльмен может взять $$$2$$$-ю карточку, тем самым получив $$$3$$$ очка. В таком случае на своем ходу $$$2$$$-й джентльмен сможет взять только $$$1$$$-ю или $$$3$$$-ю карточку, то есть получить $$$1$$$ или $$$2$$$ очка.
Во втором примере первый игрок точно не выиграет, так что берет себе первую карточку, чтобы максимизировать количество набранных очков для вторичного приза. Тогда что бы ни взял $$$2$$$-й игрок, $$$3$$$-й получит больше очков и победит.
Given an array $$$a$$$ of length $$$n$$$ consisting of integers. Then the following operation is sequentially applied to it $$$q$$$ times:
Let $$$b_j$$$ be the array $$$a$$$ obtained after applying the first $$$j$$$ operations ($$$0 \le j \le q$$$). Note that $$$b_0$$$ is the array $$$a$$$ before applying any operations.
You need to find the lexicographically minimum$$$^{\dagger}$$$ array among all arrays $$$b_j$$$.
$$$^{\dagger}$$$An array $$$x$$$ is lexicographically smaller than array $$$y$$$ if there is an index $$$i$$$ such that $$$x_i \lt y_i$$$, and $$$x_j = y_j$$$ for all $$$j \lt i$$$. In other words, for the first index $$$i$$$ where the arrays differ, $$$x_i \lt y_i$$$.
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^5$$$) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the length of array $$$a$$$.
The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of array $$$a$$$.
The third line of each test case contains a single integer $$$q$$$ ($$$0 \le q \le 5 \cdot 10^5$$$) — the number of operations on the array.
In each of the next $$$q$$$ lines, there are three integers $$$l_j$$$, $$$r_j$$$, and $$$x_j$$$ $$$(1 \le l_j \le r_j \le n, -10^9 \le x_j \le 10^9)$$$ — the description of each operation. The operations are given in the order they are applied.
It is guaranteed that the sum of $$$n$$$ over all test cases and the sum of $$$q$$$ over all test cases do not exceed $$$5 \cdot 10^5$$$.
For each test case, output the lexicographically minimum array among all arrays $$$b_j$$$.
241 2 3 421 4 01 3 -10052 1 2 5 432 4 32 5 -21 3 1
-99 -98 -97 4 2 1 2 5 4
In the first test case:
Thus, the lexicographically minimum array is $$$b_2$$$.
In the second test case, the lexicographically minimum array is $$$b_0$$$.
You had a sequence $$$a_1, a_2, \ldots, a_n$$$ consisting of integers from $$$1$$$ to $$$n$$$, not necessarily distinct. For some unknown reason, you decided to calculate the following characteristic of the sequence:
Each test consist of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the lost sequence $$$a$$$.
The second line of each test case contains $$$n$$$ integers $$$r_1, r_2, \ldots, r_n$$$ ($$$i \le r_i \le n+1$$$) — the characteristic of the lost sequence $$$a$$$.
It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
For each test case, output the following:
532 3 452 3 5 4 61131 3 483 6 6 6 8 9 9 9
Yes 1 2 1 No Yes 1 No Yes 1 3 5 3 5 1 1 3
In the first test case, the sequence $$$a = [1, 2, 1]$$$ is suitable. The integers $$$1$$$ and $$$2$$$ appear on the subsegments $$$[1, 2]$$$ and $$$[2, 3]$$$.
In the second test case, it can be proved that there is no suitable sequence $$$a$$$.
Berland is a country with ancient history, where roads were built and destroyed for centuries. It is known that there always were $$$n$$$ cities in Berland. You also have records of $$$t$$$ key moments in the history of the country, numbered from $$$1$$$ to $$$t$$$. Each record contains a list of bidirectional roads between some pairs of cities, which could be used for travel in Berland at a specific moment in time.
You have discovered a time machine that transports you between key moments. Unfortunately, you cannot choose what point in time to end up at, but you know the order consisting of $$$k$$$ moments in time $$$a_{i}$$$, in which the machine will transport you. Since there is little time between the travels, when you find yourself in the next key moment in time (including after the last time travel), you can travel on at most one existing road at that moment, coming out from the city you were in before time travel.
Currently, you are in city $$$1$$$, and the time machine has already transported you to moment $$$a_{1}$$$. You want to reach city $$$n$$$ as quickly as possible. Determine the minimum number of time travels, including the first one, that you need to make in order to reach city $$$n$$$.
The first line contains two integers $$$n$$$ and $$$t$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le t \le 2 \cdot 10^5$$$) — the number of cities in Berland and the number of records about key moments in history. Then follows the description of each of the $$$t$$$ records.
The first line of each record description contains a single integer $$$m_{i}$$$ ($$$0 \le m_{i} \le \min \left(\frac{n(n-1)}{2}, 2 \cdot 10^5\right)$$$) — the number of roads in the $$$i$$$-th record.
Each of the next $$$m_i$$$ lines contains two integers $$$v_{j}$$$ and $$$u_{j}$$$ ($$$1 \le v_{j}, u_{j} \le n$$$, $$$v_{j} \neq u_{j}$$$) — the numbers of cities connected by the $$$j$$$-th road in the $$$i$$$-th key moment in history.
The next line contains a single integer $$$k$$$ ($$$1 \le k \le 2 \cdot 10^5$$$) — the number of time moments between which movements will occur.
The next line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_{i} \le t$$$) — the time moments at which you will be after each movement.
It is guaranteed that the sum of $$$m_{i}$$$ does not exceed $$$2 \cdot 10^5$$$. It is guaranteed that each unordered pair $$$(u, v)$$$ occurs in the road description for one record no more than once.
Output a single integer — the minimum number of time travels required to reach city $$$n$$$ from city $$$1$$$, or $$$-1$$$ if it is impossible.
Note that movement to time moment $$$a_{1}$$$ is also considered a movement.
5 241 22 33 44 522 33 562 1 2 1 2 1
5
5 231 23 14 322 14 551 2 1 1 1
-1
In the first example, you are in city $$$1$$$ and move to moment $$$a_{1} = 2$$$. Since there are no suitable roads to pass, you do nothing and move to moment $$$a_{2} = 1$$$, after which you travel along the road $$$(1, 2)$$$. Moving to moment $$$a_{3} = 2$$$, you travel along the road $$$(2, 3)$$$. Moving to moment $$$a_{4} = 1$$$, you stay in city $$$3$$$ and make the next time travel. At time moment $$$a_{5} = 2$$$, you travel along the road $$$(3, 5)$$$ and end up in the final city after $$$5$$$ time travels.
In the second example, it can be shown that it is impossible to reach city $$$5$$$ with the given time travels.
Let's call an array $$$b_1, b_2, \ldots, b_m$$$ ($$$m \ge 2$$$) good if it can be split into two parts such that all elements in the left part are strictly smaller than all elements in the right part. In other words, there must exist an index $$$1 \le i \lt m$$$ such that every element from $$$b_1, \ldots, b_i$$$ is strictly smaller than every element from $$$b_{i+1}, \ldots, b_m$$$.
Given an array $$$a_1, a_2, \ldots a_n$$$ consisting of distinct integers from $$$1$$$ to $$$n$$$. There are $$$q$$$ queries. Each query consists of two numbers $$$l$$$ and $$$r$$$. For each query, determine whether the array $$$a_l, a_{l+1}, \ldots, a_r$$$ is good.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array.
The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_n \le n$$$) — the elements of the array $$$a$$$.
The third line contains a single integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries.
Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \lt r_i \le n$$$) — the description of the $$$i$$$-th query.
For each query, output "Yes" (without quotes) if the array $$$a_l, a_{l+1}, \ldots, a_r$$$ is good, and "No" (without quotes) otherwise.
You can output "Yes" and "No" in any case (for example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as a positive answer).
5 3 2 1 4 5 5 1 5 1 3 1 4 1 2 2 5
Yes No Yes No Yes
6 1 6 2 4 3 5 3 3 5 2 6 4 6
Yes No Yes
In the first example:
In the second example:
Alice suggested Bob to play a game. Bob didn't like this idea, but he couldn't refuse Alice, so he asked you to write a program that would play instead of him.
The game starts with Alice taking out a grid sheet of size $$$n \times n$$$, the cells of which are initially not colored. After that she colors some $$$2n$$$ cells with colors $$$1,2,\ldots, 2n$$$, respectively, and informs Bob about these cells.
In one move, Bob can point to a cell that has not been colored yet and ask Alice to color that cell. Alice colors that cell with one of the $$$2n$$$ colors of her choice, informing Bob of the chosen color. Bob can make no more than $$$10$$$ moves, after which he needs to find a good set of four cells.
A set of four cells is considered good if the following conditions are met:
Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 1000$$$) — the size of the grid.
The $$$i$$$-th of the following $$$2n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — the coordinates of the cell colored with the $$$i$$$-th color.
It is guaranteed that all coordinates $$$(x_i, y_i)$$$ are pairwise distinct for the same test case.
After reading the input data for each test case, continue the interaction as described below.
You can make no more than $$$10$$$ moves. To make a move, output "? $$$x$$$ $$$y$$$" ($$$1 \leq x,y \leq n$$$). In response to this, the jury's program will output a single integer from $$$1$$$ to $$$2n$$$ — the color of cell $$$(x,y)$$$.
After all moves (it is not necessary to make all $$$10$$$ moves and it is not necessary to make at least one move), output a string in the format "! $$$x_1$$$ $$$x_2$$$ $$$y_1$$$ $$$y_2$$$" ($$$1 \leq x_1, x_2, y_1, y_2 \leq n, x_1 \ne x_2, y_1 \ne y_2$$$). If cells $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ are colored with different colors, the jury's program will output "OK". After that, proceed to the next test case or terminate the program if there are no more test cases left.
Otherwise, if any of the specified cells are colored with the same color or one of the cells is not colored yet, the jury's program will output "ERROR". In this case, your program should immediately terminate its execution to receive the Wrong Answer verdict. Otherwise, you may receive an arbitrary verdict.
After each move or answer, do not forget to output the end of line and flush the output. Otherwise, you will get the Idleness limit exceeded verdict.
To do this, use:
Note that the interactor is adaptive, meaning that the color Alice will use to color the cells during Bob's moves is not fixed in advance.
Hacks
You cannot use hacks in this problem.
2 3 1 2 1 3 2 1 2 3 3 1 3 2 1 OK 3 1 1 1 2 1 3 2 1 2 2 2 3 OK
? 1 1 ! 1 2 1 3 ! 1 2 1 2
In the first test case:
In the second test case, cells with coordinates $$$(1, 1), (1, 2), (2, 1), (2, 2)$$$ are initially colored by Alice in different colors.
Ваша команда принимает участие в очередной олимпиаде. Всего в контесте $$$n$$$ задач, $$$i$$$-я из них имеет сложность $$$a_i$$$. Умственных возможностей вашей команды хватит на то, чтобы решить набор задач, с суммарной сложностью не более $$$S$$$.
В конце контеста, после того, как вы уже решили сколько-то задач, вам может прийти озарение, и вы без затраты умственных усилий сможете решить еще одну любую задачу, если среди решенных вами задач, хотя бы половина не проще этой. После этого продолжить решать задачи вы не сможете. Обратите внимание, что даже если вы решили 0 задач, то в конце контеста можете без затраты умственных усилий решить любую задачу.
Сколько максимум задач вы можете решить за контест?
В первой строке вам даны два числа $$$n, S$$$ ($$$1 \leqslant n \leqslant 300000, 1 \leqslant S \leqslant 10^9$$$) — количество задач в контесте, а также умственные возможности вашей команды.
Во второй строке записаны $$$n$$$ чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leqslant a_i \leqslant 10^9$$$) — сложности задач.
Выведите единственное число — максимальное число задач, которое может решить ваша команда.
6 124 2 1 3 6 5
5
7 115 4 3 2 1 100 1000000000
4
3 100100 101 101
1
2 35 105
1
В первом примере с помощью умственных усилий можно решить задачи сложностью 4, 2, 1 и 5, а в конце контеста с помощью озарения решить задачу сложностью 3.
Как вы все знаете, МКОШП — это Московская Командная Олимпиада Школьников по Пошаговым стратегиям. На новом этапе олимпиады произошло что-то странное: приглашена только одна команда, и ей предложен только один шаг.
Команда состоит из $$$n$$$ школьников, им предстоит сражаться с $$$m$$$ монстрами. Каждый школьник характеризуется тремя параметрами — $$$i$$$-й школьник имеет $$$h_i$$$ здоровья, $$$a_i$$$ атаки и $$$b_i$$$ защиты. Каждый монстр также характеризуется тремя числами — $$$j$$$-й монстр имеет $$$w_j$$$ здоровья, целью его атаки будет $$$t_j$$$-й школьник, и монстр нанесет ему $$$d_j$$$ урона. Игра состоит всего из двух ходов: сначала ходят школьники, а потом монстры атакуют свои цели. Во время своего хода каждый школьник может сделать одно из двух действий:
Если после хода школьников здоровье монстра станет меньше или равно 0, то он не сможет атаковать школьника, на которого нацелился. После хода школьников все монстры с положительным здоровьем атакуют школьников. После хода монстров игра заканчивается. Если здоровье школьника стало меньше или равно 0, то школьник как игрок выбывает из соревнования. Ваша задача сказать, какое максимальное количество школьников смогут остаться в игре.
В первой строке даны два числа $$$n$$$ и $$$m$$$ ($$$1 \leqslant n \leqslant 12$$$, $$$1 \leqslant m \leqslant 100$$$) — количество школьников и количество монстров соответственно.
Следующие $$$n$$$ строк содержат по три числа: $$$h_i, a_i, b_i$$$ ($$$1 \leqslant h_i, a_i, b_i \leqslant 10^9$$$) — характеристики здоровья, атаки и защиты $$$i$$$-го школьника соответственно.
Следующие $$$m$$$ строк содержат по три числа: $$$w_j, t_j, d_j$$$ ($$$1 \leqslant w_j, d_j \leqslant 10^9, 1 \leqslant t_j \leqslant n$$$) — здоровье, цель и силу атаки $$$j$$$-го монстра соответственно.
Выведите одно число — максимальное количество школьников, которые могут остаться в игре.
2 31 2 33 1 23 1 13 1 21 1 9
2
3 41 2 31 2 31 2 31 1 11 1 31 2 15 2 5
2
Боб — туристический агент. Его задача — продавать туристам путёвки на Острова Кука. Вдохновившись успехом Биба — туристического агента с Бермудских Островов, Боб решил распространить информацию о мистических треугольниках Кука!
Острова Кука состоят из $$$3n$$$ небольших островов. Острова настолько маленькие, что каждый остров может быть представлен на карте одной точкой $$$(x, y)$$$ с целыми положительными координатами.
Боб хочет разбить все $$$3n$$$ островов на $$$n$$$ групп по $$$3$$$ острова так, чтобы координаты трёх островов в каждой из групп образовывали невырожденный треугольник. Напомним, что треугольник называется невырожденным, если все его углы строго больше нуля и меньше $$$180^{\circ}$$$.
Помогите Бобу найти любое подходящее разбиение островов на треугольники, чтобы продать все путёвки на Острова Кука! Если подходящего разбиения не существует, вы также должны сообщить об этом.
Каждый тест состоит из нескольких наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество наборов входных данных. Далее следует описание наборов входных данных.
Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество треугольников, которые нужно сформировать из $$$3n$$$ островов.
В каждой из следующих $$$3n$$$ строк находятся два целых числа $$$x, y$$$ ($$$1 \le x, y, \le 10^9$$$) — координаты очередного острова. Гарантируется, что координаты всех островов попарно различны, другими словами, никакие два острова не находятся в одной и той же точке.
Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.
Для каждого набора входных данных, если ответа не существует, в единственной строке выведите «No». Иначе, выведите «Yes», а затем, в последующих $$$n$$$ строках, индексы островов образующих очередной треугольник. Острова нумеруются с $$$1$$$ в том же порядке, как и во входных данных. Если ответов несколько, вы можете вывести любой из них.
Вы можете выводить «Yes» и «No» в любом регистре.
421 12 23 34 44 52 419 33 16 237 88 109 1210 1410 1016 1419 161 1228 185100000000 1000000000200000000 1000000000300000000 1000000000400000000 1000000000500000000 1000000000600000000 1000000000700000000 1000000000800000000 1000000000900000000 10000000001000000000 10000000001 12 23 34 45 5
Yes 5 2 4 6 3 1 No Yes 1 2 8 3 4 5 6 7 9 Yes 1 2 15 3 4 14 5 6 13 7 8 12 9 10 11