contestId
int64
0
1.01k
name
stringlengths
2
58
tags
listlengths
0
11
title
stringclasses
523 values
time-limit
stringclasses
8 values
memory-limit
stringclasses
8 values
problem-description
stringlengths
0
7.15k
input-specification
stringlengths
0
2.05k
output-specification
stringlengths
0
1.5k
demo-input
listlengths
0
7
demo-output
listlengths
0
7
note
stringlengths
0
5.24k
test_cases
listlengths
0
402
timeConsumedMillis
int64
0
8k
memoryConsumedBytes
int64
0
537M
score
float64
-1
3.99
__index_level_0__
int64
0
621k
3
Least Cost Bracket Sequence
[ "greedy" ]
D. Least Cost Bracket Sequence
1
64
This is yet another problem on regular bracket sequences. A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence. For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow *m* lines, where *m* is the number of characters "?" in the pattern. Each line contains two integer numbers *a**i* and *b**i* (1<=≤<=*a**i*,<=<=*b**i*<=≤<=106), where *a**i* is the cost of replacing the *i*-th character "?" with an opening bracket, and *b**i* — with a closing one.
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.
[ "(??)\n1 2\n2 8\n" ]
[ "4\n()()\n" ]
none
[ { "input": "(??)\n1 2\n2 8", "output": "4\n()()" }, { "input": "??\n1 1\n1 1", "output": "2\n()" }, { "input": "(???\n1 1\n1 1\n1 1", "output": "3\n(())" }, { "input": "(??)\n2 1\n1 1", "output": "2\n()()" }, { "input": "(???)?\n3 3\n3 1\n3 3\n2 3", "output": ...
124
0
0
17,575
912
Fishes
[ "data structures", "graphs", "greedy", "probabilities", "shortest paths" ]
null
null
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size *n*<=×<=*m*, divided into cells of size 1<=×<=1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!). The gift bundle also includes a square scoop of size *r*<=×<=*r*, designed for fishing. If the lower-left corner of the scoop-net is located at cell (*x*,<=*y*), all fishes inside the square (*x*,<=*y*)...(*x*<=+<=*r*<=-<=1,<=*y*<=+<=*r*<=-<=1) get caught. Note that the scoop-net should lie completely inside the pond when used. Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release *k* fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put *k* fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (*n*<=-<=*r*<=+<=1)·(*m*<=-<=*r*<=+<=1) possible positions, the average number of caught fishes is as high as possible.
The only line contains four integers *n*,<=*m*,<=*r*,<=*k* (1<=≤<=*n*,<=*m*<=≤<=105, 1<=≤<=*r*<=≤<=*min*(*n*,<=*m*), 1<=≤<=*k*<=≤<=*min*(*n*·*m*,<=105)).
Print a single number — the maximum possible expected number of caught fishes. You answer is considered correct, is its absolute or relative error does not exceed 10<=-<=9. Namely, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct, if .
[ "3 3 2 3\n", "12 17 9 40\n" ]
[ "2.0000000000\n", "32.8333333333\n" ]
In the first example you can put the fishes in cells (2, 1), (2, 2), (2, 3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value.
[ { "input": "3 3 2 3", "output": "2.0000000000" }, { "input": "12 17 9 40", "output": "32.8333333333" }, { "input": "1 1 1 1", "output": "1.0000000000" }, { "input": "10 10 5 100", "output": "25.0000000000" }, { "input": "7 1 1 4", "output": "0.5714285714" },...
217
6,348,800
3
17,592
71
Round Table Knights
[ "dp", "math", "number theory" ]
C. Round Table Knights
0
256
There are *n* knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood. Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes. A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated. On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
The first line contains number *n*, which is the number of knights at the round table (3<=≤<=*n*<=≤<=105). The second line contains space-separated moods of all the *n* knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.
Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".
[ "3\n1 1 1\n", "6\n1 0 1 1 1 0\n", "6\n1 0 0 1 0 1\n" ]
[ "YES", "YES", "NO" ]
none
[ { "input": "3\n1 1 1", "output": "YES" }, { "input": "6\n1 0 1 1 1 0", "output": "YES" }, { "input": "6\n1 0 0 1 0 1", "output": "NO" }, { "input": "10\n1 0 1 1 1 0 1 0 1 0", "output": "YES" }, { "input": "15\n0 0 0 1 0 1 1 0 1 0 0 1 0 1 0", "output": "YES" ...
61
2,867,200
-1
17,617
426
Sereja and Mirroring
[ "implementation" ]
null
null
Let's assume that we are given a matrix *b* of size *x*<=×<=*y*, let's determine the operation of mirroring matrix *b*. The mirroring of matrix *b* is a 2*x*<=×<=*y* matrix *c* which has the following properties: - the upper half of matrix *c* (rows with numbers from 1 to *x*) exactly matches *b*; - the lower half of matrix *c* (rows with numbers from *x*<=+<=1 to 2*x*) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows *x* and *x*<=+<=1). Sereja has an *n*<=×<=*m* matrix *a*. He wants to find such matrix *b*, that it can be transformed into matrix *a*, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
The first line contains two integers, *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). Each of the next *n* lines contains *m* integers — the elements of matrix *a*. The *i*-th line contains integers *a**i*1,<=*a**i*2,<=...,<=*a**im* (0<=≤<=*a**ij*<=≤<=1) — the *i*-th row of the matrix *a*.
In the single line, print the answer to the problem — the minimum number of rows of matrix *b*.
[ "4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1\n", "3 3\n0 0 0\n0 0 0\n0 0 0\n", "8 1\n0\n1\n1\n0\n0\n1\n1\n0\n" ]
[ "2\n", "3\n", "2\n" ]
In the first test sample the answer is a 2 × 3 matrix *b*: If we perform a mirroring operation with this matrix, we get the matrix *a* that is given in the input:
[ { "input": "4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "output": "2" }, { "input": "3 3\n0 0 0\n0 0 0\n0 0 0", "output": "3" }, { "input": "8 1\n0\n1\n1\n0\n0\n1\n1\n0", "output": "2" }, { "input": "10 4\n0 0 1 0\n0 0 1 0\n1 1 0 1\n0 0 1 1\n1 0 1 0\n1 0 1 0\n0 0 1 1\n1 1 0 1\n0 0 1 0\...
77
0
3
17,622
923
Perfect Security
[ "data structures", "greedy", "strings", "trees" ]
null
null
Alice has a very important message *M* consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key *K* of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message *A*. Alice is smart. Be like Alice. For example, Alice may have wanted to store a message *M*<==<=(0,<=15,<=9,<=18). She generated a key *K*<==<=(16,<=7,<=6,<=3). The encrypted message is thus *A*<==<=(16,<=8,<=15,<=17). Alice realised that she cannot store the key with the encrypted message. Alice sent her key *K* to Bob and deleted her own copy. Alice is smart. Really, be like Alice. Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob. In the above example, Bob may have, for instance, selected a permutation (3,<=4,<=1,<=2) and stored the permuted key *P*<==<=(6,<=3,<=16,<=7). One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart? Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message *A* and the permuted key *P*. What is the lexicographically smallest message that could have resulted in the given encrypted text? More precisely, for given *A* and *P*, find the lexicographically smallest message *O*, for which there exists a permutation π such that for every *i*. Note that the sequence *S* is lexicographically smaller than the sequence *T*, if there is an index *i* such that *S**i*<=&lt;<=*T**i* and for all *j*<=&lt;<=*i* the condition *S**j*<==<=*T**j* holds.
The first line contains a single integer *N* (1<=≤<=*N*<=≤<=300000), the length of the message. The second line contains *N* integers *A*1,<=*A*2,<=...,<=*A**N* (0<=≤<=*A**i*<=&lt;<=230) representing the encrypted message. The third line contains *N* integers *P*1,<=*P*2,<=...,<=*P**N* (0<=≤<=*P**i*<=&lt;<=230) representing the permuted encryption key.
Output a single line with *N* integers, the lexicographically smallest possible message *O*. Note that all its elements should be non-negative.
[ "3\n8 4 13\n17 2 7\n", "5\n12 7 87 22 11\n18 39 9 12 16\n", "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667\n" ]
[ "10 3 28\n", "0 14 69 6 44\n", "128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284\n" ]
In the first case, the solution is (10, 3, 28), since <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a896b30a69636d1bfbfa981eae10650f5fee843c.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e383e4333ea37c4652ce2ac1ccfc2cfcf96e0896.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c24ed3c6f88805eb3710487b3fe07ff64034151a.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
[ { "input": "3\n8 4 13\n17 2 7", "output": "10 3 28" }, { "input": "5\n12 7 87 22 11\n18 39 9 12 16", "output": "0 14 69 6 44" }, { "input": "10\n331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951\n226011312 266003835 342809544 504667531 529...
3,500
53,043,200
0
17,629
0
none
[ "none" ]
null
null
Вам задано прямоугольное клетчатое поле, состоящее из *n* строк и *m* столбцов. Поле содержит цикл из символов «*», такой что: - цикл можно обойти, посетив каждую его клетку ровно один раз, перемещаясь каждый раз вверх/вниз/вправо/влево на одну клетку; - цикл не содержит самопересечений и самокасаний, то есть две клетки цикла соседствуют по стороне тогда и только тогда, когда они соседние при перемещении вдоль цикла (самокасание по углу тоже запрещено). Ниже изображены несколько примеров допустимых циклов: Все клетки поля, отличные от цикла, содержат символ «.». Цикл на поле ровно один. Посещать клетки, отличные от цикла, Роботу нельзя. В одной из клеток цикла находится Робот. Эта клетка помечена символом «S». Найдите последовательность команд для Робота, чтобы обойти цикл. Каждая из четырёх возможных команд кодируется буквой и обозначает перемещение Робота на одну клетку: - «U» — сдвинуться на клетку вверх, - «R» — сдвинуться на клетку вправо, - «D» — сдвинуться на клетку вниз, - «L» — сдвинуться на клетку влево. Робот должен обойти цикл, побывав в каждой его клетке ровно один раз (кроме стартовой точки — в ней он начинает и заканчивает свой путь). Найдите искомую последовательность команд, допускается любое направление обхода цикла.
В первой строке входных данных записаны два целых числа *n* и *m* (3<=≤<=*n*,<=*m*<=≤<=100) — количество строк и столбцов прямоугольного клетчатого поля соответственно. В следующих *n* строках записаны по *m* символов, каждый из которых — «.», «*» или «S». Гарантируется, что отличные от «.» символы образуют цикл без самопересечений и самокасаний. Также гарантируется, что на поле ровно одна клетка содержит «S» и что она принадлежит циклу. Робот не может посещать клетки, помеченные символом «.».
В первую строку выходных данных выведите искомую последовательность команд для Робота. Направление обхода цикла Роботом может быть любым.
[ "3 3\n***\n*.*\n*S*\n", "6 7\n.***...\n.*.*...\n.*.S**.\n.*...**\n.*....*\n.******\n" ]
[ "LUURRDDL\n", "UULLDDDDDRRRRRUULULL\n" ]
В первом тестовом примере для обхода по часовой стрелке последовательность посещенных роботом клеток выглядит следующим образом: 1. клетка (3, 2); 1. клетка (3, 1); 1. клетка (2, 1); 1. клетка (1, 1); 1. клетка (1, 2); 1. клетка (1, 3); 1. клетка (2, 3); 1. клетка (3, 3); 1. клетка (3, 2).
[ { "input": "3 3\n***\n*.*\n*S*", "output": "LUURRDDL" }, { "input": "6 7\n.***...\n.*.*...\n.*.S**.\n.*...**\n.*....*\n.******", "output": "UULLDDDDDRRRRRUULULL" }, { "input": "100 3\n***\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\...
93
23,142,400
-1
17,644
86
Tetris revisited
[ "constructive algorithms", "graph matchings", "greedy", "math" ]
B. Tetris revisited
1
256
Physicist Woll likes to play one relaxing game in between his search of the theory of everything. Game interface consists of a rectangular *n*<=×<=*m* playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed. Woll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun. Every initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board. In the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.
First line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the height and the width of the field correspondingly. Next *n* lines contain *m* symbols each. They represent the field in a natural way: *j*-th character of the *i*-th line is "#" if the corresponding cell is filled, and "." if it is empty.
If there is no chance to win the game output the only number "-1" (without the quotes). Otherwise output any filling of the field by the figures in the following format: each figure should be represented by some digit and figures that touch each other by side should be represented by distinct digits. Every initially filled cell should be represented by "#".
[ "2 3\n...\n#.#\n", "3 3\n.#.\n...\n..#\n", "3 3\n...\n.##\n.#.\n", "1 2\n##\n" ]
[ "000\n#0#\n", "5#1\n511\n55#\n", "-1\n", "##\n" ]
In the third sample, there is no way to fill a cell with no empty neighbours. In the forth sample, Woll does not have to fill anything, so we should output the field from the input.
[]
31
0
0
17,678
0
none
[ "none" ]
null
null
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves long lucky numbers very much. He is interested in the minimum lucky number *d* that meets some condition. Let *cnt*(*x*) be the number of occurrences of number *x* in number *d* as a substring. For example, if *d*<==<=747747, then *cnt*(4)<==<=2, *cnt*(7)<==<=4, *cnt*(47)<==<=2, *cnt*(74)<==<=2. Petya wants the following condition to fulfil simultaneously: *cnt*(4)<==<=*a*1, *cnt*(7)<==<=*a*2, *cnt*(47)<==<=*a*3, *cnt*(74)<==<=*a*4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
The single line contains four integers *a*1, *a*2, *a*3 and *a*4 (1<=≤<=*a*1,<=*a*2,<=*a*3,<=*a*4<=≤<=106).
On the single line print without leading zeroes the answer to the problem — the minimum lucky number *d* such, that *cnt*(4)<==<=*a*1, *cnt*(7)<==<=*a*2, *cnt*(47)<==<=*a*3, *cnt*(74)<==<=*a*4. If such number does not exist, print the single number "-1" (without the quotes).
[ "2 2 1 1\n", "4 7 3 1\n" ]
[ "4774\n", "-1\n" ]
none
[ { "input": "2 2 1 1", "output": "4774" }, { "input": "4 7 3 1", "output": "-1" }, { "input": "4 7 4 7", "output": "-1" }, { "input": "1 1 1 1", "output": "-1" }, { "input": "2 2 1 2", "output": "7474" }, { "input": "2 1 2 1", "output": "-1" }, ...
218
307,200
0
17,687
13
Sequence
[ "dp", "sortings" ]
C. Sequence
1
64
Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of *N* integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help. The sequence *a* is called non-decreasing if *a*1<=≤<=*a*2<=≤<=...<=≤<=*a**N* holds, where *N* is the length of the sequence.
The first line of the input contains single integer *N* (1<=≤<=*N*<=≤<=5000) — the length of the initial sequence. The following *N* lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.
Output one integer — minimum number of steps required to achieve the goal.
[ "5\n3 2 -1 2 11\n", "5\n2 1 1 1 1\n" ]
[ "4\n", "1\n" ]
none
[ { "input": "5\n3 2 -1 2 11", "output": "4" }, { "input": "5\n2 1 1 1 1", "output": "1" }, { "input": "5\n0 0 0 0 0", "output": "0" }, { "input": "1\n11", "output": "0" }, { "input": "2\n10 2", "output": "8" }, { "input": "6\n1000000000 -1000000000 1000...
92
0
0
17,706
625
Finals in arithmetic
[ "constructive algorithms", "implementation", "math" ]
null
null
Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder. Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13. Oksana Fillipovna picked some number *a* without leading zeroes, and flipped it to get number *a**r*. Then she summed *a* and *a**r*, and told Vitya the resulting value *n*. His goal is to find any valid *a*. As Oksana Fillipovna picked some small integers as *a* and *a**r*, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given *n* finds any *a* without leading zeroes, such that *a*<=+<=*a**r*<==<=*n* or determine that such *a* doesn't exist.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=10100<=000).
If there is no such positive integer *a* without leading zeroes that *a*<=+<=*a**r*<==<=*n* then print 0. Otherwise, print any valid *a*. If there are many possible answers, you are allowed to pick any.
[ "4\n", "11\n", "5\n", "33\n" ]
[ "2\n", "10\n", "0\n", "21\n" ]
In the first sample 4 = 2 + 2, *a* = 2 is the only possibility. In the second sample 11 = 10 + 1, *a* = 10 — the only valid solution. Note, that *a* = 01 is incorrect, because *a* can't have leading zeroes. It's easy to check that there is no suitable *a* in the third sample. In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for *a*: *a* = 30, *a* = 12, *a* = 21. Any of these is considered to be correct answer.
[ { "input": "4", "output": "2" }, { "input": "11", "output": "10" }, { "input": "5", "output": "0" }, { "input": "33", "output": "21" }, { "input": "1", "output": "0" }, { "input": "99", "output": "54" }, { "input": "100", "output": "0" ...
2,000
1,331,200
0
17,708
711
ZS and The Birthday Paradox
[ "math", "number theory", "probabilities" ]
null
null
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland. In Udayland, there are 2*n* days in a year. ZS the Coder wants to interview *k* people from Udayland, each of them has birthday in one of 2*n* days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day. ZS the Coder knows that the answer can be written as an irreducible fraction . He wants to find the values of *A* and *B* (he does not like to deal with floating point numbers). Can you help him?
The first and only line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=1018,<=2<=≤<=*k*<=≤<=1018), meaning that there are 2*n* days in a year and that ZS the Coder wants to interview exactly *k* people.
If the probability of at least two *k* people having the same birthday in 2*n* days long year equals (*A*<=≥<=0, *B*<=≥<=1, ), print the *A* and *B* in a single line. Since these numbers may be too large, print them modulo 106<=+<=3. Note that *A* and *B* must be coprime before their remainders modulo 106<=+<=3 are taken.
[ "3 2\n", "1 3\n", "4 3\n" ]
[ "1 8", "1 1", "23 128" ]
In the first sample case, there are 2<sup class="upper-index">3</sup> = 8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5947a169159fe867f85f3fd8b9690019b48152f5.png" style="max-width: 100.0%;max-height: 100.0%;"/>, so *A* = 1, *B* = 8. In the second sample case, there are only 2<sup class="upper-index">1</sup> = 2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and *A* = *B* = 1.
[ { "input": "3 2", "output": "1 8" }, { "input": "1 3", "output": "1 1" }, { "input": "4 3", "output": "23 128" }, { "input": "1000000000000000000 1000000000000000000", "output": "906300 906300" }, { "input": "59 576460752303423489", "output": "1 1" }, { ...
514
61,440,000
0
17,712
325
The Red Button
[ "combinatorics", "dfs and similar", "dsu", "graphs", "greedy" ]
null
null
Piegirl found the red button. You have one last chance to change the inevitable end. The circuit under the button consists of *n* nodes, numbered from 0 to *n* - 1. In order to deactivate the button, the *n* nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node *i*, the next node to be disarmed must be either node (2·*i*) modulo *n* or node (2·*i*)<=+<=1 modulo *n*. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once. Your task is to find any such order and print it. If there is no such order, print -1.
Input consists of a single integer *n* (2<=≤<=*n*<=≤<=105).
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
[ "2\n", "3\n", "4\n", "16\n" ]
[ "0 1 0\n", "-1", "0 1 3 2 0\n", "0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0\n" ]
none
[ { "input": "2", "output": "0 1 0" }, { "input": "3", "output": "-1" }, { "input": "4", "output": "0 1 3 2 0" }, { "input": "16", "output": "0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0" }, { "input": "5", "output": "-1" }, { "input": "7", "output": "-1"...
60
0
0
17,719
467
Alex and Complicated Task
[ "data structures", "dp", "greedy" ]
null
null
After you have read all the problems, probably, you think Alex is genius person. That's true! One day he came up with the following task. Given a sequence of integer numbers *a*1,<=*a*2,<=...,<=*a**n*. You are to find a longest sequence *b*1,<=*b*2,<=...,<=*b*4*m*, that satisfies the following conditions: - *b*4*k*<=+<=1<==<=*b*4*k*<=+<=3 for all valid integer *k*; - *b*4*k*<=+<=2<==<=*b*4*k*<=+<=4 for all valid integer *k*; - sequence *b* is subsequence of *a* (not necessarily contiguous subsequence). And finally... Alex had given this complicated task to George, and George gave it to you. Help George to cope with the task.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=5·105). The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
In the first line print a single integer 4*m* — the maximal possible length of required sequence *b*. In the second line print 4*m* integers *b*1,<=*b*2,<=...,<=*b*4*m*, that is required sequence. If there are multiple optimal answers you may print any of them.
[ "4\n3 5 3 5\n", "10\n35 1 2 1 2 35 100 200 100 200\n" ]
[ "4\n3 5 3 5\n", "8\n1 2 1 2 100 200 100 200\n" ]
none
[ { "input": "4\n3 5 3 5", "output": "4\n3 5 3 5" }, { "input": "10\n35 1 2 1 2 35 100 200 100 200", "output": "8\n1 2 1 2 100 200 100 200" }, { "input": "9\n20 12 9 8 13 7 4 9 8", "output": "4\n9 8 9 8" }, { "input": "14\n15 11 1 16 12 10 8 2 13 14 10 8 2 18", "output": "4...
61
2,867,200
-1
17,766
1,007
Pave the Parallelepiped
[ "bitmasks", "brute force", "combinatorics", "math", "number theory" ]
null
null
You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$. Find the number of different groups of three integers ($a$, $b$, $c$) such that $1\leq a\leq b\leq c$ and parallelepiped $A\times B\times C$ can be paved with parallelepipeds $a\times b\times c$. Note, that all small parallelepipeds have to be rotated in the same direction. For example, parallelepiped $1\times 5\times 6$ can be divided into parallelepipeds $1\times 3\times 5$, but can not be divided into parallelepipeds $1\times 2\times 3$.
The first line contains a single integer $t$ ($1 \leq t \leq 10^5$) — the number of test cases. Each of the next $t$ lines contains three integers $A$, $B$ and $C$ ($1 \leq A, B, C \leq 10^5$) — the sizes of the parallelepiped.
For each test case, print the number of different groups of three points that satisfy all given conditions.
[ "4\n1 1 1\n1 6 1\n2 2 2\n100 100 100\n" ]
[ "1\n4\n4\n165\n" ]
In the first test case, rectangular parallelepiped $(1, 1, 1)$ can be only divided into rectangular parallelepiped with sizes $(1, 1, 1)$. In the second test case, rectangular parallelepiped $(1, 6, 1)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 1, 3)$ and $(1, 1, 6)$. In the third test case, rectangular parallelepiped $(2, 2, 2)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 2, 2)$ and $(2, 2, 2)$.
[ { "input": "4\n1 1 1\n1 6 1\n2 2 2\n100 100 100", "output": "1\n4\n4\n165" }, { "input": "10\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1", "output": "1\n1\n1\n1\n1\n1\n1\n1\n1\n1" }, { "input": "10\n9 6 8\n5 5 2\n8 9 2\n2 7 9\n6 4 10\n1 1 8\n2 8 1\n10 6 3\n7 5 2...
998
8,396,800
3
17,828
725
Family Photos
[ "games", "greedy" ]
null
null
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are *n* stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks. Each photo is described by two non-negative integers *a* and *b*, indicating that it is worth *a* units of happiness to Alice and *b* units of happiness to Bonnie. Values of *a* and *b* might differ for different photos. It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively. The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has *x* happiness and Bonnie has *y* happiness at the end, you should print *x*<=-<=*y*.
The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of two-photo stacks. Then follow *n* lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers *a*1, *b*1, *a*2 and *b*2, each not exceeding 109. *a*1 and *b*1 describe the top photo in the stack, while *a*2 and *b*2 describe the bottom photo in the stack.
Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.
[ "2\n12 3 4 7\n1 15 9 1\n", "2\n5 4 8 8\n4 12 14 0\n", "1\n0 10 0 10\n" ]
[ "1\n", "4\n", "-10\n" ]
none
[ { "input": "2\n12 3 4 7\n1 15 9 1", "output": "1" }, { "input": "2\n5 4 8 8\n4 12 14 0", "output": "4" }, { "input": "1\n0 10 0 10", "output": "-10" }, { "input": "10\n0 1000000000 0 1000000000\n0 1000000000 0 1000000000\n0 1000000000 0 1000000000\n0 1000000000 0 1000000000\n...
421
6,246,400
3
17,865
271
Prime Matrix
[ "binary search", "brute force", "math", "number theory" ]
null
null
You've got an *n*<=×<=*m* matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: - the matrix has a row with prime numbers only; - the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=500) — the number of rows and columns in the matrix, correspondingly. Each of the following *n* lines contains *m* integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
[ "3 3\n1 2 3\n5 6 1\n4 4 1\n", "2 3\n4 8 8\n9 2 9\n", "2 2\n1 3\n4 2\n" ]
[ "1\n", "3\n", "0\n" ]
In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
[ { "input": "3 3\n1 2 3\n5 6 1\n4 4 1", "output": "1" }, { "input": "2 3\n4 8 8\n9 2 9", "output": "3" }, { "input": "2 2\n1 3\n4 2", "output": "0" }, { "input": "1 1\n14", "output": "3" }, { "input": "5 3\n2 14 8\n8 8 2\n8 10 10\n1 2 1\n100 100 8", "output": "...
2,000
13,619,200
0
17,879
49
Sum
[ "math" ]
B. Sum
2
256
Vasya studies positional numeral systems. Unfortunately, he often forgets to write the base of notation in which the expression is written. Once he saw a note in his notebook saying *a*<=+<=*b*<==<=?, and that the base of the positional notation wasn’t written anywhere. Now Vasya has to choose a base *p* and regard the expression as written in the base *p* positional notation. Vasya understood that he can get different results with different bases, and some bases are even invalid. For example, expression 78<=+<=87 in the base 16 positional notation is equal to *FF*16, in the base 15 positional notation it is equal to 11015, in the base 10 one — to 16510, in the base 9 one — to 1769, and in the base 8 or lesser-based positional notations the expression is invalid as all the numbers should be strictly less than the positional notation base. Vasya got interested in what is the length of the longest possible expression value. Help him to find this length. The length of a number should be understood as the number of numeric characters in it. For example, the length of the longest answer for 78<=+<=87<==<=? is 3. It is calculated like that in the base 15 (11015), base 10 (16510), base 9 (1769) positional notations, for example, and in some other ones.
The first letter contains two space-separated numbers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=1000) which represent the given summands.
Print a single number — the length of the longest answer.
[ "78 87\n", "1 1\n" ]
[ "3\n", "2\n" ]
none
[ { "input": "78 87", "output": "3" }, { "input": "1 1", "output": "2" }, { "input": "9 7", "output": "2" }, { "input": "11 11", "output": "3" }, { "input": "43 21", "output": "3" }, { "input": "84 89", "output": "3" }, { "input": "12 34", ...
154
0
3.9615
17,945
729
Subordinates
[ "constructive algorithms", "data structures", "graphs", "greedy", "sortings" ]
null
null
There are *n* workers in a company, each of them has a unique id from 1 to *n*. Exaclty one of them is a chief, his id is *s*. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself. Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.
The first line contains two positive integers *n* and *s* (1<=≤<=*n*<=≤<=2·105, 1<=≤<=*s*<=≤<=*n*) — the number of workers and the id of the chief. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=*n*<=-<=1), where *a**i* is the number of superiors (not only immediate) the worker with id *i* reported about.
Print the minimum number of workers that could make a mistake.
[ "3 2\n2 0 2\n", "5 3\n1 0 0 4 1\n" ]
[ "1\n", "2\n" ]
In the first example it is possible that only the first worker made a mistake. Then: - the immediate superior of the first worker is the second worker, - the immediate superior of the third worker is the first worker, - the second worker is the chief.
[ { "input": "3 2\n2 0 2", "output": "1" }, { "input": "5 3\n1 0 0 4 1", "output": "2" }, { "input": "1 1\n0", "output": "0" }, { "input": "2 1\n0 0", "output": "1" }, { "input": "2 1\n0 1", "output": "0" }, { "input": "2 1\n1 0", "output": "2" }, ...
62
0
0
17,960
592
BCPC
[ "binary search", "geometry", "two pointers" ]
null
null
BCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces. BCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team. In BSU there are *n* students numbered from 1 to *n*. Since all BSU students are infinitely smart, the only important parameters for Blenda are their reading and writing speed. After a careful measuring, Blenda have found that the *i*-th student have a reading speed equal to *r**i* (words per minute), and a writing speed of *w**i* (symbols per minute). Since BSU students are very smart, the measured speeds are sometimes very big and Blenda have decided to subtract some constant value *c* from all the values of reading speed and some value *d* from all the values of writing speed. Therefore she considers *r**i*'<==<=*r**i*<=-<=*c* and *w**i*'<==<=*w**i*<=-<=*d*. The student *i* is said to overwhelm the student *j* if and only if *r**i*'·*w**j*'<=&gt;<=*r**j*'·*w**i*'. Blenda doesn’t like fights in teams, so she thinks that a team consisting of three distinct students *i*,<=*j* and *k* is good if *i* overwhelms *j*, *j* overwhelms *k*, and *k* overwhelms *i*. Yes, the relation of overwhelming is not transitive as it often happens in real life. Since Blenda is busy preparing a training camp in Codeforces, you are given a task to calculate the number of different good teams in BSU. Two teams are considered to be different if there is at least one student that is present in one team but is not present in the other. In other words, two teams are different if the sets of students that form these teams are different.
In the first line of the input three integers *n*, *c* and *d* (3<=≤<=*n*<=≤<=345678,<=1<=≤<=*c*,<=*d*<=≤<=109) are written. They denote the number of students Blenda can use to form teams, the value subtracted from all reading speeds and the value subtracted from all writing speeds respectively. Each of the next *n* lines contains two integers *r**i* and *w**i* (0<=&lt;<=*r**i*,<=*w**i*<=≤<=109,<=|*r**i*<=-<=*c*|<=+<=|*w**i*<=-<=*d*|<=&gt;<=0). There are no two students, such that both their reading and writing speeds coincide, i.e. for every *i*<=≠<=*j* condition |*r**i*<=-<=*r**j*|<=+<=|*w**i*<=-<=*w**j*|<=&gt;<=0 holds.
Print the number of different teams in BSU, that are good according to Blenda's definition.
[ "5 2 2\n1 1\n4 1\n2 3\n3 2\n3 4\n", "7 6 6\n3 2\n1 7\n5 7\n3 7\n6 4\n8 9\n8 5\n" ]
[ "4\n", "11\n" ]
In the first sample the following teams are good: (*i* = 1, *j* = 2, *k* = 3), (*i* = 2, *j* = 5, *k* = 1), (*i* = 1, *j* = 4, *k* = 3), (*i* = 5, *j* = 1, *k* = 4). Note, that for example the team (*i* = 3, *j* = 1, *k* = 2) is also good, but is considered to be the same as the team (*i* = 1, *j* = 2, *k* = 3).
[]
4,000
307,200
0
17,982
709
Checkpoints
[ "greedy", "implementation", "sortings" ]
null
null
Vasya takes part in the orienteering competition. There are *n* checkpoints located along the line at coordinates *x*1,<=*x*2,<=...,<=*x**n*. Vasya starts at the point with coordinate *a*. His goal is to visit at least *n*<=-<=1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order. Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
The first line of the input contains two integers *n* and *a* (1<=≤<=*n*<=≤<=100<=000, <=-<=1<=000<=000<=≤<=*a*<=≤<=1<=000<=000) — the number of checkpoints and Vasya's starting position respectively. The second line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=1<=000<=000<=≤<=*x**i*<=≤<=1<=000<=000) — coordinates of the checkpoints.
Print one integer — the minimum distance Vasya has to travel in order to visit at least *n*<=-<=1 checkpoint.
[ "3 10\n1 7 12\n", "2 0\n11 -10\n", "5 0\n0 0 1000 0 0\n" ]
[ "7\n", "10\n", "0\n" ]
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7. In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point  - 10.
[ { "input": "3 10\n1 7 12", "output": "7" }, { "input": "2 0\n11 -10", "output": "10" }, { "input": "5 0\n0 0 1000 0 0", "output": "0" }, { "input": "1 0\n0", "output": "0" }, { "input": "2 1\n4 -8", "output": "3" }, { "input": "3 4\n4 2 4", "output...
109
7,372,800
3
18,063
132
Logo Turtle
[ "dp" ]
null
null
A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward"). You are given a list of commands that will be given to the turtle. You have to change exactly *n* commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows all the commands of the modified list?
The first line of input contains a string *commands* — the original list of commands. The string *commands* contains between 1 and 100 characters, inclusive, and contains only characters "T" and "F". The second line contains an integer *n* (1<=≤<=*n*<=≤<=50) — the number of commands you have to change in the list.
Output the maximum distance from the starting point to the ending point of the turtle's path. The ending point of the turtle's path is turtle's coordinate after it follows all the commands of the modified list.
[ "FT\n1\n", "FFFTFFF\n2\n" ]
[ "2\n", "6\n" ]
In the first example the best option is to change the second command ("T") to "F" — this way the turtle will cover a distance of 2 units. In the second example you have to change two commands. One of the ways to cover maximal distance of 6 units is to change the fourth command and first or last one.
[ { "input": "FT\n1", "output": "2" }, { "input": "FFFTFFF\n2", "output": "6" }, { "input": "F\n1", "output": "0" }, { "input": "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n50", "output": "100" }, { "input": ...
216
204,800
0
18,084
582
Number of Binominal Coefficients
[ "dp", "math", "number theory" ]
null
null
For a given prime integer *p* and integers α,<=*A* calculate the number of pairs of integers (*n*,<=*k*), such that 0<=≤<=*k*<=≤<=*n*<=≤<=*A* and is divisible by *p*α. As the answer can be rather large, print the remainder of the answer moduly 109<=+<=7. Let us remind you that is the number of ways *k* objects can be chosen from the set of *n* objects.
The first line contains two integers, *p* and α (1<=≤<=*p*,<=α<=≤<=109, *p* is prime). The second line contains the decimal record of integer *A* (0<=≤<=*A*<=&lt;<=101000) without leading zeroes.
In the single line print the answer to the problem.
[ "2 2\n7\n", "3 1\n9\n", "3 3\n9\n", "2 4\n5000\n" ]
[ "3\n", "17\n", "0\n", "8576851\n" ]
In the first sample three binominal coefficients divisible by 4 are <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a4c2b94fb12d1298dafcd1d14d7e1f6a47500264.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/80436d3bb1008bf8943b41f46211501e7fea05e9.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bb01b873c593007ca5b10a8897a71c4b0d7dabae.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[]
483
268,390,400
0
18,149
242
XOR on Segment
[ "bitmasks", "data structures" ]
null
null
You've got an array *a*, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. You are allowed to perform two operations on this array: 1. Calculate the sum of current array elements on the segment [*l*,<=*r*], that is, count value *a**l*<=+<=*a**l*<=+<=1<=+<=...<=+<=*a**r*. 1. Apply the xor operation with a given number *x* to each array element on the segment [*l*,<=*r*], that is, execute . This operation changes exactly *r*<=-<=*l*<=+<=1 array elements. Expression means applying bitwise xor operation to numbers *x* and *y*. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor". You've got a list of *m* operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the size of the array. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106) — the original array. The third line contains integer *m* (1<=≤<=*m*<=≤<=5·104) — the number of operations with the array. The *i*-th of the following *m* lines first contains an integer *t**i* (1<=≤<=*t**i*<=≤<=2) — the type of the *i*-th query. If *t**i*<==<=1, then this is the query of the sum, if *t**i*<==<=2, then this is the query to change array elements. If the *i*-th operation is of type 1, then next follow two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). If the *i*-th operation is of type 2, then next follow three integers *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*x**i*<=≤<=106). The numbers on the lines are separated by single spaces.
For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier.
[ "5\n4 10 3 13 7\n8\n1 2 4\n2 1 3 3\n1 2 4\n1 3 3\n2 2 5 5\n1 1 5\n2 1 2 10\n1 2 3\n", "6\n4 7 4 0 7 3\n5\n2 2 3 8\n1 1 5\n2 3 5 1\n2 4 5 6\n1 2 3\n" ]
[ "26\n22\n0\n34\n11\n", "38\n28\n" ]
none
[]
186
4,710,400
-1
18,182
992
Nastya and a Wardrobe
[ "math" ]
null
null
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month). Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year. Nastya owns *x* dresses now, so she became interested in the [expected number](https://en.wikipedia.org/wiki/Expected_value) of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for *k*<=+<=1 months. Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 109<=+<=7, because it is easy to see that it is always integer.
The only line contains two integers *x* and *k* (0<=≤<=*x*,<=*k*<=≤<=1018), where *x* is the initial number of dresses and *k*<=+<=1 is the number of months in a year in Byteland.
In the only line print a single integer — the expected number of dresses Nastya will own one year later modulo 109<=+<=7.
[ "2 0\n", "2 1\n", "3 2\n" ]
[ "4\n", "7\n", "21\n" ]
In the first example a year consists on only one month, so the wardrobe does not eat dresses at all. In the second example after the first month there are 3 dresses with 50% probability and 4 dresses with 50% probability. Thus, in the end of the year there are 6 dresses with 50% probability and 8 dresses with 50% probability. This way the answer for this test is (6 + 8) / 2 = 7.
[ { "input": "2 0", "output": "4" }, { "input": "2 1", "output": "7" }, { "input": "3 2", "output": "21" }, { "input": "1 411", "output": "485514976" }, { "input": "1 692", "output": "860080936" }, { "input": "16 8", "output": "7937" }, { "in...
93
0
0
18,193
332
Theft of Blueprints
[ "graphs", "math" ]
null
null
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of *n* missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos *i* and *j* is patrolled by *c**i*,<=*j* war droids. The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any *k*-element set of silos *S* there is exactly one silo that is directly connected by a passage with each silo from *S* (we'll call this silo adjacent with *S*). Having considered that, the insurgents decided to act as follows: 1. they choose a *k*-element set of silos *S*; 1. a group of scouts lands from the air into each silo from *S*; 1. each group moves along the corresponding passage to the silo, adjacent with *S* (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); 1. in the silo, adjacent with *S*, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set *S*. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set *S*. Solve this problem to help the insurgents protect the ideals of the Republic!
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=2000, 1<=≤<=*k*<=≤<=*n*<=-<=1) — the number of silos and the number of scout groups, correspondingly. The next *n*<=-<=1 lines describe the polygon plan: the *i*-th of these lines contains *n*<=-<=*i* integers *c**i*,<=*i*<=+<=1,<=*c**i*,<=*i*<=+<=2,<=...,<=*c**i*,<=*n* — the number of droids that patrol the corresponding passages (-1<=≤<=*c**i*,<=*j*<=≤<=109; if *c**i*,<=*j*<==<= -1, then silos *i* and *j* don't have a passage between them). All passages are bidirectional, that is, we can assume that *c**i*,<=*j*<==<=*c**j*,<=*i*. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
[ "6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1\n", "3 2\n10 0\n11\n" ]
[ "5\n", "14\n" ]
In the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3bc833659595c25e73150ed7f23907011961ceca.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/02946ba8c525c97041629189ab4acc976074d8d1.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "output": "5" }, { "input": "3 2\n10 0\n11", "output": "14" }, { "input": "4 3\n15 1 3\n5 8\n9", "output": "20" }, { "input": "5 2\n-1 -1 14 3\n19 -1 1\n-1 6\n0", "output": "10" }, { "input": "10 9\n...
1,558
268,390,400
0
18,224
698
Fix a Tree
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "trees" ]
null
null
A tree is an undirected connected graph without cycles. Let's consider a rooted undirected tree with *n* vertices, numbered 1 through *n*. There are many ways to represent such a tree. One way is to create an array with *n* integers *p*1,<=*p*2,<=...,<=*p**n*, where *p**i* denotes a parent of vertex *i* (here, for convenience a root is considered its own parent). Given a sequence *p*1,<=*p*2,<=...,<=*p**n*, one is able to restore a tree: 1. There must be exactly one index *r* that *p**r*<==<=*r*. A vertex *r* is a root of the tree. 1. For all other *n*<=-<=1 vertices *i*, there is an edge between vertex *i* and vertex *p**i*. A sequence *p*1,<=*p*2,<=...,<=*p**n* is called valid if the described procedure generates some (any) rooted tree. For example, for *n*<==<=3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid. You are given a sequence *a*1,<=*a*2,<=...,<=*a**n*, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
The first line of the input contains an integer *n* (2<=≤<=*n*<=≤<=200<=000) — the number of vertices in the tree. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*).
In the first line print the minimum number of elements to change, in order to get a valid sequence. In the second line, print any valid sequence possible to get from (*a*1,<=*a*2,<=...,<=*a**n*) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
[ "4\n2 3 3 4\n", "5\n3 2 2 5 3\n", "8\n2 3 5 4 1 6 6 7\n" ]
[ "1\n2 3 4 4 \n", "0\n3 2 2 5 3 \n", "2\n2 3 7 8 1 6 6 7\n" ]
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because *p*<sub class="lower-index">4</sub> = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red. In the second sample, the given sequence is already valid.
[ { "input": "4\n2 3 3 4", "output": "1\n2 3 4 4 " }, { "input": "5\n3 2 2 5 3", "output": "0\n3 2 2 5 3 " }, { "input": "8\n2 3 5 4 1 6 6 7", "output": "2\n2 3 7 8 1 6 6 7" }, { "input": "2\n1 2", "output": "1\n2 2 " }, { "input": "7\n4 3 2 6 3 5 2", "output": ...
62
0
0
18,244
379
New Year Tree Decorations
[ "geometry", "schedules", "sortings" ]
null
null
Due to atheistic Soviet past, Christmas wasn't officially celebrated in Russia for most of the twentieth century. As a result, the Russian traditions for Christmas and New Year mixed into one event celebrated on the New Year but including the tree, a Santa-like 'Grandfather Frost', presents and huge family reunions and dinner parties all over the country. Bying a Tree at the New Year and installing it in the house is a tradition. Usually the whole family decorates the tree on the New Year Eve. We hope that Codeforces is a big and loving family, so in this problem we are going to decorate a tree as well. So, our decoration consists of *n* pieces, each piece is a piece of colored paper, its border is a closed polyline of a special shape. The pieces go one by one as is shown on the picture. The *i*-th piece is a polyline that goes through points: (0,<=0), (0,<=*y*0), (1,<=*y*1), (2,<=*y*2), ..., (*k*,<=*y**k*), (*k*,<=0). The width of each piece equals *k*. The piece number 1 (shown red on the figure) is the outer piece (we see it completely), piece number 2 (shown yellow) follows it (we don't see it completely as it is partially closed by the first piece) and so on. The programmers are quite curious guys, so the moment we hung a decoration on the New Year tree we started to wonder: what area of each piece can people see?
The first line contains two integers, *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=300). Each of the following *n* lines contains *k*<=+<=1 integers — the description of the polyline. If the *i*-th line contains ontegers *y**i*,<=0,<=*y**i*,<=1,<=...,<=*y**i*,<=*k*, that means that the polyline of the *i*-th piece goes through points (0,<=0), (0,<=*y**i*,<=0), (1,<=*y**i*,<=1), (2,<=*y**i*,<=2), ..., (*k*,<=*y**i*,<=*k*), (*k*,<=0) (1<=≤<=*y**i*,<=*j*<=≤<=1000).
Print *n* real numbers — for each polyline, the area of its visible part. The answer will be considered correct if its relative or absolute error do not exceed 10<=-<=4.
[ "2 2\n2 1 2\n1 2 1\n", "1 1\n1 1\n", "4 1\n2 7\n7 2\n5 5\n6 4\n" ]
[ "3.000000000000\n0.500000000000\n", "1.000000000000\n", "4.500000000000\n1.250000000000\n0.050000000000\n0.016666666667\n" ]
none
[]
46
0
0
18,247
915
Coprime Arrays
[ "math", "number theory" ]
null
null
Let's call an array *a* of size *n* coprime iff *gcd*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1, where *gcd* is the greatest common divisor of the arguments. You are given two numbers *n* and *k*. For each *i* (1<=≤<=*i*<=≤<=*k*) you have to determine the number of coprime arrays *a* of size *n* such that for every *j* (1<=≤<=*j*<=≤<=*n*) 1<=≤<=*a**j*<=≤<=*i*. Since the answers can be very large, you have to calculate them modulo 109<=+<=7.
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=2·106) — the size of the desired arrays and the maximum upper bound on elements, respectively.
Since printing 2·106 numbers may take a lot of time, you have to output the answer in such a way: Let *b**i* be the number of coprime arrays with elements in range [1,<=*i*], taken modulo 109<=+<=7. You have to print , taken modulo 109<=+<=7. Here denotes bitwise xor operation (^ in C++ or Java, xor in Pascal).
[ "3 4\n", "2000000 8\n" ]
[ "82\n", "339310063\n" ]
Explanation of the example: Since the number of coprime arrays is large, we will list the arrays that are non-coprime, but contain only elements in range [1, *i*]: For *i* = 1, the only array is coprime. *b*<sub class="lower-index">1</sub> = 1. For *i* = 2, array [2, 2, 2] is not coprime. *b*<sub class="lower-index">2</sub> = 7. For *i* = 3, arrays [2, 2, 2] and [3, 3, 3] are not coprime. *b*<sub class="lower-index">3</sub> = 25. For *i* = 4, arrays [2, 2, 2], [3, 3, 3], [2, 2, 4], [2, 4, 2], [2, 4, 4], [4, 2, 2], [4, 2, 4], [4, 4, 2] and [4, 4, 4] are not coprime. *b*<sub class="lower-index">4</sub> = 55.
[ { "input": "3 4", "output": "82" }, { "input": "2000000 8", "output": "339310063" }, { "input": "1000 1000", "output": "293255159" }, { "input": "400000 400000", "output": "641589365" }, { "input": "1000 2000", "output": "946090030" }, { "input": "4000...
46
0
0
18,261
993
Nikita and Order Statistics
[ "chinese remainder theorem", "fft", "math" ]
null
null
Nikita likes tasks on order statistics, for example, he can easily find the $k$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $x$ is the $k$-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly $k$ numbers of this segment which are less than $x$. Nikita wants to get answer for this question for each $k$ from $0$ to $n$, where $n$ is the size of the array.
The first line contains two integers $n$ and $x$ $(1 \le n \le 2 \cdot 10^5, -10^9 \le x \le 10^9)$. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(-10^9 \le a_i \le 10^9)$ — the given array.
Print $n+1$ integers, where the $i$-th number is the answer for Nikita's question for $k=i-1$.
[ "5 3\n1 2 3 4 5\n", "2 6\n-5 9\n", "6 99\n-1 -1 -1 -1 -1 -1\n" ]
[ "6 5 4 0 0 0 ", "1 2 0 ", "0 6 5 4 3 2 1 " ]
none
[ { "input": "5 3\n1 2 3 4 5", "output": "6 5 4 0 0 0 " }, { "input": "2 6\n-5 9", "output": "1 2 0 " }, { "input": "6 99\n-1 -1 -1 -1 -1 -1", "output": "0 6 5 4 3 2 1 " }, { "input": "5 -2\n-1 -1 -4 -5 1", "output": "4 5 6 0 0 0 " }, { "input": "5 -6\n-4 2 -7 -1 -5...
30
0
0
18,273
853
Michael and Charging Stations
[ "binary search", "dp", "greedy" ]
null
null
Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs. Michael's day starts from charging his electric car for getting to the work and back. He spends 1000 burles on charge if he goes to the first job, and 2000 burles if he goes to the second job. On a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of *x* burles, he is allowed to pay an amount of *y* (0<=≤<=*y*<=≤<=*x*) burles that does not exceed the bonus card balance with bonus burles. In this case he pays *x*<=-<=*y* burles with cash, and the balance on the bonus card is decreased by *y* bonus burles. If customer pays whole price with cash (i.e., *y*<==<=0) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by bonus burles. Initially the bonus card balance is equal to 0 bonus burles. Michael has planned next *n* days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.
The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=300<=000), the number of days Michael has planned. Next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=1000 or *a**i*<==<=2000) with *a**i* denoting the charging cost at the day *i*.
Output the minimum amount of burles Michael has to spend.
[ "3\n1000 2000 1000\n", "6\n2000 2000 2000 2000 2000 1000\n" ]
[ "3700\n", "10000\n" ]
In the first sample case the most optimal way for Michael is to pay for the first two days spending 3000 burles and get 300 bonus burles as return. After that he is able to pay only 700 burles for the third days, covering the rest of the price with bonus burles. In the second sample case the most optimal way for Michael is to pay the whole price for the first five days, getting 1000 bonus burles as return and being able to use them on the last day without paying anything in cash.
[]
202
15,462,400
0
18,305
1,004
Sonya and Matrix
[ "brute force", "constructive algorithms", "implementation" ]
null
null
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit. Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so. The Manhattan distance between two cells ($x_1$, $y_1$) and ($x_2$, $y_2$) is defined as $|x_1 - x_2| + |y_1 - y_2|$. For example, the Manhattan distance between the cells $(5, 2)$ and $(7, 1)$ equals to $|5-7|+|2-1|=3$. Note that rhombic matrices are uniquely defined by $n$, $m$, and the coordinates of the cell containing the zero. She drew a $n\times m$ rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of $n\cdot m$ numbers). Note that Sonya will not give you $n$ and $m$, so only the sequence of numbers in this matrix will be at your disposal. Write a program that finds such an $n\times m$ rhombic matrix whose elements are the same as the elements in the sequence in some order.
The first line contains a single integer $t$ ($1\leq t\leq 10^6$) — the number of cells in the matrix. The second line contains $t$ integers $a_1, a_2, \ldots, a_t$ ($0\leq a_i&lt; t$) — the values in the cells in arbitrary order.
In the first line, print two positive integers $n$ and $m$ ($n \times m = t$) — the size of the matrix. In the second line, print two integers $x$ and $y$ ($1\leq x\leq n$, $1\leq y\leq m$) — the row number and the column number where the cell with $0$ is located. If there are multiple possible answers, print any of them. If there is no solution, print the single integer $-1$.
[ "20\n1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4\n", "18\n2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1\n", "6\n2 1 0 2 1 2\n" ]
[ "4 5\n2 2\n", "3 6\n2 3\n", "-1\n" ]
You can see the solution to the first example in the legend. You also can choose the cell $(2, 2)$ for the cell where $0$ is located. You also can choose a $5\times 4$ matrix with zero at $(4, 2)$. In the second example, there is a $3\times 6$ matrix, where the zero is located at $(2, 3)$ there. In the third example, a solution does not exist.
[ { "input": "20\n1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4", "output": "4 5\n2 2" }, { "input": "18\n2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1", "output": "3 6\n2 3" }, { "input": "6\n2 1 0 2 1 2", "output": "-1" }, { "input": "1\n0", "output": "1 1\n1 1" }, { "input": "7\...
2,000
62,464,000
0
18,327
731
Funny Game
[ "dp", "games" ]
null
null
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them. The game they came up with has the following rules. Initially, there are *n* stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first. One move happens as follows. Lets say there are *m*<=≥<=2 stickers on the wall. The player, who makes the current move, picks some integer *k* from 2 to *m* and takes *k* leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent. Given the integer *n* and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
The first line of input contains a single integer *n* (2<=≤<=*n*<=≤<=200<=000) — the number of stickers, initially located on the wall. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (<=-<=10<=000<=≤<=*a**i*<=≤<=10<=000) — the numbers on stickers in order from left to right.
Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
[ "3\n2 4 8\n", "4\n1 -7 -2 3\n" ]
[ "14\n", "-3\n" ]
In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0. In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value  - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) =  - 8, Gena's score is ( - 8) + 3 =  - 5, i.e. the score difference will be  - 3.
[ { "input": "3\n2 4 8", "output": "14" }, { "input": "4\n1 -7 -2 3", "output": "-3" }, { "input": "10\n35 11 35 28 48 25 2 43 23 10", "output": "260" }, { "input": "100\n437 89 481 95 29 326 10 304 97 414 52 46 106 181 385 173 337 148 437 133 52 136 86 250 289 61 480 314 166 6...
31
0
0
18,370
374
Inna and Pink Pony
[ "greedy", "implementation" ]
null
null
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an *n*<=×<=*m* chessboard, a very tasty candy and two numbers *a* and *b*. Dima put the chessboard in front of Inna and placed the candy in position (*i*,<=*j*) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types: - move the candy from position (*x*,<=*y*) on the board to position (*x*<=-<=*a*,<=*y*<=-<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=+<=*a*,<=*y*<=-<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=-<=*a*,<=*y*<=+<=*b*); - move the candy from position (*x*,<=*y*) on the board to position (*x*<=+<=*a*,<=*y*<=+<=*b*). Naturally, Dima doesn't allow to move the candy beyond the chessboard borders. Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (*i*,<=*j*) to one of the chessboard corners. Help them cope with the task!
The first line of the input contains six integers *n*,<=*m*,<=*i*,<=*j*,<=*a*,<=*b* (1<=≤<=*n*,<=*m*<=≤<=106; 1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*; 1<=≤<=*a*,<=*b*<=≤<=106). You can assume that the chessboard rows are numbered from 1 to *n* from top to bottom and the columns are numbered from 1 to *m* from left to right. Position (*i*,<=*j*) in the statement is a chessboard cell on the intersection of the *i*-th row and the *j*-th column. You can consider that the corners are: (1,<=*m*), (*n*,<=1), (*n*,<=*m*), (1,<=1).
In a single line print a single integer — the minimum number of moves needed to get the candy. If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes.
[ "5 7 1 3 2 2\n", "5 5 2 3 1 1\n" ]
[ "2\n", "Poor Inna and pony!\n" ]
Note to sample 1: Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two.
[ { "input": "5 7 1 3 2 2", "output": "2" }, { "input": "5 5 2 3 1 1", "output": "Poor Inna and pony!" }, { "input": "1 1 1 1 1 1", "output": "0" }, { "input": "23000 15500 100 333 9 1", "output": "15167" }, { "input": "33999 99333 33000 99000 3 9", "output": "3...
46
0
0
18,386
0
none
[ "none" ]
null
null
Some company is going to hold a fair in Byteland. There are $n$ towns in Byteland and $m$ two-way roads between towns. Of course, you can reach any town from any other town using roads. There are $k$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $s$ different types of goods. It costs $d(u,v)$ coins to bring goods from town $u$ to town $v$ where $d(u,v)$ is the length of the shortest path from $u$ to $v$. Length of a path is the number of roads in this path. The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of $n$ towns.
There are $4$ integers $n$, $m$, $k$, $s$ in the first line of input ($1 \le n \le 10^{5}$, $0 \le m \le 10^{5}$, $1 \le s \le k \le min(n, 100)$) — the number of towns, the number of roads, the number of different types of goods, the number of different types of goods necessary to hold a fair. In the next line there are $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_{i} \le k$), where $a_i$ is the type of goods produced in the $i$-th town. It is guaranteed that all integers between $1$ and $k$ occur at least once among integers $a_{i}$. In the next $m$ lines roads are described. Each road is described by two integers $u$ $v$ ($1 \le u, v \le n$, $u \ne v$) — the towns connected by this road. It is guaranteed that there is no more than one road between every two towns. It is guaranteed that you can go from any town to any other town via roads.
Print $n$ numbers, the $i$-th of them is the minimum number of coins you need to spend on travel expenses to hold a fair in town $i$. Separate numbers with spaces.
[ "5 5 4 3\n1 2 4 3 2\n1 2\n2 3\n3 4\n4 1\n4 5\n", "7 6 3 2\n1 2 3 3 2 2 1\n1 2\n2 3\n3 4\n2 5\n5 6\n6 7\n" ]
[ "2 2 2 2 3 \n", "1 1 1 2 2 1 1 \n" ]
Let's look at the first sample. To hold a fair in town $1$ you can bring goods from towns $1$ ($0$ coins), $2$ ($1$ coin) and $4$ ($1$ coin). Total numbers of coins is $2$. Town $2$: Goods from towns $2$ ($0$), $1$ ($1$), $3$ ($1$). Sum equals $2$. Town $3$: Goods from towns $3$ ($0$), $2$ ($1$), $4$ ($1$). Sum equals $2$. Town $4$: Goods from towns $4$ ($0$), $1$ ($1$), $5$ ($1$). Sum equals $2$. Town $5$: Goods from towns $5$ ($0$), $4$ ($1$), $3$ ($2$). Sum equals $3$.
[]
31
0
0
18,403
730
Minimum and Maximum
[ "constructive algorithms", "interactive" ]
null
null
This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush(). In this problem, you need to find maximal and minimal elements of an array. What could be simpler? You can imagine that the jury has an array, and initially you know the only number *n* — array's length. Array's elements are numbered from 1 to *n*. You are allowed to compare two elements of the array by using their indices *i* and *j*. There are three possible responses to this query: '&lt;' (if *a**i* is less than *a**j*), '=' (if *a**i* is equal to *a**j*) and finally '&gt;' (if *a**i* is greater than *a**j*). It's known that it's always possible to find both maximal and minimal elements of the array by using no more than comparisons, where ⌈ *x*⌉ is the result of rounding *x* up. Write the program that will find positions of the minimum and the maximum in the jury's array of length *n*, by using no more than *f*(*n*) comparisons.
none
none
[ "2\n2\n \n&gt;\n \n3\n \n=\n \n=\n " ]
[ "? 1 2\n \n! 2 1\n \n? 3 1\n \n? 2 1\n \n! 2 3" ]
none
[ { "input": "2\n2\n2 1\n3\n1 1 1", "output": "1 out of 1\n3 out of 3\n2 queries processed [sumn=5]" }, { "input": "1\n4\n1 1 2 2", "output": "4 out of 4\n1 queries processed [sumn=4]" }, { "input": "2\n5\n1 1 2 1 1\n3\n3 2 1", "output": "6 out of 6\n3 out of 3\n2 queries processed [su...
15
4,608,000
0
18,420
293
Weird Game
[ "games", "greedy" ]
null
null
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2·*n* binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·*n*, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as *s*<==<=*s*1*s*2... *s*2*n*. Similarly, let's represent Andrey's word as *t*<==<=*t*1*t*2... *t*2*n*. Then, if Yaroslav choose number *k* during his move, then he is going to write out character *s**k* on the piece of paper. Similarly, if Andrey choose number *r* during his move, then he is going to write out character *t**r* on the piece of paper. The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw. You are given two strings *s* and *t*. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
The first line contains integer *n* (1<=≤<=*n*<=≤<=106). The second line contains string *s* — Yaroslav's word. The third line contains string *t* — Andrey's word. It is guaranteed that both words consist of 2·*n* characters "0" and "1".
Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.
[ "2\n0111\n0001\n", "3\n110110\n001001\n", "3\n111000\n000111\n", "4\n01010110\n00101101\n", "4\n01100000\n10010011\n" ]
[ "First\n", "First\n", "Draw\n", "First\n", "Second\n" ]
none
[ { "input": "2\n0111\n0001", "output": "First" }, { "input": "3\n110110\n001001", "output": "First" }, { "input": "3\n111000\n000111", "output": "Draw" }, { "input": "4\n01010110\n00101101", "output": "First" }, { "input": "4\n01100000\n10010011", "output": "Se...
1,870
12,083,200
3
18,457
258
Little Elephant and Broken Sorting
[ "dp", "math", "probabilities" ]
null
null
The Little Elephant loves permutations of integers from 1 to *n* very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1,<=2,<=3,<=...,<=*n*. This time the Little Elephant has permutation *p*1,<=*p*2,<=...,<=*p**n*. Its sorting program needs to make exactly *m* moves, during the *i*-th move it swaps elements that are at that moment located at the *a**i*-th and the *b**i*-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements. Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed. We'll call a pair of integers *i*,<=*j* (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*) an inversion in permutatuon *p*1,<=*p*2,<=...,<=*p**n*, if the following inequality holds: *p**i*<=&gt;<=*p**j*.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000,<=*n*<=&gt;<=1) — the permutation size and the number of moves. The second line contains *n* distinct integers, not exceeding *n* — the initial permutation. Next *m* lines each contain two integers: the *i*-th line contains integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*) — the positions of elements that were changed during the *i*-th move.
In the only line print a single real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10<=-<=6.
[ "2 1\n1 2\n1 2\n", "4 3\n1 3 2 4\n1 2\n2 3\n1 4\n" ]
[ "0.500000000\n", "3.000000000\n" ]
none
[ { "input": "2 1\n1 2\n1 2", "output": "0.500000000" }, { "input": "4 3\n1 3 2 4\n1 2\n2 3\n1 4", "output": "3.000000000" }, { "input": "7 4\n7 6 4 2 1 5 3\n1 3\n2 1\n7 2\n3 5", "output": "11.250000000" }, { "input": "10 1\n1 2 3 4 5 6 7 8 9 10\n1 10", "output": "8.5000000...
122
0
0
18,469
335
Palindrome
[ "constructive algorithms", "dp" ]
null
null
Given a string *s*, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of *s* and is as long as possible.
The only line of the input contains one string *s* of length *n* (1<=≤<=*n*<=≤<=5·104) containing only lowercase English letters.
If *s* contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of *s*. If *s* doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of *s* and is as long as possible. If there exists multiple answers, you are allowed to print any of them.
[ "bbbabcbbb\n", "rquwmzexectvnbanemsmdufrg\n" ]
[ "bbbcbbb\n", "rumenanemur\n" ]
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
[ { "input": "bbbabcbbb", "output": "bbbcbbb" }, { "input": "rquwmzexectvnbanemsmdufrg", "output": "rumenanemur" }, { "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
280
6,041,600
0
18,476
19
Deletion of Repeats
[ "greedy", "hashing", "string suffix structures" ]
C. Deletion of Repeats
2
256
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length *x* is such a substring of length 2*x*, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat. You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.
The first input line contains integer *n* (1<=≤<=*n*<=≤<=105) — length of the string. The following line contains *n* space-separated integer numbers from 0 to 109 inclusive — numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times.
In the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way.
[ "6\n1 2 3 1 2 3\n", "7\n4 5 6 5 6 7 7\n" ]
[ "3\n1 2 3 \n", "1\n7 \n" ]
none
[ { "input": "6\n1 2 3 1 2 3", "output": "3\n1 2 3 " }, { "input": "7\n4 5 6 5 6 7 7", "output": "1\n7 " }, { "input": "10\n5 7 2 1 8 8 5 10 2 5", "output": "5\n8 5 10 2 5 " }, { "input": "10\n0 1 1 1 0 3 0 1 4 0", "output": "7\n1 0 3 0 1 4 0 " }, { "input": "10\n0 ...
186
0
0
18,489
226
The table
[ "constructive algorithms", "greedy" ]
null
null
Harry Potter has a difficult homework. Given a rectangular table, consisting of *n*<=×<=*m* cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells. Alone, the boy can not cope. Help the young magician!
The first line contains two integers *n* and *m* (1<=≤<=*n*,<= *m*<=≤<=100) — the number of rows and the number of columns. Next *n* lines follow, each contains *m* integers: *j*-th integer in the *i*-th line is *a**i*,<=*j* (|*a**i*,<=*j*|<=≤<=100), the number in the *i*-th row and *j*-th column of the table. The rows of the table numbered from 1 to *n*. The columns of the table numbered from 1 to *m*.
In the first line print the number *a* — the number of required applications of the first spell. Next print *a* space-separated integers — the row numbers, you want to apply a spell. These row numbers must be distinct! In the second line print the number *b* — the number of required applications of the second spell. Next print *b* space-separated integers — the column numbers, you want to apply a spell. These column numbers must be distinct! If there are several solutions are allowed to print any of them.
[ "4 1\n-1\n-1\n-1\n-1\n", "2 4\n-1 -1 -1 2\n1 1 1 1\n" ]
[ "4 1 2 3 4 \n0 \n", "1 1 \n1 4 \n" ]
none
[ { "input": "4 1\n-1\n-1\n-1\n-1", "output": "4 1 2 3 4 \n0 " }, { "input": "2 4\n-1 -1 -1 2\n1 1 1 1", "output": "1 1 \n1 4 " }, { "input": "10 5\n1 7 1 6 -3\n8 -8 0 -7 -8\n7 -10 -8 -3 6\n-3 0 -9 0 -3\n-1 5 -2 -9 10\n-2 9 2 0 7\n5 0 -1 -10 6\n7 -8 -3 -9 1\n-5 10 -10 5 9\n-7 4 -8 0 -4", ...
62
0
0
18,497
0
none
[ "none" ]
null
null
You are given a sequence of positive integers *a*1,<=*a*2,<=...,<=*a**n*. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to *x*, delete both and insert a single integer *x*<=+<=1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements. For example, if the initial sequence is [5,<=2,<=1,<=1,<=2,<=2], then after the first operation you get [5,<=2,<=2,<=2,<=2], after the second — [5,<=3,<=2,<=2], after the third — [5,<=3,<=3], and finally after the fourth you get [5,<=4]. After that there are no equal consecutive elements left in the sequence, so you stop the process. Determine the final sequence after you stop performing the operation.
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of elements in the sequence. The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
In the first line print a single integer *k* — the number of elements in the sequence after you stop performing the operation. In the second line print *k* integers — the sequence after you stop performing the operation.
[ "6\n5 2 1 1 2 2\n", "4\n1000000000 1000000000 1000000000 1000000000\n", "7\n4 10 22 11 12 5 6\n" ]
[ "2\n5 4 ", "1\n1000000002 ", "7\n4 10 22 11 12 5 6 " ]
The first example is described in the statements. In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002]. In the third example there are no two equal consecutive elements initially, so the sequence does not change.
[ { "input": "6\n5 2 1 1 2 2", "output": "2\n5 4 " }, { "input": "4\n1000000000 1000000000 1000000000 1000000000", "output": "1\n1000000002 " }, { "input": "7\n4 10 22 11 12 5 6", "output": "7\n4 10 22 11 12 5 6 " }, { "input": "2\n1 1", "output": "1\n2 " }, { "inpu...
78
7,065,600
0
18,516
69
Subsegments
[ "data structures", "implementation" ]
E. Subsegments
1
256
Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in , which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem.
The first line contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=*n*) — the number of array elements and the length of the segment. Then follow *n* lines: the *i*-th one contains a single number *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109).
Print *n*–*k*<=+<=1 numbers, one per line: on the *i*-th line print of the maximum number of those numbers from the subarray *a**i* *a**i*<=+<=1 … *a**i*<=+<=*k*<=-<=1 that occur in this subarray exactly 1 time. If there are no such numbers in this subarray, print "Nothing".
[ "5 3\n1\n2\n2\n3\n3\n", "6 4\n3\n3\n3\n4\n4\n2\n" ]
[ "1\n3\n2\n", "4\nNothing\n3\n" ]
none
[ { "input": "5 3\n1\n2\n2\n3\n3", "output": "1\n3\n2" }, { "input": "6 4\n3\n3\n3\n4\n4\n2", "output": "4\nNothing\n3" }, { "input": "10 3\n-55\n-35\n-80\n91\n-96\n-93\n-39\n-77\n4\n29", "output": "-35\n91\n91\n91\n-39\n-39\n4\n29" }, { "input": "10 3\n-13\n26\n-97\n-38\n43\n-...
1,000
409,600
0
18,522
595
Pasha and Phone
[ "binary search", "math" ]
null
null
Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly *n* digits. Also Pasha has a number *k* and two sequences of length *n*<=/<=*k* (*n* is divisible by *k*) *a*1,<=*a*2,<=...,<=*a**n*<=/<=*k* and *b*1,<=*b*2,<=...,<=*b**n*<=/<=*k*. Let's split the phone number into blocks of length *k*. The first block will be formed by digits from the phone number that are on positions 1, 2,..., *k*, the second block will be formed by digits from the phone number that are on positions *k*<=+<=1, *k*<=+<=2, ..., 2·*k* and so on. Pasha considers a phone number good, if the *i*-th block doesn't start from the digit *b**i* and is divisible by *a**i* if represented as an integer. To represent the block of length *k* as an integer, let's write it out as a sequence *c*1, *c*2,...,*c**k*. Then the integer is calculated as the result of the expression *c*1·10*k*<=-<=1<=+<=*c*2·10*k*<=-<=2<=+<=...<=+<=*c**k*. Pasha asks you to calculate the number of good phone numbers of length *n*, for the given *k*, *a**i* and *b**i*. As this number can be too big, print it modulo 109<=+<=7.
The first line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*k*<=≤<=*min*(*n*,<=9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that *n* is divisible by *k*. The second line of the input contains *n*<=/<=*k* space-separated positive integers — sequence *a*1,<=*a*2,<=...,<=*a**n*<=/<=*k* (1<=≤<=*a**i*<=&lt;<=10*k*). The third line of the input contains *n*<=/<=*k* space-separated positive integers — sequence *b*1,<=*b*2,<=...,<=*b**n*<=/<=*k* (0<=≤<=*b**i*<=≤<=9).
Print a single integer — the number of good phone numbers of length *n* modulo 109<=+<=7.
[ "6 2\n38 56 49\n7 3 4\n", "8 2\n1 22 3 44\n5 4 3 2\n" ]
[ "8\n", "32400\n" ]
In the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698.
[ { "input": "6 2\n38 56 49\n7 3 4", "output": "8" }, { "input": "8 2\n1 22 3 44\n5 4 3 2", "output": "32400" }, { "input": "2 1\n9 9\n9 9", "output": "1" }, { "input": "2 1\n9 9\n0 9", "output": "1" }, { "input": "4 1\n4 3 2 1\n1 2 3 4", "output": "540" }, ...
61
0
0
18,535
371
Vessels
[ "data structures", "dsu", "implementation", "trees" ]
null
null
There is a system of *n* vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to *n*, in the order from the highest to the lowest, the volume of the *i*-th vessel is *a**i* liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the *i*-th vessel goes to the (*i*<=+<=1)-th one. The liquid that overflows from the *n*-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add *x**i* liters of water to the *p**i*-th vessel; 1. Print the number of liters of water in the *k**i*-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
The first line contains integer *n* — the number of vessels (1<=≤<=*n*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* — the vessels' capacities (1<=≤<=*a**i*<=≤<=109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer *m* — the number of queries (1<=≤<=*m*<=≤<=2·105). Each of the next *m* lines contains the description of one query. The query of the first type is represented as "1 *p**i* *x**i*", the query of the second type is represented as "2 *k**i*" (1<=≤<=*p**i*<=≤<=*n*, 1<=≤<=*x**i*<=≤<=109, 1<=≤<=*k**i*<=≤<=*n*).
For each query, print on a single line the number of liters of water in the corresponding vessel.
[ "2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2\n", "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3\n" ]
[ "4\n5\n8\n", "7\n10\n5\n" ]
none
[ { "input": "2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2", "output": "4\n5\n8" }, { "input": "3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3", "output": "7\n10\n5" }, { "input": "10\n71 59 88 55 18 98 38 73 53 58\n20\n1 5 93\n1 7 69\n2 3\n1 1 20\n2 10\n1 6 74\n1 7 100\n1 9 14\n2 3\n...
826
22,118,400
3
18,544
8
Two Friends
[ "binary search", "geometry" ]
D. Two Friends
1
64
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than *t*1, and the distance covered by Bob should not differ from the shortest one by more than *t*2. Find the maximum distance that Alan and Bob will cover together, discussing the film.
The first line contains two integers: *t*1,<=*t*2 (0<=≤<=*t*1,<=*t*2<=≤<=100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.
In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.
[ "0 2\n0 0\n4 0\n-3 0\n", "0 0\n0 0\n2 0\n1 0\n" ]
[ "1.0000000000\n", "2.0000000000\n" ]
none
[ { "input": "0 2\n0 0\n4 0\n-3 0", "output": "1.0000000000" }, { "input": "0 0\n0 0\n2 0\n1 0", "output": "2.0000000000" }, { "input": "0 2\n0 0\n40 0\n-31 1", "output": "1.0002538218" }, { "input": "100 2\n0 0\n4 0\n-3 0", "output": "6.0000000000" }, { "input": "2...
30
0
0
18,582
924
Minimal Subset Difference
[ "dp" ]
null
null
We call a positive integer *x* a *k*-beautiful integer if and only if it is possible to split the multiset of its digits in the decimal representation into two subsets such that the difference between the sum of digits in one subset and the sum of digits in the other subset is less than or equal to *k*. Each digit should belong to exactly one subset after the split. There are *n* queries for you. Each query is described with three integers *l*, *r* and *k*, which mean that you are asked how many integers *x* between *l* and *r* (inclusive) are *k*-beautiful.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=5·104), indicating the number of queries. Each of the next *n* lines describes a query, containing three integers *l*, *r* and *k* (1<=≤<=*l*<=≤<=*r*<=≤<=1018, 0<=≤<=*k*<=≤<=9).
For each query print a single number — the answer to the query.
[ "10\n1 100 0\n1 100 1\n1 100 2\n1 100 3\n1 100 4\n1 100 5\n1 100 6\n1 100 7\n1 100 8\n1 100 9\n", "10\n1 1000 0\n1 1000 1\n1 1000 2\n1 1000 3\n1 1000 4\n1 1000 5\n1 1000 6\n1 1000 7\n1 1000 8\n1 1000 9\n" ]
[ "9\n28\n44\n58\n70\n80\n88\n94\n98\n100\n", "135\n380\n573\n721\n830\n906\n955\n983\n996\n1000\n" ]
If 1 ≤ *x* ≤ 9, integer *x* is *k*-beautiful if and only if *x* ≤ *k*. If 10 ≤ *x* ≤ 99, integer *x* = 10*a* + *b* is *k*-beautiful if and only if |*a* - *b*| ≤ *k*, where *a* and *b* are integers between 0 and 9, inclusive. 100 is *k*-beautiful if and only if *k* ≥ 1.
[]
374
9,728,000
0
18,600
199
Special Olympics
[ "geometry" ]
null
null
A renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine. Let us remind you that a ring is a region located between two concentric circles with radii *r* and *R* (*r*<=&lt;<=*R*). These radii are called internal and external, respectively. Concentric circles are circles with centers located at the same point. Soon a white canvas, which can be considered as an infinite Cartesian plane, had two perfect rings, painted with solid black paint. As Sasha is very impulsive, the rings could have different radii and sizes, they intersect and overlap with each other in any way. We know only one thing for sure: the centers of the pair of rings are not the same. When Sasha got tired and fell into a deep sleep, a girl called Ilona came into the room and wanted to cut a circle for the sake of good memories. To make the circle beautiful, she decided to cut along the contour. We'll consider a contour to be a continuous closed line through which there is transition from one color to another (see notes for clarification). If the contour takes the form of a circle, then the result will be cutting out a circle, which Iona wants. But the girl's inquisitive mathematical mind does not rest: how many ways are there to cut a circle out of the canvas?
The input contains two lines. Each line has four space-separated integers *x**i*, *y**i*, *r**i*, *R**i*, that describe the *i*-th ring; *x**i* and *y**i* are coordinates of the ring's center, *r**i* and *R**i* are the internal and external radii of the ring correspondingly (<=-<=100<=≤<=*x**i*,<=*y**i*<=≤<=100; 1<=≤<=*r**i*<=&lt;<=*R**i*<=≤<=100). It is guaranteed that the centers of the rings do not coinside.
A single integer — the number of ways to cut out a circle from the canvas.
[ "60 60 45 55\n80 80 8 32\n", "60 60 45 55\n80 60 15 25\n", "50 50 35 45\n90 50 35 45\n" ]
[ "1", "4", "0" ]
Figures for test samples are given below. The possible cuts are marked with red dotted line.
[ { "input": "60 60 45 55\n80 80 8 32", "output": "1" }, { "input": "60 60 45 55\n80 60 15 25", "output": "4" }, { "input": "50 50 35 45\n90 50 35 45", "output": "0" }, { "input": "0 0 50 70\n1 0 60 80", "output": "2" }, { "input": "0 0 1 2\n10 0 2 20", "output"...
154
0
3
18,626
863
Almost Permutation
[ "flows" ]
null
null
Recently Ivan noticed an array *a* while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were *n* elements in the array, and each element was not less than 1 and not greater than *n*. Also he remembers *q* facts about the array. There are two types of facts that Ivan remembers: - 1 *l**i* *r**i* *v**i* — for each *x* such that *l**i*<=≤<=*x*<=≤<=*r**i* *a**x*<=≥<=*v**i*; - 2 *l**i* *r**i* *v**i* — for each *x* such that *l**i*<=≤<=*x*<=≤<=*r**i* *a**x*<=≤<=*v**i*. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the *q* facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the *cost* of array as follows: , where *cnt*(*i*) is the number of occurences of *i* in the array. Help Ivan to determine minimum possible *cost* of the array that corresponds to the facts!
The first line contains two integer numbers *n* and *q* (1<=≤<=*n*<=≤<=50, 0<=≤<=*q*<=≤<=100). Then *q* lines follow, each representing a fact about the array. *i*-th line contains the numbers *t**i*, *l**i*, *r**i* and *v**i* for *i*-th fact (1<=≤<=*t**i*<=≤<=2, 1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*, 1<=≤<=*v**i*<=≤<=*n*, *t**i* denotes the type of the fact).
If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible *cost* of the array.
[ "3 0\n", "3 1\n1 1 3 2\n", "3 2\n1 1 3 2\n2 1 3 2\n", "3 2\n1 1 3 2\n2 1 3 1\n" ]
[ "3\n", "5\n", "9\n", "-1\n" ]
none
[ { "input": "3 0", "output": "3" }, { "input": "3 1\n1 1 3 2", "output": "5" }, { "input": "3 2\n1 1 3 2\n2 1 3 2", "output": "9" }, { "input": "3 2\n1 1 3 2\n2 1 3 1", "output": "-1" }, { "input": "50 0", "output": "50" }, { "input": "50 1\n2 31 38 25"...
280
1,843,200
3
18,659
44
Toys
[ "brute force", "combinatorics" ]
I. Toys
5
256
Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her *n* toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=10) — the number of toys.
In the first line print the number of different variants of arrangement of toys into piles. Then print all the ways of arranging toys into piles in the order in which Sasha should try them (i.e. every next way must result from the previous one through the operation described in the statement). Every way should be printed in the following format. In every pile the toys should be arranged in ascending order of the numbers. Then the piles should be sorted in ascending order of the numbers of the first toys there. Output every way on a single line. Cf. the example to specify the output data format. If the solution is not unique, output any of them.
[ "3\n" ]
[ "5\n{1,2,3}\n{1,2},{3}\n{1},{2,3}\n{1},{2},{3}\n{1,3},{2}" ]
none
[ { "input": "3", "output": "5\n{1,2,3}\n{1,2},{3}\n{1},{2,3}\n{1},{2},{3}\n{1,3},{2}" }, { "input": "1", "output": "1\n{1}" }, { "input": "2", "output": "2\n{1,2}\n{1},{2}" }, { "input": "4", "output": "15\n{1,2,3,4}\n{1,2,3},{4}\n{1,2},{3,4}\n{1,2},{3},{4}\n{1,2,4},{3}\n{...
92
0
0
18,668
873
Strange Game On Matrix
[ "greedy", "two pointers" ]
null
null
Ivan is playing a strange game. He has a matrix *a* with *n* rows and *m* columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows: 1. Initially Ivan's score is 0; 1. In each column, Ivan will find the topmost 1 (that is, if the current column is *j*, then he will find minimum *i* such that *a**i*,<=*j*<==<=1). If there are no 1's in the column, this column is skipped; 1. Ivan will look at the next *min*(*k*,<=*n*<=-<=*i*<=+<=1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.
The first line contains three integer numbers *n*, *m* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=100, 1<=≤<=*m*<=≤<=100). Then *n* lines follow, *i*-th of them contains *m* integer numbers — the elements of *i*-th row of matrix *a*. Each number is either 0 or 1.
Print two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.
[ "4 3 2\n0 1 0\n1 0 1\n0 1 0\n1 1 1\n", "3 2 1\n1 0\n0 1\n0 0\n" ]
[ "4 1\n", "2 0\n" ]
In the first example Ivan will replace the element *a*<sub class="lower-index">1, 2</sub>.
[ { "input": "4 3 2\n0 1 0\n1 0 1\n0 1 0\n1 1 1", "output": "4 1" }, { "input": "3 2 1\n1 0\n0 1\n0 0", "output": "2 0" }, { "input": "3 4 2\n0 1 1 1\n1 0 1 1\n1 0 0 1", "output": "7 0" }, { "input": "3 57 3\n1 0 0 1 1 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 1 1 1...
62
5,632,000
0
18,672
954
Fight Against Traffic
[ "dfs and similar", "graphs", "shortest paths" ]
null
null
Little town Nsk consists of *n* junctions connected by *m* bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them. In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction *s* to work located near junction *t*. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease. You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between *s* and *t* won't decrease.
The firt line of the input contains integers *n*, *m*, *s* and *t* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*m*<=≤<=1000, 1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The *i*-th of the following *m* lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*), meaning that this road connects junctions *u**i* and *v**i* directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions *s* and *t*.
[ "5 4 1 5\n1 2\n2 3\n3 4\n4 5\n", "5 4 3 5\n1 2\n2 3\n3 4\n4 5\n", "5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5\n" ]
[ "0\n", "5\n", "3\n" ]
none
[ { "input": "5 4 1 5\n1 2\n2 3\n3 4\n4 5", "output": "0" }, { "input": "5 4 3 5\n1 2\n2 3\n3 4\n4 5", "output": "5" }, { "input": "5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5", "output": "3" }, { "input": "2 1 2 1\n1 2", "output": "0" }, { "input": "3 2 2 3\n1 2\n2 3", ...
139
24,268,800
-1
18,693
735
Urbanization
[ "greedy", "number theory", "sortings" ]
null
null
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are *n* people who plan to move to the cities. The wealth of the *i* of them is equal to *a**i*. Authorities plan to build two cities, first for *n*1 people and second for *n*2 people. Of course, each of *n* candidates can settle in only one of the cities. Thus, first some subset of candidates of size *n*1 settle in the first city and then some subset of size *n*2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home. To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth *a**i* among all its residents divided by the number of them (*n*1 or *n*2 depending on the city). The division should be done in real numbers without any rounding. Please, help authorities find the optimal way to pick residents for two cities.
The first line of the input contains three integers *n*, *n*1 and *n*2 (1<=≤<=*n*,<=*n*1,<=*n*2<=≤<=100<=000, *n*1<=+<=*n*2<=≤<=*n*) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100<=000), the *i*-th of them is equal to the wealth of the *i*-th candidate.
Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You 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 .
[ "2 1 1\n1 5\n", "4 2 1\n1 4 2 3\n" ]
[ "6.00000000\n", "6.50000000\n" ]
In the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second. In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (*a*<sub class="lower-index">3</sub> + *a*<sub class="lower-index">4</sub>) / 2 + *a*<sub class="lower-index">2</sub> = (3 + 2) / 2 + 4 = 6.5
[ { "input": "2 1 1\n1 5", "output": "6.00000000" }, { "input": "4 2 1\n1 4 2 3", "output": "6.50000000" }, { "input": "3 1 2\n1 2 3", "output": "4.50000000" }, { "input": "10 4 6\n3 5 7 9 12 25 67 69 83 96", "output": "88.91666667" }, { "input": "19 7 12\n1 2 4 8 1...
155
10,649,600
3
18,705
67
Optical Experiment
[ "binary search", "data structures", "dp" ]
D. Optical Experiment
5
256
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for *n* rays is as follows. There is a rectangular box having exactly *n* holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?". Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
The first line contains *n* (1<=≤<=*n*<=≤<=106), the number of rays. The second line contains *n* distinct integers. The *i*-th integer *x**i* (1<=≤<=*x**i*<=≤<=*n*) shows that the *x**i*-th ray enters from the *i*-th hole. Similarly, third line contains *n* distinct integers. The *i*-th integer *y**i* (1<=≤<=*y**i*<=≤<=*n*) shows that the *y**i*-th ray exits from the *i*-th hole. All rays are numbered from 1 to *n*.
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
[ "5\n1 4 5 2 3\n3 4 2 1 5\n", "3\n3 1 2\n2 3 1\n" ]
[ "3\n", "2\n" ]
For the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
[ { "input": "5\n1 4 5 2 3\n3 4 2 1 5", "output": "3" }, { "input": "3\n3 1 2\n2 3 1", "output": "2" }, { "input": "5\n1 2 4 5 3\n1 5 4 2 3", "output": "3" }, { "input": "3\n3 1 2\n1 3 2", "output": "2" }, { "input": "7\n1 5 2 7 4 3 6\n6 3 1 2 5 4 7", "output": ...
1,558
131,993,600
3.598343
18,706
95
Lucky Country
[ "dp", "dsu", "graphs" ]
E. Lucky Country
1
256
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One night Petya was sleeping. He was dreaming of being the president of some island country. The country is represented by islands connected by two-way roads. Between some islands there is no road way, even through other islands, that's why the country is divided into several regions. More formally, each island belongs to exactly one region, there is a path between any two islands located in the same region; there is no path between any two islands from different regions. A region is lucky if the amount of islands in it is a lucky number. As a real president, Petya first decided to build a presidential palace. Being a lucky numbers' fan, Petya wants to position his palace in one of the lucky regions. However, it is possible that initially the country has no such regions. In this case Petya can build additional roads between different regions, thus joining them. Find the minimum number of roads needed to build to create a lucky region.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105). They are the number of islands and the number of roads correspondingly. Next *m* lines contain road descriptions. Each road is defined by the numbers of islands that it connects: that is, by two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*). Some roads can connect an island with itself; there can be more than one road between a pair of islands. Numbers in each line are separated by exactly one space character.
If there's no solution, output the only number "-1" (without the quotes). Otherwise, output the minimum number of roads *r* that need to be built to get a lucky region.
[ "4 3\n1 2\n2 3\n1 3\n", "5 4\n1 2\n3 4\n4 5\n3 5\n" ]
[ "1\n", "-1\n" ]
none
[ { "input": "4 3\n1 2\n2 3\n1 3", "output": "1" }, { "input": "5 4\n1 2\n3 4\n4 5\n3 5", "output": "-1" }, { "input": "7 6\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7", "output": "0" }, { "input": "7 5\n2 3\n3 4\n4 5\n3 6\n2 2", "output": "2" }, { "input": "1 1\n1 1", "outpu...
62
614,400
0
18,715
189
Counting Rhombi
[ "brute force", "math" ]
null
null
You have two positive integers *w* and *h*. Your task is to count the number of rhombi which have the following properties: - Have positive area. - With vertices at integer points. - All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points (0,<=0), (*w*,<=0), (*w*,<=*h*), (0,<=*h*). In other words, for all vertices (*x**i*,<=*y**i*) of the rhombus the following conditions should fulfill: 0<=≤<=*x**i*<=≤<=*w* and 0<=≤<=*y**i*<=≤<=*h*. - Its diagonals are parallel to the axis. Count the number of such rhombi. Let us remind you that a rhombus is a quadrilateral whose four sides all have the same length.
The first line contains two integers *w* and *h* (1<=≤<=*w*,<=*h*<=≤<=4000) — the rectangle's sizes.
Print a single number — the number of sought rhombi. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
[ "2 2\n", "1 2\n" ]
[ "1\n", "0\n" ]
In the first example there exists only one such rhombus. Its vertices are located at points (1, 0), (2, 1), (1, 2), (0, 1).
[ { "input": "2 2", "output": "1" }, { "input": "1 2", "output": "0" }, { "input": "1 4000", "output": "0" }, { "input": "4000 1", "output": "0" }, { "input": "4000 4000", "output": "16000000000000" }, { "input": "15 10", "output": "1400" }, { ...
30
0
-1
18,803
109
Lucky Interval
[ "brute force", "math" ]
E. Lucky Interval
4
512
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya came across an interval of numbers [*a*,<=*a*<=+<=*l*<=-<=1]. Let *F*(*x*) be the number of lucky digits of number *x*. Find the minimum *b* (*a*<=&lt;<=*b*) such, that *F*(*a*) = *F*(*b*), *F*(*a*<=+<=1) = *F*(*b*<=+<=1), ..., *F*(*a*<=+<=*l*<=-<=1) = *F*(*b*<=+<=*l*<=-<=1).
The single line contains two integers *a* and *l* (1<=≤<=*a*,<=*l*<=≤<=109) — the interval's first number and the interval's length correspondingly.
On the single line print number *b* — the answer to the problem.
[ "7 4\n", "4 7\n" ]
[ "17\n", "14\n" ]
Consider that [*a*, *b*] denotes an interval of integers; this interval includes the boundaries. That is, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/18b4a6012d95ad18891561410f0314497a578d63.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "7 4", "output": "17" }, { "input": "4 7", "output": "14" }, { "input": "10 10", "output": "20" }, { "input": "47 74", "output": "147" }, { "input": "469 1", "output": "480" }, { "input": "47 74", "output": "147" }, { "input": "1...
62
0
3.99225
18,804
765
Artsem and Saunders
[ "constructive algorithms", "dsu", "math" ]
null
null
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem. Let [*n*] denote the set {1,<=...,<=*n*}. We will also write *f*:<=[*x*]<=→<=[*y*] when a function *f* is defined in integer points 1, ..., *x*, and all its values are integers from 1 to *y*. Now then, you are given a function *f*:<=[*n*]<=→<=[*n*]. Your task is to find a positive integer *m*, and two functions *g*:<=[*n*]<=→<=[*m*], *h*:<=[*m*]<=→<=[*n*], such that *g*(*h*(*x*))<==<=*x* for all , and *h*(*g*(*x*))<==<=*f*(*x*) for all , or determine that finding these is impossible.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105). The second line contains *n* space-separated integers — values *f*(1),<=...,<=*f*(*n*) (1<=≤<=*f*(*i*)<=≤<=*n*).
If there is no answer, print one integer -1. Otherwise, on the first line print the number *m* (1<=≤<=*m*<=≤<=106). On the second line print *n* numbers *g*(1),<=...,<=*g*(*n*). On the third line print *m* numbers *h*(1),<=...,<=*h*(*m*). If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.
[ "3\n1 2 3\n", "3\n2 2 2\n", "2\n2 1\n" ]
[ "3\n1 2 3\n1 2 3\n", "1\n1 1 1\n2\n", "-1\n" ]
none
[ { "input": "3\n1 2 3", "output": "3\n1 2 3\n1 2 3" }, { "input": "3\n2 2 2", "output": "1\n1 1 1\n2" }, { "input": "2\n2 1", "output": "-1" }, { "input": "1\n1", "output": "1\n1\n1" }, { "input": "2\n2 1", "output": "-1" }, { "input": "2\n2 2", "ou...
436
9,216,000
3
18,856
342
Xenia and Spies
[ "brute force", "greedy", "implementation" ]
null
null
Xenia the vigorous detective faced *n* (*n*<=≥<=2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to *n* from left to right. Spy *s* has an important note. He has to pass the note to spy *f*. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is *x*, he can pass the note to another spy, either *x*<=-<=1 or *x*<=+<=1 (if *x*<==<=1 or *x*<==<=*n*, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone. But nothing is that easy. During *m* steps Xenia watches some spies attentively. Specifically, during step *t**i* (steps are numbered from 1) Xenia watches spies numbers *l**i*,<=*l**i*<=+<=1,<=*l**i*<=+<=2,<=...,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him. You've got *s* and *f*. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy *s* to spy *f* as quickly as possible (in the minimum number of steps).
The first line contains four integers *n*, *m*, *s* and *f* (1<=≤<=*n*,<=*m*<=≤<=105; 1<=≤<=*s*,<=*f*<=≤<=*n*; *s*<=≠<=*f*; *n*<=≥<=2). Each of the following *m* lines contains three integers *t**i*,<=*l**i*,<=*r**i* (1<=≤<=*t**i*<=≤<=109,<=1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). It is guaranteed that *t*1<=&lt;<=*t*2<=&lt;<=*t*3<=&lt;<=...<=&lt;<=*t**m*.
Print *k* characters in a line: the *i*-th character in the line must represent the spies' actions on step *i*. If on step *i* the spy with the note must pass the note to the spy with a lesser number, the *i*-th character should equal "L". If on step *i* the spy with the note must pass it to the spy with a larger number, the *i*-th character must equal "R". If the spy must keep the note at the *i*-th step, the *i*-th character must equal "X". As a result of applying the printed sequence of actions spy *s* must pass the note to spy *f*. The number of printed characters *k* must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.
[ "3 5 1 3\n1 1 2\n2 2 3\n3 3 3\n4 1 1\n10 1 3\n" ]
[ "XXRR\n" ]
none
[ { "input": "3 5 1 3\n1 1 2\n2 2 3\n3 3 3\n4 1 1\n10 1 3", "output": "XXRR" }, { "input": "2 3 2 1\n1 1 2\n2 1 2\n4 1 2", "output": "XXL" }, { "input": "5 11 1 5\n1 1 5\n2 2 2\n3 1 1\n4 3 3\n5 3 3\n6 1 1\n7 4 4\n8 4 5\n10 1 3\n11 5 5\n13 1 5", "output": "XXXRXRXXRR" }, { "inpu...
93
23,142,400
-1
18,871
343
Pumping Stations
[ "brute force", "dfs and similar", "divide and conquer", "flows", "graphs", "greedy", "trees" ]
null
null
Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations. The system consists of *n* pumping stations, which are numbered by integers from 1 to *n*. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a time). For each pipe you know its bandwidth — the maximum number of liters of water that can flow through it in one hour. Each pumping station can pump incoming water from some stations to other stations through the pipes, provided that in one hour the total influx of water to the station is equal to the total outflux of water from the station. It is Mike's responsibility to pump water between stations. From station *a* to station *b* through the pipes (possibly through other stations) within one hour one can transmit a certain number of liters of water according to the rules described above. During this time, water from other stations can not flow into station *a*, and can not flow out of the station *b*. However, any amount of water can flow out of station *a* or in station *b*. If a total of *x* litres of water flows out of the station *a* in an hour, then Mike gets *x* bollars more to his salary. To get paid, Mike needs to work for *n*<=-<=1 days, according to the contract. On the first day he selects two stations *v*1 and *v*2, and within one hour he pumps a certain amount of water from *v*1 to *v*2. Next, on the *i*-th day Mike chooses a station *v**i*<=+<=1 that has been never selected before, and pumps a certain amount of water out of the station *v**i* to station *v**i*<=+<=1 for one hour. The quantity of water he pumps on the *i*-th day does not depend on the amount of water pumped on the (*i*<=-<=1)-th day. Mike needs to earn as much bollars as he can for his projects. Help Mike find such a permutation of station numbers *v*1, *v*2, ..., *v**n* so Mike will be able to earn the highest possible salary.
The first line of the input contains two space-separated integers *n* and *m* (2<=≤<=*n*<=≤<=200, 1<=≤<=*m*<=≤<=1000) — the number of stations and pipes in the system, accordingly. The *i*-th of the next *m* lines contains three space-separated integers *a**i*, *b**i* and *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*, 1<=≤<=*c**i*<=≤<=100) — the numbers of stations connected by the *i*-th pipe and the pipe's bandwidth, accordingly. It is guaranteed that any two stations are connected by at most one pipe and that there is a pipe path between any two stations.
On the first line print a single integer — the maximum salary Mike can earn. On the second line print a space-separated permutation of *n* numbers from 1 to *n* — the numbers of stations in the sequence *v*1, *v*2, ..., *v**n*. If there are multiple answers, print any of them.
[ "6 11\n1 2 10\n1 6 8\n2 3 4\n2 5 2\n2 6 3\n3 4 5\n3 5 4\n3 6 2\n4 5 7\n4 6 2\n5 6 3\n" ]
[ "77\n6 2 1 5 3 4 \n" ]
none
[]
60
307,200
0
18,885
659
New Reform
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy" ]
null
null
Berland has *n* cities connected by *m* bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads. The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another). In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city. Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
The first line of the input contains two positive integers, *n* and *m* — the number of the cities and the number of roads in Berland (2<=≤<=*n*<=≤<=100<=000, 1<=≤<=*m*<=≤<=100<=000). Next *m* lines contain the descriptions of the roads: the *i*-th road is determined by two distinct integers *x**i*,<=*y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, *x**i*<=≠<=*y**i*), where *x**i* and *y**i* are the numbers of the cities connected by the *i*-th road. It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
Print a single integer — the minimum number of separated cities after the reform.
[ "4 3\n2 1\n1 3\n4 3\n", "5 5\n2 1\n1 3\n2 3\n2 5\n4 3\n", "6 5\n1 2\n2 3\n4 5\n4 6\n5 6\n" ]
[ "1\n", "0\n", "1\n" ]
In the first sample the following road orientation is allowed: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5b18c46402af724bd3841d549d5d6f52fc16253.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/04481aced8a9d501ae5d785ab654c542ff5497a1.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/0d220a75a508edc0d540dbaec5e198345049b66f.png" style="max-width: 100.0%;max-height: 100.0%;"/>. The second sample: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5b18c46402af724bd3841d549d5d6f52fc16253.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/030fc9181b578c2d906254d38dc56da5554323eb.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29f71c065c3536e88b54429c734103ad3604f68b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a6011a68d6de05246ad6ba8aa24a5c5c71cd450a.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/0d220a75a508edc0d540dbaec5e198345049b66f.png" style="max-width: 100.0%;max-height: 100.0%;"/>. The third sample: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5b18c46402af724bd3841d549d5d6f52fc16253.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29f71c065c3536e88b54429c734103ad3604f68b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7113d83514735a488d7b85262585381d26986195.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/98300067e46d036076e429b208db829296ebca9d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/146f3f3d208399fbab4d1d8c2800f07bf7b463e5.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "4 3\n2 1\n1 3\n4 3", "output": "1" }, { "input": "5 5\n2 1\n1 3\n2 3\n2 5\n4 3", "output": "0" }, { "input": "6 5\n1 2\n2 3\n4 5\n4 6\n5 6", "output": "1" }, { "input": "4 4\n1 2\n2 3\n3 4\n4 1", "output": "0" }, { "input": "10 45\n3 5\n2 3\n4 8\n2 5\n...
1,000
13,824,000
0
18,907
407
k-d-sequence
[ "data structures" ]
null
null
We'll call a sequence of integers a good *k*-*d* sequence if we can add to it at most *k* numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference *d*. You got hold of some sequence *a*, consisting of *n* integers. Your task is to find its longest contiguous subsegment, such that it is a good *k*-*d* sequence.
The first line contains three space-separated integers *n*,<=*k*,<=*d* (1<=≤<=*n*<=≤<=2·105; 0<=≤<=*k*<=≤<=2·105; 0<=≤<=*d*<=≤<=109). The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the actual sequence.
Print two space-separated integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) show that sequence *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* is the longest subsegment that is a good *k*-*d* sequence. If there are multiple optimal answers, print the one with the minimum value of *l*.
[ "6 1 2\n4 3 2 8 6 2\n" ]
[ "3 5\n" ]
In the first test sample the answer is the subsegment consisting of numbers 2, 8, 6 — after adding number 4 and sorting it becomes sequence 2, 4, 6, 8 — the arithmetic progression with difference 2.
[]
15
0
0
18,913
31
Schedule
[ "implementation" ]
C. Schedule
2
256
At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, *n* groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect. The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that.
The first line contains integer *n* (1<=≤<=*n*<=≤<=5000) — amount of groups, which have lessons in the room 31. Then *n* lines follow, each of them contains two integers *l**i* *r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=106) — starting and finishing times of lesson of the *i*-th group. It is possible that initially no two lessons intersect (see sample 1).
Output integer *k* — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output *k* numbers — indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order.
[ "3\n3 10\n20 30\n1 3\n", "4\n3 10\n20 30\n1 3\n1 39\n", "3\n1 5\n2 6\n3 7\n" ]
[ "3\n1 2 3 ", "1\n4 ", "0\n" ]
none
[ { "input": "3\n3 10\n20 30\n1 3", "output": "3\n1 2 3 " }, { "input": "4\n3 10\n20 30\n1 3\n1 39", "output": "1\n4 " }, { "input": "3\n1 5\n2 6\n3 7", "output": "0" }, { "input": "4\n1 5\n5 7\n6 9\n9 10", "output": "2\n2 3 " }, { "input": "11\n717170 795210\n86642...
310
0
0
18,919
338
GCD Table
[ "chinese remainder theorem", "math", "number theory" ]
null
null
Consider a table *G* of size *n*<=×<=*m* such that *G*(*i*,<=*j*)<==<=*GCD*(*i*,<=*j*) for all 1<=≤<=*i*<=≤<=*n*,<=1<=≤<=*j*<=≤<=*m*. *GCD*(*a*,<=*b*) is the greatest common divisor of numbers *a* and *b*. You have a sequence of positive integer numbers *a*1,<=*a*2,<=...,<=*a**k*. We say that this sequence occurs in table *G* if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1<=≤<=*i*<=≤<=*n* and 1<=≤<=*j*<=≤<=*m*<=-<=*k*<=+<=1 should exist that *G*(*i*,<=*j*<=+<=*l*<=-<=1)<==<=*a**l* for all 1<=≤<=*l*<=≤<=*k*. Determine if the sequence *a* occurs in table *G*.
The first line contains three space-separated integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=1012; 1<=≤<=*k*<=≤<=10000). The second line contains *k* space-separated integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=1012).
Print a single word "YES", if the given sequence occurs in table *G*, otherwise print "NO".
[ "100 100 5\n5 2 1 2 1\n", "100 8 5\n5 2 1 2 1\n", "100 100 7\n1 2 3 4 5 6 7\n" ]
[ "YES\n", "NO\n", "NO\n" ]
Sample 1. The tenth row of table *G* starts from sequence {1, 2, 1, 2, 5, 2, 1, 2, 1, 10}. As you can see, elements from fifth to ninth coincide with sequence *a*. Sample 2. This time the width of table *G* equals 8. Sequence *a* doesn't occur there.
[ { "input": "100 100 5\n5 2 1 2 1", "output": "YES" }, { "input": "100 8 5\n5 2 1 2 1", "output": "NO" }, { "input": "100 100 7\n1 2 3 4 5 6 7", "output": "NO" }, { "input": "5 5 5\n1 1 1 1 1", "output": "YES" }, { "input": "11 10 1\n11", "output": "NO" }, ...
154
0
0
18,926
935
Fifa and Fafa
[ "geometry" ]
null
null
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of *r* meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius *R*. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet. The world is represented as an infinite 2D plane. The flat is centered at (*x*1,<=*y*1) and has radius *R* and Fafa's laptop is located at (*x*2,<=*y*2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.
The single line of the input contains 5 space-separated integers *R*,<=*x*1,<=*y*1,<=*x*2,<=*y*2 (1<=≤<=*R*<=≤<=105, |*x*1|,<=|*y*1|,<=|*x*2|,<=|*y*2|<=≤<=105).
Print three space-separated numbers *x**ap*,<=*y**ap*,<=*r* where (*x**ap*,<=*y**ap*) is the position which Fifa chose for the access point and *r* is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10<=-<=6 absolutely or relatively, and also the radius you printed can be changed by no more than 10<=-<=6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.
[ "5 3 3 1 1\n", "10 5 5 5 15\n" ]
[ "3.7677669529663684 3.7677669529663684 3.914213562373095\n", "5.0 5.0 10.0\n" ]
none
[ { "input": "5 3 3 1 1", "output": "3.7677669529663684 3.7677669529663684 3.914213562373095" }, { "input": "10 5 5 5 15", "output": "5.0 5.0 10.0" }, { "input": "5 0 0 0 7", "output": "0 0 5" }, { "input": "10 0 0 0 0", "output": "5.0 0.0 5.0" }, { "input": "100000...
31
512,000
0
18,932
396
On Number of Decompositions into Multipliers
[ "combinatorics", "math", "number theory" ]
null
null
You are given an integer *m* as a product of integers *a*1,<=*a*2,<=... *a**n* . Your task is to find the number of distinct decompositions of number *m* into the product of *n* ordered positive integers. Decomposition into *n* products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo 1000000007 (109<=+<=7).
The first line contains positive integer *n* (1<=≤<=*n*<=≤<=500). The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
In a single line print a single number *k* — the number of distinct decompositions of number *m* into *n* ordered multipliers modulo 1000000007 (109<=+<=7).
[ "1\n15\n", "3\n1 1 2\n", "2\n5 7\n" ]
[ "1\n", "3\n", "4\n" ]
In the second sample, the get a decomposition of number 2, you need any one number out of three to equal 2, and the rest to equal 1. In the third sample, the possible ways of decomposing into ordered multipliers are [7,5], [5,7], [1,35], [35,1]. A decomposition of positive integer *m* into *n* ordered multipliers is a cortege of positive integers *b* = {*b*<sub class="lower-index">1</sub>, *b*<sub class="lower-index">2</sub>, ... *b*<sub class="lower-index">*n*</sub>} such that <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/607dd79be814c0a988453395ca6d82109b016083.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Two decompositions *b* and *c* are considered different, if there exists index *i* such that *b*<sub class="lower-index">*i*</sub> ≠ *c*<sub class="lower-index">*i*</sub>.
[ { "input": "1\n15", "output": "1" }, { "input": "3\n1 1 2", "output": "3" }, { "input": "2\n5 7", "output": "4" }, { "input": "2\n5 10", "output": "6" }, { "input": "3\n1 30 1", "output": "27" }, { "input": "2\n1000000000 1000000000", "output": "36...
389
13,107,200
0
18,992
175
Plane of Tanks: Pro
[ "implementation" ]
null
null
Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has *n* records in total. In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category: - "noob" — if more than 50% of players have better results; - "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results; - "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results; - "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results; - "pro" — if his result is not worse than the result that 99% of players have. When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have. Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.
The first line contains the only integer number *n* (1<=≤<=*n*<=≤<=1000) — a number of records with the players' results. Each of the next *n* lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.
Print on the first line the number *m* — the number of players, who participated in one round at least. Each one of the next *m* lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.
[ "5\nvasya 100\nvasya 200\nartem 100\nkolya 200\nigor 250\n", "3\nvasya 200\nkolya 1000\nvasya 1000\n" ]
[ "4\nartem noob\nigor pro\nkolya random\nvasya random\n", "2\nkolya pro\nvasya pro\n" ]
In the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro". In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".
[ { "input": "5\nvasya 100\nvasya 200\nartem 100\nkolya 200\nigor 250", "output": "4\nartem noob\nigor pro\nkolya random\nvasya random" }, { "input": "3\nvasya 200\nkolya 1000\nvasya 1000", "output": "2\nkolya pro\nvasya pro" }, { "input": "1\nvasya 1000", "output": "1\nvasya pro" },...
92
0
0
19,087
97
Domino
[ "brute force", "implementation" ]
A. Domino
0
256
Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2<=×<=1. Both halves of each domino contain one digit from 0 to 6. The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2<=×<=2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear — he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size *n*<=×<=*m* and put there rectangular chips of sizes 1<=×<=2 and 2<=×<=1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round.
The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=30). Each of the following *n* lines contains *m* characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists.
Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next *n* lines containing *m* characters each, should contain a field from dots and numbers from 0 to 6 — any of the possible solutions. All dominoes should be different.
[ "8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy\n" ]
[ "10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344\n" ]
none
[]
500
1,331,200
0
19,121
303
Rectangle Puzzle II
[ "implementation", "math" ]
null
null
You are given a rectangle grid. That grid's size is *n*<=×<=*m*. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers (*x*,<=*y*) (0<=≤<=*x*<=≤<=*n*,<=0<=≤<=*y*<=≤<=*m*). Your task is to find a maximum sub-rectangle on the grid (*x*1,<=*y*1,<=*x*2,<=*y*2) so that it contains the given point (*x*,<=*y*), and its length-width ratio is exactly (*a*,<=*b*). In other words the following conditions must hold: 0<=≤<=*x*1<=≤<=*x*<=≤<=*x*2<=≤<=*n*, 0<=≤<=*y*1<=≤<=*y*<=≤<=*y*2<=≤<=*m*, . The sides of this sub-rectangle should be parallel to the axes. And values *x*1,<=*y*1,<=*x*2,<=*y*2 should be integers. If there are multiple solutions, find the rectangle which is closest to (*x*,<=*y*). Here "closest" means the Euclid distance between (*x*,<=*y*) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (*x*1,<=*y*1,<=*x*2,<=*y*2), so we can choose the lexicographically minimum one.
The first line contains six integers *n*,<=*m*,<=*x*,<=*y*,<=*a*,<=*b* (1<=≤<=*n*,<=*m*<=≤<=109,<=0<=≤<=*x*<=≤<=*n*,<=0<=≤<=*y*<=≤<=*m*,<=1<=≤<=*a*<=≤<=*n*,<=1<=≤<=*b*<=≤<=*m*).
Print four integers *x*1,<=*y*1,<=*x*2,<=*y*2, which represent the founded sub-rectangle whose left-bottom point is (*x*1,<=*y*1) and right-up point is (*x*2,<=*y*2).
[ "9 9 5 5 2 1\n", "100 100 52 50 46 56\n" ]
[ "1 3 9 7\n", "17 8 86 92\n" ]
none
[ { "input": "9 9 5 5 2 1", "output": "1 3 9 7" }, { "input": "100 100 52 50 46 56", "output": "17 8 86 92" }, { "input": "100 100 16 60 42 75", "output": "0 0 56 100" }, { "input": "100 100 28 22 47 50", "output": "0 0 94 100" }, { "input": "100 100 44 36 96 21", ...
156
5,222,400
0
19,174
439
Devu and Partitioning of the Array
[ "brute force", "constructive algorithms", "implementation", "number theory" ]
null
null
Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into *k* disjoint non-empty parts such that *p* of the parts have even sum (each of them must have even sum) and remaining *k* - *p* have odd sum? (note that parts need not to be continuous). If it is possible to partition the array, also give any possible way of valid partitioning.
The first line will contain three space separated integers *n*, *k*, *p* (1<=≤<=*k*<=≤<=*n*<=≤<=105; 0<=≤<=*p*<=≤<=*k*). The next line will contain *n* space-separated distinct integers representing the content of array *a*: *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print *k* lines after the first line. The *i**th* of them should contain the content of the *i**th* part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly *p* parts with even sum, each of the remaining *k* - *p* parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition.
[ "5 5 3\n2 6 10 5 9\n", "5 5 3\n7 14 2 9 5\n", "5 3 1\n1 2 3 7 5\n" ]
[ "YES\n1 9\n1 5\n1 10\n1 6\n1 2\n", "NO\n", "YES\n3 5 1 3\n1 7\n1 2\n" ]
none
[ { "input": "5 5 3\n2 6 10 5 9", "output": "YES\n1 9\n1 5\n1 10\n1 6\n1 2" }, { "input": "5 5 3\n7 14 2 9 5", "output": "NO" }, { "input": "5 3 1\n1 2 3 7 5", "output": "YES\n3 5 1 3\n1 7\n1 2" }, { "input": "10 5 3\n194757070 828985446 11164 80016 84729 117765558 111730436 16...
155
10,956,800
0
19,176
796
Exam Cheating
[ "binary search", "dp" ]
null
null
Zane and Zane's crush have just decided to date! However, the girl is having a problem with her Physics final exam, and needs your help. There are *n* questions, numbered from 1 to *n*. Question *i* comes before question *i*<=+<=1 (1<=≤<=*i*<=&lt;<=*n*). Each of the questions cannot be guessed on, due to the huge penalty for wrong answers. The girl luckily sits in the middle of two geniuses, so she is going to cheat. However, the geniuses have limitations. Each of them may or may not know the answers to some questions. Anyway, it is safe to assume that the answers on their answer sheets are absolutely correct. To make sure she will not get caught by the proctor, the girl will glance at most *p* times, each time looking at no more than *k* consecutive questions on one of the two geniuses' answer sheet. When the girl looks at some question on an answer sheet, she copies the answer to that question if it is on that answer sheet, or does nothing otherwise. Help the girl find the maximum number of questions she can get correct.
The first line contains three integers *n*, *p*, and *k* (1<=≤<=*n*,<=*p*<=≤<=1,<=000, 1<=≤<=*k*<=≤<=*min*(*n*,<=50)) — the number of questions, the maximum number of times the girl can glance, and the maximum number of consecutive questions that can be looked at in one time glancing, respectively. The second line starts with one integer *r* (0<=≤<=*r*<=≤<=*n*), denoting the number of questions the first genius has answered on his answer sheet. Then follow *r* integers *a*1,<=*a*2,<=...,<=*a**r* (1<=≤<=*a**i*<=≤<=*n*) — the answered questions, given in a strictly-increasing order (that is, *a**i*<=&lt;<=*a**i*<=+<=1). The third line starts with one integer *s* (0<=≤<=*s*<=≤<=*n*), denoting the number of questions the second genius has answered on his answer sheet. Then follow *s* integers *b*1,<=*b*2,<=...,<=*b**s* (1<=≤<=*b**i*<=≤<=*n*) — the answered questions, given in a strictly-increasing order (that is, *b**i*<=&lt;<=*b**i*<=+<=1).
Print one integer — the maximum number of questions the girl can answer correctly.
[ "6 2 3\n3 1 3 6\n4 1 2 5 6\n", "8 3 3\n4 1 3 5 6\n5 2 4 6 7 8\n" ]
[ "4", "7" ]
Let (*x*, *l*, *r*) denote the action of looking at all questions *i* such that *l* ≤ *i* ≤ *r* on the answer sheet of the *x*-th genius. In the first sample, the girl could get 4 questions correct by performing sequence of actions (1, 1, 3) and (2, 5, 6). In the second sample, the girl could perform sequence of actions (1, 3, 5), (2, 2, 4), and (2, 6, 8) to get 7 questions correct.
[]
46
0
0
19,178
10
LCIS
[ "dp" ]
D. LCIS
1
256
This problem differs from one which was on the online contest. The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=&lt;<=*a**i*<=+<=1 for *i*<=&lt;<=*n*. The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements. You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=500) — the length of the first sequence. The second line contains *n* space-separated integers from the range [0,<=109] — elements of the first sequence. The third line contains an integer *m* (1<=≤<=*m*<=≤<=500) — the length of the second sequence. The fourth line contains *m* space-separated integers from the range [0,<=109] — elements of the second sequence.
In the first line output *k* — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
[ "7\n2 3 1 6 5 4 6\n4\n1 3 5 6\n", "5\n1 2 0 2 1\n3\n1 0 1\n" ]
[ "3\n3 5 6 \n", "2\n0 1 \n" ]
none
[ { "input": "7\n2 3 1 6 5 4 6\n4\n1 3 5 6", "output": "3\n3 5 6 " }, { "input": "5\n1 2 0 2 1\n3\n1 0 1", "output": "2\n0 1 " }, { "input": "2\n6 10\n3\n6 3 3", "output": "1\n6 " }, { "input": "1\n7\n2\n7 9", "output": "1\n7 " }, { "input": "3\n37 49 24\n3\n33 5 70...
109
1,843,200
3.942067
19,208
487
Fight the Monster
[ "binary search", "brute force", "implementation" ]
null
null
A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (*HP*), offensive power (*ATK*) and defensive power (*DEF*). During the battle, every second the monster's HP decrease by *max*(0,<=*ATK**Y*<=-<=*DEF**M*), while Yang's HP decreases by *max*(0,<=*ATK**M*<=-<=*DEF**Y*), where index *Y* denotes Master Yang and index *M* denotes monster. Both decreases happen simultaneously Once monster's *HP*<=≤<=0 and the same time Master Yang's *HP*<=&gt;<=0, Master Yang wins. Master Yang can buy attributes from the magic shop of Cyberland: *h* bitcoins per *HP*, *a* bitcoins per *ATK*, and *d* bitcoins per *DEF*. Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win.
The first line contains three integers *HP**Y*,<=*ATK**Y*,<=*DEF**Y*, separated by a space, denoting the initial *HP*, *ATK* and *DEF* of Master Yang. The second line contains three integers *HP**M*,<=*ATK**M*,<=*DEF**M*, separated by a space, denoting the *HP*, *ATK* and *DEF* of the monster. The third line contains three integers *h*,<=*a*,<=*d*, separated by a space, denoting the price of 1 *HP*, 1 *ATK* and 1 *DEF*. All numbers in input are integer and lie between 1 and 100 inclusively.
The only output line should contain an integer, denoting the minimum bitcoins Master Yang should spend in order to win.
[ "1 2 1\n1 100 1\n1 100 100\n", "100 100 100\n1 1 1\n1 1 1\n" ]
[ "99\n", "0\n" ]
For the first sample, prices for *ATK* and *DEF* are extremely high. Master Yang can buy 99 HP, then he can beat the monster with 1 HP left. For the second sample, Master Yang is strong enough to beat the monster, so he doesn't need to buy anything.
[ { "input": "1 2 1\n1 100 1\n1 100 100", "output": "99" }, { "input": "100 100 100\n1 1 1\n1 1 1", "output": "0" }, { "input": "50 80 92\n41 51 56\n75 93 12", "output": "0" }, { "input": "76 63 14\n89 87 35\n20 15 56", "output": "915" }, { "input": "12 59 66\n43 15...
155
2,252,800
3
19,220
630
Forecast
[ "math" ]
null
null
The 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.
The only line of the input contains three integers *a*,<=*b*,<=*c* (<=-<=1000<=≤<=*a*,<=*b*,<=*c*<=≤<=1000) — the coefficients of *ax*2<=+<=*bx*<=+<=*c*<==<=0 equation.
In 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.
[ "1 30 200\n" ]
[ "-10.000000000000000\n-20.000000000000000" ]
none
[ { "input": "1 30 200", "output": "-10.000000000000000\n-20.000000000000000" }, { "input": "1 1 -1", "output": "0.618033988749895\n-1.618033988749895" }, { "input": "-1 1 1", "output": "1.618033988749895\n-0.618033988749895" }, { "input": "1000 1 -1", "output": "0.03112672...
46
0
0
19,229
392
Tower of Hanoi
[ "dp" ]
null
null
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1. Only one disk can be moved at a time. 1. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 1. No disk may be placed on top of a smaller disk. With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2*n*<=-<=1, where *n* is the number of disks. (c) Wikipedia. SmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all *n* disks are on the first rod. Moving a disk from rod *i* to rod *j* (1<=≤<=*i*,<=*j*<=≤<=3) costs *t**ij* units of money. The goal of the puzzle is to move all the disks to the third rod. In the problem you are given matrix *t* and an integer *n*. You need to count the minimal cost of solving SmallY's puzzle, consisting of *n* disks.
Each of the first three lines contains three integers — matrix *t*. The *j*-th integer in the *i*-th line is *t**ij* (1<=≤<=*t**ij*<=≤<=10000; *i*<=≠<=*j*). The following line contains a single integer *n* (1<=≤<=*n*<=≤<=40) — the number of disks. It is guaranteed that for all *i* (1<=≤<=*i*<=≤<=3), *t**ii*<==<=0.
Print a single integer — the minimum cost of solving SmallY's puzzle.
[ "0 1 1\n1 0 1\n1 1 0\n3\n", "0 2 2\n1 0 100\n1 2 0\n3\n", "0 2 1\n1 0 100\n1 2 0\n5\n" ]
[ "7\n", "19\n", "87\n" ]
none
[ { "input": "0 1 1\n1 0 1\n1 1 0\n3", "output": "7" }, { "input": "0 2 2\n1 0 100\n1 2 0\n3", "output": "19" }, { "input": "0 2 1\n1 0 100\n1 2 0\n5", "output": "87" }, { "input": "0 5835 1487\n6637 0 9543\n6961 6820 0\n7", "output": "723638" }, { "input": "0 3287 ...
140
0
3
19,234
526
Om Nom and Dark Park
[ "dfs and similar", "greedy", "implementation" ]
null
null
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2*n*<=+<=1<=-<=1 squares connected by roads so that the scheme of the park is a full binary tree of depth *n*. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2*n*,<=2*n*<=+<=1,<=...,<=2*n*<=+<=1<=-<=1 and these exits lead straight to the Om Nom friends' houses. From each square *i* (2<=≤<=*i*<=&lt;<=2*n*<=+<=1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly *n* roads. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
The first line contains integer *n* (1<=≤<=*n*<=≤<=10) — the number of roads on the path from the entrance to any exit. The next line contains 2*n*<=+<=1<=-<=2 numbers *a*2,<=*a*3,<=... *a*2*n*<=+<=1<=-<=1 — the initial numbers of street lights on each road of the park. Here *a**i* is the number of street lights on the road between squares *i* and . All numbers *a**i* are positive integers, not exceeding 100.
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
[ "2\n1 2 3 4 5 6\n" ]
[ "5\n" ]
Picture for the sample test. Green color denotes the additional street lights.
[ { "input": "2\n1 2 3 4 5 6", "output": "5" }, { "input": "2\n1 2 3 3 2 2", "output": "0" }, { "input": "1\n39 52", "output": "13" }, { "input": "2\n59 96 34 48 8 72", "output": "139" }, { "input": "3\n87 37 91 29 58 45 51 74 70 71 47 38 91 89", "output": "210"...
46
0
-1
19,255
45
Dancing Lessons
[ "data structures" ]
C. Dancing Lessons
2
256
There are *n* people taking dancing lessons. Every person is characterized by his/her dancing skill *a**i*. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of *a**i* variable. Your task is to find out what pairs and in what order will start dancing.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of people. The next line contains *n* symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=107) — the dancing skill. People are specified from left to right in the order in which they lined up.
Print the resulting number of couples *k*. Then print *k* lines containing two numerals each — the numbers of people forming the couple. The people are numbered with integers from 1 to *n* from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance.
[ "4\nBGBG\n4 2 4 3\n", "4\nBBGG\n4 6 1 5\n", "4\nBGBB\n1 1 2 3\n" ]
[ "2\n3 4\n1 2\n", "2\n2 3\n1 4\n", "1\n1 2\n" ]
none
[ { "input": "4\nBGBG\n4 2 4 3", "output": "2\n3 4\n1 2" }, { "input": "4\nBBGG\n4 6 1 5", "output": "2\n2 3\n1 4" }, { "input": "4\nBGBB\n1 1 2 3", "output": "1\n1 2" }, { "input": "1\nB\n490297", "output": "0" }, { "input": "2\nBB\n2518190 6313112", "output": ...
0
0
-1
19,278
696
PLEASE
[ "combinatorics", "dp", "implementation", "math", "matrices" ]
null
null
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts *n* turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After *n*-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number *n* of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array *a*1,<=*a*2,<=...,<=*a**k* such that in other words, *n* is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction *p*<=/<=*q* such that , where is the greatest common divisor. Since *p* and *q* can be extremely large, you only need to find the remainders of dividing each of them by 109<=+<=7. Please note that we want of *p* and *q* to be 1, not of their remainders after dividing by 109<=+<=7.
The first line of input contains a single integer *k* (1<=≤<=*k*<=≤<=105) — the number of elements in array Barney gave you. The second line contains *k* integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=1018) — the elements of the array.
In the only line of output print a single string *x*<=/<=*y* where *x* is the remainder of dividing *p* by 109<=+<=7 and *y* is the remainder of dividing *q* by 109<=+<=7.
[ "1\n2\n", "3\n1 1 1\n" ]
[ "1/2\n", "0/1\n" ]
none
[ { "input": "1\n2", "output": "1/2" }, { "input": "3\n1 1 1", "output": "0/1" }, { "input": "1\n983155795040951739", "output": "145599903/436799710" }, { "input": "2\n467131402341701583 956277077729692725", "output": "63467752/190403257" }, { "input": "10\n21767322...
1,000
15,769,600
0
19,295
282
Painting Eggs
[ "greedy", "math" ]
null
null
The Bitlandians are quite weird people. They have very peculiar customs. As is customary, Uncle J. wants to have *n* eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work. The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got *n* eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000. Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500. Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.
The first line contains integer *n* (1<=≤<=*n*<=≤<=106) — the number of eggs. Next *n* lines contain two integers *a**i* and *g**i* each (0<=≤<=*a**i*,<=*g**i*<=≤<=1000; *a**i*<=+<=*g**i*<==<=1000): *a**i* is the price said by A. for the *i*-th egg and *g**i* is the price said by G. for the *i*-th egg.
If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of *n* letters "G" and "A". The *i*-th letter of this string should represent the child who will get the *i*-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as *S**a*, and the money Uncle J. must pay G. for the painting as *S**g*, then this inequality must hold: |*S**a*<=<=-<=<=*S**g*|<=<=≤<=<=500. If there are several solutions, you are allowed to print any of them.
[ "2\n1 999\n999 1\n", "3\n400 600\n400 600\n400 600\n" ]
[ "AG\n", "AGA\n" ]
none
[ { "input": "2\n1 999\n999 1", "output": "AG" }, { "input": "3\n400 600\n400 600\n400 600", "output": "AGA" }, { "input": "2\n500 500\n500 500", "output": "AG" }, { "input": "1\n1 999", "output": "A" }, { "input": "10\n1 999\n1 999\n1 999\n1 999\n1 999\n1 999\n1 99...
62
0
0
19,304
696
Lorenzo Von Matterhorn
[ "brute force", "data structures", "implementation", "trees" ]
null
null
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections *i* and 2*i* and another road between *i* and 2*i*<=+<=1 for every positive integer *i*. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will *q* consecutive events happen soon. There are two types of events: 1. Government makes a new rule. A rule can be denoted by integers *v*, *u* and *w*. As the result of this action, the passing fee of all roads on the shortest path from *u* to *v* increases by *w* dollars. 2. Barney starts moving from some intersection *v* and goes to intersection *u* where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections. Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
The first line of input contains a single integer *q* (1<=≤<=*q*<=≤<=1<=000). The next *q* lines contain the information about the events in chronological order. Each event is described in form 1 *v* *u* *w* if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from *u* to *v* by *w* dollars, or in form 2 *v* *u* if it's an event when Barnie goes to cuddle from the intersection *v* to the intersection *u*. 1<=≤<=*v*,<=*u*<=≤<=1018,<=*v*<=≠<=*u*,<=1<=≤<=*w*<=≤<=109 states for every description line.
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
[ "7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4\n" ]
[ "94\n0\n32\n" ]
In the example testcase: Here are the intersections used: 1. Intersections on the path are 3, 1, 2 and 4. 1. Intersections on the path are 4, 2 and 1. 1. Intersections on the path are only 3 and 6. 1. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. 1. Intersections on the path are 6, 3 and 1. 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. 1. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
[ { "input": "7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4", "output": "94\n0\n32" }, { "input": "1\n2 666077344481199252 881371880336470888", "output": "0" }, { "input": "10\n1 1 63669439577744021 396980128\n1 2582240553355225 63669439577744021 997926286\n1 258224055335522...
296
8,192,000
3
19,313
915
Imbalance Value of a Tree
[ "data structures", "dsu", "graphs", "trees" ]
null
null
You are given a tree *T* consisting of *n* vertices. A number is written on each vertex; the number written on vertex *i* is *a**i*. Let's denote the function *I*(*x*,<=*y*) as the difference between maximum and minimum value of *a**i* on a simple path connecting vertices *x* and *y*. Your task is to calculate .
The first line contains one integer number *n* (1<=≤<=*n*<=≤<=106) — the number of vertices in the tree. The second line contains *n* integer numbers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the numbers written on the vertices. Then *n*<=-<=1 lines follow. Each line contains two integers *x* and *y* denoting an edge connecting vertex *x* and vertex *y* (1<=≤<=*x*,<=*y*<=≤<=*n*, *x*<=≠<=*y*). It is guaranteed that these edges denote a tree.
Print one number equal to .
[ "4\n2 2 3 1\n1 2\n1 3\n1 4\n" ]
[ "6\n" ]
none
[ { "input": "4\n2 2 3 1\n1 2\n1 3\n1 4", "output": "6" } ]
77
0
0
19,314
85
Domino
[ "constructive algorithms", "implementation" ]
A. Domino
1
256
We all know the problem about the number of ways one can tile a 2<=×<=*n* field by 1<=×<=2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes. You are given a 4<=×<=*n* rectangular field, that is the field that contains four lines and *n* columns. You have to find for it any tiling by 1<=×<=2 dominoes such that each of the *n*<=-<=1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2<=×<=1 as well as 1<=×<=2 dominoes. Write a program that finds an arbitrary sought tiling.
The input contains one positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of the field's columns.
If there's no solution, print "-1" (without the quotes). Otherwise, print four lines containing *n* characters each — that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling.
[ "4\n" ]
[ "yyzz\nbccd\nbxxd\nyyaa\n" ]
none
[ { "input": "4", "output": "aacc\nbbdd\nzkkz\nzllz" }, { "input": "2", "output": "aa\nbb\naa\nbb" }, { "input": "3", "output": "aab\nccb\nbaa\nbcc" }, { "input": "5", "output": "aaccz\nbbddz\nzkkmm\nzllnn" }, { "input": "1", "output": "a\na\nb\nb" }, { ...
1,000
33,792,000
0
19,337
581
Developing Skills
[ "implementation", "math", "sortings" ]
null
null
Petya loves computer games. Finally a game that he's been waiting for so long came out! The main character of this game has *n* different skills, each of which is characterized by an integer *a**i* from 0 to 100. The higher the number *a**i* is, the higher is the *i*-th skill of the character. The total rating of the character is calculated as the sum of the values ​​of for all *i* from 1 to *n*. The expression ⌊ *x*⌋ denotes the result of rounding the number *x* down to the nearest integer. At the beginning of the game Petya got *k* improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if *a*4<==<=46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused. Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.
The first line of the input contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=105, 0<=≤<=*k*<=≤<=107) — the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of *n* integers *a**i* (0<=≤<=*a**i*<=≤<=100), where *a**i* characterizes the level of the *i*-th skill of the character.
The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using *k* or less improvement units.
[ "2 4\n7 9\n", "3 8\n17 15 19\n", "2 2\n99 100\n" ]
[ "2\n", "5\n", "20\n" ]
In the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to *lfloor* *frac*{100}{10} *rfloor* +  *lfloor* *frac*{100}{10} *rfloor* = 10 + 10 =  20. In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ccaa4e1e435ea3a339c322e03a32de69d214a257.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b246630ca7d1b95b91970759bd8455cb3e930bf9.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "2 4\n7 9", "output": "2" }, { "input": "3 8\n17 15 19", "output": "5" }, { "input": "2 2\n99 100", "output": "20" }, { "input": "100 10000\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
31
0
0
19,356
271
Good Substrings
[ "data structures", "strings" ]
null
null
You've got string *s*, consisting of small English letters. Some of the English letters are good, the rest are bad. A substring *s*[*l*...*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) of string *s*<=<==<=<=*s*1*s*2...*s*|*s*| (where |*s*| is the length of string *s*) is string <=*s**l**s**l*<=+<=1...*s**r*. The substring *s*[*l*...*r*] is good, if among the letters <=*s**l*,<=*s**l*<=+<=1,<=...,<=*s**r* there are at most *k* bad ones (look at the sample's explanation to understand it more clear). Your task is to find the number of distinct good substrings of the given string *s*. Two substrings *s*[*x*...*y*] and *s*[*p*...*q*] are considered distinct if their content is different, i.e. *s*[*x*...*y*]<=≠<=*s*[*p*...*q*].
The first line of the input is the non-empty string *s*, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the *i*-th character of this string equals "1", then the *i*-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer *k* (0<=≤<=*k*<=≤<=|*s*|) — the maximum acceptable number of bad characters in a good substring.
Print a single integer — the number of distinct good substrings of string *s*.
[ "ababab\n01000000000000000000000000\n1\n", "acbacbacaa\n00000000000000000000000000\n2\n" ]
[ "5\n", "8\n" ]
In the first example there are following good substrings: "a", "ab", "b", "ba", "bab". In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".
[ { "input": "ababab\n01000000000000000000000000\n1", "output": "5" }, { "input": "acbacbacaa\n00000000000000000000000000\n2", "output": "8" }, { "input": "a\n00000000000000000000000000\n0", "output": "0" }, { "input": "aaaa\n00000000000000000000000000\n0", "output": "0" ...
1,122
1,228,800
3
19,407
883
Renovation
[ "constructive algorithms", "greedy", "sortings" ]
null
null
The mayor of the Berland city S sees the beauty differently than other city-dwellers. In particular, he does not understand at all, how antique houses can be nice-looking. So the mayor wants to demolish all ancient buildings in the city. The city S is going to host the football championship very soon. In order to make the city beautiful, every month the Berland government provides mayor a money tranche. The money has to be spent on ancient buildings renovation. There are *n* months before the championship and the *i*-th month tranche equals to *a**i* burles. The city S has *m* antique buildings and the renovation cost of the *j*-th building is *b**j* burles. The mayor has his own plans for spending the money. As he doesn't like antique buildings he wants to demolish as much of them as possible. For the *j*-th building he calculated its demolishing cost *p**j*. The mayor decided to act according to the following plan. Each month he chooses several (possibly zero) of *m* buildings to demolish in such a way that renovation cost of each of them separately is not greater than the money tranche *a**i* of this month (*b**j*<=≤<=*a**i*) — it will allow to deceive city-dwellers that exactly this building will be renovated. Then the mayor has to demolish all selected buildings during the current month as otherwise the dwellers will realize the deception and the plan will fail. Definitely the total demolishing cost can not exceed amount of money the mayor currently has. The mayor is not obliged to spend all the money on demolishing. If some money is left, the mayor puts it to the bank account and can use it in any subsequent month. Moreover, at any month he may choose not to demolish any buildings at all (in this case all the tranche will remain untouched and will be saved in the bank). Your task is to calculate the maximal number of buildings the mayor can demolish.
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — the number of months before the championship and the number of ancient buildings in the city S. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is the tranche of the *i*-th month. The third line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**j*<=≤<=109), where *b**j* is renovation cost of the *j*-th building. The fourth line contains *m* integers *p*1,<=*p*2,<=...,<=*p**m* (1<=≤<=*p**j*<=≤<=109), where *p**j* is the demolishing cost of the *j*-th building.
Output single integer — the maximal number of buildings the mayor can demolish.
[ "2 3\n2 4\n6 2 3\n1 3 2\n", "3 5\n5 3 1\n5 2 9 1 10\n4 2 1 3 10\n", "5 6\n6 3 2 4 3\n3 6 4 5 4 2\n1 4 3 2 5 3\n" ]
[ "2\n", "3\n", "6\n" ]
In the third example the mayor acts as follows. In the first month he obtains 6 burles tranche and demolishes buildings #2 (renovation cost 6, demolishing cost 4) and #4 (renovation cost 5, demolishing cost 2). He spends all the money on it. After getting the second month tranche of 3 burles, the mayor selects only building #1 (renovation cost 3, demolishing cost 1) for demolishing. As a result, he saves 2 burles for the next months. In the third month he gets 2 burle tranche, but decides not to demolish any buildings at all. As a result, he has 2 + 2 = 4 burles in the bank. This reserve will be spent on the fourth month together with the 4-th tranche for demolishing of houses #3 and #5 (renovation cost is 4 for each, demolishing costs are 3 and 5 correspondingly). After this month his budget is empty. Finally, after getting the last tranche of 3 burles, the mayor demolishes building #6 (renovation cost 2, demolishing cost 3). As it can be seen, he demolished all 6 buildings.
[ { "input": "2 3\n2 4\n6 2 3\n1 3 2", "output": "2" }, { "input": "3 5\n5 3 1\n5 2 9 1 10\n4 2 1 3 10", "output": "3" }, { "input": "5 6\n6 3 2 4 3\n3 6 4 5 4 2\n1 4 3 2 5 3", "output": "6" }, { "input": "1 5\n9\n1 2 3 4 5\n5 4 3 2 1", "output": "3" }, { "input": "...
30
0
0
19,515
297
Parity Game
[ "constructive algorithms" ]
null
null
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") *a* and *b*. Then you try to turn *a* into *b* using two types of operations: - Write *parity*(*a*) to the end of *a*. For example, . - Remove the first character of *a*. For example, . You cannot perform this operation if *a* is empty. You can use as many operations as you want. The problem is, is it possible to turn *a* into *b*? The *parity* of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
The first line contains the string *a* and the second line contains the string *b* (1<=≤<=|*a*|,<=|*b*|<=≤<=1000). Both strings contain only the characters "0" and "1". Here |*x*| denotes the length of the string *x*.
Print "YES" (without quotes) if it is possible to turn *a* into *b*, and "NO" (without quotes) otherwise.
[ "01011\n0110\n", "0011\n1110\n" ]
[ "YES\n", "NO\n" ]
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
[ { "input": "01011\n0110", "output": "YES" }, { "input": "0011\n1110", "output": "NO" }, { "input": "11111\n111111", "output": "YES" }, { "input": "0110011\n01100110", "output": "YES" }, { "input": "10000100\n011110", "output": "NO" }, { "input": "1\n0"...
1,000
111,104,000
0
19,538
758
Ability To Convert
[ "constructive algorithms", "dp", "greedy", "math", "strings" ]
null
null
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter *A* he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets 11311 (475<==<=1·162<=+<=13·161<=+<=11·160). Alexander lived calmly until he tried to convert the number back to the decimal number system. Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base *n* he will get the number *k*.
The first line contains the integer *n* (2<=≤<=*n*<=≤<=109). The second line contains the integer *k* (0<=≤<=*k*<=&lt;<=1060), it is guaranteed that the number *k* contains no more than 60 symbols. All digits in the second line are strictly less than *n*. Alexander guarantees that the answer exists and does not exceed 1018. The number *k* doesn't contain leading zeros.
Print the number *x* (0<=≤<=*x*<=≤<=1018) — the answer to the problem.
[ "13\n12\n", "16\n11311\n", "20\n999\n", "17\n2016\n" ]
[ "12", "475", "3789", "594" ]
In the first example 12 could be obtained by converting two numbers to the system with base 13: 12 = 12·13<sup class="upper-index">0</sup> or 15 = 1·13<sup class="upper-index">1</sup> + 2·13<sup class="upper-index">0</sup>.
[ { "input": "13\n12", "output": "12" }, { "input": "16\n11311", "output": "475" }, { "input": "20\n999", "output": "3789" }, { "input": "17\n2016", "output": "594" }, { "input": "1000\n1001", "output": "100001" }, { "input": "1000\n1000", "output": ...
62
0
3
19,570
140
New Year Cards
[ "brute force", "greedy", "implementation" ]
null
null
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has *n* friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to *n* in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the *i*-th friend sent to Alexander a card number *i*. Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: 1. He will never send to a firend a card that this friend has sent to him. 1. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times. Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to *n*. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card. Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible. Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
The first line contains an integer *n* (2<=≤<=*n*<=≤<=300) — the number of Alexander's friends, equal to the number of cards. Next *n* lines contain his friends' preference lists. Each list consists of *n* different integers from 1 to *n*. The last line contains Alexander's preference list in the same format.
Print *n* space-separated numbers: the *i*-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the *i*-th friend. If there are several solutions, print any of them.
[ "4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4\n" ]
[ "2 1 1 4\n" ]
In the sample, the algorithm of actions Alexander and his friends perform is as follows: 1. Alexander receives card 1 from the first friend. 1. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3. 1. Alexander receives card 2 from the second friend, now he has two cards — 1 and 2. 1. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend. 1. Alexander receives card 3 from the third friend. 1. Alexander receives card 4 from the fourth friend. 1. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).
[ { "input": "4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4", "output": "2 1 1 3" }, { "input": "2\n1 2\n2 1\n2 1", "output": "2 1" }, { "input": "3\n1 2 3\n2 3 1\n1 3 2\n3 2 1", "output": "2 3 1" }, { "input": "5\n1 4 2 3 5\n5 1 3 4 2\n3 2 4 1 5\n1 4 5 3 2\n5 2 3 4 1\n5 4 2 1...
218
0
0
19,597
559
Gerald and Giant Chess
[ "combinatorics", "dp", "math", "number theory" ]
null
null
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an *h*<=×<=*w* field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
The first line of the input contains three integers: *h*,<=*w*,<=*n* — the sides of the board and the number of black cells (1<=≤<=*h*,<=*w*<=≤<=105,<=1<=≤<=*n*<=≤<=2000). Next *n* lines contain the description of black cells. The *i*-th of these lines contains numbers *r**i*,<=*c**i* (1<=≤<=*r**i*<=≤<=*h*,<=1<=≤<=*c**i*<=≤<=*w*) — the number of the row and column of the *i*-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109<=+<=7.
[ "3 4 2\n2 2\n2 3\n", "100 100 3\n15 16\n16 15\n99 88\n" ]
[ "2\n", "545732279\n" ]
none
[ { "input": "3 4 2\n2 2\n2 3", "output": "2" }, { "input": "100 100 3\n15 16\n16 15\n99 88", "output": "545732279" }, { "input": "1000 1000 4\n50 50\n51 50\n50 51\n51 51", "output": "899660737" }, { "input": "100000 100000 4\n50001 50001\n50000 50000\n50000 50001\n50001 50000"...
1,450
48,742,400
3
19,622
94
Friends
[ "graphs", "implementation", "math" ]
B. Friends
1
256
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something. The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people" Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" — he kept on repeating in his mind. — "Let's take, say, Max, Ilya, Vova — here, they all know each other! And now let's add Dima and Oleg to Vova — none of them is acquainted with each other! Now, that math is just rubbish!" Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.
The first line contains an integer *m* (0<=≤<=*m*<=≤<=10), which is the number of relations of acquaintances among the five friends of Igor's. Each of the following *m* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=5;*a**i*<=≠<=*b**i*), where (*a**i*,<=*b**i*) is a pair of acquainted people. It is guaranteed that each pair of the acquaintances is described exactly once. The acquaintance relation is symmetrical, i.e. if *x* is acquainted with *y*, then *y* is also acquainted with *x*.
Print "FAIL", if among those five people there are no either three pairwise acquainted or three pairwise unacquainted people. Otherwise print "WIN".
[ "4\n1 3\n2 3\n1 4\n5 3\n", "5\n1 2\n2 3\n3 4\n4 5\n5 1\n" ]
[ "WIN\n", "FAIL\n" ]
none
[ { "input": "4\n1 3\n2 3\n1 4\n5 3", "output": "WIN" }, { "input": "5\n1 2\n2 3\n3 4\n4 5\n5 1", "output": "FAIL" }, { "input": "1\n4 3", "output": "WIN" }, { "input": "6\n1 3\n2 3\n1 2\n5 3\n4 2\n4 5", "output": "WIN" }, { "input": "2\n1 3\n2 5", "output": "WI...
46
307,200
0
19,751
413
Maze 2D
[ "data structures", "divide and conquer" ]
null
null
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a 2<=×<=*n* maze. Imagine a maze that looks like a 2<=×<=*n* rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move from an empty cell of the maze to any side-adjacent empty cell. The shortest path problem is formulated as follows. Given two free maze cells, you need to determine the minimum time required to go from one cell to the other. Unfortunately, the developed algorithm works well for only one request for finding the shortest path, in practice such requests occur quite often. You, as the chief R2 programmer, are commissioned to optimize the algorithm to find the shortest path. Write a program that will effectively respond to multiple requests to find the shortest path in a 2<=×<=*n* maze.
The first line contains two integers, *n* and *m* (1<=≤<=*n*<=≤<=2·105; 1<=≤<=*m*<=≤<=2·105) — the width of the maze and the number of queries, correspondingly. Next two lines contain the maze. Each line contains *n* characters, each character equals either '.' (empty cell), or 'X' (obstacle). Each of the next *m* lines contains two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=2*n*) — the description of the *i*-th request. Numbers *v**i*, *u**i* mean that you need to print the value of the shortest path from the cell of the maze number *v**i* to the cell number *u**i*. We assume that the cells of the first line of the maze are numbered from 1 to *n*, from left to right, and the cells of the second line are numbered from *n*<=+<=1 to 2*n* from left to right. It is guaranteed that both given cells are empty.
Print *m* lines. In the *i*-th line print the answer to the *i*-th request — either the size of the shortest path or -1, if we can't reach the second cell from the first one.
[ "4 7\n.X..\n...X\n5 1\n1 3\n7 7\n1 4\n6 1\n4 7\n5 7\n", "10 3\nX...X..X..\n..X...X..X\n11 7\n7 18\n18 10\n" ]
[ "1\n4\n0\n5\n2\n2\n2\n", "9\n-1\n3\n" ]
none
[ { "input": "4 7\n.X..\n...X\n5 1\n1 3\n7 7\n1 4\n6 1\n4 7\n5 7", "output": "1\n4\n0\n5\n2\n2\n2" }, { "input": "10 3\nX...X..X..\n..X...X..X\n11 7\n7 18\n18 10", "output": "9\n-1\n3" }, { "input": "1 1\n.\n.\n1 2", "output": "1" }, { "input": "2 1\n..\n.X\n1 2", "output":...
1,247
75,776,000
3
19,757
381
Sereja and Stairs
[ "greedy", "implementation", "sortings" ]
null
null
Sereja loves integer sequences very much. He especially likes stairs. Sequence *a*1,<=*a*2,<=...,<=*a*|*a*| (|*a*| is the length of the sequence) is stairs if there is such index *i* (1<=≤<=*i*<=≤<=|*a*|), that the following condition is met: For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't. Sereja has *m* cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?
The first line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of Sereja's cards. The second line contains *m* integers *b**i* (1<=≤<=*b**i*<=≤<=5000) — the numbers on the Sereja's cards.
In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.
[ "5\n1 2 3 4 5\n", "6\n1 1 2 2 3 3\n" ]
[ "5\n5 4 3 2 1\n", "5\n1 2 3 2 1\n" ]
none
[ { "input": "5\n1 2 3 4 5", "output": "5\n5 4 3 2 1" }, { "input": "6\n1 1 2 2 3 3", "output": "5\n1 2 3 2 1" }, { "input": "47\n3 4 5 3 1 4 4 3 4 6 1 5 1 3 5 3 6 5 1 4 3 2 6 5 3 1 4 6 4 6 2 1 1 1 4 3 6 1 6 6 3 5 1 4 6 4 4", "output": "11\n1 2 3 4 5 6 5 4 3 2 1" }, { "input": ...
108
6,246,400
3
19,787
138
Mushroom Gnomes - 2
[ "binary search", "data structures", "probabilities", "sortings" ]
null
null
One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story: Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are *n* trees and *m* magic mushrooms in the woods: the *i*-th tree grows at a point on a straight line with coordinates *a**i* and has the height of *h**i*, the *j*-th mushroom grows at the point with coordinates *b**j* and has magical powers *z**j*. But one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate *x* and height *h* falls to the left, then all the mushrooms that belong to the right-open interval [*x*<=-<=*h*,<=*x*), are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval (*x*,<=*x*<=+<=*h*] are destroyed. Only those mushrooms that are not hit by a single tree survive. Knowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death. Natalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=≤<=104) — the number of trees and mushrooms, respectively. Each of the next *n* lines contain four integers — *a**i*, *h**i*, *l**i*, *r**i* (|*a**i*|<=≤<=109, 1<=≤<=*h**i*<=≤<=109, 0<=≤<=*l**i*,<=*r**i*,<=*l**i*<=+<=*r**i*<=≤<=100) which represent the coordinate of the *i*-th tree, its height, the percentage of the probabilities that the tree falls to the left and to the right, respectively (the remaining percentage is the probability that the tree will stand on). Each of next *m* lines contain two integers *b**j*, *z**j* (|*b**j*|<=≤<=109, 1<=≤<=*z**j*<=≤<=103) which represent the coordinate and the magical power of the *j*-th mushroom, respectively. An arbitrary number of trees and mushrooms can grow in one point.
Print a real number — the expectation of the total magical power of the surviving mushrooms. The result is accepted with relative or absolute accuracy 10<=-<=4.
[ "1 1\n2 2 50 50\n1 1\n", "2 1\n2 2 50 50\n4 2 50 50\n3 1\n" ]
[ "0.5000000000\n", "0.2500000000\n" ]
It is believed that the mushroom with the coordinate *x* belongs to the right-open interval [*l*, *r*) if and only if *l* ≤ *x* &lt; *r*. Similarly, the mushroom with the coordinate *x* belongs to the left-open interval (*l*, *r*] if and only if *l* &lt; *x* ≤ *r*. In the first test the mushroom survives with the probability of 50%, depending on where the single tree falls. In the second test the mushroom survives only if neither of the two trees falls on it. It occurs with the probability of 50%  ×  50% = 25%. Pretest №12 is the large test with 10<sup class="upper-index">5</sup> trees and one mushroom.
[ { "input": "1 1\n2 2 50 50\n1 1", "output": "0.5000000000" }, { "input": "2 1\n2 2 50 50\n4 2 50 50\n3 1", "output": "0.2500000000" }, { "input": "1 1\n3 2 73 12\n1 5", "output": "1.3500000000" }, { "input": "2 2\n-8 4 66 9\n-2 3 55 43\n3 8\n7 9", "output": "17.0000000000...
46
0
0
19,819
372
Watching Fireworks is Fun
[ "data structures", "dp", "math" ]
null
null
A festival will be held in a town's main street. There are *n* sections in the main street. The sections are numbered 1 through *n* from left to right. The distance between each adjacent sections is 1. In the festival *m* fireworks will be launched. The *i*-th (1<=≤<=*i*<=≤<=*m*) launching is on time *t**i* at section *a**i*. If you are at section *x* (1<=≤<=*x*<=≤<=*n*) at the time of *i*-th launching, you'll gain happiness value *b**i*<=-<=|*a**i*<=-<=*x*| (note that the happiness value might be a negative value). You can move up to *d* length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness. Note that two or more fireworks can be launched at the same time.
The first line contains three integers *n*, *m*, *d* (1<=≤<=*n*<=≤<=150000; 1<=≤<=*m*<=≤<=300; 1<=≤<=*d*<=≤<=*n*). Each of the next *m* lines contains integers *a**i*, *b**i*, *t**i* (1<=≤<=*a**i*<=≤<=*n*; 1<=≤<=*b**i*<=≤<=109; 1<=≤<=*t**i*<=≤<=109). The *i*-th line contains description of the *i*-th launching. It is guaranteed that the condition *t**i*<=≤<=*t**i*<=+<=1 (1<=≤<=*i*<=&lt;<=*m*) will be satisfied.
Print a single integer — the maximum sum of happiness that you can gain from watching all the fireworks. Please, do not write the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "50 3 1\n49 1 1\n26 1 4\n6 1 10\n", "10 2 1\n1 1000 4\n9 1000 4\n" ]
[ "-31\n", "1992\n" ]
none
[ { "input": "50 3 1\n49 1 1\n26 1 4\n6 1 10", "output": "-31" }, { "input": "10 2 1\n1 1000 4\n9 1000 4", "output": "1992" }, { "input": "30 8 2\n15 97 3\n18 64 10\n20 14 20\n16 18 36\n10 23 45\n12 60 53\n17 93 71\n11 49 85", "output": "418" }, { "input": "100 20 5\n47 93 3\n6...
3,275
22,732,800
3
19,861
570
Tree Requests
[ "binary search", "bitmasks", "constructive algorithms", "dfs and similar", "graphs", "trees" ]
null
null
Roman planted a tree consisting of *n* vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the *n*<=-<=1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex *i* is vertex *p**i*, the parent index is always less than the index of the vertex (i.e., *p**i*<=&lt;<=*i*). The depth of the vertex is the number of nodes on the path from the root to *v* along the edges. In particular, the depth of the root is equal to 1. We say that vertex *u* is in the subtree of vertex *v*, if we can get from *u* to *v*, moving from the vertex to the parent. In particular, vertex *v* is in its subtree. Roma gives you *m* queries, the *i*-th of which consists of two numbers *v**i*, *h**i*. Let's consider the vertices in the subtree *v**i* located at depth *h**i*. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.
The first line contains two integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=500<=000) — the number of nodes in the tree and queries, respectively. The following line contains *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* — the parents of vertices from the second to the *n*-th (1<=≤<=*p**i*<=&lt;<=*i*). The next line contains *n* lowercase English letters, the *i*-th of these letters is written on vertex *i*. Next *m* lines describe the queries, the *i*-th line contains two numbers *v**i*, *h**i* (1<=≤<=*v**i*,<=*h**i*<=≤<=*n*) — the vertex and the depth that appear in the *i*-th query.
Print *m* lines. In the *i*-th line print "Yes" (without the quotes), if in the *i*-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).
[ "6 5\n1 1 1 3 3\nzacccd\n1 1\n3 3\n4 1\n6 1\n1 2\n" ]
[ "Yes\nNo\nYes\nYes\nYes\n" ]
String *s* is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".
[ { "input": "6 5\n1 1 1 3 3\nzacccd\n1 1\n3 3\n4 1\n6 1\n1 2", "output": "Yes\nNo\nYes\nYes\nYes" }, { "input": "5 6\n1 1 2 3\ncbcab\n3 1\n5 2\n1 3\n4 1\n4 2\n1 1", "output": "Yes\nYes\nNo\nYes\nYes\nYes" }, { "input": "5 6\n1 2 2 1\nbaabb\n1 1\n1 2\n5 1\n4 1\n4 2\n3 2", "output": "Ye...
1,216
268,390,400
0
19,891
0
none
[ "none" ]
null
null
Профиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*». Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправо — в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце. Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины: - наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма), - наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска).
В первой строке входных данных записаны два целых числа *n* и *m* (1<=≤<=*n*,<=*m*<=≤<=100) — количество строк и столбцов в схематичном изображении соответственно. Далее следуют *n* строк по *m* символов в каждой — схематичное изображение горного хребта. Каждый символ схематичного изображения — это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».
Выведите через пробел два целых числа: - величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма), - величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска).
[ "6 11\n...........\n.........*.\n.*.......*.\n**.......*.\n**..*...**.\n***********\n", "5 5\n....*\n...**\n..***\n.****\n*****\n", "8 7\n.......\n.*.....\n.*.....\n.**....\n.**.*..\n.****.*\n.******\n*******\n" ]
[ "3 4\n", "1 0\n", "6 2\n" ]
В первом тестовом примере высоты гор равны: 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).
[ { "input": "6 11\n...........\n.........*.\n.*.......*.\n**.......*.\n**..*...**.\n***********", "output": "3 4" }, { "input": "5 5\n....*\n...**\n..***\n.****\n*****", "output": "1 0" }, { "input": "8 7\n.......\n.*.....\n.*.....\n.**....\n.**.*..\n.****.*\n.******\n*******", "outpu...
46
4,608,000
-1
19,933
584
Marina and Vasya
[ "constructive algorithms", "greedy", "strings" ]
null
null
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly *t* characters. Help Vasya find at least one such string. More formally, you are given two strings *s*1, *s*2 of length *n* and number *t*. Let's denote as *f*(*a*,<=*b*) the number of characters in which strings *a* and *b* are different. Then your task will be to find any string *s*3 of length *n*, such that *f*(*s*1,<=*s*3)<==<=*f*(*s*2,<=*s*3)<==<=*t*. If there is no such string, print <=-<=1.
The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=105, 0<=≤<=*t*<=≤<=*n*). The second line contains string *s*1 of length *n*, consisting of lowercase English letters. The third line contain string *s*2 of length *n*, consisting of lowercase English letters.
Print a string of length *n*, differing from string *s*1 and from *s*2 in exactly *t* characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.
[ "3 2\nabc\nxyc\n", "1 0\nc\nb\n" ]
[ "ayd", "-1\n" ]
none
[ { "input": "3 2\nabc\nxyc", "output": "bac" }, { "input": "1 0\nc\nb", "output": "-1" }, { "input": "1 1\na\na", "output": "b" }, { "input": "2 1\naa\naa", "output": "ab" }, { "input": "3 1\nbcb\nbca", "output": "bcc" }, { "input": "4 3\nccbb\ncaab", ...
61
5,734,400
0
19,967
22
Segments
[ "greedy", "sortings" ]
D. Segments
1
256
You are given *n* segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?
The first line of the input contains single integer number *n* (1<=≤<=*n*<=≤<=1000) — amount of segments. Following *n* lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.
The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.
[ "2\n0 2\n2 5\n", "5\n0 3\n4 2\n4 8\n8 10\n7 7\n" ]
[ "1\n2 ", "3\n7 10 3\n" ]
none
[ { "input": "2\n0 2\n2 5", "output": "1\n2 " }, { "input": "5\n0 3\n4 2\n4 8\n8 10\n7 7", "output": "3\n3 7 10 " }, { "input": "3\n40 -83\n52 -80\n-21 -4", "output": "1\n-4 " }, { "input": "4\n67 -88\n37 -62\n-26 91\n-99 -50", "output": "2\n-50 91 " }, { "input": "...
109
409,600
3.944737
20,001
78
Beaver Game
[ "dp", "games", "number theory" ]
C. Beaver Game
1
256
Two beavers, Timur and Marsel, play the following game. There are *n* logs, each of exactly *m* meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than *k* meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins. Timur makes the first move. The players play in the optimal way. Determine the winner.
The first line contains three integers *n*, *m*, *k* (1<=≤<=*n*,<=*m*,<=*k*<=≤<=109).
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
[ "1 15 4\n", "4 9 5\n" ]
[ "Timur", "Marsel" ]
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as *k* = 4. Thus, the winner is Timur. In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
[ { "input": "1 15 4", "output": "Timur" }, { "input": "4 9 5", "output": "Marsel" }, { "input": "14 30 9", "output": "Marsel" }, { "input": "81 180 53", "output": "Timur" }, { "input": "225 187 20", "output": "Marsel" }, { "input": "501 840 11", "ou...
186
1,024,000
-1
20,060
940
Machine Learning
[ "brute force", "data structures" ]
null
null
You come home and fell some unpleasant smell. Where is it coming from? You are given an array *a*. You have to answer the following queries: 1. You are given two integers *l* and *r*. Let *c**i* be the number of occurrences of *i* in *a**l*:<=*r*, where *a**l*:<=*r* is the subarray of *a* from *l*-th element to *r*-th inclusive. Find the Mex of {*c*0,<=*c*1,<=...,<=*c*109} 1. You are given two integers *p* to *x*. Change *a**p* to *x*. The Mex of a multiset of numbers is the smallest non-negative integer not in the set. Note that in this problem all elements of *a* are positive, which means that *c*0 = 0 and 0 is never the answer for the query of the second type.
The first line of input contains two integers *n* and *q* (1<=≤<=*n*,<=*q*<=≤<=100<=000) — the length of the array and the number of queries respectively. The second line of input contains *n* integers — *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109). Each of the next *q* lines describes a single query. The first type of query is described by three integers *t**i*<==<=1, *l**i*, *r**i*, where 1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n* — the bounds of the subarray. The second type of query is described by three integers *t**i*<==<=2, *p**i*, *x**i*, where 1<=≤<=*p**i*<=≤<=*n* is the index of the element, which must be changed and 1<=≤<=*x**i*<=≤<=109 is the new value.
For each query of the first type output a single integer  — the Mex of {*c*0,<=*c*1,<=...,<=*c*109}.
[ "10 4\n1 2 3 1 1 2 2 2 9 9\n1 1 1\n1 2 8\n2 7 1\n1 2 8\n" ]
[ "2\n3\n2\n" ]
The subarray of the first query consists of the single element — 1. The subarray of the second query consists of four 2s, one 3 and two 1s. The subarray of the fourth query consists of three 1s, three 2s and one 3.
[ { "input": "10 4\n1 2 3 1 1 2 2 2 9 9\n1 1 1\n1 2 8\n2 7 1\n1 2 8", "output": "2\n3\n2" } ]
15
0
-1
20,111
840
Leha and Function
[ "combinatorics", "greedy", "math", "number theory", "sortings" ]
null
null
Leha like all kinds of strange things. Recently he liked the function *F*(*n*,<=*k*). Consider all possible *k*-element subsets of the set [1,<=2,<=...,<=*n*]. For subset find minimal element in it. *F*(*n*,<=*k*) — mathematical expectation of the minimal element among all *k*-element subsets. But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays *A* and *B*, each consists of *m* integers. For all *i*,<=*j* such that 1<=≤<=*i*,<=*j*<=≤<=*m* the condition *A**i*<=≥<=*B**j* holds. Help Leha rearrange the numbers in the array *A* so that the sum is maximally possible, where *A*' is already rearranged array.
First line of input data contains single integer *m* (1<=≤<=*m*<=≤<=2·105) — length of arrays *A* and *B*. Next line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=109) — array *A*. Next line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=109) — array *B*.
Output *m* integers *a*'1,<=*a*'2,<=...,<=*a*'*m* — array *A*' which is permutation of the array *A*.
[ "5\n7 3 5 3 4\n2 1 3 2 3\n", "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2\n" ]
[ "4 7 3 5 3\n", "2 6 4 5 8 8 6\n" ]
none
[ { "input": "5\n7 3 5 3 4\n2 1 3 2 3", "output": "4 7 3 5 3" }, { "input": "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2", "output": "2 6 4 5 8 8 6" } ]
2,000
19,353,600
0
20,126