problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
C. Table Compressiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.Petya decided to compress tables. He is given a table a consisting of n rows and m columns that is filled with positive integers. He wants to build the table a' consisting of positive integers such that the relative order of the elements in each row and each column remains the same. That is, if in some row i of the initial table ai, j < ai, k, then in the resulting table a'i, j < a'i, k, and if ai, j = ai, k then a'i, j = a'i, k. Similarly, if in some column j of the initial table ai, j < ap, j then in compressed table a'i, j < a'p, j and if ai, j = ap, j then a'i, j = a'p, j. Because large values require more space to store them, the maximum value in a' should be as small as possible.Petya is good in theory, however, he needs your help to implement the algorithm.InputThe first line of the input contains two integers n and m (, the number of rows and the number of columns of the table respectively.Each of the following n rows contain m integers ai, j (1 ≤ ai, j ≤ 109) that are the values in the table.OutputOutput the compressed table in form of n lines each containing m integers.If there exist several answers such that the maximum number in the compressed table is minimum possible, you are allowed to output any of them.ExamplesInput2 21 23 4Output1 22 3Input4 320 10 3050 40 3050 60 7090 80 70Output2 1 35 4 35 6 79 8 7NoteIn the first sample test, despite the fact a1, 2 ≠ a21, they are not located in the same row or column so they may become equal after the compression. | Input2 21 23 4 | Output1 22 3 | 4 seconds | 256 megabytes | ['dfs and similar', 'dp', 'dsu', 'graphs', 'greedy', '*2200'] |
B. Image Previewtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.For each photo it is known which orientation is intended for it — horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.Help Vasya find the maximum number of photos he is able to watch during T seconds.InputThe first line of the input contains 4 integers n, a, b, T (1 ≤ n ≤ 5·105, 1 ≤ a, b ≤ 1000, 1 ≤ T ≤ 109) — the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.Second line of the input contains a string of length n containing symbols 'w' and 'h'. If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.OutputOutput the only integer, the maximum number of photos Vasya is able to watch during those T seconds.ExamplesInput4 2 3 10wwhwOutput2Input5 2 4 13hhwhhOutput4Input5 2 4 1000hhwhhOutput5Input3 1 100 10whwOutput0NoteIn the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | Input4 2 3 10wwhw | Output2 | 1 second | 256 megabytes | ['binary search', 'brute force', 'dp', 'two pointers', '*1900'] |
A. Watchmentime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWatchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.InputThe first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).Some positions may coincide.OutputPrint the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.ExamplesInput31 17 51 5Output2Input60 00 10 2-1 10 11 1Output11NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | Input31 17 51 5 | Output2 | 3 seconds | 256 megabytes | ['data structures', 'geometry', 'math', '*1400'] |
E. Автобусограничение по времени на тест8 секундограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводВдоль дороги стоят n путешественников. Дорога представляет собой прямую, размерами путешественников можно пренебречь, считая их точками.Водитель автобуса Василий, благодаря мобильному приложению, знает для каждого путешественника точку xi, в которой тот стоит. Кроме того, он знает расстояние di, которое i-й путешественник хочет проехать на автобусе. Таким образом, i-й путешественник планирует выйти из автобуса в точке xi + di. Теперь Василий хочет решить, кого из путешественников он подвезёт, а кого оставит пылиться у дороги.Василий решил, что сегодня он должен хорошо заработать, поэтому решил перевезти в точности a путешественников. В автопарке есть автобусы любых видов. Чем больше мест в автобусе, тем дороже стоит его аренда.Помогите Василию определить минимальное количество пассажирских мест в автобусе, которых будет достаточно для перевозки ровно a путешественников. Ни в какой момент времени в автобусе не может быть путешественников больше, чем количество пассажирских мест в автобусе. Василий сам может решить какое конкретно подмножество из a путешественников он перевезёт на автобусе.Считайте, что автобус всегда едет слева направо (от меньших координат к большим) и начинает свой путь левее самого левостоящего путешественника. Если в одной точке какой-то путешественник должен выйти из автобуса, а другой войти, считайте, что сначала произойдет выход одного путешественника из автобуса, а затем другой путешественник сможет зайти в автобус.Входные данныеВ первой строке входных данных следует два целых положительных числа n и a (1 ≤ a ≤ n ≤ 200 000) — количество путешественников, стоящих вдоль дороги, и минимальное количество путешественников, которых Василий хочет подвезти.В каждой из следующих n строк содержится по два целых числа xi и di (1 ≤ xi, di ≤ 109) — координата, в которой находится i-й путешественник, а также расстояние, на которое он хочет переместиться на автобусе. Координаты путешественников заданы в произвольном порядке. В одной точке могут находиться несколько путешественников.Выходные данныеСначала выведите одно целое число — минимальное количество пассажирских мест в автобусе, которых будет достаточно для перевозки хотя бы a путешественников. Затем выведите a целых чисел — номера путешественников, которых подвезёт Василий. Путешественники нумеруются, начиная с единицы, в том порядке, в котором заданы во входных данных. Номера можно выводить в произвольном порядке. Если ответов несколько, разрешается вывести любой из них.ПримерыВходные данные3 28 93 51 3Выходные данные11 3 Входные данные5 420 4010 1015 55 1520 30Выходные данные24 2 5 1ПримечаниеВ первом тестовом примере достаточно одноместного автобуса. К примеру, Василий может подвезти третьего и первого путешественников, либо второго и первого путешественников. | Входные данные3 28 93 51 3 | Выходные данные11 3 | ограничение по времени на тест8 секунд | ограничение по памяти на тест256 мегабайт | ['binary search', 'data structures', 'greedy', 'sortings', '*2100'] |
D. Дефрагментация памятиограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводПамять компьютера состоит из n ячеек, которые выстроены в ряд. Пронумеруем ячейки от 1 до n слева направо. Про каждую ячейку известно, свободна она или принадлежит какому-либо процессу (в таком случае известен процесс, которому она принадлежит).Для каждого процесса известно, что принадлежащие ему ячейки занимают в памяти непрерывный участок. С помощью операций вида «переписать данные из занятой ячейки в свободную, а занятую теперь считать свободной» требуется расположить все принадлежащие процессам ячейки в начале памяти компьютера. Другими словами, любая свободная ячейка должна располагаться правее (иметь больший номер) любой занятой.Вам необходимо найти минимальное количество операций переписывания данных из одной ячейки в другую, с помощью которых можно достичь описанных условий. Допустимо, что относительный порядок ячеек в памяти для каждого из процессов изменится после дефрагментации, но относительный порядок самих процессов должен остаться без изменений. Это значит, что если все ячейки, принадлежащие процессу i, находились в памяти раньше всех ячеек процесса j, то и после перемещений это условие должно выполняться.Считайте, что номера всех процессов уникальны, хотя бы одна ячейка памяти занята каким-либо процессом.Входные данныеВ первой строке входных данных записано число n (1 ≤ n ≤ 200 000) — количество ячеек в памяти компьютера.Во второй строке входных данных следуют n целых чисел a1, a2, ..., an (1 ≤ ai ≤ n), где ai равно либо 0 (это означает, что i-я ячейка памяти свободна), либо номеру процесса, которому принадлежит i-я ячейка памяти. Гарантируется, что хотя бы одно значение ai не равно 0.Процессы пронумерованы целыми числами от 1 до n в произвольном порядке. При этом процессы не обязательно пронумерованы последовательными числами.Выходные данныеВыведите одно целое число — минимальное количество операций, которое нужно сделать для дефрагментации памяти.ПримерыВходные данные40 2 2 1Выходные данные2Входные данные80 8 8 8 0 4 4 2Выходные данные4ПримечаниеВ первом тестовом примере достаточно двух операций: Переписать данные из третьей ячейки в первую. После этого память компьютера примет вид: 2 2 0 1. Переписать данные из четвертой ячейки в третью. После этого память компьютера примет вид: 2 2 1 0. | Входные данные40 2 2 1 | Выходные данные2 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', 'greedy', 'implementation', '*1600'] |
C. Печать условийограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводНа тренировку по подготовке к соревнованиям по программированию пришли n команд. Тренер для каждой команды подобрал тренировку, комплект задач для i-й команды занимает ai страниц. В распоряжении тренера есть x листов бумаги, у которых обе стороны чистые, и y листов, у которых только одна сторона чистая. При печати условия на листе первого типа можно напечатать две страницы из условий задач, а при печати на листе второго типа — только одну. Конечно, на листе нельзя печатать условия из двух разных комплектов задач. Обратите внимание, что при использовании листов, у которых обе стороны чистые, не обязательно печатать условие на обеих сторонах, одна из них может остаться чистой.Вам предстоит определить максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.Входные данныеВ первой строке входных данных следуют три целых числа n, x и y (1 ≤ n ≤ 200 000, 0 ≤ x, y ≤ 109) — количество команд, количество листов бумаги с двумя чистыми сторонами и количество листов бумаги с одной чистой стороной.Во второй строке входных данных следует последовательность из n целых чисел a1, a2, ..., an (1 ≤ ai ≤ 10 000), где i-е число равно количеству страниц в комплекте задач для i-й команды.Выходные данныеВыведите единственное целое число — максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.ПримерыВходные данные2 3 54 6Выходные данные2Входные данные2 3 54 7Выходные данные2Входные данные6 3 512 11 12 11 12 11Выходные данные1ПримечаниеВ первом тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать весь первый комплект задач на листах с одной чистой стороной (после этого останется 3 листа с двумя чистыми сторонами и 1 лист с одной чистой стороной), а второй комплект напечатать на трех листах с двумя чистыми сторонами.Во втором тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать первый комплект задач на двух листах с двумя чистыми сторонами (после этого останется 1 лист с двумя чистыми сторонами и 5 листов с одной чистой стороной), а второй комплект напечатать на одном листе с двумя чистыми сторонами и на пяти листах с одной чистой стороной. Таким образом, тренер использует все листы для печати.В третьем тестовом примере можно напечатать только один комплект задач (любой из трёх 11-страничных). Для печати 11-страничного комплекта задач будет израсходована вся бумага. | Входные данные2 3 54 6 | Выходные данные2 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', 'greedy', 'sortings', '*1500'] |
B. Этажиограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводЕсть n-подъездный дом, в каждом подъезде по m этажей, и на каждом этаже каждого подъезда ровно k квартир. Таким образом, в доме всего n·m·k квартир. Они пронумерованы естественным образом от 1 до n·m·k, то есть первая квартира на первом этаже в первом подъезде имеет номер 1, первая квартира на втором этаже первого подъезда имеет номер k + 1 и так далее. Особенность этого дома состоит в том, что он круглый. То есть если обходить его по часовой стрелке, то после подъезда номер 1 следует подъезд номер 2, затем подъезд номер 3 и так далее до подъезда номер n. После подъезда номер n снова идёт подъезд номер 1.Эдвард живёт в квартире номер a, а Наташа — в квартире номер b. Переход на 1 этаж вверх или вниз по лестнице занимает 5 секунд, переход от двери подъезда к двери соседнего подъезда — 15 секунд, а переход в пределах одного этажа одного подъезда происходит мгновенно. Также в каждом подъезде дома есть лифт. Он устроен следующим образом: он всегда приезжает ровно через 10 секунд после вызова, а чтобы переместить пассажира на один этаж вверх или вниз, лифт тратит ровно 1 секунду. Посадка и высадка происходят мгновенно.Помогите Эдварду найти минимальное время, за которое он сможет добраться до квартиры Наташи. Считайте, что Эдвард может выйти из подъезда только с первого этажа соответствующего подъезда (это происходит мгновенно). Если Эдвард стоит перед дверью какого-то подъезда, он может зайти в него и сразу окажется на первом этаже этого подъезда (это также происходит мгновенно). Эдвард может выбирать, в каком направлении идти вокруг дома.Входные данныеВ первой строке входных данных следуют три числа n, m, k (1 ≤ n, m, k ≤ 1000) — количество подъездов в доме, количество этажей в каждом подъезде и количество квартир на каждом этаже каждого подъезда соответственно.Во второй строке входных данных записаны два числа a и b (1 ≤ a, b ≤ n·m·k) — номера квартир, в которых живут Эдвард и Наташа, соответственно. Гарантируется, что эти номера различны. Выходные данныеВыведите единственное целое число — минимальное время (в секундах), за которое Эдвард сможет добраться от своей квартиры до квартиры Наташи.ПримерыВходные данные4 10 5200 6Выходные данные39Входные данные3 1 57 2Выходные данные15ПримечаниеВ первом тестовом примере Эдвард находится в 4 подъезде на 10 этаже, а Наташа находится в 1 подъезде на 2 этаже. Поэтому Эдварду выгодно сначала спуститься на лифте на первый этаж (на это он потратит 19 секунд, из которых 10 — на ожидание и 9 — на поездку на лифте), затем обойти дом против часовой стрелки до подъезда номер 1 (на это он потратит 15 секунд), и наконец подняться по лестнице на этаж номер 2 (на это он потратит 5 секунд). Таким образом, ответ равен 19 + 15 + 5 = 39.Во втором тестовом примере Эдвард живёт в подъезде 2 на этаже 1, а Наташа находится в подъезде 1 на этаже 1. Поэтому Эдварду выгодно просто обойти дом по часовой стрелке до подъезда 1, на это он потратит 15 секунд. | Входные данные4 10 5200 6 | Выходные данные39 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', '*1400'] |
A. Любимые числа Поликарпаограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводПоликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2. По заданной последовательности целых положительных чисел a1, a2, ..., an требуется найти r — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел ai, которые делятся на r.Входные данныеВ первой строке записано целое число n (1 ≤ n ≤ 100) — длина последовательности a.Во второй строке записана последовательность целых чисел a1, a2, ..., an (1 ≤ ai ≤ 109).Выходные данныеВыведите два числа: r — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности, количество элементов последовательности, которые делятся на r. ПримерыВходные данные580 7 16 4 48Выходные данные16 3Входные данные421 5 3 33Выходные данные1 4ПримечаниеВ первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 24, на неё делятся числа 80, 16 и 48.Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 20. Это и будет максимальной степенью двойки для данного примера. | Входные данные580 7 16 4 48 | Выходные данные16 3 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', 'implementation', '*1000'] |
E. Собери числоограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводДано целое неотрицательное число k и n неотрицательных целых чисел a1, a2, ..., an. Записывая некоторые из этих чисел друг за другом в произвольном порядке и, возможно, используя какие-то из них несколько раз (а какие-то вообще не используя), требуется составить кратчайшее (наименьшее по количеству цифр) число, делящееся на k, или определить, что это невозможно.Входные данныеВ первой строке содержится два целых числа n (1 ≤ n ≤ 1 000 000) и k (1 ≤ k ≤ 1000) — количество чисел и требуемый делитель соответственно.Во второй строке содержится n целых чисел a1, a2, ..., an (0 ≤ ai ≤ 109).Выходные данныеЕсли ответ существует, в первой строке выведите «YES» (без кавычек), а во второй строке — искомое кратчайшее число без ведущих нулей. В случае если ответа не существует, в единственной строке выходных данных выведите «NO» (без кавычек).ПримерыВходные данные2 3123 1Выходные данныеYES123Входные данные1 101Выходные данныеNOВходные данные3 41 2 3Выходные данныеYES12Входные данные3 77712 23 345Выходные данныеYES121212 | Входные данные2 3123 1 | Выходные данныеYES123 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['graphs', 'shortest paths', '*2300'] |
D. Собачки и мискиограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводНа координатной прямой сидит n собачек, i-я собачка находится в точке xi. Кроме того, на прямой есть m мисок с едой, для каждой известна её координата на прямой uj и время tj, через которое еда в миске остынет и станет невкусной. Это значит, что если собачка прибежит к миске в момент времени, строго больший tj, то еда уже остынет, и собачка кушать её не станет.Считая, что каждая собачка бежит со скоростью 1, найдите максимальное количество собачек, которые смогут покушать. Считайте, что собачки побегут к тем мискам, на которые вы им укажете. Из одной миски не могут кушать две или более собачки.Собачки могут обгонять друг друга, то есть, если одна из них остановится покушать, другая может пройти мимо неё, чтобы попасть к другой миске.Входные данныеВ первой строке находится пара целых чисел n и m (1 ≤ n, m ≤ 200 000) — количество собачек и мисок соответственно.Во второй строке находятся n целых чисел xi ( - 109 ≤ xi ≤ 109) — координата i-й собачки.В следующих m строках находятся пары целых чисел uj и tj ( - 109 ≤ uj ≤ 109, 1 ≤ tj ≤ 109) — координата j-й миски и время, когда остынет еда в ней, соответственно.Гарантируется, что никакие две собачки не находятся в одной точке. Никакие две миски также не могут находиться в одной точке.Выходные данныеВыведите одно целое число a — максимальное количество собачек, которые смогут покушать.ПримерыВходные данные5 4-2 0 4 8 13-1 14 36 311 2Выходные данные4Входные данные3 3-1 3 71 14 17 1Выходные данные2Входные данные4 420 1 10 301 12 522 240 10Выходные данные3ПримечаниеВ первом примере первая собачка побежит направо к первой миске, третья собачка сразу начнёт есть из второй миски, четвёртая собачка побежит влево к третьей миске, а пятая собачка побежит влево к четвёртой миске. | Входные данные5 4-2 0 4 8 13-1 14 36 311 2 | Выходные данные4 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['data structures', 'greedy', 'sortings', '*1900'] |
C. Путь Роботаограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводВам задано прямоугольное клетчатое поле, состоящее из n строк и m столбцов. Поле содержит цикл из символов «*», такой что: цикл можно обойти, посетив каждую его клетку ровно один раз, перемещаясь каждый раз вверх/вниз/вправо/влево на одну клетку; цикл не содержит самопересечений и самокасаний, то есть две клетки цикла соседствуют по стороне тогда и только тогда, когда они соседние при перемещении вдоль цикла (самокасание по углу тоже запрещено). Ниже изображены несколько примеров допустимых циклов: Все клетки поля, отличные от цикла, содержат символ «.». Цикл на поле ровно один. Посещать клетки, отличные от цикла, Роботу нельзя.В одной из клеток цикла находится Робот. Эта клетка помечена символом «S». Найдите последовательность команд для Робота, чтобы обойти цикл. Каждая из четырёх возможных команд кодируется буквой и обозначает перемещение Робота на одну клетку: «U» — сдвинуться на клетку вверх, «R» — сдвинуться на клетку вправо, «D» — сдвинуться на клетку вниз, «L» — сдвинуться на клетку влево. Робот должен обойти цикл, побывав в каждой его клетке ровно один раз (кроме стартовой точки — в ней он начинает и заканчивает свой путь).Найдите искомую последовательность команд, допускается любое направление обхода цикла.Входные данныеВ первой строке входных данных записаны два целых числа n и m (3 ≤ n, m ≤ 100) — количество строк и столбцов прямоугольного клетчатого поля соответственно.В следующих n строках записаны по m символов, каждый из которых — «.», «*» или «S». Гарантируется, что отличные от «.» символы образуют цикл без самопересечений и самокасаний. Также гарантируется, что на поле ровно одна клетка содержит «S» и что она принадлежит циклу. Робот не может посещать клетки, помеченные символом «.».Выходные данныеВ первую строку выходных данных выведите искомую последовательность команд для Робота. Направление обхода цикла Роботом может быть любым.ПримерыВходные данные3 3****.**S*Выходные данныеLUURRDDLВходные данные6 7.***....*.*....*.S**..*...**.*....*.******Выходные данныеUULLDDDDDRRRRRUULULLПримечаниеВ первом тестовом примере для обхода по часовой стрелке последовательность посещенных роботом клеток выглядит следующим образом: клетка (3, 2); клетка (3, 1); клетка (2, 1); клетка (1, 1); клетка (1, 2); клетка (1, 3); клетка (2, 3); клетка (3, 3); клетка (3, 2). | Входные данные3 3****.**S* | Выходные данныеLUURRDDL | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', 'dfs and similar', 'graphs', '*1100'] |
B. Собери столограничение по времени на тест2 секундыограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводВася купил стол, у которого n ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке.Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.Входные данныеВ первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей.Во второй строке следует последовательность из 2n целых положительных чисел a1, a2, ..., a2n (1 ≤ ai ≤ 100 000) — длины частей ножек стола в произвольном порядке.Выходные данныеВыведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.ПримерыВходные данные31 3 2 4 5 3Выходные данные1 52 43 3Входные данные31 1 1 2 2 2Выходные данные1 22 11 2 | Входные данные31 3 2 4 5 3 | Выходные данные1 52 43 3 | ограничение по времени на тест2 секунды | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', 'sortings', '*800'] |
A. Наибольший подъемограничение по времени на тест1 секундаограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводПрофиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*». ....................*..*.......*.**.......*.**..*...**.*********** Пример изображения горного хребта. Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправо — в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце.Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины: наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма), наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска). Входные данныеВ первой строке входных данных записаны два целых числа n и m (1 ≤ n, m ≤ 100) — количество строк и столбцов в схематичном изображении соответственно.Далее следуют n строк по m символов в каждой — схематичное изображение горного хребта. Каждый символ схематичного изображения — это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».Выходные данныеВыведите через пробел два целых числа: величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма), величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска). ПримерыВходные данные6 11....................*..*.......*.**.......*.**..*...**.***********Выходные данные3 4Входные данные5 5....*...**..***.*********Выходные данные1 0Входные данные8 7........*......*......**.....**.*...****.*.*************Выходные данные6 2ПримечаниеВ первом тестовом примере высоты гор равны: 3, 4, 1, 1, 2, 1, 1, 1, 2, 5, 1. Наибольший подъем равен 3 и находится между горой номер 9 (её высота равна 2) и горой номер 10 (её высота равна 5). Наибольший спуск равен 4 и находится между горой номер 10 (её высота равна 5) и горой номер 11 (её высота равна 1).Во втором тестовом примере высоты гор равны: 1, 2, 3, 4, 5. Наибольший подъём равен 1 и находится, например, между горой номер 2 (ее высота равна 2) и горой номер 3 (её высота равна 3). Так как в данном горном хребте нет спусков, то величина наибольшего спуска равна 0.В третьем тестовом примере высоты гор равны: 1, 7, 5, 3, 4, 2, 3. Наибольший подъём равен 6 и находится между горой номер 1 (её высота равна 1) и горой номер 2 (её высота равна 7). Наибольший спуск равен 2 и находится между горой номер 2 (её высота равна 7) и горой номер 3 (её высота равна 5). Такой же спуск находится между горой номер 5 (её высота равна 4) и горой номер 6 (её высота равна 2). | Входные данные6 11....................*..*.......*.**.......*.**..*...**.*********** | Выходные данные3 4 | ограничение по времени на тест1 секунда | ограничение по памяти на тест256 мегабайт | ['constructive algorithms', 'implementation', '*900'] |
G. Armistice Area Apportionmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a drawn-out mooclear arms race, Farmer John and the Mischievous Mess Makers have finally agreed to establish peace. They plan to divide the territory of Bovinia with a line passing through at least two of the n outposts scattered throughout the land. These outposts, remnants of the conflict, are located at the points (x1, y1), (x2, y2), ..., (xn, yn).In order to find the optimal dividing line, Farmer John and Elsie have plotted a map of Bovinia on the coordinate plane. Farmer John's farm and the Mischievous Mess Makers' base are located at the points P = (a, 0) and Q = ( - a, 0), respectively. Because they seek a lasting peace, Farmer John and Elsie would like to minimize the maximum difference between the distances from any point on the line to P and Q.Formally, define the difference of a line relative to two points P and Q as the smallest real number d so that for all points X on line , |PX - QX| ≤ d. (It is guaranteed that d exists and is unique.) They wish to find the line passing through two distinct outposts (xi, yi) and (xj, yj) such that the difference of relative to P and Q is minimized.InputThe first line of the input contains two integers n and a (2 ≤ n ≤ 100 000, 1 ≤ a ≤ 10 000) — the number of outposts and the coordinates of the farm and the base, respectively.The following n lines describe the locations of the outposts as pairs of integers (xi, yi) (|xi|, |yi| ≤ 10 000). These points are distinct from each other as well as from P and Q.OutputPrint a single real number—the difference of the optimal dividing line. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput2 51 02 1Output7.2111025509Input3 60 12 50 -3Output0.0000000000NoteIn the first sample case, the only possible line is y = x - 1. It can be shown that the point X which maximizes |PX - QX| is (13, 12), with , which is .In the second sample case, if we pick the points (0, 1) and (0, - 3), we get as x = 0. Because PX = QX on this line, the minimum possible difference is 0. | Input2 51 02 1 | Output7.2111025509 | 3 seconds | 256 megabytes | ['binary search', 'geometry', '*3200'] |
F. Cowslip Collectionstime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn an attempt to make peace with the Mischievious Mess Makers, Bessie and Farmer John are planning to plant some flower gardens to complement the lush, grassy fields of Bovinia. As any good horticulturist knows, each garden they plant must have the exact same arrangement of flowers. Initially, Farmer John has n different species of flowers he can plant, with ai flowers of the i-th species.On each of the next q days, Farmer John will receive a batch of flowers of a new species. On day j, he will receive cj flowers of the same species, but of a different species from those Farmer John already has. Farmer John, knowing the right balance between extravagance and minimalism, wants exactly k species of flowers to be used. Furthermore, to reduce waste, each flower of the k species Farmer John chooses must be planted in some garden. And each of the gardens must be identical; that is to say that each of the k chosen species should have an equal number of flowers in each garden. As Farmer John is a proponent of national equality, he would like to create the greatest number of gardens possible.After receiving flowers on each of these q days, Farmer John would like to know the sum, over all possible choices of k species, of the maximum number of gardens he could create. Since this could be a large number, you should output your result modulo 109 + 7.InputThe first line of the input contains three integers n, k and q (1 ≤ k ≤ n ≤ 100 000, 1 ≤ q ≤ 100 000).The i-th (1 ≤ i ≤ n) of the next n lines of the input contains an integer ai (1 ≤ ai ≤ 1 000 000), the number of flowers of species i Farmer John has initially.The j-th (1 ≤ j ≤ q) of the next q lines of the input contains an integer cj (1 ≤ cj ≤ 1 000 000), the number of flowers of a new species Farmer John receives on day j.OutputAfter each of the q days, output the sum of the maximum possible number of gardens, where the sum is taken over all possible choices of k species, modulo 109 + 7.ExamplesInput3 3 246986Output516Input4 1 2654321Output2021NoteIn the first sample case, after the first day Farmer John has (4, 6, 9, 8) of each type of flower, and k = 3.Choosing (4, 6, 8) lets him make 2 gardens, each with (2, 3, 4) of each flower, respectively. Choosing (4, 6, 9), (4, 9, 8) and (6, 9, 8) each only let him make one garden, since there is no number of gardens that each species can be evenly split into. So the sum over all choices of k = 3 flowers is 2 + 1 + 1 + 1 = 5.After the second day, Farmer John has (4, 6, 9, 8, 6) of each flower. The sum over all choices is 1 + 2 + 2 + 1 + 1 + 2 + 2 + 3 + 1 + 1 = 16.In the second sample case, k = 1. With x flowers Farmer John can make x gardens. So the answers to the queries are 6 + 5 + 4 + 3 + 2 = 20 and 6 + 5 + 4 + 3 + 2 + 1 = 21. | Input3 3 246986 | Output516 | 8 seconds | 512 megabytes | ['combinatorics', 'math', 'number theory', '*2500'] |
E. Intellectual Inquirytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts.InputThe first line of the input contains two integers n and k (0 ≤ n ≤ 1 000 000, 1 ≤ k ≤ 26).The second line contains a string t (|t| = m, 1 ≤ m ≤ 1 000 000) consisting of only first k lowercase English letters.OutputDetermine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7.Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.ExamplesInput1 3acOutput8Input0 2aabaOutput10NoteIn the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb". In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once. | Input1 3ac | Output8 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'strings', '*2200'] |
D. Robot Rapping Results Reporttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.InputThe first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m ().The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.It is guaranteed that at least one ordering of the robots satisfies all m relations.OutputPrint the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.ExamplesInput4 52 11 32 34 24 3Output4Input3 21 23 2Output-1NoteIn the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles. | Input4 52 11 32 34 24 3 | Output4 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'graphs', '*1800'] |
C. Enduring Exodustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.InputThe first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John.The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.OutputPrint the minimum possible distance between Farmer John's room and his farthest cow.ExamplesInput7 20100100Output2Input5 101010Output2Input3 2000Output1NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1. | Input7 20100100 | Output2 | 2 seconds | 256 megabytes | ['binary search', 'two pointers', '*1600'] |
B. Mischievous Mess Makerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his k minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute.Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the k minutes that they have. We denote as pi the label of the cow in the i-th stall. The messiness of an arrangement of cows is defined as the number of pairs (i, j) such that i < j and pi > pj.InputThe first line of the input contains two integers n and k (1 ≤ n, k ≤ 100 000) — the number of cows and the length of Farmer John's nap, respectively.OutputOutput a single integer, the maximum messiness that the Mischievous Mess Makers can achieve by performing no more than k swaps. ExamplesInput5 2Output10Input1 10Output0NoteIn the first sample, the Mischievous Mess Makers can swap the cows in the stalls 1 and 5 during the first minute, then the cows in stalls 2 and 4 during the second minute. This reverses the arrangement of cows, giving us a total messiness of 10.In the second sample, there is only one cow, so the maximum possible messiness is 0. | Input5 2 | Output10 | 1 second | 256 megabytes | ['greedy', 'math', '*1200'] |
A. Amity Assessmenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below: In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.InputThe first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.OutputOutput "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).ExamplesInputABXCXBACOutputYESInputABXCACBXOutputNONoteThe solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all... | InputABXCXBAC | OutputYES | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*1200'] |
C. Hostname Aliasestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: <hostname> — server name (consists of words and maybe some dots separating them), /<path> — optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where: <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20. <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct.OutputFirst print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one.Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.ExamplesInput10http://abacaba.ru/testhttp://abacaba.ru/http://abacaba.comhttp://abacaba.com/testhttp://abacaba.de/http://abacaba.ru/testhttp://abacaba.de/testhttp://abacaba.com/http://abacaba.com/thttp://abacaba.com/testOutput1http://abacaba.de http://abacaba.ru Input14http://chttp://ccc.bbbb/aba..bhttp://cba.comhttp://a.c/aba..b/ahttp://abc/http://a.c/http://ccc.bbbbhttp://ab.ac.bc.aa/http://a.a.a/http://ccc.bbbb/http://cba.com/http://cba.com/aba..bhttp://a.a.a/aba..b/ahttp://abc/aba..b/aOutput2http://cba.com http://ccc.bbbb http://a.a.a http://a.c http://abc | Input10http://abacaba.ru/testhttp://abacaba.ru/http://abacaba.comhttp://abacaba.com/testhttp://abacaba.de/http://abacaba.ru/testhttp://abacaba.de/testhttp://abacaba.com/http://abacaba.com/thttp://abacaba.com/test | Output1http://abacaba.de http://abacaba.ru | 5 seconds | 256 megabytes | ['*special problem', 'binary search', 'data structures', 'implementation', 'sortings', 'strings', '*2100'] |
B. Processing Queriestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways: If server is free and query queue is empty, then server immediately starts to process this query. If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue. If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.InputThe first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue.Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.OutputPrint the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or - 1 if the corresponding query will be rejected.ExamplesInput5 12 94 810 915 219 1Output11 19 -1 21 22 Input4 12 84 810 915 2Output10 18 27 -1 NoteConsider the first sample. The server will start to process first query at the moment 2 and will finish to process it at the moment 11. At the moment 4 second query appears and proceeds to the queue. At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected. At the moment 11 server will finish to process first query and will take the second query from the queue. At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue. At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there. Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue. Server finishes to process query number 5 at the moment 22. | Input5 12 94 810 915 219 1 | Output11 19 -1 21 22 | 5 seconds | 256 megabytes | ['*special problem', 'constructive algorithms', 'data structures', 'two pointers', '*1700'] |
A. Parliament of Berlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.InputThe first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.OutputIf there is no way to assigns seats to parliamentarians in a proper way print -1.Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.ExamplesInput3 2 2Output0 31 2Input8 4 3Output7 8 30 1 46 0 50 2 0Input10 2 2Output-1NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | Input3 2 2 | Output0 31 2 | 1 second | 256 megabytes | ['*special problem', 'constructive algorithms', '*1000'] |
G. Choosing Adstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOne social network developer recently suggested a new algorithm of choosing ads for users.There are n slots which advertisers can buy. It is possible to buy a segment of consecutive slots at once. The more slots you own, the bigger are the chances your ad will be shown to users.Every time it is needed to choose ads to show, some segment of slots is picked by a secret algorithm. Then some advertisers are chosen. The only restriction is that it should be guaranteed for advertisers which own at least p% of slots composing this segment that their ad will be shown.From the other side, users don't like ads. So it was decided to show no more than ads at once. You are asked to develop a system to sell segments of slots and choose ads in accordance with the rules described above.InputThe first line of the input contains three integers n, m and p (1 ≤ n, m ≤ 150 000, 20 ≤ p ≤ 100) — the number of slots, the number of queries to your system and threshold for which display of the ad is guaranteed.Next line contains n integers ai (1 ≤ ai ≤ 150 000), where the i-th number means id of advertiser who currently owns the i-th slot.Next m lines contain queries descriptions. Each description is of one of the following forms: 1 l r id (1 ≤ l ≤ r ≤ n, 1 ≤ id ≤ 150 000) — advertiser id bought all slots in a range from l to r inclusive; 2 l r (1 ≤ l ≤ r) — you need to choose advertisers for segment [l, r]. OutputFor each query of the second type answer should be printed in a separate line. First integer of the answer should be the number of advertisements that will be shown . Next cnt integers should be advertisers' ids. It is allowed to print one advertiser more than once, but each advertiser that owns at least slots of the segment from l to r should be in your answer.ExampleInput5 9 331 2 1 3 32 1 52 1 52 1 32 3 31 2 4 52 1 52 3 51 4 5 12 1 5Output3 1 2 32 1 32 2 13 1 1000 10001 52 5 32 1 5NoteSamples demonstrate that you actually have quite a lot of freedom in choosing advertisers. | Input5 9 331 2 1 3 32 1 52 1 52 1 32 3 31 2 4 52 1 52 3 51 4 5 12 1 5 | Output3 1 2 32 1 32 2 13 1 1000 10001 52 5 32 1 5 | 3 seconds | 512 megabytes | ['data structures', '*3200'] |
F. Bears and Juicetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.Each night, the following happens in this exact order: Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears. Each bear drinks a glass from each barrel he chose. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately. At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).Radewoosh wants to allow bears to win. He considers q scenarios. In the i-th scenario the party will last for i nights. Then, let Ri denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define . Your task is to find , where denotes the exclusive or (also denoted as XOR).Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.InputThe only line of the input contains three integers n, p and q (1 ≤ n ≤ 109, 1 ≤ p ≤ 130, 1 ≤ q ≤ 2 000 000) — the number of bears, the number of places to sleep and the number of scenarios, respectively.OutputPrint one integer, equal to .ExamplesInput5 1 3Output32Input1 100 4Output4Input3 2 1Output7Input100 100 100Output381863924NoteIn the first sample, there are 5 bears and only 1 place to sleep. We have R1 = 6, R2 = 11, R3 = 16 so the answer is . Let's analyze the optimal strategy for scenario with 2 days. There are R2 = 11 barrels and 10 of them contain juice. In the first night, the i-th bear chooses a barrel i only. If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear. But let's say none of the first 5 barrels contains wine. In the second night, the i-th bear chooses a barrel 5 + i. If one of barrels 6 – 10 contains wine then one bear goes to sleep. And again, bears win in such a situation. If nobody went to sleep then wine is in a barrel 11. In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have Ri = 1. The answer is . | Input5 1 3 | Output32 | 5 seconds | 256 megabytes | ['dp', 'math', 'meet-in-the-middle', '*2900'] |
E. Bear and Destroying Subtreestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLimak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index 1 and is a root of the tree.Sometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each of its edges is destroyed with probability , independently of other edges. Then, Limak gets the penalty — an integer equal to the height of the subtree after the attack. The height is defined as the maximum number of edges on the path between the root of the subtree and any vertex in the subtree.You must handle queries of two types. 1 v denotes a query of the first type. A new vertex appears and its parent is v. A new vertex has the next available index (so, new vertices will be numbered 2, 3, ...). 2 v denotes a query of the second type. For a moment let's assume that the game allows Limak to attack a subtree rooted in v. Then, what would be the expected value of the penalty Limak gets after the attack? In a query of the second type, Limak doesn't actually attack the subtree and thus the query doesn't affect next queries.InputThe first line of the input contains one integer q (1 ≤ q ≤ 500 000) — the number of queries.Then, q lines follow. The i-th of them contains two integers typei and vi (1 ≤ typei ≤ 2). If typei = 1 then vi denotes a parent of a new vertex, while if typei = 2 then you should print the answer for a subtree rooted in vi.It's guaranteed that there will be at least 1 query of the second type, that is, the output won't be empty.It's guaranteed that just before the i-th query a vertex vi already exists.OutputFor each query of the second type print one real number —the expected value of the penalty if Limak attacks the given subtree. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput71 11 12 11 21 32 22 1Output0.75000000000.50000000001.1875000000Input82 11 11 21 31 42 11 42 1Output0.00000000000.93750000000.9687500000NoteBelow, you can see the drawing for the first sample. Red circles denote queries of the second type. | Input71 11 12 11 21 32 22 1 | Output0.75000000000.50000000001.1875000000 | 5 seconds | 512 megabytes | ['dp', 'math', 'probabilities', 'trees', '*2700'] |
D. Bearish Fanpagestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a social website with n fanpages, numbered 1 through n. There are also n companies, and the i-th company owns the i-th fanpage.Recently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow.The website doesn’t allow a situation where i follows j and at the same time j follows i. Also, a fanpage can't follow itself.Let’s say that fanpage i follows some other fanpage j0. Also, let’s say that i is followed by k other fanpages j1, j2, ..., jk. Then, when people visit fanpage i they see ads from k + 2 distinct companies: i, j0, j1, ..., jk. Exactly ti people subscribe (like) the i-th fanpage, and each of them will click exactly one add. For each of k + 1 companies j0, j1, ..., jk, exactly people will click their ad. Remaining people will click an ad from company i (the owner of the fanpage).The total income of the company is equal to the number of people who click ads from this copmany.Limak and Radewoosh ask you for help. Initially, fanpage i follows fanpage fi. Your task is to handle q queries of three types: 1 i j — fanpage i follows fanpage j from now. It's guaranteed that i didn't follow j just before the query. Note an extra constraint for the number of queries of this type (below, in the Input section). 2 i — print the total income of the i-th company. 3 — print two integers: the smallest income of one company and the biggest income of one company. InputThe first line of the input contains two integers n and q (3 ≤ n ≤ 100 000, 1 ≤ q ≤ 100 000) — the number of fanpages and the number of queries, respectively.The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 1012) where ti denotes the number of people subscribing the i-th fanpage.The third line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ n). Initially, fanpage i follows fanpage fi.Then, q lines follow. The i-th of them describes the i-th query. The first number in the line is an integer typei (1 ≤ typei ≤ 3) — the type of the query.There will be at most 50 000 queries of the first type. There will be at least one query of the second or the third type (so, the output won't be empty).It's guaranteed that at each moment a fanpage doesn't follow itself, and that no two fanpages follow each other.OutputFor each query of the second type print one integer in a separate line - the total income of the given company. For each query of the third type print two integers in a separate line - the minimum and the maximum total income, respectively.ExampleInput5 1210 20 30 40 502 3 4 5 22 12 22 32 42 51 4 22 12 22 32 42 53Output10362840369572728299 57Note In the sample test, there are 5 fanpages. The i-th of them has i·10 subscribers.On drawings, numbers of subscribers are written in circles. An arrow from A to B means that A follows B.The left drawing shows the initial situation. The first company gets income from its own fanpage, and gets income from the 2-nd fanpage. So, the total income is 5 + 5 = 10. After the first query ("2 1") you should print 10.The right drawing shows the situation after a query "1 4 2" (after which fanpage 4 follows fanpage 2). Then, the first company still gets income 5 from its own fanpage, but now it gets only from the 2-nd fanpage. So, the total income is 5 + 4 = 9 now. | Input5 1210 20 30 40 502 3 4 5 22 12 22 32 42 51 4 22 12 22 32 42 53 | Output10362840369572728299 57 | 5 seconds | 256 megabytes | ['*2900'] |
C. Levels and Regionstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRadewoosh is playing a computer game. There are n levels, numbered 1 through n. Levels are divided into k regions (groups). Each region contains some positive number of consecutive levels.The game repeats the the following process: If all regions are beaten then the game ends immediately. Otherwise, the system finds the first region with at least one non-beaten level. Let X denote this region. The system creates an empty bag for tokens. Each token will represent one level and there may be many tokens representing the same level. For each already beaten level i in the region X, the system adds ti tokens to the bag (tokens representing the i-th level). Let j denote the first non-beaten level in the region X. The system adds tj tokens to the bag. Finally, the system takes a uniformly random token from the bag and a player starts the level represented by the token. A player spends one hour and beats the level, even if he has already beaten it in the past. Given n, k and values t1, t2, ..., tn, your task is to split levels into regions. Each level must belong to exactly one region, and each region must contain non-empty consecutive set of levels. What is the minimum possible expected number of hours required to finish the game?InputThe first line of the input contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ min(50, n)) — the number of levels and the number of regions, respectively.The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 100 000).OutputPrint one real number — the minimum possible expected value of the number of hours spent to finish the game if levels are distributed between regions in the optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput4 2100 3 5 7Output5.7428571429Input6 21 2 4 8 16 32Output8.5000000000NoteIn the first sample, we are supposed to split 4 levels into 2 regions. It's optimal to create the first region with only one level (it must be the first level). Then, the second region must contain other three levels.In the second sample, it's optimal to split levels into two regions with 3 levels each. | Input4 2100 3 5 7 | Output5.7428571429 | 3 seconds | 256 megabytes | ['dp', '*2400'] |
B. Bear and Two Pathstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally: There is no road between a and b. There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.InputThe first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).OutputPrint -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.ExamplesInput7 112 4 7 3Output2 7 1 3 6 5 47 1 5 4 6 2 3Input1000 99910 20 30 40Output-1NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3. | Input7 112 4 7 3 | Output2 7 1 3 6 5 47 1 5 4 6 2 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', '*1600'] |
A. Bear and Colorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls.The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball.OutputPrint n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.ExamplesInput41 2 1 2Output7 3 0 0 Input31 1 1Output6 0 0 NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Input41 2 1 2 | Output7 3 0 0 | 2 seconds | 256 megabytes | ['implementation', '*1500'] |
G. Little Artem and Graphtime limit per test12 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem is given a graph, constructed as follows: start with some k-clique, then add new vertices one by one, connecting them to k already existing vertices that form a k-clique.Artem wants to count the number of spanning trees in this graph modulo 109 + 7.InputFirst line of the input contains two integers n and k (1 ≤ n ≤ 10 000, 1 ≤ k ≤ min(n, 5)) — the total size of the graph and the size of the initial clique, respectively.Next n - k lines describe k + 1-th, k + 2-th, ..., i-th, ..., n-th vertices by listing k distinct vertex indices 1 ≤ aij < i it is connected to. It is guaranteed that those vertices form a k-clique.OutputOutput a single integer — the number of spanning trees in the given graph modulo 109 + 7.ExamplesInput3 21 2Output3Input4 31 2 3Output16 | Input3 21 2 | Output3 | 12 seconds | 256 megabytes | ['*2300'] |
F. Little Artem and 2-SATtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem is a very smart programmer. He knows many different difficult algorithms. Recently he has mastered in 2-SAT one.In computer science, 2-satisfiability (abbreviated as 2-SAT) is the special case of the problem of determining whether a conjunction (logical AND) of disjunctions (logical OR) have a solution, in which all disjunctions consist of no more than two arguments (variables). For the purpose of this problem we consider only 2-SAT formulas where each disjunction consists of exactly two arguments.Consider the following 2-SAT problem as an example: . Note that there might be negations in 2-SAT formula (like for x1 and for x4).Artem now tries to solve as many problems with 2-SAT as possible. He found a very interesting one, which he can not solve yet. Of course, he asks you to help him. The problem is: given two 2-SAT formulas f and g, determine whether their sets of possible solutions are the same. Otherwise, find any variables assignment x such that f(x) ≠ g(x). InputThe first line of the input contains three integers n, m1 and m2 (1 ≤ n ≤ 1000, 1 ≤ m1, m2 ≤ n2) — the number of variables, the number of disjunctions in the first formula and the number of disjunctions in the second formula, respectively.Next m1 lines contains the description of 2-SAT formula f. The description consists of exactly m1 pairs of integers xi ( - n ≤ xi ≤ n, xi ≠ 0) each on separate line, where xi > 0 corresponds to the variable without negation, while xi < 0 corresponds to the variable with negation. Each pair gives a single disjunction. Next m2 lines contains formula g in the similar format.OutputIf both formulas share the same set of solutions, output a single word "SIMILAR" (without quotes). Otherwise output exactly n integers xi () — any set of values x such that f(x) ≠ g(x).ExamplesInput2 1 11 21 2OutputSIMILARInput2 1 11 21 -2Output0 0 NoteFirst sample has two equal formulas, so they are similar by definition.In second sample if we compute first function with x1 = 0 and x2 = 0 we get the result 0, because . But the second formula is 1, because . | Input2 1 11 21 2 | OutputSIMILAR | 3 seconds | 256 megabytes | ['*3000'] |
E. Little Artem and Time Machinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.Help Artem implement time travellers multiset.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries.Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.OutputFor each ask operation output the number of instances of integer being queried at the given moment of time.ExamplesInput61 1 53 5 51 2 53 6 52 3 53 7 5Output121Input31 1 12 2 13 3 1Output0 | Input61 1 53 5 51 2 53 6 52 3 53 7 5 | Output121 | 2 seconds | 256 megabytes | ['data structures', '*2000'] |
D. Little Artem and Random Variabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.We throw both dices simultaneously and then calculate values max(a, b) and min(a, b), where a is equal to the outcome of the first dice, while b is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for max(a, b) and min(a, b). That is, for each x from 1 to n you know the probability that max(a, b) would be equal to x and the probability that min(a, b) would be equal to x. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.InputFirst line contains the integer n (1 ≤ n ≤ 100 000) — the number of different values for both dices.Second line contains an array consisting of n real values with up to 8 digits after the decimal point — probability distribution for max(a, b), the i-th of these values equals to the probability that max(a, b) = i. It's guaranteed that the sum of these values for one dice is 1. The third line contains the description of the distribution min(a, b) in the same format.OutputOutput two descriptions of the probability distribution for a on the first line and for b on the second line. The answer will be considered correct if each value of max(a, b) and min(a, b) probability distribution values does not differ by more than 10 - 6 from ones given in input. Also, probabilities should be non-negative and their sums should differ from 1 by no more than 10 - 6.ExamplesInput20.25 0.750.75 0.25Output0.5 0.5 0.5 0.5 Input30.125 0.25 0.6250.625 0.25 0.125Output0.25 0.25 0.5 0.5 0.25 0.25 | Input20.25 0.750.75 0.25 | Output0.5 0.5 0.5 0.5 | 2 seconds | 256 megabytes | ['dp', 'implementation', 'math', 'probabilities', '*2400'] |
C. Little Artem and Dancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy.InputThe first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even.Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type.OutputOutput n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves.ExamplesInput6 31 221 2Output4 3 6 5 2 1Input2 31 121 -2Output1 2Input4 221 3Output1 4 3 2 | Input6 31 221 2 | Output4 3 6 5 2 1 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*1800'] |
B. Little Artem and Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.InputThe first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively.Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≤ ti ≤ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≤ ri ≤ n) or ci (1 ≤ ci ≤ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≤ ri ≤ n, 1 ≤ ci ≤ m, - 109 ≤ xi ≤ 109) are given.Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.OutputPrint the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value.If there are multiple valid solutions, output any of them.ExamplesInput2 2 62 12 23 1 1 13 2 2 23 1 2 83 2 1 8Output8 2 1 8 Input3 3 21 23 2 2 5Output0 0 0 0 0 5 0 0 0 | Input2 2 62 12 23 1 1 13 2 2 23 1 2 83 2 1 8 | Output8 2 1 8 | 2 seconds | 256 megabytes | ['implementation', '*1400'] |
A. Little Artem and Grasshoppertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip. Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.OutputPrint "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).ExamplesInput2><1 2OutputFINITEInput3>><2 1 1OutputINFINITENoteIn the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | Input2><1 2 | OutputFINITE | 2 seconds | 256 megabytes | ['implementation', '*1000'] |
F. Bear and Chemistrytime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a smart brown bear who loves chemistry, reactions and transforming elements.In Bearland (Limak's home) there are n elements, numbered 1 through n. There are also special machines, that can transform elements. Each machine is described by two integers ai, bi representing two elements, not necessarily distinct. One can use a machine either to transform an element ai to bi or to transform bi to ai. Machines in Bearland aren't very resistant and each of them can be used at most once. It is possible that ai = bi and that many machines have the same pair ai, bi.Radewoosh is Limak's biggest enemy and rival. He wants to test Limak in the chemistry. They will meet tomorrow and both of them will bring all their machines. Limak has m machines but he doesn't know much about his enemy. They agreed Radewoosh will choose two distinct elements, let's denote them as x and y. Limak will be allowed to use both his and Radewoosh's machines. He may use zero or more (maybe even all) machines to achieve the goal, each machine at most once. Limak will start from an element x and his task will be to first get an element y and then to again get an element x — then we say that he succeeds. After that Radewoosh would agree that Limak knows the chemistry (and Radewoosh would go away).Radewoosh likes some particular non-empty set of favorite elements and he will choose x, y from that set. Limak doesn't know exactly which elements are in the set and also he doesn't know what machines Radewoosh has. Limak has heard q gossips (queries) though and each of them consists of Radewoosh's machines and favorite elements. For each gossip Limak wonders if he would be able to succeed tomorrow for every pair x, y chosen from the set of favorite elements. If yes then print "YES" (without the quotes). But if there exists a pair (x, y) from the given set that Limak wouldn't be able to succeed then you should print "NO" (without the quotes).InputThe first line contains three integers n, m and q (1 ≤ n, q ≤ 300 000, 0 ≤ m ≤ 300 000) — the number of elements, the number of Limak's machines and the number of gossips, respectively.Each of the next m lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) describing one of Limak's machines.Then, the description of q gossips follows.The first line of the description of the i-th gossip contains two integers ni and mi (1 ≤ ni ≤ 300 000, 0 ≤ mi ≤ 300 000). The second line contains ni distinct integers xi, 1, xi, 2, ..., xi, ni (1 ≤ xi, j ≤ n) — Radewoosh's favorite elements in the i-th gossip. Note that ni = 1 is allowed, in this case there are no pairs of distinct elements, so Limak automatically wins (the answer is "YES"). Then mi lines follow, each containing two integers ai, j, bi, j (1 ≤ ai, j, bi, j) describing one of Radewoosh's machines in the i-th gossip.The sum of ni over all gossips won't exceed 300 000. Also, the sum of mi over all gossips won't exceed 300 000.Important: Because we want you to process the gossips online, in order to know the elements in Radewoosh's favorite set and elements that his machines can transform, for on each number that denotes them in the input you should use following function:int rotate(int element){ element=(element+R)%n; if (element==0) { element=n; } return element;}where R is initially equal to 0 and is increased by the number of the query any time the answer is "YES". Queries are numbered starting with 1 in the order they appear in the input.OutputYou should print q lines. The i-th of them should contain "YES" (without quotes) if for the i-th gossip for each pair of elements x and y (in the set xi, 1, xi, 2, ..., xi, ni) Limak is able to succeed. Otherwise you should print "NO" (without quotes).ExamplesInput6 5 41 22 33 42 45 62 04 22 16 23 43 26 3 42 54 62 11 21 2OutputYESNOYESYESInput7 6 21 21 32 42 53 63 77 21 2 3 4 5 6 74 56 77 21 2 3 4 5 6 74 65 7OutputNOYESNoteLets look at first sample:In first gossip Radewoosh's favorite set is {4, 2} and he has no machines. Limak can tranform element 4 into 2 (so half of a task is complete) and then 2 into 3, and 3 into 4. Answer is "YES", so R is increased by 1.In second gossip set in the input is denoted by {6, 2} and machine by (3, 4), but R is equal to 1, so set is {1, 3} and machine is (4, 5). Answer is "NO", so R isn't changed.In third gossip set {6, 4, 3} and machines (2, 5) and (4, 6) are deciphered to be {1, 5, 4}, (3, 6) and (5, 1).Consider Radewoosh's choices: If he chooses elements 1 and 5, then Limak is able to transform 1 into 5, then 6 into 3, 3 into 2 and 2 into 1. If he chooses elements 5 and 4, then Limak is able to transform 5 into 6, 6 into 3, 3 into 4 (half way already behind him), 4 into 2, 2 into 1, 1 into 5. If he chooses elements 1 and 4, then Limak is able to transform 1 into 2, 2 into 4, 4 into 3, 3 into 6, 6 into 5 and 5 into 1. So Limak is able to execute task. Answer is "YES" and R is increased by 3 (it's equal to 4 now).In last gossip {1, 2} and (1, 2) are deciphered to be {5, 6} and (5, 6). Now there are 2 machines (5, 6) so Limak is able to execute task again. | Input6 5 41 22 33 42 45 62 04 22 16 23 43 26 3 42 54 62 11 21 2 | OutputYESNOYESYES | 6 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'graphs', 'trees', '*3300'] |
E. Bear and Paradoxtime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a big polar bear. He prepared n problems for an algorithmic contest. The i-th problem has initial score pi. Also, testers said that it takes ti minutes to solve the i-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it — Limak has already announced initial scores for problems. Though it's still possible to adjust the speed of losing points, denoted by c in this statement.Let T denote the total number of minutes needed to solve all problems (so, T = t1 + t2 + ... + tn). The contest will last exactly T minutes. So it's just enough to solve all problems.Points given for solving a problem decrease linearly. Solving the i-th problem after x minutes gives exactly points, where is some real constant that Limak must choose.Let's assume that c is fixed. During a contest a participant chooses some order in which he or she solves problems. There are n! possible orders and each of them gives some total number of points, not necessarily integer. We say that an order is optimal if it gives the maximum number of points. In other words, the total number of points given by this order is greater or equal than the number of points given by any other order. It's obvious that there is at least one optimal order. However, there may be more than one optimal order.Limak assumes that every participant will properly estimate ti at the very beginning and will choose some optimal order. He also assumes that testers correctly predicted time needed to solve each problem.For two distinct problems i and j such that pi < pj Limak wouldn't be happy to see a participant with strictly more points for problem i than for problem j. He calls such a situation a paradox.It's not hard to prove that there will be no paradox for c = 0. The situation may be worse for bigger c. What is the maximum real value c (remember that ) for which there is no paradox possible, that is, there will be no paradox for any optimal order of solving problems?It can be proved that the answer (the maximum c as described) always exists.InputThe first line contains one integer n (2 ≤ n ≤ 150 000) — the number of problems.The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 108) — initial scores.The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 108) where ti is the number of minutes needed to solve the i-th problem.OutputPrint one real value on a single line — the maximum value of c that and there is no optimal order with a paradox. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput34 3 101 1 8Output0.62500000000Input47 20 15 107 20 15 10Output0.31901840491Input210 2010 1Output1.00000000000NoteIn the first sample, there are 3 problems. The first is (4, 1) (initial score is 4 and required time is 1 minute), the second problem is (3, 1) and the third one is (10, 8). The total time is T = 1 + 1 + 8 = 10.Let's show that there is a paradox for c = 0.7. Solving problems in order 1, 2, 3 turns out to give the best total score, equal to the sum of: solved 1 minute after the start: solved 2 minutes after the start: solved 10 minutes after the start: So, this order gives 3.72 + 2.58 + 3 = 9.3 points in total and this is the only optimal order (you can calculate total scores for other 5 possible orders too see that they are lower). You should check points for problems 1 and 3 to see a paradox. There is 4 < 10 but 3.72 > 3. It turns out that there is no paradox for c = 0.625 but there is a paradox for any bigger c.In the second sample, all 24 orders are optimal.In the third sample, even for c = 1 there is no paradox. | Input34 3 101 1 8 | Output0.62500000000 | 3.5 seconds | 256 megabytes | ['binary search', 'greedy', 'math', 'sortings', '*2800'] |
D. Bear and Contributiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCodeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution — an integer number, not necessarily positive. There are n registered users and the i-th of them has contribution ti.Limak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments. Limak can spend b minutes to read one blog and upvote it. Author's contribution will be increased by 5. Limak can spend c minutes to read one comment and upvote it. Author's contribution will be increased by 1. Note that it's possible that Limak reads blogs faster than comments.Limak likes ties. He thinks it would be awesome to see a tie between at least k registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value x that at least k registered users have contribution exactly x.How much time does Limak need to achieve his goal?InputThe first line contains four integers n, k, b and c (2 ≤ k ≤ n ≤ 200 000, 1 ≤ b, c ≤ 1000) — the number of registered users, the required minimum number of users with the same contribution, time needed to read and upvote a blog, and time needed to read and upvote a comment, respectively.The second line contains n integers t1, t2, ..., tn (|ti| ≤ 109) where ti denotes contribution of the i-th registered user.OutputPrint the minimum number of minutes Limak will spend to get a tie between at least k registered users.ExamplesInput4 3 100 3012 2 6 1Output220Input4 3 30 10012 2 6 1Output190Input6 2 987 789-8 42 -4 -65 -8 -8Output0NoteIn the first sample, there are 4 registered users and Limak wants a tie between at least 3 of them. Limak should behave as follows. He spends 100 minutes to read one blog of the 4-th user and increase his contribution from 1 to 6. Then he spends 4·30 = 120 minutes to read four comments of the 2-nd user and increase his contribution from 2 to 6 (four times it was increaded by 1). In the given scenario, Limak spends 100 + 4·30 = 220 minutes and after that each of users 2, 3, 4 has contribution 6.In the second sample, Limak needs 30 minutes to read a blog and 100 minutes to read a comment. This time he can get 3 users with contribution equal to 12 by spending 100 + 3·30 = 190 minutes: Spend 2·30 = 60 minutes to read two blogs of the 1-st user to increase his contribution from 2 to 12. Spend 30 + 100 minutes to read one blog and one comment of the 3-rd user. His contribution will change from 6 to 6 + 5 + 1 = 12. | Input4 3 100 3012 2 6 1 | Output220 | 4 seconds | 256 megabytes | ['data structures', 'greedy', 'sortings', 'two pointers', '*2400'] |
C. Bear and Polynomialstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:Let a0, a1, ..., an denote the coefficients, so . Then, a polynomial P(x) is valid if all the following conditions are satisfied: ai is integer for every i; |ai| ≤ k for every i; an ≠ 0. Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.InputThe first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 109) — the degree of the polynomial and the limit for absolute values of coefficients.The second line contains n + 1 integers a0, a1, ..., an (|ai| ≤ k, an ≠ 0) — describing a valid polynomial . It's guaranteed that P(2) ≠ 0.OutputPrint the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.ExamplesInput3 100000000010 -9 -3 5Output3Input3 1210 -9 -3 5Output2Input2 2014 -7 19Output0NoteIn the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.Limak can change one coefficient in three ways: He can set a0 = - 10. Then he would get Q(x) = - 10 - 9x - 3x2 + 5x3 and indeed Q(2) = - 10 - 18 - 12 + 40 = 0. Or he can set a2 = - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0. Or he can set a1 = - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0. In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time. | Input3 100000000010 -9 -3 5 | Output3 | 2 seconds | 256 megabytes | ['hashing', 'implementation', 'math', '*2200'] |
B. Bear and Forgotten Tree 3time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".InputThe first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.OutputIf there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.ExamplesInput5 3 2Output1 21 33 43 5Input8 5 2Output-1Input8 4 2Output4 85 72 38 12 15 61 5NoteBelow you can see trees printed to the output in the first sample and the third sample. | Input5 3 2 | Output1 21 33 43 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'trees', '*1600'] |
A. Bear and Displayed Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest ti.Your task is to handle queries of two types: "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before. "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type?InputThe first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively.The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 109) where ti describes how good is Limak's relation with the i-th friend.The i-th of the following q lines contains two integers typei and idi (1 ≤ typei ≤ 2, 1 ≤ idi ≤ n) — the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed.It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty.OutputFor each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise.ExamplesInput4 2 8300 950 500 2001 32 42 31 11 22 12 22 3OutputNOYESNOYESYESInput6 3 950 20 51 17 99 241 31 41 51 22 42 21 12 42 3OutputNOYESNOYESNoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries: "1 3" — Friend 3 becomes online. "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO". "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES". "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3. "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed "2 1" — Print "NO". "2 2" — Print "YES". "2 3" — Print "YES". | Input4 2 8300 950 500 2001 32 42 31 11 22 12 22 3 | OutputNOYESNOYESYES | 2 seconds | 256 megabytes | ['implementation', '*1200'] |
D. Three-dimensional Turtle Super Computer time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA super computer has been built in the Turtle Academy of Sciences. The computer consists of n·m·k CPUs. The architecture was the paralellepiped of size n × m × k, split into 1 × 1 × 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x, y, z) can send messages to CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) (of course, if they exist), there is no feedback, that is, CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) cannot send messages to CPU (x, y, z).Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a, b, c) controls CPU (d, e, f) , if there is a chain of CPUs (xi, yi, zi), such that (x1 = a, y1 = b, z1 = c), (xp = d, yp = e, zp = f) (here and below p is the length of the chain) and the CPU in the chain with number i (i < p) can send messages to CPU i + 1.Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x, y, z) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x, y, z) CPUs: (a, b, c) and (d, e, f), such that (a, b, c) controls (d, e, f) before (x, y, z) is turned off and stopped controlling it after the turning off.InputThe first line contains three integers n, m and k (1 ≤ n, m, k ≤ 100) — the dimensions of the Super Computer. Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each — the description of a layer in the format of an m × k table. Thus, the state of the CPU (x, y, z) is corresponded to the z-th character of the y-th line of the block number x. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line.OutputPrint a single integer — the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control.ExamplesInput2 2 3000000111111Output2Input3 3 3111111111111111111111111111Output19Input1 1 100101010101Output0NoteIn the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2, 1, 2) turns off, it disrupts the control by CPU (2, 1, 3) over CPU (2, 1, 1), and when CPU (2, 2, 2) is turned off, it disrupts the control over CPU (2, 2, 3) by CPU (2, 2, 1).In the second sample all processors except for the corner ones are critical.In the third sample there is not a single processor controlling another processor, so the answer is 0. | Input2 2 3000000111111 | Output2 | 3 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'graphs', '*1800'] |
C. Road Improvementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.InputThe first line of the input contains a positive integer n (2 ≤ n ≤ 200 000) — the number of cities in Berland.Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≤ ui, vi ≤ n, ui ≠ vi).OutputFirst print number k — the minimum number of days needed to repair all the roads in Berland.In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di — the number of roads that should be repaired on the i-th day, and then di space-separated integers — the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one.If there are multiple variants, you can print any of them.ExamplesInput41 23 43 2Output22 2 11 3Input63 45 43 21 34 6Output31 1 2 2 3 2 4 5 NoteIn the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 — on the second day. | Input41 23 43 2 | Output22 2 11 3 | 2 seconds | 256 megabytes | ['*special problem', 'dfs and similar', 'graphs', 'greedy', 'trees', '*1800'] |
B. Making Genome in Berlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct English letters to all nucleotides, then the genome of a Berland dinosaur will represent a non-empty string consisting of small English letters, such that each letter occurs in it at most once.Scientists have n genome fragments that are represented as substrings (non-empty sequences of consecutive nucleotides) of the sought genome.You face the following problem: help scientists restore the dinosaur genome. It is guaranteed that the input is not contradictory and at least one suitable line always exists. When the scientists found out that you are a strong programmer, they asked you in addition to choose the one with the minimum length. If there are multiple such strings, choose any string.InputThe first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of genome fragments.Each of the next lines contains one descriptions of a fragment. Each fragment is a non-empty string consisting of distinct small letters of the English alphabet. It is not guaranteed that the given fragments are distinct. Fragments could arbitrarily overlap and one fragment could be a substring of another one.It is guaranteed that there is such string of distinct letters that contains all the given fragments as substrings.OutputIn the single line of the output print the genome of the minimum length that contains all the given parts. All the nucleotides in the genome must be distinct. If there are multiple suitable strings, print the string of the minimum length. If there also are multiple suitable strings, you can print any of them.ExamplesInput3bcdabcdefOutputabcdefInput4xyzwOutputxyzw | Input3bcdabcdef | Outputabcdef | 1 second | 256 megabytes | ['*special problem', 'dfs and similar', 'strings', '*1500'] |
A. Home Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from left to right). The houses with even numbers are at the other side of the street and are numbered from 2 to n in the order from the end of the street to its beginning (in the picture: from right to left). The corresponding houses with even and odd numbers are strictly opposite each other, that is, house 1 is opposite house n, house 3 is opposite house n - 2, house 5 is opposite house n - 4 and so on. Vasya needs to get to house number a as quickly as possible. He starts driving from the beginning of the street and drives his car to house a. To get from the beginning of the street to houses number 1 and n, he spends exactly 1 second. He also spends exactly one second to drive the distance between two neighbouring houses. Vasya can park at any side of the road, so the distance between the beginning of the street at the houses that stand opposite one another should be considered the same.Your task is: find the minimum time Vasya needs to reach house a.InputThe first line of the input contains two integers, n and a (1 ≤ a ≤ n ≤ 100 000) — the number of houses on the street and the number of the house that Vasya needs to reach, correspondingly. It is guaranteed that number n is even.OutputPrint a single integer — the minimum time Vasya needs to get from the beginning of the street to house a.ExamplesInput4 2Output2Input8 5Output3NoteIn the first sample there are only four houses on the street, two houses at each side. House 2 will be the last at Vasya's right.The second sample corresponds to picture with n = 8. House 5 is the one before last at Vasya's left. | Input4 2 | Output2 | 1 second | 256 megabytes | ['*special problem', 'constructive algorithms', 'math', '*1100'] |
D. Running with Obstaclestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.On the way of an athlete are n obstacles at coordinates x1, x2, ..., xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.InputThe first line of the input containsd four integers n, m, s and d (1 ≤ n ≤ 200 000, 2 ≤ m ≤ 109, 1 ≤ s, d ≤ 109) — the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly.The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ m - 1) — the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.OutputIf the runner cannot reach the finishing point, print in the first line of the output "IMPOSSIBLE" (without the quotes).If the athlete can get from start to finish, print any way to do this in the following format: print a line of form "RUN X>" (where "X" should be a positive integer), if the athlete should run for "X" more meters; print a line of form "JUMP Y" (where "Y" should be a positive integer), if the sportsman starts a jump and should remain in air for "Y" more meters. All commands "RUN" and "JUMP" should strictly alternate, starting with "RUN", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish.ExamplesInput3 10 1 33 4 7OutputRUN 2JUMP 3RUN 1JUMP 2RUN 2Input2 9 2 36 4OutputIMPOSSIBLE | Input3 10 1 33 4 7 | OutputRUN 2JUMP 3RUN 1JUMP 2RUN 2 | 2 seconds | 256 megabytes | ['*special problem', 'data structures', 'dp', 'greedy', '*1600'] |
C. Promocodes with Mistakestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k = 0 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits.InputThe first line of the output contains number n (1 ≤ n ≤ 1000) — the number of promocodes.Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit "0".OutputPrint the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.ExamplesInput2000000999999Output2Input6211111212111222111111111112111121111Output0NoteIn the first sample k < 3, so if a bar customer types in value "090909", then it will be impossible to define which promocode exactly corresponds to it. | Input2000000999999 | Output2 | 1 second | 256 megabytes | ['*special problem', 'brute force', 'constructive algorithms', 'implementation', '*1400'] |
B. Chat Ordertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.InputThe first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.OutputPrint all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.ExamplesInput4alexivanromanivanOutputivanromanalexInput8alinamariaekaterinadaryadaryaekaterinamariaalinaOutputalinamariaekaterinadaryaNoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Input4alexivanromanivan | Outputivanromanalex | 3 seconds | 256 megabytes | ['*special problem', 'binary search', 'constructive algorithms', 'data structures', 'sortings', '*1200'] |
A. Voting for Photostime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 1 000 000), where ai is the identifier of the photo which got the i-th like.OutputPrint the identifier of the photo which won the elections.ExamplesInput51 3 2 2 1Output2Input9100 200 300 200 100 300 300 100 200Output300NoteIn the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got: more likes than the photo with id 3; as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier. | Input51 3 2 2 1 | Output2 | 1 second | 256 megabytes | ['*special problem', 'constructive algorithms', 'implementation', '*1000'] |
A. Orchestratime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.Two pictures are considered to be different if the coordinates of corresponding rectangles are different.InputThe first line of input contains four space-separated integers r, c, n, k (1 ≤ r, c, n ≤ 10, 1 ≤ k ≤ n) — the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively.The next n lines each contain two integers xi and yi (1 ≤ xi ≤ r, 1 ≤ yi ≤ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.OutputPrint a single integer — the number of photographs Paul can take which include at least k violas. ExamplesInput2 2 1 11 2Output4Input3 2 3 31 13 12 2Output1Input3 2 3 21 13 12 2Output4NoteWe will use '*' to denote violinists and '#' to denote violists.In the first sample, the orchestra looks as follows *#** Paul can take a photograph of just the viola, the 1 × 2 column containing the viola, the 2 × 1 row containing the viola, or the entire string section, for 4 pictures total.In the second sample, the orchestra looks as follows #**##* Paul must take a photograph of the entire section.In the third sample, the orchestra looks the same as in the second sample. | Input2 2 1 11 2 | Output4 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1100'] |
A. Island Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.InputThe first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands.The second line contains n space-separated integers ai (0 ≤ ai ≤ n - 1) — the statue currently placed on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct.The third line contains n space-separated integers bi (0 ≤ bi ≤ n - 1) — the desired statues of the ith island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.OutputPrint "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.ExamplesInput31 0 22 0 1OutputYESInput21 00 1OutputYESInput41 2 3 00 3 2 1OutputNONoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position. | Input31 0 22 0 1 | OutputYES | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*1300'] |
H. Fibonacci-ish IItime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYash is finally tired of computing the length of the longest Fibonacci-ish sequence. He now plays around with more complex things such as Fibonacci-ish potentials. Fibonacci-ish potential of an array ai is computed as follows: Remove all elements j if there exists i < j such that ai = aj. Sort the remaining elements in ascending order, i.e. a1 < a2 < ... < an. Compute the potential as P(a) = a1·F1 + a2·F2 + ... + an·Fn, where Fi is the i-th Fibonacci number (see notes for clarification). You are given an array ai of length n and q ranges from lj to rj. For each range j you have to compute the Fibonacci-ish potential of the array bi, composed using all elements of ai from lj to rj inclusive. Find these potentials modulo m.InputThe first line of the input contains integers of n and m (1 ≤ n, m ≤ 30 000) — the length of the initial array and the modulo, respectively.The next line contains n integers ai (0 ≤ ai ≤ 109) — elements of the array.Then follow the number of ranges q (1 ≤ q ≤ 30 000).Last q lines contain pairs of indices li and ri (1 ≤ li ≤ ri ≤ n) — ranges to compute Fibonacci-ish potentials.OutputPrint q lines, i-th of them must contain the Fibonacci-ish potential of the i-th range modulo m.ExampleInput5 102 1 2 1 222 44 5Output33NoteFor the purpose of this problem define Fibonacci numbers as follows: F1 = F2 = 1. Fn = Fn - 1 + Fn - 2 for each n > 2. In the first query, the subarray [1,2,1] can be formed using the minimal set {1,2}. Thus, the potential of this subarray is 1*1+2*1=3. | Input5 102 1 2 1 222 44 5 | Output33 | 5 seconds | 512 megabytes | ['data structures', 'implementation', '*3100'] |
G. Yash And Treestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYash loves playing with trees and gets especially excited when they have something to do with prime numbers. On his 20th birthday he was granted with a rooted tree of n nodes to answer queries on. Hearing of prime numbers on trees, Yash gets too intoxicated with excitement and asks you to help out and answer queries on trees for him. Tree is rooted at node 1. Each node i has some value ai associated with it. Also, integer m is given.There are queries of two types: for given node v and integer value x, increase all ai in the subtree of node v by value x for given node v, find the number of prime numbers p less than m, for which there exists a node u in the subtree of v and a non-negative integer value k, such that au = p + m·k.InputThe first of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ 1000) — the number of nodes in the tree and value m from the problem statement, respectively.The second line consists of n integers ai (0 ≤ ai ≤ 109) — initial values of the nodes.Then follow n - 1 lines that describe the tree. Each of them contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of nodes connected by the i-th edge.Next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries to proceed.Each of the last q lines is either 1 v x or 2 v (1 ≤ v ≤ n, 0 ≤ x ≤ 109), giving the query of the first or the second type, respectively. It's guaranteed that there will be at least one query of the second type.OutputFor each of the queries of the second type print the number of suitable prime numbers.ExamplesInput8 203 7 9 8 4 11 7 31 21 33 44 54 64 75 842 11 1 12 52 4Output311Input5 108 7 5 1 01 22 31 52 431 1 01 1 22 2Output2 | Input8 203 7 9 8 4 11 7 31 21 33 44 54 64 75 842 11 1 12 52 4 | Output311 | 4 seconds | 512 megabytes | ['bitmasks', 'data structures', 'dfs and similar', 'math', 'number theory', '*2800'] |
F. The Chocolate Spreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob have a tree (undirected acyclic connected graph). There are ai chocolates waiting to be picked up in the i-th vertex of the tree. First, they choose two different vertices as their starting positions (Alice chooses first) and take all the chocolates contained in them.Then, they alternate their moves, selecting one vertex at a time and collecting all chocolates from this node. To make things more interesting, they decided that one can select a vertex only if he/she selected a vertex adjacent to that one at his/her previous turn and this vertex has not been already chosen by any of them during other move.If at any moment one of them is not able to select the node that satisfy all the rules, he/she will skip his turns and let the other person pick chocolates as long as he/she can. This goes on until both of them cannot pick chocolates any further.Due to their greed for chocolates, they want to collect as many chocolates as possible. However, as they are friends they only care about the total number of chocolates they obtain together. What is the maximum total number of chocolates they may pick?InputThe first line of the input contains the single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.The second line contains n integers ai (1 ≤ ai ≤ 109), i-th of these numbers stands for the number of chocolates stored at the node i.Then follow n - 1 lines that describe the tree. Each of them contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of vertices connected by the i-th edge.OutputPrint the number of chocolates Alice and Bob can collect together if they behave optimally.ExamplesInput91 2 3 4 5 6 7 8 91 21 31 41 51 61 71 81 9Output25Input220 101 2Output30NoteIn the first sample, Alice may start at the vertex 9 and Bob at vertex 8. Alice will select vertex 1 and Bob has no options now. Alice selects the vertex 7 and they both stop.In the second sample, both of them will pick either of the nodes alternately. | Input91 2 3 4 5 6 7 8 91 21 31 41 51 61 71 81 9 | Output25 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'trees', '*2600'] |
E. Startup Fundingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn e-commerce startup pitches to the investors to get funding. They have been functional for n weeks now and also have a website!For each week they know the number of unique visitors during this week vi and the revenue ci. To evaluate the potential of the startup at some range of weeks from l to r inclusive investors use the minimum among the maximum number of visitors multiplied by 100 and the minimum revenue during this period, that is: The truth is that investors have no idea how to efficiently evaluate the startup, so they are going to pick some k random distinct weeks li and give them to managers of the startup. For each li they should pick some ri ≥ li and report maximum number of visitors and minimum revenue during this period.Then, investors will calculate the potential of the startup for each of these ranges and take minimum value of p(li, ri) as the total evaluation grade of the startup. Assuming that managers of the startup always report the optimal values of ri for some particular li, i.e., the value such that the resulting grade of the startup is maximized, what is the expected resulting grade of the startup? InputThe first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 1 000 000).The second line contains n integers vi (1 ≤ vi ≤ 107) — the number of unique visitors during each week.The third line contains n integers ci (1 ≤ ci ≤ 107) —the revenue for each week.OutputPrint a single real value — the expected grade of the startup. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3 23 2 1300 200 300Output133.3333333NoteConsider the first sample.If the investors ask for li = 1 onwards, startup will choose ri = 1, such that max number of visitors is 3 and minimum revenue is 300. Thus, potential in this case is min(3·100, 300) = 300.If the investors ask for li = 2 onwards, startup will choose ri = 3, such that max number of visitors is 2 and minimum revenue is 200. Thus, potential in this case is min(2·100, 200) = 200.If the investors ask for li = 3 onwards, startup will choose ri = 3, such that max number of visitors is 1 and minimum revenue is 300. Thus, potential in this case is min(1·100, 300) = 100.We have to choose a set of size 2 equi-probably and take minimum of each. The possible sets here are : {200, 300},{100, 300},{100, 200}, effectively the set of possible values as perceived by investors equi-probably: {200, 100, 100}. Thus, the expected value is (100 + 200 + 100) / 3 = 133.(3). | Input3 23 2 1300 200 300 | Output133.3333333 | 3 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'probabilities', 'two pointers', '*2400'] |
D. Fibonacci-ishtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.InputThe first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).OutputPrint the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.ExamplesInput31 2 -1Output3Input528 35 7 14 21Output4NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Input31 2 -1 | Output3 | 3 seconds | 512 megabytes | ['brute force', 'dp', 'hashing', 'implementation', 'math', '*2000'] |
C. Spy Syndrome 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.For a given sentence, the cipher is processed as: Convert all letters of the sentence to lowercase. Reverse each of the words of the sentence individually. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentenceKira is childish and he hates losingthe resulting string isariksihsidlihcdnaehsetahgnisolNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t.The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000.OutputPrint one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.ExamplesInput30ariksihsidlihcdnaehsetahgnisol10KirahatesishelosingdeathchildishLandNoteOutputKira is childish and he hates losing Input12iherehtolleh5HIHothereHeLLohelloOutputHI there HeLLo NoteIn sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them. | Input30ariksihsidlihcdnaehsetahgnisol10KirahatesishelosingdeathchildishLandNote | OutputKira is childish and he hates losing | 2 seconds | 256 megabytes | ['data structures', 'dp', 'hashing', 'implementation', 'sortings', 'string suffix structures', 'strings', '*1900'] |
B. A Trivial Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem?InputThe only line of input contains an integer m (1 ≤ m ≤ 100 000) — the required number of trailing zeroes in factorial.OutputFirst print k — the number of values of n such that the factorial of n ends with m zeroes. Then print these k integers in increasing order.ExamplesInput1Output55 6 7 8 9 Input5Output0NoteThe factorial of n is equal to the product of all integers from 1 to n inclusive, that is n! = 1·2·3·...·n.In the first sample, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320 and 9! = 362880. | Input1 | Output55 6 7 8 9 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'math', 'number theory', '*1300'] |
A. Ebony and Ivorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots.For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of damage. In order to break the shield Dante has to deal exactly c units of damage. Find out if this is possible.InputThe first line of the input contains three integers a, b, c (1 ≤ a, b ≤ 100, 1 ≤ c ≤ 10 000) — the number of units of damage dealt by Ebony gun and Ivory gun, and the total number of damage required to break the shield, respectively.OutputPrint "Yes" (without quotes) if Dante can deal exactly c damage to the shield and "No" (without quotes) otherwise.ExamplesInput4 6 15OutputNoInput3 2 7OutputYesInput6 11 6OutputYesNoteIn the second sample, Dante can fire 1 bullet from Ebony and 2 from Ivory to deal exactly 1·3 + 2·2 = 7 damage. In the third sample, Dante can fire 1 bullet from ebony and no bullets from ivory to do 1·6 + 0·11 = 6 damage. | Input4 6 15 | OutputNo | 2 seconds | 256 megabytes | ['brute force', 'math', 'number theory', '*1100'] |
F. Magic Matrixtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou're given a matrix A of size n × n.Let's call the matrix with nonnegative elements magic if it is symmetric (so aij = aji), aii = 0 and aij ≤ max(aik, ajk) for all triples i, j, k. Note that i, j, k do not need to be distinct.Determine if the matrix is magic.As the input/output can reach very huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe first line contains integer n (1 ≤ n ≤ 2500) — the size of the matrix A.Each of the next n lines contains n integers aij (0 ≤ aij < 109) — the elements of the matrix A.Note that the given matrix not necessarily is symmetric and can be arbitrary.OutputPrint ''MAGIC" (without quotes) if the given matrix A is magic. Otherwise print ''NOT MAGIC".ExamplesInput30 1 21 0 22 2 0OutputMAGICInput20 12 3OutputNOT MAGICInput40 1 2 31 0 3 42 3 0 53 4 5 0OutputNOT MAGIC | Input30 1 21 0 22 2 0 | OutputMAGIC | 5 seconds | 512 megabytes | ['brute force', 'divide and conquer', 'graphs', 'matrices', 'trees', '*2400'] |
E. Thief in a Shoptime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA thief made his way to a shop.As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai.The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind).Find all the possible total costs of products the thief can nick into his knapsack.InputThe first line contains two integers n and k (1 ≤ n, k ≤ 1000) — the number of kinds of products and the number of products the thief will take.The second line contains n integers ai (1 ≤ ai ≤ 1000) — the costs of products for kinds from 1 to n.OutputPrint the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order.ExamplesInput3 21 2 3Output2 3 4 5 6Input5 51 1 1 1 1Output5Input3 33 5 11Output9 11 13 15 17 19 21 25 27 33 | Input3 21 2 3 | Output2 3 4 5 6 | 5 seconds | 512 megabytes | ['divide and conquer', 'dp', 'fft', 'math', '*2400'] |
D. Longest Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value l ≤ m.A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase zero or all elements.The LCM of an empty array equals 1.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 106) — the size of the array a and the parameter from the problem statement.The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of a.OutputIn the first line print two integers l and kmax (1 ≤ l ≤ m, 0 ≤ kmax ≤ n) — the value of LCM and the number of elements in optimal subsequence.In the second line print kmax integers — the positions of the elements from the optimal subsequence in the ascending order.Note that you can find and print any subsequence with the maximum length.ExamplesInput7 86 2 9 2 7 2 3Output6 51 2 4 6 7Input6 42 2 2 3 3 3Output2 31 2 3 | Input7 86 2 9 2 7 2 3 | Output6 51 2 4 6 7 | 2 seconds | 256 megabytes | ['brute force', 'math', 'number theory', '*2100'] |
C. The Smallest String Concatenationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.Given the list of strings, output the lexicographically smallest concatenation.InputThe first line contains integer n — the number of strings (1 ≤ n ≤ 5·104).Each of the next n lines contains one string ai (1 ≤ |ai| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·104.OutputPrint the only string a — the lexicographically smallest string concatenation.ExamplesInput4abbaabacababcderOutputabacabaabbabcderInput5xxxxxaxxaaxxaaaOutputxxaaaxxaaxxaxxxInput3ccbcbaOutputcbacbc | Input4abbaabacababcder | Outputabacabaabbabcder | 3 seconds | 256 megabytes | ['sortings', 'strings', '*1700'] |
B. Alice, Bob, Two Teamstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.The way to split up game pieces is split into several steps: First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once. Alice will get all the pieces marked A and Bob will get all the pieces marked B. The strength of a player is then the sum of strengths of the pieces in the group.Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.InputThe first line contains integer n (1 ≤ n ≤ 5·105) — the number of game pieces.The second line contains n integers pi (1 ≤ pi ≤ 109) — the strength of the i-th piece.The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).OutputPrint the only integer a — the maximum strength Bob can achieve.ExamplesInput51 2 3 4 5ABABAOutput11Input51 2 3 4 5AAAAAOutput15Input11BOutput1NoteIn the first sample Bob should flip the suffix of length one.In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.In the third sample Bob should do nothing. | Input51 2 3 4 5ABABA | Output11 | 1.5 seconds | 256 megabytes | ['brute force', 'constructive algorithms', '*1400'] |
A. Grandma Laura and Applestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGrandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).Print the total money grandma should have at the end of the day to check if some buyers cheated her.InputThe first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even.The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift.It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.OutputPrint the only integer a — the total money grandma should have at the end of the day.Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.ExamplesInput2 10halfhalfplusOutput15Input3 10halfplushalfplushalfplusOutput55NoteIn the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer. | Input2 10halfhalfplus | Output15 | 1 second | 256 megabytes | ['*1200'] |
E. Product Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBlake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.You are given an array a of length n. The characteristic of this array is the value — the sum of the products of the values ai by i. One may perform the following operation exactly once: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic. InputThe first line of the input contains a single integer n (2 ≤ n ≤ 200 000) — the size of the array a.The second line contains n integers ai (1 ≤ i ≤ n, |ai| ≤ 1 000 000) — the elements of the array a.OutputPrint a single integer — the maximum possible value of characteristic of a that can be obtained by performing no more than one move.ExamplesInput44 3 2 5Output39Input51 1 2 7 1Output49Input31 1 2Output9NoteIn the first sample, one may pick the first element and place it before the third (before 5). Thus, the answer will be 3·1 + 2·2 + 4·3 + 5·4 = 39.In the second sample, one may pick the fifth element of the array and place it before the third. The answer will be 1·1 + 1·2 + 1·3 + 2·4 + 7·5 = 49. | Input44 3 2 5 | Output39 | 1 second | 256 megabytes | ['data structures', 'dp', 'geometry', '*2600'] |
D. Messengertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEach employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs .Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t.Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as , , ...InputThe first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of blocks in the strings t and s, respectively.The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≤ li ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≤ li ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.OutputPrint a single integer — the number of occurrences of s in t.ExamplesInput5 33-a 2-b 4-c 3-a 2-c2-a 2-b 1-cOutput1Input6 13-a 6-b 7-a 4-c 8-e 2-a3-aOutput6Input5 51-h 1-e 1-l 1-l 1-o1-w 1-o 1-r 1-l 1-dOutput0NoteIn the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2.In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. | Input5 33-a 2-b 4-c 3-a 2-c2-a 2-b 1-c | Output1 | 2 seconds | 512 megabytes | ['data structures', 'hashing', 'implementation', 'string suffix structures', 'strings', '*2100'] |
C. Reporttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.InputThe first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.OutputPrint n integers — the final report, which will be passed to Blake by manager number m.ExamplesInput3 11 2 32 2Output2 1 3 Input4 21 2 4 32 31 2Output2 4 1 3 NoteIn the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | Input3 11 2 32 2 | Output2 1 3 | 2 seconds | 256 megabytes | ['data structures', 'sortings', '*1700'] |
B. Print Checktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.Printer works with a rectangular sheet of paper of size n × m. Consider the list as a table consisting of n rows and m columns. Rows are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m. Initially, all cells are painted in color 0.Your program has to support two operations: Paint all cells in row ri in color ai; Paint all cells in column ci in color ai. If during some operation i there is a cell that have already been painted, the color of this cell also changes to ai.Your program has to print the resulting table after k operation.InputThe first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 5000, n·m ≤ 100 000, 1 ≤ k ≤ 100 000) — the dimensions of the sheet and the number of operations, respectively.Each of the next k lines contains the description of exactly one query: 1 ri ai (1 ≤ ri ≤ n, 1 ≤ ai ≤ 109), means that row ri is painted in color ai; 2 ci ai (1 ≤ ci ≤ m, 1 ≤ ai ≤ 109), means that column ci is painted in color ai. OutputPrint n lines containing m integers each — the resulting table after all operations are applied.ExamplesInput3 3 31 1 32 2 11 2 2Output3 1 3 2 2 2 0 1 0 Input5 3 51 1 11 3 11 5 12 1 12 3 1Output1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 NoteThe figure below shows all three operations for the first sample step by step. The cells that were painted on the corresponding step are marked gray. | Input3 3 31 1 32 2 11 2 2 | Output3 1 3 2 2 2 0 1 0 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1200'] |
A. Interviewtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBlake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. InputThe first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays.The second line contains n integers ai (0 ≤ ai ≤ 109).The third line contains n integers bi (0 ≤ bi ≤ 109).OutputPrint a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.ExamplesInput51 2 4 3 22 3 3 12 1Output22Input1013 2 7 11 8 4 9 8 5 15 7 18 9 2 3 0 11 8 6Output46NoteBitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5.In the second sample, the maximum value is obtained for l = 1 and r = 9. | Input51 2 4 3 22 3 3 12 1 | Output22 | 1 second | 256 megabytes | ['brute force', 'implementation', '*900'] |
R. Gametime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThere is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.The professor have chosen the field size n and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.InputThe only line of the input contains one integer n (1 ≤ n ≤ 1018) — the size of the field.OutputOutput number 1, if the player making the first turn wins when both players play optimally, otherwise print number 2.ExamplesInput1Output1Input2Output2 | Input1 | Output1 | 0.5 seconds | 64 megabytes | ['games', 'math', '*1200'] |
Q. Pyramidstime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. InputThe only line of the input contains three integers l3, l4, l5 (1 ≤ l3, l4, l5 ≤ 1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.OutputOutput one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10 - 9.ExamplesInput2 5 3Output38.546168065709 | Input2 5 3 | Output38.546168065709 | 0.5 seconds | 64 megabytes | ['geometry', 'math', '*1700'] |
P. Area of a Startime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIt was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.A "star" figure having n ≥ 5 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts. InputThe only line of the input contains two integers n (5 ≤ n < 109, n is prime) and r (1 ≤ r ≤ 109) — the number of the star corners and the radius of the circumcircle correspondingly.OutputOutput one number — the star area. The relative error of your answer should not be greater than 10 - 7.ExamplesInput7 10Output108.395919545675 | Input7 10 | Output108.395919545675 | 0.5 seconds | 64 megabytes | ['geometry', '*2100'] |
O. Arrowtime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPetya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip. InputThe only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx2 + vy2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).OutputOutput coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9.ExamplesInput8 8 0 2 8 3 4 5Output8.000000000000 11.0000000000004.000000000000 8.0000000000006.000000000000 8.0000000000006.000000000000 3.00000000000010.000000000000 3.00000000000010.000000000000 8.00000000000012.000000000000 8.000000000000 | Input8 8 0 2 8 3 4 5 | Output8.000000000000 11.0000000000004.000000000000 8.0000000000006.000000000000 8.0000000000006.000000000000 3.00000000000010.000000000000 3.00000000000010.000000000000 8.00000000000012.000000000000 8.000000000000 | 0.5 seconds | 64 megabytes | ['geometry', '*2000'] |
N. Forecasttime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.InputThe only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation.OutputIn the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6.ExamplesInput1 30 200Output-10.000000000000000-20.000000000000000 | Input1 30 200 | Output-10.000000000000000-20.000000000000000 | 0.5 seconds | 64 megabytes | ['math', '*1300'] |
M. Turntime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputVasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face.One of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget — a rotating camera — come up to it to see it better, look into it. And the camera takes their photo at that time. What could be better for high quality identification?But not everything is so simple. The pictures from camera appear rotated too (on clockwise camera rotation frame the content becomes rotated counter-clockwise). But the identification algorithm can work only with faces that are just slightly deviated from vertical.Vasya was entrusted to correct the situation — to rotate a captured image so that image would be minimally deviated from vertical. Requirements were severe. Firstly, the picture should be rotated only on angle divisible by 90 degrees to not lose a bit of information about the image. Secondly, the frames from the camera are so huge and FPS is so big that adequate rotation speed is provided by hardware FPGA solution only. And this solution can rotate only by 90 degrees clockwise. Of course, one can apply 90 degrees turn several times but for the sake of performance the number of turns should be minimized.Help Vasya implement the program that by the given rotation angle of the camera can determine the minimum number of 90 degrees clockwise turns necessary to get a picture in which up direction deviation from vertical is minimum.The next figure contains frames taken from an unrotated camera, then from rotated 90 degrees clockwise, then from rotated 90 degrees counter-clockwise. Arrows show direction to "true up". The next figure shows 90 degrees clockwise turn by FPGA hardware. InputThe only line of the input contains one integer x ( - 1018 ≤ x ≤ 1018) — camera angle in degrees. Positive value denotes clockwise camera rotation, negative — counter-clockwise.OutputOutput one integer — the minimum required number of 90 degrees clockwise turns.ExamplesInput60Output1Input-60Output3NoteWhen the camera is rotated 60 degrees counter-clockwise (the second example), an image from it is rotated 60 degrees clockwise. One 90 degrees clockwise turn of the image result in 150 degrees clockwise total rotation and deviation from "true up" for one turn is 150 degrees. Two 90 degrees clockwise turns of the image result in 240 degrees clockwise total rotation and deviation from "true up" for two turns is 120 degrees because 240 degrees clockwise equal to 120 degrees counter-clockwise. Three 90 degrees clockwise turns of the image result in 330 degrees clockwise total rotation and deviation from "true up" for three turns is 30 degrees because 330 degrees clockwise equal to 30 degrees counter-clockwise.From 60, 150, 120 and 30 degrees deviations the smallest is 30, and it it achieved in three 90 degrees clockwise turns. | Input60 | Output1 | 0.5 seconds | 64 megabytes | ['geometry', 'math', '*1800'] |
L. Cracking the Codetime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose — to show the developer the imperfection of their protection.The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.Vasya is going to write a keygen program implementing this algorithm. Can you do the same?InputThe only line of the input contains a positive integer five digit number for which the activation code should be found.OutputOutput exactly 5 digits without spaces between them — the found activation code of the program.ExamplesInput12345Output71232 | Input12345 | Output71232 | 0.5 seconds | 64 megabytes | ['implementation', 'math', '*1400'] |
K. Indivisibilitytime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus.A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.InputThe only line of the input contains one integer n (1 ≤ n ≤ 1018) — the prediction on the number of people who will buy the game.OutputOutput one integer showing how many numbers from 1 to n are not divisible by any number from 2 to 10.ExamplesInput12Output2 | Input12 | Output2 | 0.5 seconds | 64 megabytes | ['math', 'number theory', '*1500'] |
J. Divisibilitytime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer of this game gets a small bonus.A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.InputThe only line of the input contains one integer n (1 ≤ n ≤ 1018) — the prediction on the number of people who will buy the game.OutputOutput one integer showing how many numbers from 1 to n are divisible by all numbers from 2 to 10.ExamplesInput3000Output1 | Input3000 | Output1 | 0.5 seconds | 64 megabytes | ['math', 'number theory', '*1100'] |
I. Parking Lottime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputTo quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly n successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.InputThe only line of the input contains one integer n (3 ≤ n ≤ 30) — the amount of successive cars of the same make.OutputOutput one integer — the number of ways to fill the parking lot by cars of four makes using the described way.ExamplesInput3Output24NoteLet's denote car makes in the following way: A — Aston Martin, B — Bentley, M — Mercedes-Maybach, Z — Zaporozhets. For n = 3 there are the following appropriate ways to fill the parking lot: AAAB AAAM AAAZ ABBB AMMM AZZZ BBBA BBBM BBBZ BAAA BMMM BZZZ MMMA MMMB MMMZ MAAA MBBB MZZZ ZZZA ZZZB ZZZM ZAAA ZBBB ZMMMOriginally it was planned to grant sport cars of Ferrari, Lamborghini, Maserati and Bugatti makes but this idea was renounced because it is impossible to drive these cars having small road clearance on the worn-down roads of IT City. | Input3 | Output24 | 0.5 seconds | 64 megabytes | ['combinatorics', 'math', '*1700'] |
H. Benchestime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.Help the park administration count the number of ways to place the benches.InputThe only line of the input contains one integer n (5 ≤ n ≤ 100) — the number of east to west paths and north to south paths.OutputOutput one integer — the number of ways to place the benches.ExamplesInput5Output120 | Input5 | Output120 | 0.5 seconds | 64 megabytes | ['combinatorics', 'math', '*1400'] |
G. Challenge Pennantstime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputBecause of budget cuts one IT company established new non-financial reward system instead of bonuses.Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.InputThe only line of the input contains one integer n (1 ≤ n ≤ 500) — the number of tables in the IT company.OutputOutput one integer — the amount of ways to place the pennants on n tables.ExamplesInput2Output24 | Input2 | Output24 | 0.5 seconds | 64 megabytes | ['combinatorics', 'math', '*1600'] |
F. Selection of Personneltime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputOne company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.InputThe only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.OutputOutput one integer — the number of different variants of group composition.ExamplesInput7Output29 | Input7 | Output29 | 0.5 seconds | 64 megabytes | ['combinatorics', 'math', '*1300'] |
E. A rectangletime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputDeveloping tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.More formally, if a game designer selected cells having coordinates (x1, y1) and (x2, y2), where x1 ≤ x2 and y1 ≤ y2, then all cells having center coordinates (x, y) such that x1 ≤ x ≤ x2 and y1 ≤ y ≤ y2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x2 - x1 is divisible by 2.Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.Help him implement counting of these units before painting. InputThe only line of input contains four integers x1, y1, x2, y2 ( - 109 ≤ x1 ≤ x2 ≤ 109, - 109 ≤ y1 ≤ y2 ≤ 109) — the coordinates of the centers of two cells.OutputOutput one integer — the number of cells to be filled.ExamplesInput1 1 5 5Output13 | Input1 1 5 5 | Output13 | 0.5 seconds | 64 megabytes | ['math', '*1900'] |
D. Hexagons!time limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputAfter a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell. InputThe only line of the input contains one integer n (0 ≤ n ≤ 109).OutputOutput one integer — the number of hexagons situated not farther than n cells away from a given cell.ExamplesInput2Output19 | Input2 | Output19 | 0.5 seconds | 64 megabytes | ['math', '*1100'] |
C. Lucky Numberstime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.InputThe only line of input contains one integer n (1 ≤ n ≤ 55) — the maximum length of a number that a door-plate can hold.OutputOutput one integer — the maximum number of offices, than can have unique lucky numbers not longer than n digits.ExamplesInput2Output6 | Input2 | Output6 | 0.5 seconds | 64 megabytes | ['combinatorics', 'math', '*1100'] |
B. Moore's Lawtime limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.InputThe only line of the input contains a pair of integers n (1000 ≤ n ≤ 10 000) and t (0 ≤ t ≤ 2 000 000 000) — the number of transistors in the initial time and the number of seconds passed since the initial time.OutputOutput one number — the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10 - 6.ExamplesInput1000 1000000Output1011.060722383550382782399454922040 | Input1000 1000000 | Output1011.060722383550382782399454922040 | 0.5 seconds | 64 megabytes | ['math', '*1200'] |
A. Again Twenty Five!time limit per test0.5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions."Could you pass the interview in the machine vision company in IT City?InputThe only line of the input contains a single integer n (2 ≤ n ≤ 2·1018) — the power in which you need to raise number 5.OutputOutput the last two digits of 5n without spaces between them.ExamplesInput2Output25 | Input2 | Output25 | 0.5 seconds | 64 megabytes | ['number theory', '*800'] |
E. Famil Door and Roadstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFamil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are n intersections in the city connected by n - 1 bidirectional roads.There are m friends of Famil Door living in the city. The i-th friend lives at the intersection ui and works at the intersection vi. Everyone in the city is unhappy because there is exactly one simple path between their home and work.Famil Door plans to construct exactly one new road and he will randomly choose one among n·(n - 1) / 2 possibilities. Note, that he may even build a new road between two cities that are already connected by one.He knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both ui and vi. Moreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both ui and vi if we consider only cases when such a cycle exists.InputThe first line of the input contains integers n and m (2 ≤ n, m ≤ 100 000) — the number of the intersections in the Treeland and the number of Famil Door's friends.Then follow n - 1 lines describing bidirectional roads. Each of them contains two integers ai and bi (1 ≤ ai, bi ≤ n) — the indices of intersections connected by the i-th road.Last m lines of the input describe Famil Door's friends. The i-th of these lines contain two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of intersections where the i-th friend lives and works.OutputFor each friend you should print the expected value of pleasure if he will be happy. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput4 32 44 13 23 12 34 1Output4.000000003.000000003.00000000Input3 31 21 31 21 32 3Output2.500000002.500000003.00000000NoteConsider the second sample. Both roads (1, 2) and (2, 3) work, so the expected length if Roads (1, 3) and (2, 3) make the second friend happy. Same as for friend 1 the answer is 2.5 The only way to make the third friend happy is to add road (2, 3), so the answer is 3 | Input4 32 44 13 23 12 34 1 | Output4.000000003.000000003.00000000 | 5 seconds | 512 megabytes | ['combinatorics', 'data structures', 'dfs and similar', 'dp', 'probabilities', 'trees', '*2300'] |
D. Babaei and Birthday Caketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special cake placing some cylinders on each other.However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number i can be placed only on the table or on some cake number j where j < i. Moreover, in order to impress friends Babaei will put the cake i on top of the cake j only if the volume of the cake i is strictly greater than the volume of the cake j.Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of simple cakes Babaei has.Each of the following n lines contains two integers ri and hi (1 ≤ ri, hi ≤ 10 000), giving the radius and height of the i-th cake.OutputPrint the maximum volume of the cake that Babaei can make. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput2100 3040 10Output942477.796077000Input41 19 71 410 7Output3983.539484752NoteIn first sample, the optimal way is to choose the cake number 1.In second sample, the way to get the maximum volume is to use cakes with indices 1, 2 and 4. | Input2100 3040 10 | Output942477.796077000 | 2 seconds | 256 megabytes | ['data structures', 'dp', '*2000'] |
C. Famil Door and Bracketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109 + 7.InputFirst line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively.The second line contains string s of length m consisting of characters '(' and ')' only.OutputPrint the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 109 + 7.ExamplesInput4 1(Output4Input4 4(())Output1Input4 3(((Output0NoteIn the first sample there are four different valid pairs: p = "(", q = "))" p = "()", q = ")" p = "", q = "())" p = "", q = ")()" In the second sample the only way to obtain a desired string is choose empty p and q.In the third sample there is no way to get a valid sequence of brackets. | Input4 1( | Output4 | 2 seconds | 256 megabytes | ['dp', 'strings', '*2000'] |
B. Far Relative’s Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFamil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.OutputPrint the maximum number of people that may come to Famil Door's party.ExamplesInput4M 151 307F 343 352F 117 145M 24 128Output2Input6M 128 130F 128 131F 131 140F 131 141M 131 200M 140 200Output4NoteIn the first sample, friends 3 and 4 can come on any day in range [117, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140. | Input4M 151 307F 343 352F 117 145M 24 128 | Output2 | 2 seconds | 256 megabytes | ['brute force', '*1100'] |
A. Far Relative’s Birthday Caketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoor's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.InputIn the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake.Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.OutputPrint the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.ExamplesInput3.CCC..C.COutput4Input4CC..C..C.CC..CC.Output9NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are: (1, 2) and (1, 3) (3, 1) and (3, 3) Pieces that share the same column are: (2, 1) and (3, 1) (1, 3) and (3, 3) | Input3.CCC..C.C | Output4 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'constructive algorithms', 'implementation', '*800'] |
F. Bear and Fair Settime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve.It's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set: The elements of the set are distinct positive integers. The number of elements in the set is n. The number n is divisible by 5. All elements are between 1 and b, inclusive: bears don't know numbers greater than b. For each r in {0, 1, 2, 3, 4}, the set contains exactly elements that give remainder r when divided by 5. (That is, there are elements divisible by 5, elements of the form 5k + 1, elements of the form 5k + 2, and so on.) Limak smiles mysteriously and gives you q hints about his set. The i-th hint is the following sentence: "If you only look at elements that are between 1 and upToi, inclusive, you will find exactly quantityi such elements in my set."In a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear?Given n, b, q and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair". Otherwise, print ''unfair".InputThe first line contains three integers n, b and q (5 ≤ n ≤ b ≤ 104, 1 ≤ q ≤ 104, n divisible by 5) — the size of the set, the upper limit for numbers in the set and the number of hints.The next q lines describe the hints. The i-th of them contains two integers upToi and quantityi (1 ≤ upToi ≤ b, 0 ≤ quantityi ≤ n).OutputPrint ''fair" if there exists at least one set that has all the required properties and matches all the given hints. Otherwise, print ''unfair".ExamplesInput10 20 110 10OutputfairInput10 20 315 105 010 5OutputfairInput10 20 215 320 10OutputunfairNoteIn the first example there is only one set satisfying all conditions: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.In the second example also there is only one set satisfying all conditions: {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}.Easy to see that there is no set satisfying all conditions from the third example. So Limak lied to you :-( | Input10 20 110 10 | Outputfair | 2 seconds | 256 megabytes | ['flows', 'graphs', '*2500'] |
E. Zbazi in Zeydabadtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad).The country Zeydabad is a rectangular table consisting of n rows and m columns. Each cell on the country is either 'z' or '.'.The tourist knows this country is named Zeydabad because there are lots of ''Z-pattern"s in the country. A ''Z-pattern" is a square which anti-diagonal is completely filled with 'z' and its upper and lower rows are also completely filled with 'z'. All other cells of a square can be arbitrary. Note that a ''Z-pattern" can consist of only one cell (see the examples).So he wants to count the number of ''Z-pattern"s in the country (a necessary skill for Zbazi).Now your task is to help tourist with counting number of ''Z-pattern"s.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe first line contains two integers n, m (1 ≤ n, m ≤ 3000) — the number of rows and columns respectively.Each of the next n lines contains m characters 'z' or '.' — the description of Zeydabad.OutputPrint the only integer a — the number of ''Z-pattern"s in Zeydabad.ExamplesInput4 4zzzzzzz..z..zzzzOutput16Input1 4z.z.Output2Input2 2zzzzOutput5 | Input4 4zzzzzzz..z..zzzz | Output16 | 5 seconds | 512 megabytes | ['data structures', 'implementation', '*2300'] |
D. Magic Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).InputThe first line contains two integers m, d (1 ≤ m ≤ 2000, 0 ≤ d ≤ 9) — the parameters from the problem statement.The second line contains positive integer a in decimal presentation (without leading zeroes).The third line contains positive integer b in decimal presentation (without leading zeroes).It is guaranteed that a ≤ b, the number of digits in a and b are the same and don't exceed 2000.OutputPrint the only integer a — the remainder after dividing by 109 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.ExamplesInput2 61099Output8Input2 019Output4Input19 710009999Output6NoteThe numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.The numbers from the answer of the second example are 2, 4, 6 and 8.The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747. | Input2 61099 | Output8 | 2 seconds | 256 megabytes | ['dp', '*2200'] |
C. Bear and String Distancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 106).The second line contains a string s of length n, consisting of lowercase English letters.OutputIf there is no string satisfying the given conditions then print "-1" (without the quotes).Otherwise, print any nice string s' that .ExamplesInput4 26bearOutputroarInput2 7afOutputdbInput3 1000heyOutput-1 | Input4 26bear | Outputroar | 1 second | 256 megabytes | ['greedy', 'strings', '*1300'] |
B. New Skateboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMax wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.A substring of a string is a nonempty sequence of consecutive characters.For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe only line contains string s (1 ≤ |s| ≤ 3·105). The string s contains only digits from 0 to 9.OutputPrint integer a — the number of substrings of the string s that are divisible by 4.Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.ExamplesInput124Output4Input04Output3Input5810438174Output9 | Input124 | Output4 | 1 second | 256 megabytes | ['dp', '*1300'] |
Subsets and Splits