problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
E. Wavy numberstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA wavy number is such positive integer that for any digit of its decimal representation except for the first one and the last one following condition holds: the digit is either strictly larger than both its adjacent digits or strictly less than both its adjacent digits. For example, numbers 35270, 102, 747, 20 and 3 are wavy and numbers 123, 1000 and 2212 are not.The task is to find the k-th smallest wavy number r that is divisible by n for the given integer values n and k.You are to write a program that will find the value of r if it doesn't exceed 1014.InputThe only line of input contains two integers n and k, separated by a single space (1 ≀ n, k ≀ 1014). OutputYour task is to output the only integer r β€” the answer to the given problem. If such number does not exist or it is larger than 1014, then print "-1" (minus one without the quotes) instead.ExamplesInput123 4Output1845Input100 1Output-1Input97461 457Output1805270103NoteThe values of the first four wavy numbers that are divisible by n for the first sample are: 492, 615, 738 and 1845.
Input123 4
Output1845
1.5 seconds
256 megabytes
['brute force', 'dfs and similar', 'meet-in-the-middle', 'sortings', '*2900']
D. Red-Green Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: Red-green tower is consisting of some number of levels; Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; Each level of the red-green tower should contain blocks of the same color. Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks.Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower.You are to write a program that will find the number of different red-green towers of height h moduloΒ 109 + 7.InputThe only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1).OutputOutput the only integer β€” the number of different possible red-green towers of height h moduloΒ 109 + 7.ExamplesInput4 6Output2Input9 7Output6Input1 1Output2NoteThe image in the problem statement shows all possible red-green towers for the first sample.
Input4 6
Output2
2 seconds
256 megabytes
['dp', '*2000']
C. Table Decorationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color?Your task is to write a program that for given values r, g and b will find the maximum number t of tables, that can be decorated in the required manner.InputThe single line contains three integers r, g and b (0 ≀ r, g, b ≀ 2Β·109) β€” the number of red, green and blue baloons respectively. The numbers are separated by exactly one space.OutputPrint a single integer t β€” the maximum number of tables that can be decorated in the required manner.ExamplesInput5 4 3Output4Input1 1 1Output1Input2 3 3Output2NoteIn the first sample you can decorate the tables with the following balloon sets: "rgg", "gbb", "brr", "rrg", where "r", "g" and "b" represent the red, green and blue balls, respectively.
Input5 4 3
Output4
1 second
256 megabytes
['greedy', '*1800']
B. Random Teamstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.InputThe only line of input contains two integers n and m, separated by a single space (1 ≀ m ≀ n ≀ 109) β€” the number of participants and the number of teams respectively. OutputThe only line of the output should contain two integers kmin and kmax β€” the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively.ExamplesInput5 1Output10 10Input3 2Output1 1Input6 3Output3 6NoteIn the first sample all the participants get into one team, so there will be exactly ten pairs of friends.In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people.
Input5 1
Output10 10
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'greedy', 'math', '*1300']
A. Initial Bettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size b of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins b in the initial bet.InputThe input consists of a single line containing five integers c1, c2, c3, c4 and c5 β€” the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0 ≀ c1, c2, c3, c4, c5 ≀ 100).OutputPrint the only line containing a single positive integer b β€” the number of coins in the initial bet of each player. If there is no such value of b, then print the only value "-1" (quotes for clarity).ExamplesInput2 5 4 0 4Output3Input4 5 9 2 1Output-1NoteIn the first sample the following sequence of operations is possible: One coin is passed from the fourth player to the second player; One coin is passed from the fourth player to the fifth player; One coin is passed from the first player to the third player; One coin is passed from the fourth player to the second player.
Input2 5 4 0 4
Output3
1 second
256 megabytes
['implementation', '*1100']
E. Dreamoon and Notepadtime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon has just created a document of hard problems using notepad.exe. The document consists of n lines of text, ai denotes the length of the i-th line. He now wants to know what is the fastest way to move the cursor around because the document is really long.Let (r, c) be a current cursor position, where r is row number and c is position of cursor in the row. We have 1 ≀ r ≀ n and 0 ≀ c ≀ ar.We can use following six operations in notepad.exe to move our cursor assuming the current cursor position is at (r, c): up key: the new cursor position (nr, nc) = (max(r - 1, 1), min(anr, c)) down key: the new cursor position (nr, nc) = (min(r + 1, n), min(anr, c)) left key: the new cursor position (nr, nc) = (r, max(0, c - 1)) right key: the new cursor position (nr, nc) = (r, min(anr, c + 1)) HOME key: the new cursor position (nr, nc) = (r, 0) END key: the new cursor position (nr, nc) = (r, ar) You're given the document description (n and sequence ai) and q queries from Dreamoon. Each query asks what minimal number of key presses is needed to move the cursor from (r1, c1) to (r2, c2).InputThe first line contains an integer n(1 ≀ n ≀ 400, 000) β€” the number of lines of text. The second line contains n integers a1, a2, ..., an(1 ≀ ai ≀ 108).The third line contains an integer q(1 ≀ q ≀ 400, 000). Each of the next q lines contains four integers r1, c1, r2, c2 representing a query (1 ≀ r1, r2 ≀ n, 0 ≀ c1 ≀ ar1, 0 ≀ c2 ≀ ar2).OutputFor each query print the result of the query.ExamplesInput91 3 5 3 1 3 5 3 143 5 3 13 3 7 31 0 3 36 0 7 3Output2532Input210 511 0 1 5Output3NoteIn the first sample, the first query can be solved with keys: HOME, right.The second query can be solved with keys: down, down, down, END, down.The third query can be solved with keys: down, END, down.The fourth query can be solved with keys: END, down.
Input91 3 5 3 1 3 5 3 143 5 3 13 3 7 31 0 3 36 0 7 3
Output2532
3.5 seconds
256 megabytes
['data structures', '*3100']
D. Dreamoon and Binarytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDreamoon saw a large integer x written on the ground and wants to print its binary form out. Dreamoon has accomplished the part of turning x into its binary format. Now he is going to print it in the following manner.He has an integer n = 0 and can only perform the following two operations in any order for unlimited times each: Print n in binary form without leading zeros, each print will append to the right of previous prints. Increase n by 1. Let's define an ideal sequence as a sequence of operations that can successfully print binary representation of x without leading zeros and ends with a print operation (i.e. operation 1). Dreamoon wants to know how many different ideal sequences are there and the length (in operations) of the shortest ideal sequence.The answers might be large so please print them modulo 1000000007 (109 + 7).Let's define the string representation of an ideal sequence as a string of '1' and '2' where the i-th character in the string matches the i-th operation performed. Two ideal sequences are called different if their string representations are different.InputThe single line of the input contains a binary integer representing x (1 ≀ x < 25000) without leading zeros.OutputThe first line of the output should contain an integer representing the number of different ideal sequences modulo 1000000007 (109 + 7).The second line of the output contains an integer representing the minimal length of an ideal sequence modulo 1000000007 (109 + 7).ExamplesInput101Output16Input11010Output35NoteFor the first sample, the shortest and the only ideal sequence is Β«222221Β» of length 6.For the second sample, there are three ideal sequences Β«21211Β», Β«212222222221Β», Β«222222222222222222222222221Β». Among them the shortest one has length 5.
Input101
Output16
2 seconds
512 megabytes
['dp', 'strings', '*2700']
E. Dreamoon and Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.More formally, let's define as maximum value of over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know for all x from 0 to |s| where |s| denotes the length of string s.InputThe first line of the input contains the string s (1 ≀ |s| ≀ 2 000).The second line of the input contains the string p (1 ≀ |p| ≀ 500).Both strings will only consist of lower case English letters.OutputPrint |s| + 1 space-separated integers in a single line representing the for all x from 0 to |s|.ExamplesInputaaaaaaaOutput2 2 1 1 0 0InputaxbaxxbabOutput0 1 1 2 1 1 0 0NoteFor the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}. For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
Inputaaaaaaa
Output2 2 1 1 0 0
1 second
256 megabytes
['dp', 'strings', '*2200']
D. Dreamoon and Setstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon likes to play with sets, integers and . is defined as the largest positive integer that divides both a and b.Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, .Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.InputThe single line of the input contains two space separated integers n, k (1 ≀ n ≀ 10 000, 1 ≀ k ≀ 100).OutputOn the first line print a single integer β€” the minimal possible m. On each of the next n lines print four space separated integers representing the i-th set.Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.ExamplesInput1 1Output51 2 3 5Input2 2Output222 4 6 2214 18 10 16NoteFor the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since .
Input1 1
Output51 2 3 5
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1900']
C. Dreamoon and Sumstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if and , where k is some integer number in range [1, a].By we denote the quotient of integer division of x and y. By we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT.The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon?InputThe single line of the input contains two integers a, b (1 ≀ a, b ≀ 107).OutputPrint a single integer representing the answer modulo 1 000 000 007 (109 + 7).ExamplesInput1 1Output0Input2 2Output8NoteFor the first sample, there are no nice integers because is always zero.For the second sample, the set of nice integers is {3, 5}.
Input1 1
Output0
1.5 seconds
256 megabytes
['math', '*1600']
B. Dreamoon and WiFitime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.Each command is one of the following two types: Go 1 unit towards the positive direction, denoted as '+' Go 1 unit towards the negative direction, denoted as '-' But the Wi-Fi condition is so poor that Dreamoon's smartphone reports some of the commands can't be recognized and Dreamoon knows that some of them might even be wrong though successfully recognized. Dreamoon decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the 1 unit to the negative or positive direction with the same probability 0.5). You are given an original list of commands sent by Drazil and list received by Dreamoon. What is the probability that Dreamoon ends in the position originally supposed to be final by Drazil's commands?InputThe first line contains a string s1 β€” the commands Drazil sends to Dreamoon, this string consists of only the characters in the set {'+', '-'}. The second line contains a string s2 β€” the commands Dreamoon's smartphone recognizes, this string consists of only the characters in the set {'+', '-', '?'}. '?' denotes an unrecognized command.Lengths of two strings are equal and do not exceed 10.OutputOutput a single real number corresponding to the probability. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9.ExamplesInput++-+-+-+-+Output1.000000000000Input+-+-+-??Output0.500000000000Input+++??-Output0.000000000000NoteFor the first sample, both s1 and s2 will lead Dreamoon to finish at the same position  + 1. For the second sample, s1 will lead Dreamoon to finish at position 0, while there are four possibilites for s2: {"+-++", "+-+-", "+--+", "+---"} with ending position {+2, 0, 0, -2} respectively. So there are 2 correct cases out of 4, so the probability of finishing at the correct position is 0.5. For the third sample, s2 could only lead us to finish at positions {+1, -1, -3}, so the probability to finish at the correct position  + 3 is 0.
Input++-+-+-+-+
Output1.000000000000
1 second
256 megabytes
['bitmasks', 'brute force', 'combinatorics', 'dp', 'math', 'probabilities', '*1300']
A. Dreamoon and Stairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?InputThe single line contains two space separated integers n, m (0 < n ≀ 10000, 1 < m ≀ 10).OutputPrint a single integer β€” the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print  - 1 instead.ExamplesInput10 2Output6Input3 5Output-1NoteFor the first sample, Dreamoon could climb in 6 moves with following sequence of steps: {2, 2, 2, 2, 1, 1}.For the second sample, there are only three valid sequence of steps {2, 1}, {1, 2}, {1, 1, 1} with 2, 2, and 3 steps respectively. All these numbers are not multiples of 5.
Input10 2
Output6
1 second
256 megabytes
['implementation', 'math', '*1000']
F. Meta-universetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider infinite grid of unit cells. Some of those cells are planets. Meta-universe M = {p1, p2, ..., pk} is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet pi of meta-universe M on it; 2) there are planets of M located on both sides from this row or column. In this case we can turn the meta-universe M into two non-empty meta-universes M1 and M2 containing planets that are located on respective sides of this row or column. A meta-universe which can't be split using operation above is called a universe. We perform such operations until all meta-universes turn to universes.Given positions of the planets in the original meta-universe, find the number of universes that are result of described process. It can be proved that each universe is uniquely identified not depending from order of splitting.InputThe first line of input contains an integer n, (1 ≀ n ≀ 105), denoting the number of planets in the meta-universe.The next n lines each contain integers xi and yi, ( - 109 ≀ xi, yi ≀ 109), denoting the coordinates of the i-th planet. All planets are located in different cells.OutputPrint the number of resulting universes.ExamplesInput50 00 22 02 12 2Output3Input80 01 00 20 33 03 12 33 3Output1NoteThe following figure describes the first test case:
Input50 00 22 02 12 2
Output3
2 seconds
256 megabytes
['data structures', '*2900']
E. Strongly Connected City 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine a city with n junctions and m streets. Junctions are numbered from 1 to n.In order to increase the traffic flow, mayor of the city has decided to make each street one-way. This means in the street between junctions u and v, the traffic moves only from u to v or only from v to u. The problem is to direct the traffic flow of streets in a way that maximizes the number of pairs (u, v) where 1 ≀ u, v ≀ n and it is possible to reach junction v from u by passing the streets in their specified direction. Your task is to find out maximal possible number of such pairs.InputThe first line of input contains integers n and m, (), denoting the number of junctions and streets of the city.Each of the following m lines contains two integers u and v, (u ≠ v), denoting endpoints of a street in the city.Between every two junctions there will be at most one street. It is guaranteed that before mayor decision (when all streets were two-way) it was possible to reach each junction from any other junction.OutputPrint the maximal number of pairs (u, v) such that that it is possible to reach junction v from u after directing the streets.ExamplesInput5 41 21 31 41 5Output13Input4 51 22 33 44 11 3Output16Input2 11 2Output3Input6 71 22 31 31 44 55 66 4Output27NoteIn the first sample, if the mayor makes first and second streets one-way towards the junction 1 and third and fourth streets in opposite direction, there would be 13 pairs of reachable junctions: {(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (2, 1), (3, 1), (1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)}
Input5 41 21 31 41 5
Output13
2 seconds
256 megabytes
['dfs and similar', '*2700']
D. CGCDSSQtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 ≀ l ≀ r ≀ n and gcd(al, al + 1, ..., ar) = xi. is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi.InputThe first line of the input contains integer n, (1 ≀ n ≀ 105), denoting the length of the sequence. The next line contains n space separated integers a1, ..., an, (1 ≀ ai ≀ 109).The third line of the input contains integer q, (1 ≀ q ≀ 3 × 105), denoting the number of queries. Then follows q lines, each contain an integer xi, (1 ≀ xi ≀ 109).OutputFor each query print the result in a separate line.ExamplesInput32 6 3512346Output12201Input710 20 3 15 1000 60 16101234561020601000Output14022202211
Input32 6 3512346
Output12201
2 seconds
256 megabytes
['brute force', 'data structures', 'math', '*2000']
C. Kamal-ol-molk's Paintingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.Consider the painting as a n × m rectangular grid. At the beginning an x × y rectangular brush is placed somewhere in the frame, with edges parallel to the frame, (1 ≀ x ≀ n, 1 ≀ y ≀ m). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment.You have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush. InputThe first line of input contains two integers n and m, (1 ≀ n, m ≀ 1000), denoting the height and width of the painting.The next n lines contain the painting. Each line has m characters. Character 'X' denotes an altered cell, otherwise it's showed by '.'. There will be at least one altered cell in the painting.OutputPrint the minimum area of the brush in a line, if the painting is possibly altered, otherwise print  - 1.ExamplesInput4 4XX..XX..XXXXXXXXOutput4Input4 4.....XXX.XXX....Output2Input4 5XXXX.XXXX..XX...XX..Output-1
Input4 4XX..XX..XXXXXXXX
Output4
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', '*2100']
B. Strongly Connected Citytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection. The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.InputThe first line of input contains two integers n and m, (2 ≀ n, m ≀ 20), denoting the number of horizontal streets and the number of vertical streets.The second line contains a string of length n, made of characters '<' and '>', denoting direction of each horizontal street. If the i-th character is equal to '<', the street is directed from east to west otherwise, the street is directed from west to east. Streets are listed in order from north to south.The third line contains a string of length m, made of characters '^' and 'v', denoting direction of each vertical street. If the i-th character is equal to '^', the street is directed from south to north, otherwise the street is directed from north to south. Streets are listed in order from west to east.OutputIf the given pattern meets the mayor's criteria, print a single line containing "YES", otherwise print a single line containing "NO".ExamplesInput3 3><>v^vOutputNOInput4 6<><>v^v^v^OutputYESNoteThe figure above shows street directions in the second sample test case.
Input3 3><>v^v
OutputNO
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'implementation', '*1400']
A. Bayan Bustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. The event coordinator has a list of k participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one. In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by k participants. Your task is to draw the figure representing occupied seats.InputThe only line of input contains integer k, (0 ≀ k ≀ 34), denoting the number of participants.OutputPrint the figure of a bus with k passengers as described in sample tests. Character '#' denotes an empty seat, while 'O' denotes a taken seat. 'D' is the bus driver and other characters in the output are for the purpose of beautifying the figure. Strictly follow the sample test cases output format. Print exactly six lines. Do not output extra space or other characters.ExamplesInput9Output+------------------------+|O.O.O.#.#.#.#.#.#.#.#.|D|)|O.O.O.#.#.#.#.#.#.#.#.|.||O.......................||O.O.#.#.#.#.#.#.#.#.#.|.|)+------------------------+Input20Output+------------------------+|O.O.O.O.O.O.O.#.#.#.#.|D|)|O.O.O.O.O.O.#.#.#.#.#.|.||O.......................||O.O.O.O.O.O.#.#.#.#.#.|.|)+------------------------+
Input9
Output+------------------------+|O.O.O.#.#.#.#.#.#.#.#.|D|)|O.O.O.#.#.#.#.#.#.#.#.|.||O.......................||O.O.#.#.#.#.#.#.#.#.#.|.|)+------------------------+
2 seconds
256 megabytes
['implementation', '*1100']
F. Ant colonytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≀ i ≀ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of Β«Hunger GamesΒ» for the ants. He chooses two numbers l and r (1 ≀ l ≀ r ≀ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.InputThe first line contains one integer n (1 ≀ n ≀ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≀ si ≀ 109), the strengths of the ants. The third line contains one integer t (1 ≀ t ≀ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≀ li ≀ ri ≀ n), describing one query.OutputPrint to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].ExamplesInput51 3 2 4 241 52 53 54 5Output4411NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
Input51 3 2 4 241 52 53 54 5
Output4411
1 second
256 megabytes
['data structures', 'math', 'number theory', '*2100']
E. Pillarstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1 ≀ i1 < i2 < ... < ik ≀ n). From a pillar i Marmot can jump on a pillar j only if i < j and |hi - hj| β‰₯ d, where |x| is the absolute value of the number x.Now Marmot is asking you find out a jump sequence with maximal length and print it.InputThe first line contains two integers n and d (1 ≀ n ≀ 105, 0 ≀ d ≀ 109).The second line contains n numbers h1, h2, ..., hn (1 ≀ hi ≀ 1015).OutputThe first line should contain one integer k, the maximal length of a jump sequence.The second line should contain k integers i1, i2, ..., ik (1 ≀ i1 < i2 < ... < ik ≀ n), representing the pillars' indices from the maximal length jump sequence.If there is more than one maximal length jump sequence, print any.ExamplesInput5 21 3 6 7 4Output41 2 3 5 Input10 32 1 3 6 9 11 7 3 20 18Output61 4 6 7 8 9 NoteIn the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.
Input5 21 3 6 7 4
Output41 2 3 5
1 second
256 megabytes
['binary search', 'data structures', 'dp', 'sortings', 'trees', '*2000']
D. Flowerstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109 + 7).InputInput contains several test cases.The first line contains two integers t and k (1 ≀ t, k ≀ 105), where t represents the number of test cases.The next t lines contain two integers ai and bi (1 ≀ ai ≀ bi ≀ 105), describing the i-th test.OutputPrint t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109 + 7).ExamplesInput3 21 32 34 4Output655Note For K = 2 and length 1 Marmot can eat (R). For K = 2 and length 2 Marmot can eat (RR) and (WW). For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR). For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).
Input3 21 32 34 4
Output655
1.5 seconds
256 megabytes
['dp', '*1700']
C. Captain Marmottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaptain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≀ i ≀ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.InputThe first line contains one integer n (1 ≀ n ≀ 100), the number of regiments.The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≀ xi, yi, ai, bi ≀ 104).OutputPrint n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).ExamplesInput41 1 0 0-1 1 0 0-1 1 0 01 -1 0 01 1 0 0-2 1 0 0-1 1 0 01 -1 0 01 1 0 0-1 1 0 0-1 1 0 0-1 1 0 02 2 0 1-1 0 0 -23 0 0 -2-1 1 -2 0Output1-133NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole.
Input41 1 0 0-1 1 0 0-1 1 0 01 -1 0 01 1 0 0-2 1 0 0-1 1 0 01 -1 0 01 1 0 0-1 1 0 0-1 1 0 0-1 1 0 02 2 0 1-1 0 0 -23 0 0 -2-1 1 -2 0
Output1-133
1 second
256 megabytes
['brute force', 'geometry', '*2000']
B. Wormstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.InputThe first line contains a single integer n (1 ≀ n ≀ 105), the number of piles.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile.The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot.The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.OutputPrint m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.ExamplesInput52 7 3 4 931 25 11Output153NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Input52 7 3 4 931 25 11
Output153
1 second
256 megabytes
['binary search', 'implementation', '*1200']
A. Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOur good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:qwertyuiopasdfghjkl;zxcvbnm,./Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).We have a sequence of characters he has typed and we want to find the original message.InputFirst line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right).Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard.It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it.OutputPrint a line that contains the original message.ExamplesInputRs;;upimrrfod;pbrOutputallyouneedislove
InputRs;;upimrrfod;pbr
Outputallyouneedislove
2 seconds
256 megabytes
['implementation', '*900']
G. Design Tutorial: Increase the Constraintstime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a simple way to create hard tasks: take one simple problem as the query, and try to find an algorithm that can solve it faster than bruteforce. This kind of tasks usually appears in OI contest, and usually involves data structures.Let's try to create a task, for example, we take the "Hamming distance problem": for two binary strings s and t with the same length, the Hamming distance between them is the number of positions at which the corresponding symbols are different. For example, the Hamming distance between "00111" and "10101" is 2 (the different symbols are marked with bold).We use the Hamming distance problem as a query in the following way: you are given two strings a and b and several queries. Each query will be: what is the Hamming distance between two strings ap1ap1 + 1...ap1 + len - 1 and bp2bp2 + 1...bp2 + len - 1?Note, that in this problem the strings are zero-based, that is s = s0s1... s|s| - 1.InputThe first line contains a string a (1 ≀ |a| ≀ 200000). The second line contains a string b (1 ≀ |b| ≀ 200000). Each character of both strings is either "0" or "1".The third line contains an integer q (1 ≀ q ≀ 400000) β€” the number of queries. Each of the following q lines contains three integers: p1, p2 and len (0 ≀ p1 ≀ |a| - len;Β 0 ≀ p2 ≀ |b| - len), these numbers denote the parameters of the current query.OutputOutput q integers β€” the answers for the queries.ExamplesInput1010101111000030 0 32 3 45 7 1Output110Input1000101010101100101010010101001101010101010010100101010010010101050 0 123 9 76 4 1512 15 1013 3 20Output543513
Input1010101111000030 0 32 3 45 7 1
Output110
7 seconds
256 megabytes
['bitmasks', 'data structures', 'fft', '*2800']
F. Design Tutorial: Change the Goaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal.Let's have a try. I have created the following task for Topcoder SRM 557 Div1-Hard: you are given n integers x1, x2, ..., xn. You are allowed to perform the assignments (as many as you want) of the following form xi ^= xj (in the original task i and j must be different, but in this task we allow i to equal j). The goal is to maximize the sum of all xi.Now we just change the goal. You are also given n integers y1, y2, ..., yn. You should make x1, x2, ..., xn exactly equal to y1, y2, ..., yn. In other words, for each i number xi should be equal to yi.InputThe first line contains an integer n (1 ≀ n ≀ 10000). The second line contains n integers: x1 to xn (0 ≀ xi ≀ 109). The third line contains n integers: y1 to yn (0 ≀ yi ≀ 109).OutputIf there is no solution, output -1.If there is a solution, then in the first line output an integer m (0 ≀ m ≀ 1000000) – the number of assignments you need to perform. Then print m lines, each line should contain two integers i and j (1 ≀ i, j ≀ n), which denote assignment xi ^= xj.If there are multiple solutions you can print any of them. We can prove that under these constraints if there exists a solution then there always exists a solution with no more than 106 operations.ExamplesInput23 56 0Output21 22 2Input50 0 0 0 01 2 3 4 5Output-1Input34 5 61 2 3Output53 11 22 22 33 1Input31 2 34 5 6Output-1NoteAssignment a ^= b denotes assignment a = a ^ b, where operation "^" is bitwise XOR of two integers.
Input23 56 0
Output21 22 2
2 seconds
256 megabytes
['constructive algorithms', 'math', 'matrices', '*2700']
E. Design Tutorial: Learn from a Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne way to create task is to learn from game. You should pick a game and focus on part of the mechanic of that game, then it might be a good task.Let's have a try. Puzzle and Dragon was a popular game in Japan, we focus on the puzzle part of that game, it is a tile-matching puzzle.(Picture from Wikipedia page: http://en.wikipedia.org/wiki/Puzzle_&_Dragons)There is an n × m board which consists of orbs. During the game you can do the following move. In the beginning of move you touch a cell of the board, then you can move your finger to one of the adjacent cells (a cell not on the boundary has 8 adjacent cells), then you can move your finger from the current cell to one of the adjacent cells one more time, and so on. Each time you move your finger from a cell to another cell, the orbs in these cells swap with each other. In other words whatever move you make, the orb in the cell you are touching never changes.The goal is to achieve such kind of pattern that the orbs will be cancelled and your monster will attack the enemy, but we don't care about these details. Instead, we will give you the initial board as an input and the target board as an output. Your goal is to determine whether there is a way to reach the target in a single move. InputThe first line contains two integers: n and m (1 ≀ n, m ≀ 30).The next n lines each contains m integers β€” the description of the initial board. The j-th integer in the i-th line is si, j (1 ≀ si, j ≀ 900), where si, j denotes the type of the orb located in the i-th row and j-th column of the board.The next n lines contain the target board in the same format. Note, that the initial board and the target board will be different.OutputIf there is no solution, then output: -1.If there is a solution, then in the first line output an integer k (1 ≀ k ≀ 106) β€” the number of finger moves.In the next line print two integers x0 and y0 (1 ≀ x0 ≀ n;Β 1 ≀ y0 ≀ m) β€” the position of the cell you touch at the beginning. In each of the next k lines print two integers xi and yi (1 ≀ xi ≀ n;Β 1 ≀ yi ≀ m) β€” the position you move to. Note that this position must be adjacent to the previous position, that is max(|xi - xi - 1|, |yi - yi - 1|) = 1.If there are multiple solutions, you can print any of them. We can prove that under these constraints if there exists a solution then there is a solution with no more than 106 operations.ExamplesInput2 21 32 31 33 2Output31 12 22 11 1Input2 21 32 31 22 3Output-1Input1 41 2 3 44 3 2 1Output-1Input4 112343124Output23 12 11 1
Input2 21 32 31 33 2
Output31 12 22 11 1
1 second
256 megabytes
['constructive algorithms', 'implementation', '*2800']
D. Design Tutorial: Inverse the Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.Now let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an n × n distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).InputThe first line contains an integer n (1 ≀ n ≀ 2000) β€” the number of nodes in that graph.Then next n lines each contains n integers di, j (0 ≀ di, j ≀ 109) β€” the distance between node i and node j.OutputIf there exists such a tree, output "YES", otherwise output "NO".ExamplesInput30 2 72 0 97 9 0OutputYESInput31 2 72 0 97 9 0OutputNOInput30 2 27 0 97 9 0OutputNOInput30 1 11 0 11 1 0OutputNOInput20 00 0OutputNONoteIn the first example, the required tree exists. It has one edge between nodes 1 and 2 with weight 2, another edge between nodes 1 and 3 with weight 7.In the second example, it is impossible because d1, 1 should be 0, but it is 1.In the third example, it is impossible because d1, 2 should equal d2, 1.
Input30 2 72 0 97 9 0
OutputYES
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'shortest paths', 'trees', '*1900']
C. Design Tutorial: Make It Nondeterministictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?More formally, if we denote the handle of the i-th person as hi, then the following condition must hold: .InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of people.The next n lines each contains two strings. The i-th line contains strings fi and si (1 ≀ |fi|, |si| ≀ 50) β€” the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct.The next line contains n distinct integers: p1, p2, ..., pn (1 ≀ pi ≀ n).OutputIf it is possible, output "YES", otherwise output "NO".ExamplesInput3gennady korotkevichpetr mitrichevgaoyuan chen1 2 3OutputNOInput3gennady korotkevichpetr mitrichevgaoyuan chen3 1 2OutputYESInput2galileo galileinicolaus copernicus2 1OutputYESInput10rean schwarzerfei claussellalisa reinfordeliot craiglaura arseidjusis albareamachias regnitzsara valestinemma millsteingaius worzel1 2 3 4 5 6 7 8 9 10OutputNOInput10rean schwarzerfei claussellalisa reinfordeliot craiglaura arseidjusis albareamachias regnitzsara valestinemma millsteingaius worzel2 4 9 6 5 7 1 3 8 10OutputYESNoteIn example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist and Petr must be the last.In example 3, if Copernicus uses "copernicus" as his handle, everything will be alright.
Input3gennady korotkevichpetr mitrichevgaoyuan chen1 2 3
OutputNO
2 seconds
256 megabytes
['greedy', '*1400']
B. Design Tutorial: Learn from Lifetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?InputThe first line contains two integers n and k (1 ≀ n, k ≀ 2000) β€” the number of people and the maximal capacity of the elevator.The next line contains n integers: f1, f2, ..., fn (2 ≀ fi ≀ 2000), where fi denotes the target floor of the i-th person.OutputOutput a single integer β€” the minimal time needed to achieve the goal.ExamplesInput3 22 3 4Output8Input4 250 100 50 100Output296Input10 32 2 2 2 2 2 2 2 2 2Output8NoteIn first sample, an optimal solution is: The elevator takes up person #1 and person #2. It goes to the 2nd floor. Both people go out of the elevator. The elevator goes back to the 1st floor. Then the elevator takes up person #3. And it goes to the 2nd floor. It picks up person #2. Then it goes to the 3rd floor. Person #2 goes out. Then it goes to the 4th floor, where person #3 goes out. The elevator goes back to the 1st floor.
Input3 22 3 4
Output8
1 second
256 megabytes
['*1300']
A. Design Tutorial: Learn from Mathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.InputThe only line contains an integer n (12 ≀ n ≀ 106).OutputOutput two composite integers x and y (1 < x, y < n) such that x + y = n. If there are multiple solutions, you can output any of them.ExamplesInput12Output4 8Input15Output6 9Input23Output8 15Input1000000Output500000 500000NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.
Input12
Output4 8
1 second
256 megabytes
['math', 'number theory', '*800']
E. MUH and Lots and Lots of Segmentstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of n segments. Each segment was either horizontal or vertical. Now the friends want to simplify the draft by deleting some segments or parts of segments so that the final masterpiece meets three conditions: Horace wants to be able to paint the whole picture in one stroke: by putting the brush on the paper and never taking it off until the picture is ready. The brush can paint the same place multiple times. That's why all the remaining segments must form a single connected shape. Menshykov wants the resulting shape to be simple. He defines a simple shape as a shape that doesn't contain any cycles. Initially all the segment on the draft have integer startpoint and endpoint coordinates. Uslada doesn't like real coordinates and she wants this condition to be fulfilled after all the changes. As in other parts the draft is already beautiful, the friends decided to delete such parts of the draft that the sum of lengths of the remaining segments is as large as possible. Your task is to count this maximum sum of the lengths that remain after all the extra segments are removed.InputThe first line of the input contains integer n (1 ≀ n ≀ 2Β·105) β€” the number of segments on the draft. The next n lines contain four integers each: x1, y1, x2, y2 ( - 109 ≀ x1 ≀ x2 ≀ 109;  - 109 ≀ y1 ≀ y2 ≀ 109) β€” the two startpoint and the two endpoint coordinates of a segment. All segments are non-degenerative and either are strictly horizontal or strictly vertical.No two horizontal segments share common points. No two vertical segments share common points.OutputPrint a single integer β€” the maximum sum of lengths for the remaining segments.ExamplesInput20 0 0 11 0 1 1Output1Input40 0 1 00 0 0 11 -1 1 20 1 1 1Output5NoteThe shapes that you can get in the two given samples are: In the first sample you need to delete any segment as the two segments together do not form a single connected shape.In the second sample the initial segments form a cycle, there are four ways to break the cycle: delete the first, second or fourth segment altogether or delete the middle of the third segment. The last way is shown on the picture.
Input20 0 0 11 0 1 1
Output1
2 seconds
512 megabytes
['data structures', 'dsu', '*2700']
D. MUH and Cube Wallstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).Your task is to count the number of segments where Horace can "see an elephant".InputThe first line contains two integers n and w (1 ≀ n, w ≀ 2Β·105) β€” the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≀ ai ≀ 109) β€” the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≀ bi ≀ 109) β€” the heights of the towers in the elephant's wall.OutputPrint the number of segments in the bears' wall where Horace can "see an elephant".ExamplesInput13 52 4 5 5 4 3 2 2 2 3 3 2 13 4 4 3 2Output2NoteThe picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
Input13 52 4 5 5 4 3 2 2 2 3 3 2 13 4 4 3 2
Output2
2 seconds
256 megabytes
['string suffix structures', 'strings', '*1800']
C. MUH and House of Cardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of n playing cards. Let's describe the house they want to make: The house consists of some non-zero number of floors. Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card. Each floor besides for the lowest one should contain less rooms than the floor below. Please note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more. While bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of n cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using exactly n cards.InputThe single line contains integer n (1 ≀ n ≀ 1012) β€” the number of cards.OutputPrint the number of distinct heights that the houses made of exactly n cards can have.ExamplesInput13Output1Input6Output0NoteIn the first sample you can build only these two houses (remember, you must use all the cards): Thus, 13 cards are enough only for two floor houses, so the answer is 1.The six cards in the second sample are not enough to build any house.
Input13
Output1
1 second
256 megabytes
['binary search', 'brute force', 'greedy', 'math', '*1700']
B. MUH and Important Thingstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.InputThe first line contains integer n (1 ≀ n ≀ 2000) β€” the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≀ hi ≀ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.OutputIn the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.If there are multiple possible answers, you can print any of them.ExamplesInput41 3 3 1OutputYES1 4 2 3 4 1 2 3 4 1 3 2 Input52 4 1 4 8OutputNONoteIn the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.In the second sample there are only two sequences of tasks that meet the conditions β€” [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Input41 3 3 1
OutputYES1 4 2 3 4 1 2 3 4 1 3 2
1 second
256 megabytes
['implementation', 'sortings', '*1300']
A. MUH and Stickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: Four sticks represent the animal's legs, these sticks should have the same length. Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks. Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.InputThe single line contains six space-separated integers li (1 ≀ li ≀ 9) β€” the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks.OutputIf you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wΔ±thout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes).ExamplesInput4 2 5 4 4 4OutputBearInput4 4 5 4 4 5OutputElephantInput1 2 3 4 5 6OutputAlienNoteIf you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue.
Input4 2 5 4 4 4
OutputBear
1 second
256 megabytes
['implementation', '*1100']
H. Array Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSorting arrays is traditionally associated with high-level languages. How hard can it be in FALSE? Sort the given array in non-descending order.InputThe input consists of a single line of space-separated integers. The first number is n (1 ≀ n ≀ 10) β€” the size of the array. The following n numbers are the elements of the array (1 ≀ ai ≀ 100).OutputOutput space-separated elements of the sorted array.ExamplesInput3 3 1 2Output1 2 3 Input7 12 2 3 44 5 60 2Output2 2 3 5 12 44 60
Input3 3 1 2
Output1 2 3
2 seconds
256 megabytes
['*special problem', '*2300']
G. Hamming Distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. You are given two strings; calculate the distance between them.InputThe input consists of two lines. Each line contains a string of characters 'A'-'Z' between 1 and 100 characters, inclusive. The strings have equal length.OutputOutput Hamming distance between the strings.ExamplesInputCODECHEFTOPCODEROutput6InputHAMMINGDISTANCOutput6
InputCODECHEFTOPCODER
Output6
2 seconds
256 megabytes
['*special problem', '*2300']
F. Pairwise Sumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers. For each element output the sum of itself and the previous element. For the first element, output the sum of the first and the last elements of the array.InputThe input consists of a single line of space-separated integers. The first number is n (2 ≀ n ≀ 50) β€” the size of the array. The following n numbers are the elements of the array (1 ≀ ai ≀ 1000).OutputOutput the sums a1 + an, a2 + a1, ..., an + an - 1, separated with spaces.ExamplesInput4 1 2 3 4Output5 3 5 7 Input5 5 46 372 81 9Output14 51 418 453 90
Input4 1 2 3 4
Output5 3 5 7
2 seconds
256 megabytes
['*special problem', '*2300']
E. Chessboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChessboard is a board of n × n squares arranged in two alternating colors (black and white). Top left square is white. You are given board size n. Output an image of a chessboard, with black and white squares marked with '#' and '.' characters, respectively.InputThe only line of input contains an integer n (1 ≀ n ≀ 9).OutputOutput an image of n × n chessboard.ExamplesInput4Output.#.##.#..#.##.#.
Input4
Output.#.##.#..#.##.#.
2 seconds
256 megabytes
['*special problem', '*1900']
D. Caesar Ciphertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaesar cipher is one of the simplest encryption techniques. To transform the original message into encrypted one using key k, one has to replace each letter with a letter which is k positions later in the alphabet (if this takes the position beyond Z, the rest of it is counted from the start of the alphabet). In a more formal way, if letters of the alphabet are enumerated starting with 0, the result of encryption for character x will be (26 is the number of letters in the Latin alphabet).You are given the original message and the encryption key k. Output the result of encryption.InputThe first line of input contains an integer k (0 ≀ k ≀ 25) β€” the encryption key.The second line contains the original message β€” a sequence of uppercase Latin letters ('A'-'Z'). The length of the message is from 1 to 10, inclusive.OutputOutput the result of encryption.ExamplesInput5CODEFORCESOutputHTIJKTWHJXInput13FALSERULEZOutputSNYFREHYRM
Input5CODEFORCES
OutputHTIJKTWHJX
2 seconds
256 megabytes
['*special problem', '*1900']
C. Evaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a simple arithmetic expression of the form a?b, where a and b are integer constants, and ? can be one of the following operations: '+' (addition), '-' (subtraction), '*' (multiplication), '/' (integer division) or '%' (modulo operation).Output the result of evaluation of this expression.InputThe input is a single line containing an expression a?b. Here a and b are integers between 1 and 999, inclusive; ? is an operation character: '+', '-' (ASCII code 45), '*', '/' or '%'.OutputOutput a single integer β€” the result of evaluation of this expression.ExamplesInput123+456Output579Input192/5Output38Input945%19Output14
Input123+456
Output579
2 seconds
256 megabytes
['*special problem', '*1900']
B. Hexakosioihexekontahexaphobiatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis (unpronounceable) word means simply fear of number 666. You are given a string of digits. Check whether it is scary for a person suffering from this phobia, i.e., whether it contains number 666 as a substring.InputThe input will consist of a single string p. The string contains between 1 and 100 digits ('0'-'9'), inclusive. The string doesn't contain any other characters except digits.OutputOutput "YES" if given string contains number 666, and "NO" otherwise (quotes for clarity only).ExamplesInput123098OutputNOInput16660OutputYESInput1606061OutputNONoteNote that 666 must be a contiguous substring of p, not a subsequence (see sample 3).
Input123098
OutputNO
2 seconds
256 megabytes
['*special problem', '*1800']
A. Crystal Ball Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCrystal ball sequence on hexagonal lattice is defined as follows: n-th element is the number of lattice points inside a hexagon with (n + 1) points on each side. The formula is Hn = 3Β·nΒ·(n + 1) + 1. You are given n; calculate n-th element of the sequence.InputThe only line of input contains an integer n (0 ≀ n ≀ 9).OutputOutput the n-th element of crystal ball sequence.ExamplesInput1Output7Input3Output37
Input1
Output7
2 seconds
256 megabytes
['*special problem', 'implementation', '*1400']
B. Chat Onlinetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle X and Little Z are good friends. They always chat online. But both of them have schedules.Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c1 and d1, between c2 and d2, ..., between cq and dq (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [ci + t, di + t] (for all i).If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l, r] suit for that?InputThe first line contains four space-separated integers p, q, l, r (1 ≀  p, q ≀ 50;Β 0 ≀ l ≀ r ≀ 1000).Each of the next p lines contains two space-separated integers ai, bi (0 ≀ ai < bi ≀ 1000). Each of the next q lines contains two space-separated integers cj, dj (0 ≀ cj < dj ≀ 1000).It's guaranteed that bi < ai + 1 and dj < cj + 1 for all valid i and j.OutputOutput a single integer β€” the number of moments of time from the segment [l, r] which suit for online conversation.ExamplesInput1 1 0 42 30 1Output3Input2 3 0 2015 1723 261 47 1115 17Output20
Input1 1 0 42 30 1
Output3
1 second
256 megabytes
['implementation', '*1300']
A. I Wanna Be the Guytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?InputThe first line contains a single integer n (1 ≀  n ≀ 100). The next line contains an integer p (0 ≀ p ≀ n) at first, then follows p distinct integers a1, a2, ..., ap (1 ≀ ai ≀ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.OutputIf they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).ExamplesInput43 1 2 32 2 4OutputI become the guy.Input43 1 2 32 2 3OutputOh, my keyboard!NoteIn the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.In the second sample, no one can pass level 4.
Input43 1 2 32 2 4
OutputI become the guy.
1 second
256 megabytes
['greedy', 'implementation', '*800']
E. Permanenttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLittle X has solved the #P-complete problem in polynomial time recently. So he gives this task to you. There is a special n × n matrix A, you should calculate its permanent modulo 1000000007Β (109 + 7). The special property of matrix A is almost all its elements equal to 1. Only k elements have specified value.You can find the definition of permanent at the link: https://en.wikipedia.org/wiki/PermanentInputThe first line contains two space-separated integers n, k (1 ≀ n ≀ 105;Β 1 ≀ k ≀ 50).The next k lines contain the description of the matrix. The i-th line contains three space-separated integers xi, yi, wi (1 ≀ xi,  yi ≀  n;Β 0  ≀  wi  ≀ 109). These numbers denote that Axi, yi = wi. All the elements of the matrix except of the given elements are equal to 1.It's guaranteed that all the positions (xi, yi) are distinct.OutputPrint the permanent of the matrix modulo 1000000007Β (109  +  7).ExamplesInput3 11 1 2Output8Input10 103 3 3670567946 2 1245612731 3 467181466 9 41591686910 5 9859683363 1 5267922651 4 38635705810 4 3493041872 7 1020324993 6 502679075Output233333333
Input3 11 1 2
Output8
2 seconds
512 megabytes
['dp', 'graph matchings', 'math', 'meet-in-the-middle', '*3100']
D. Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle X has a tree consisting of n nodes (they are numbered from 1 to n). Each edge of the tree has a positive length. Let's define the distance between two nodes v and u (we'll denote it d(v, u)) as the sum of the lengths of edges in the shortest path between v and u. A permutation p is a sequence of n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n). Little X wants to find a permutation p such that sum is maximal possible. If there are multiple optimal permutations, he wants to find the lexicographically smallest one. Help him with the task!InputThe first line contains an integer nΒ (1 ≀ n ≀ 105).Each of the next n - 1 lines contains three space separated integers ui,  vi, wiΒ (1 ≀  ui,  vi ≀  n;Β 1 ≀  wi ≀  105), denoting an edge between nodes ui and vi with length equal to wi.It is guaranteed that these edges form a tree.OutputIn the first line print the maximum possible value of the described sum. In the second line print n integers, representing the lexicographically smallest permutation.ExamplesInput21 2 3Output62 1Input51 2 21 3 32 4 42 5 5Output322 1 4 5 3
Input21 2 3
Output62 1
2 seconds
256 megabytes
['graph matchings', '*3100']
C. Hack it!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code: ans = solve(l, r) % a; if (ans <= 0) ans += a; This code will fail only on the test with . You are given number a, help Little X to find a proper test for hack.InputThe first line contains a single integer aΒ (1 ≀ a ≀ 1018).OutputPrint two integers: l, rΒ (1 ≀ l ≀ r < 10200) β€” the required test data. Leading zeros aren't allowed. It's guaranteed that the solution exists.ExamplesInput46Output1 10Input126444381000032Output2333333 2333333333333
Input46
Output1 10
1 second
256 megabytes
['binary search', 'constructive algorithms', 'math', '*2500']
B. Two Setstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: If number x belongs to set A, then number a - x must also belong to set A. If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible.InputThe first line contains three space-separated integers n, a, b (1 ≀ n ≀ 105;Β 1 ≀ a, b ≀ 109). The next line contains n space-separated distinct integers p1, p2, ..., pnΒ (1 ≀ pi ≀ 109).OutputIf there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B.If it's impossible, print "NO" (without the quotes).ExamplesInput4 5 92 3 4 5OutputYES0 0 1 1Input3 3 41 2 4OutputNONoteIt's OK if all the numbers are in the same set, and the other one is empty.
Input4 5 92 3 4 5
OutputYES0 0 1 1
1 second
256 megabytes
['2-sat', 'dfs and similar', 'dsu', 'graph matchings', 'greedy', '*2000']
A. 24 Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?InputThe first line contains a single integer n (1 ≀ n ≀ 105).OutputIf it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.If there are multiple valid answers, you may print any of them.ExamplesInput1OutputNOInput8OutputYES8 * 7 = 566 * 5 = 303 - 4 = -11 - 2 = -130 - -1 = 3156 - 31 = 2525 + -1 = 24
Input1
OutputNO
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1500']
E. Alex and Complicated Tasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter 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 a1, a2, ..., an. You are to find a longest sequence b1, b2, ..., b4m, that satisfies the following conditions: b4k + 1 = b4k + 3 for all valid integer k; b4k + 2 = b4k + 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.InputThe first line contains a single integer n (1 ≀ n ≀ 5Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputIn the first line print a single integer 4m β€” the maximal possible length of required sequence b. In the second line print 4m integers b1, b2, ..., b4m, that is required sequence.If there are multiple optimal answers you may print any of them.ExamplesInput43 5 3 5Output43 5 3 5Input1035 1 2 1 2 35 100 200 100 200Output81 2 1 2 100 200 100 200
Input43 5 3 5
Output43 5 3 5
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2300']
D. Fedor and Essaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter you had helped Fedor to find friends in the Β«Call of Soldiers 3Β» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.As a result, Fedor wants to get an essay which contains as little letters Β«RΒ» (the case doesn't matter) as possible. If there are multiple essays with minimum number of Β«RΒ»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.InputThe first line contains a single integer m (1 ≀ m ≀ 105) β€” the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 105 characters.The next line contains a single integer n (0 ≀ n ≀ 105) β€” the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words xi and yi. They mean that word xi can be replaced with word yi (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5Β·105 characters.All the words at input can only consist of uppercase and lowercase letters of the English alphabet.OutputPrint two integers β€” the minimum number of letters Β«RΒ» in an optimal essay and the minimum length of an optimal essay.ExamplesInput3AbRb r Zz4xR abRbaA xrzz Zxr yOutput2 6Input2RuruRu fedya1ruruRU fedorOutput1 10
Input3AbRb r Zz4xR abRbaA xrzz Zxr y
Output2 6
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'hashing', 'strings', '*2400']
C. George and Jobtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk]Β (1 ≀ l1 ≀ r1 < l2 ≀ r2 < ... < lk ≀ rk ≀ n;Β ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task.InputThe first line contains three integers n, m and k (1 ≀ (m × k) ≀ n ≀ 5000). The second line contains n integers p1, p2, ..., pn (0 ≀ pi ≀ 109).OutputPrint an integer in a single line β€” the maximum possible value of sum.ExamplesInput5 2 11 2 3 4 5Output9Input7 1 32 10 7 18 5 33 0Output61
Input5 2 11 2 3 4 5
Output9
1 second
256 megabytes
['dp', 'implementation', '*1700']
B. Fedor and New Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β».The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type. Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.InputThe first line contains three integers n, m, k (1 ≀ k ≀ n ≀ 20;Β 1 ≀ m ≀ 1000).The i-th of the next (m + 1) lines contains a single integer xi (1 ≀ xi ≀ 2n - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.OutputPrint a single integer β€” the number of Fedor's potential friends.ExamplesInput7 3 18511117Output0Input3 3 31234Output3
Input7 3 18511117
Output0
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'implementation', '*1100']
A. George and Accommodationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGeorge has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≀ qi). Your task is to count how many rooms has free place for both George and Alex.InputThe first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of rooms.The i-th of the next n lines contains two integers pi and qi (0 ≀ pi ≀ qi ≀ 100) β€” the number of people who already live in the i-th room and the room's capacity.OutputPrint a single integer β€” the number of rooms where George and Alex can move in.ExamplesInput31 12 23 3Output0Input31 100 1010 10Output2
Input31 12 23 3
Output0
1 second
256 megabytes
['implementation', '*800']
E. Information Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place: either employee y became the boss of employee x (at that, employee x didn't have a boss before); or employee x gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive); or comes a request of type "determine whether employee x signs certain documents". Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105) β€” the number of employees and the number of events. Each of the next m lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event t (1 ≀ t ≀ 3). If t = 1, then next follow two integers x and y (1 ≀ x, y ≀ n) β€” numbers of the company employees. It is guaranteed that employee x doesn't have the boss currently. If t = 2, then next follow integer x (1 ≀ x ≀ n) β€” the number of the employee who got a document packet. If t = 3, then next follow two integers x and i (1 ≀ x ≀ n;Β 1 ≀ i ≀ [number of packets that have already been given]) β€” the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order. It is guaranteed that the input has at least one query of the third type.OutputFor each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes.ExamplesInput4 91 4 32 43 3 11 2 32 23 1 21 3 12 23 1 3OutputYESNOYES
Input4 91 4 32 43 3 11 2 32 23 1 21 3 12 23 1 3
OutputYESNOYES
1 second
512 megabytes
['dfs and similar', 'dsu', 'graphs', 'trees', '*2100']
D. Increase Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeter has a sequence of integers a1, a2, ..., an. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments [l1, r1] and [l2, r2], where Peter added one, the following inequalities hold: l1 ≠ l2 and r1 ≠ r2.How many distinct ways are there to make all numbers in the sequence equal h? Print this number of ways modulo 1000000007Β (109 + 7). Two ways are considered distinct if one of them has a segment that isn't in the other way.InputThe first line contains two integers n, h (1 ≀ n, h ≀ 2000). The next line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 2000).OutputPrint a single integer β€” the answer to the problem modulo 1000000007Β (109 + 7).ExamplesInput3 21 1 1Output4Input5 11 1 1 1 1Output1Input4 33 2 1 1Output0
Input3 21 1 1
Output4
1 second
256 megabytes
['combinatorics', 'dp', '*2100']
C. Number of Waystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≀ i ≀ j ≀ n - 1), that .InputThe first line contains integer n (1 ≀ n ≀ 5Β·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≀  109) β€” the elements of array a.OutputPrint a single integer β€” the number of ways to split the array into three parts with the same sum.ExamplesInput51 2 3 0 3Output2Input40 1 -1 0Output1Input24 1Output0
Input51 2 3 0 3
Output2
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'dp', 'two pointers', '*1700']
B. Wonder Roomtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a × b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.InputThe first line contains three space-separated integers n, a and b (1 ≀ n, a, b ≀ 109) β€” the number of students and the sizes of the room.OutputPrint three integers s, a1 and b1 (a ≀ a1;Β b ≀ b1) β€” the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.ExamplesInput3 3 5Output183 6Input2 4 4Output164 4
Input3 3 5
Output183 6
1 second
256 megabytes
['brute force', 'math', '*2000']
A. Cheap Traveltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnn has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of money she will have to spend to make n rides?InputThe single line contains four space-separated integers n, m, a, b (1 ≀ n, m, a, b ≀ 1000) β€” the number of rides Ann has planned, the number of rides covered by the m ride ticket, the price of a one ride ticket and the price of an m ride ticket. OutputPrint a single integer β€” the minimum sum in rubles that Ann will need to spend.ExamplesInput6 2 1 2Output6Input5 2 2 3Output8NoteIn the first sample one of the optimal solutions is: each time buy a one ride ticket. There are other optimal solutions. For example, buy three m ride tickets.
Input6 2 1 2
Output6
1 second
256 megabytes
['implementation', '*1200']
B. Inbox (100500)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOver time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.The program cannot delete the letters from the list or rearrange them.Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?InputThe first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of letters in the mailbox.The second line contains n space-separated integers (zeros and ones) β€” the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read.OutputPrint a single number β€” the minimum number of operations needed to make all the letters read.ExamplesInput50 1 0 1 0Output3Input51 1 0 0 1Output4Input20 0Output0NoteIn the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.In the third sample all letters are already read.
Input50 1 0 1 0
Output3
1 second
256 megabytes
['implementation', '*1000']
A. inc ARGtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.Sergey wrote certain values ​​of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?InputThe first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of bits in the cell.The second line contains a string consisting of n characters β€” the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.OutputPrint a single integer β€” the number of bits in the cell which change their state after we add 1 to the cell.ExamplesInput41100Output3Input41111Output4NoteIn the first sample the cell ends up with value 0010, in the second sample β€” with 0000.
Input41100
Output3
1 second
256 megabytes
['implementation', '*900']
E. The Classic Problemtime limit per test5 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given a weighted undirected graph on n vertices and m edges. Find the shortest path from vertex s to vertex t or else state that such path doesn't exist.InputThe first line of the input contains two space-separated integers β€” n and m (1 ≀ n ≀ 105; 0 ≀ m ≀ 105).Next m lines contain the description of the graph edges. The i-th line contains three space-separated integers β€” ui, vi, xi (1 ≀ ui, vi ≀ n; 0 ≀ xi ≀ 105). That means that vertices with numbers ui and vi are connected by edge of length 2xi (2 to the power of xi).The last line contains two space-separated integers β€” the numbers of vertices s and t.The vertices are numbered from 1 to n. The graph contains no multiple edges and self-loops.OutputIn the first line print the remainder after dividing the length of the shortest path by 1000000007Β (109 + 7) if the path exists, and -1 if the path doesn't exist.If the path exists print in the second line integer k β€” the number of vertices in the shortest path from vertex s to vertex t; in the third line print k space-separated integers β€” the vertices of the shortest path in the visiting order. The first vertex should be vertex s, the last vertex should be vertex t. If there are multiple shortest paths, print any of them.ExamplesInput4 41 4 21 2 02 3 03 4 01 4Output341 2 3 4 Input4 31 2 42 3 53 4 61 4Output11241 2 3 4 Input4 21 2 03 4 11 4Output-1NoteA path from vertex s to vertex t is a sequence v0, ..., vk, such that v0 = s, vk = t, and for any i from 0 to k - 1 vertices vi and vi + 1 are connected by an edge. The length of the path is the sum of weights of edges between vi and vi + 1 for all i from 0 to k - 1. The shortest path from s to t is the path which length is minimum among all possible paths from s to t.
Input4 41 4 21 2 02 3 03 4 01 4
Output341 2 3 4
5 seconds
768 megabytes
['data structures', 'graphs', 'shortest paths', '*3000']
D. World of Darkraft - 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRoma found a new character in the game "World of Darkraft - 2". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters.The character can equip himself with k distinct types of items. Power of each item depends on its level (positive integer number). Initially the character has one 1-level item of each of the k types.After the victory over the monster the character finds exactly one new randomly generated item. The generation process looks as follows. Firstly the type of the item is defined; each of the k types has the same probability. Then the level of the new item is defined. Let's assume that the level of player's item of the chosen type is equal to t at the moment. Level of the new item will be chosen uniformly among integers from segment [1; t + 1].From the new item and the current player's item of the same type Roma chooses the best one (i.e. the one with greater level) and equips it (if both of them has the same level Roma choses any). The remaining item is sold for coins. Roma sells an item of level x of any type for x coins.Help Roma determine the expected number of earned coins after the victory over n monsters.InputThe first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 100).OutputPrint a real number β€” expected number of earned coins after victory over n monsters. The answer is considered correct if its relative or absolute error doesn't exceed 10 - 9.ExamplesInput1 3Output1.0000000000Input2 1Output2.3333333333Input10 2Output15.9380768924
Input1 3
Output1.0000000000
2 seconds
256 megabytes
['dp', 'probabilities', '*2700']
C. Substitutes in Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("replace 3 by an empty string") transforms it to s = 1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007Β (109 + 7). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero.Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!InputThe first line contains string s (1 ≀ |s| ≀ 105), consisting of digitsΒ β€” the string before processing all the requests.The second line contains a single integer n (0 ≀ n ≀ 105)Β β€” the number of queries.The next n lines contain the descriptions of the queries. The i-th query is described by string "di->ti", where di is exactly one digit (from 0 to 9), ti is a string consisting of digits (ti can be an empty string). The sum of lengths of ti for all queries doesn't exceed 105. The queries are written in the order in which they need to be performed.OutputPrint a single integer β€” remainder of division of the resulting number by 1000000007Β (109 + 7).ExamplesInput12312312->00Output10031003Input12312313->Output1212Input22222->00->7Output777Input10000000080Output1NoteNote that the leading zeroes are not removed from string s after the replacement (you can see it in the third sample).
Input12312312->00
Output10031003
1 second
256 megabytes
['dp', '*2100']
B. Restore Cube time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers β€” coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.InputEach of the eight lines contains three space-separated integers β€” the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 106 in their absolute value.OutputIf there is a way to restore the cube, then print in the first line "YES". In each of the next eight lines print three integers β€” the restored coordinates of the points. The numbers in the i-th output line must be a permutation of the numbers in i-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them.If there is no valid way, print "NO" (without the quotes) in the first line. Do not print anything else.ExamplesInput0 0 00 0 10 0 10 0 10 1 10 1 10 1 11 1 1OutputYES0 0 00 0 10 1 01 0 00 1 11 0 11 1 01 1 1Input0 0 00 0 00 0 00 0 01 1 11 1 11 1 11 1 1OutputNO
Input0 0 00 0 10 0 10 0 10 1 10 1 10 1 11 1 1
OutputYES0 0 00 0 10 1 01 0 00 1 11 0 11 1 01 1 1
1 second
256 megabytes
['brute force', 'geometry', '*2000']
A. No to Palindromes!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.InputThe first line contains two space-separated integers: n and p (1 ≀ n ≀ 1000; 1 ≀ p ≀ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).OutputIf the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).ExamplesInput3 3cbaOutputNOInput3 4cbaOutputcbdInput4 4abcdOutputabdaNoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Input3 3cba
OutputNO
1 second
256 megabytes
['greedy', 'strings', '*1700']
E. Caisa and Treetime limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaisa is now at home and his son has a simple task for him.Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following: Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1;Β uk = v). You need to output such a vertex ui that gcd(valueΒ ofΒ ui, valueΒ ofΒ v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1. Format of the query is "2 v w". You must change the value of vertex v to w. You are given all the queries, help Caisa to solve the problem.InputThe first line contains two space-separated integers n, q (1 ≀ n, q ≀ 105). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 2Β·106), where ai represent the value of node i.Each of the next n - 1 lines contains two integers xi and yi (1 ≀ xi, yi ≀ n;Β xi ≠ yi), denoting the edge of the tree between vertices xi and yi.Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≀ v ≀ n and 1 ≀ w ≀ 2Β·106. Note that: there are no more than 50 queries that changes the value of a vertex.OutputFor each query of the first type output the result of the query.ExamplesInput4 610 8 4 31 22 33 41 11 21 31 42 1 91 4Output-112-11Notegcd(x, y) is greatest common divisor of two integers x and y.
Input4 610 8 4 31 22 33 41 11 21 31 42 1 91 4
Output-112-11
10 seconds
256 megabytes
['brute force', 'dfs and similar', 'math', 'number theory', 'trees', '*2100']
D. Gargari and Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problemInputThe first line contains two integers n and k (1 ≀ n ≀ 1000;Β 2 ≀ k ≀ 5). Each of the next k lines contains integers 1, 2, ..., n in some order β€” description of the current permutation.OutputPrint the length of the longest common subsequence.ExamplesInput4 31 4 2 34 1 2 31 2 4 3Output3NoteThe answer for the first test sample is subsequence [1, 2, 3].
Input4 31 4 2 34 1 2 31 2 4 3
Output3
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'implementation', '*1900']
C. Gargari and Bishopstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number x written on it, if this cell is attacked by one of the bishops Gargari will get x dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).InputThe first line contains a single integer n (2 ≀ n ≀ 2000). Each of the next n lines contains n integers aij (0 ≀ aij ≀ 109) β€” description of the chessboard.OutputOn the first line print the maximal number of dollars Gargari will get. On the next line print four integers: x1, y1, x2, y2 (1 ≀ x1, y1, x2, y2 ≀ n), where xi is the number of the row where the i-th bishop should be placed, yi is the number of the column where the i-th bishop should be placed. Consider rows are numbered from 1 to n from top to bottom, and columns are numbered from 1 to n from left to right.If there are several optimal solutions, you can print any of them.ExamplesInput41 1 1 12 1 1 01 1 1 01 0 0 1Output122 2 3 2
Input41 1 1 12 1 1 01 1 1 01 0 0 1
Output122 2 3 2
3 seconds
256 megabytes
['greedy', 'hashing', 'implementation', '*1900']
B. Caisa and Pylonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?InputThe first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers h1, h2, ..., hn (1  ≀  hi  ≀  105) representing the heights of the pylons.OutputPrint a single number representing the minimum number of dollars paid by Caisa.ExamplesInput53 4 3 2 4Output4Input34 4 4Output4NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.
Input53 4 3 2 4
Output4
1 second
256 megabytes
['brute force', 'implementation', 'math', '*1100']
A. Caisa and Sugartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change. InputThe first line contains two space-separated integers n, s (1 ≀ n, s ≀ 100).The i-th of the next n lines contains two integers xi, yi (1 ≀ xi ≀ 100;Β 0 ≀ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.OutputPrint a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.ExamplesInput5 103 9012 09 705 507 0Output50Input5 510 1020 2030 3040 4050 50Output-1NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.
Input5 103 9012 09 705 507 0
Output50
1 second
256 megabytes
['brute force', 'implementation', '*1200']
B. Appleman and Card Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAppleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.OutputPrint a single integer – the answer to the problem.ExamplesInput15 10DZFDFZDFDDDDDDFOutput82Input6 4YJSNPIOutput4NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Input15 10DZFDFZDFDDDDDDF
Output82
1 second
256 megabytes
['greedy', '*1300']
A. Appleman and Easy Tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.InputThe first line contains an integer n (1 ≀ n ≀ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.OutputPrint "YES" or "NO" (without the quotes) depending on the answer to the problem.ExamplesInput3xxoxoxoxxOutputYESInput4xxxoxoxooxoxxxxxOutputNO
Input3xxoxoxoxx
OutputYES
1 second
256 megabytes
['brute force', 'implementation', '*1000']
E. Appleman and a Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAppleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings s and t both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string s as quickly as possible. Initially he has empty string, and in one second he can append to end of the current string any contiguous substring of t.Now, Toastman and Appleman are beginning to play the game. Toastman has already told string t to Appleman, but he hasn't come up with string s yet. Toastman only thinks, that he should choose string s consisting of n characters. Of course, he wants to find the worst string for Appleman (such string, that Appleman will spend as much time as possible during the game). Tell Toastman, how much time will Appleman spend during the game if Toastman finds the worst string for him. You can assume that Appleman plays optimally, therefore he builds any string s in minimal possible time.InputThe first line contains an integer n (1 ≀ n ≀ 1018). The second line contains string t (1 ≀ |t| ≀ 105). String t consists of only letters 'A', 'B', 'C', 'D'. Each letter appears at least once in string t.OutputPrint a single integer β€” the largest possible time Appleman needs.ExamplesInput5ABCCADOutput5Input5AAABACADBABBBCBDCACBCCCDDDBDCDDOutput4NoteIn the first example, Toastman can choose s equal to "AAAAA".In the second example, Toastman can choose s equal to "DADDA".
Input5ABCCAD
Output5
1 second
256 megabytes
['binary search', 'shortest paths', 'strings', '*3000']
D. Appleman and Complicated Tasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must contain only one character in the end) are there, such that for each cell the number of adjacent cells with 'o' will be even? Find the number of ways modulo 1000000007 (109 + 7). Two cells of the board are adjacent if they share a side.InputThe first line contains two integers n, k (1 ≀ n, k ≀ 105) β€” the size of the board, and the number of cells that has characters initially. Then k lines follows. The i-th line contains two integers and a character: ai, bi, ci (1 ≀ ai, bi ≀ n; ci is either 'o' or 'x'). This line means: there is a character ci in the cell that is located on the intersection of the ai-th row and bi-th column. All the given cells are distinct.Consider that the rows are numbered from 1 to n from top to bottom. Analogically, the columns are numbered from 1 to n from left to right.OutputPrint a single integer β€” the answer to the problem.ExamplesInput3 21 1 x2 2 oOutput2Input4 32 4 x3 4 x3 2 xOutput2NoteIn the first example there are two ways: xxo xoo xox ooo oxx oox
Input3 21 1 x2 2 o
Output2
2 seconds
256 megabytes
['dsu', 'math', '*2800']
C. Appleman and a Sheet of Papertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAppleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types: Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([currentΒ widthΒ ofΒ sheet] - pi). Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem.InputThe first line contains two integers: n and q (1  ≀ n ≀ 105;Β 1 ≀ q ≀ 105) β€” the width of the paper and the number of queries.Each of the following q lines contains one of the described queries in the following format: "1 pi" (1 ≀ pi < [currentΒ widthΒ ofΒ sheet]) β€” the first type query. "2 li ri" (0 ≀ li < ri ≀ [currentΒ widthΒ ofΒ sheet]) β€” the second type query. OutputFor each query of the second type, output the answer.ExamplesInput7 41 31 22 0 12 1 2Output43Input10 92 2 91 12 0 11 82 0 81 22 1 31 42 2 4Output721045NoteThe pictures below show the shapes of the paper during the queries of the first example: After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.
Input7 41 31 22 0 12 1 2
Output43
2 seconds
256 megabytes
['data structures', 'implementation', '*2200']
B. Appleman and Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAppleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≀ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).InputThe first line contains an integer n (2  ≀ n ≀ 105) β€” the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≀ pi ≀ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1.The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.OutputOutput a single integer β€” the number of ways to split the tree modulo 1000000007 (109 + 7).ExamplesInput30 00 1 1Output2Input60 1 1 0 41 1 0 0 1 0Output1Input100 1 2 1 4 4 4 0 80 0 0 1 0 1 1 0 0 1Output27
Input30 00 1 1
Output2
2 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*2000']
A. Appleman and Toastmantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAppleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?InputThe first line contains a single integer n (1 ≀ n ≀ 3Β·105). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the initial group that is given to Toastman.OutputPrint a single integer β€” the largest possible score.ExamplesInput33 1 5Output26Input110Output10NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.
Input33 1 5
Output26
2 seconds
256 megabytes
['greedy', 'sortings', '*1200']
E. Roland and Rosetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRoland loves growing flowers. He has recently grown a beautiful rose at point (0, 0) of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it. To protect the rose, Roland wants to build n watch towers. Let's assume that a tower is a point on the plane at the distance of at most r from the rose. Besides, Roland assumes that the towers should be built at points with integer coordinates and the sum of squares of distances between all pairs of towers must be as large as possible. Note, that Roland may build several towers at the same point, also he may build some of them at point (0, 0).Help Roland build the towers at the integer points so that the sum of squares of distances between all towers is maximum possible. Note that the distance in this problem is defined as the Euclidian distance between points.InputThe first line contains two integers, n and r (2 ≀ n ≀ 8;Β 1 ≀ r ≀ 30).OutputIn the first line print an integer β€” the maximum possible sum of squared distances. In the i-th of the following n lines print two integers, xi, yi β€” the coordinates of the i-th tower. Each tower must be inside or on the border of the circle with radius r. Note that there may be several towers located at the same point of the plane, also some towers can be located at point (0, 0).If there are multiple valid optimal arrangements, choose any of them.ExamplesInput4 1Output160 10 10 -10 -1Input3 6Output3120 65 -3-5 -3
Input4 1
Output160 10 10 -10 -1
3 seconds
256 megabytes
['brute force', 'geometry', 'math', 'sortings', '*2700']
D. Little Victor and Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties: for all x the following inequality holds l ≀ x ≀ r; 1 ≀ |S| ≀ k; lets denote the i-th element of the set S as si; value must be as small as possible. Help Victor find the described set.InputThe first line contains three space-separated integers l, r, k (1 ≀ l ≀ r ≀ 1012;Β 1 ≀ k ≀ min(106, r - l + 1)).OutputPrint the minimum possible value of f(S). Then print the cardinality of set |S|. Then print the elements of the set in any order.If there are multiple optimal sets, you can print any of them.ExamplesInput8 15 3Output1210 11Input8 30 7Output0514 9 28 11 16NoteOperation represents the operation of bitwise exclusive OR. In other words, it is the XOR operation.
Input8 15 3
Output1210 11
1 second
256 megabytes
['brute force', 'constructive algorithms', 'math', '*2300']
C. Presenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions. There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to ai at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?InputThe first line contains space-separated integers n, m and w (1 ≀ w ≀ n ≀ 105;Β 1 ≀ m ≀ 105). The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint a single integer β€” the maximum final height of the smallest flower.ExamplesInput6 2 32 2 2 2 1 1Output2Input2 5 15 8Output9NoteIn the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test.
Input6 2 32 2 2 2 1 1
Output2
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', '*1700']
B. Little Dima and Equationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 109) of the equation:x = bΒ·s(x)a + c,  where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in the decimal representation of number x.The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: a, b, c. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem.InputThe first line contains three space-separated integers: a, b, c (1 ≀ a ≀ 5;Β 1 ≀ b ≀ 10000;  - 10000 ≀ c ≀ 10000).OutputPrint integer n β€” the number of the solutions that you've found. Next print n integers in the increasing order β€” the solutions of the given equation. Print only integer solutions that are larger than zero and strictly less than 109.ExamplesInput3 2 8Output310 2008 13726 Input1 2 -18Output0Input2 2 -1Output41 31 337 967
Input3 2 8
Output310 2008 13726
1 second
256 megabytes
['brute force', 'implementation', 'math', 'number theory', '*1500']
A. Vasya and Sockstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?InputThe single line contains two integers n and m (1 ≀ n ≀ 100;Β 2 ≀ m ≀ 100), separated by a space.OutputPrint a single integer β€” the answer to the problem.ExamplesInput2 2Output3Input9 3Output13NoteIn the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two.In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.
Input2 2
Output3
1 second
256 megabytes
['brute force', 'implementation', 'math', '*900']
E. Pashmak and Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.InputThe first line contains two integers n, m (2 ≀ n ≀ 3Β·105;Β 1 ≀ m ≀ min(nΒ·(n - 1), 3Β·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≀ ui, vi ≀ n;Β 1 ≀ wi ≀ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi.It's guaranteed that the graph doesn't contain self-loops and multiple edges.OutputPrint a single integer β€” the answer to the problem.ExamplesInput3 31 2 12 3 13 1 1Output1Input3 31 2 12 3 23 1 3Output3Input6 71 2 13 2 52 4 22 5 22 6 95 4 34 3 4Output6NoteIn the first sample the maximum trail can be any of this trails: .In the second sample the maximum trail is .In the third sample the maximum trail is .
Input3 31 2 12 3 13 1 1
Output1
1 second
256 megabytes
['dp', 'sortings', '*1900']
D. Pashmak and Parmida's problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputParmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≀ k ≀ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≀ i < j ≀ n) such that f(1, i, ai) > f(j, n, aj).Help Pashmak with the test.InputThe first line of the input contains an integer n (1 ≀ n ≀ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint a single integer β€” the answer to the problem.ExamplesInput71 2 1 1 2 2 1Output8Input31 1 1Output1Input51 2 3 4 5Output0
Input71 2 1 1 2 2 1
Output8
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'sortings', '*1800']
C. Pashmak and Busestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.InputThe first line of input contains three space-separated integers n, k, d (1 ≀ n, d ≀ 1000;Β 1 ≀ k ≀ 109).OutputIf there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.ExamplesInput3 2 2Output1 1 2 1 2 1 Input3 2 1Output-1NoteNote that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.
Input3 2 2
Output1 1 2 1 2 1
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'math', '*1900']
B. Pashmak and Flowerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things: The maximum beauty difference of flowers that Pashmak can give to Parmida. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way. InputThe first line of the input contains n (2 ≀ n ≀ 2Β·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≀ bi ≀ 109).OutputThe only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.ExamplesInput21 2Output1 1Input31 4 5Output4 1Input53 1 2 3 1Output2 4NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this: choosing the first and the second flowers; choosing the first and the fifth flowers; choosing the fourth and the second flowers; choosing the fourth and the fifth flowers.
Input21 2
Output1 1
1 second
256 megabytes
['combinatorics', 'implementation', 'sortings', '*1300']
A. Pashmak and Gardentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.InputThe first line contains four space-separated x1, y1, x2, y2 ( - 100 ≀ x1, y1, x2, y2 ≀ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.OutputIf there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them. Note that x3, y3, x4, y4 must be in the range ( - 1000 ≀ x3, y3, x4, y4 ≀ 1000).ExamplesInput0 0 0 1Output1 0 1 1Input0 0 1 1Output0 1 1 0Input0 0 1 2Output-1
Input0 0 0 1
Output1 0 1 1
1 second
256 megabytes
['implementation', '*1200']
F. An easy problem about treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it.On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of their values with their parent, that now became a leaf (the player decides which of the two values to associate). The game ends when only one node (the one that was the root of the tree) is left.Pieguy goes first, and his goal is to maximize the value that will be associated with the root when the game ends. Piegirl wants to minimize that value. Assuming that both players are playing optimally, what number will be associated with the root when the game ends?InputFirst line contains a single integer t (1 ≀ t ≀ 100) β€” number of test cases. Then t test cases follow. Each test case begins with an empty line, followed by a line with a single integer n (1 ≀ n ≀ 250), followed by n lines describing n nodes of the tree. Each of those n lines either contains a non-negative number ai, indicating a leaf node with value ai (0 ≀ ai ≀ 1000) associated with it, or  - 1 followed by integers l and r, indicating a non-leaf node with children l and r (0 ≀ l, r ≀ n - 1). Nodes are numbered from 0 to n - 1. The root is always node 0.OutputFor each test case print one line with one integer on it β€” the number that will be associated with the root when the game ends.ExamplesInput43-1 1 21055-1 1 2-1 3 4105207-1 1 2-1 3 4-1 5 6123411-1 1 2-1 3 4-1 5 6-1 7 8157-1 9 1078911Output101048
Input43-1 1 21055-1 1 2-1 3 4105207-1 1 2-1 3 4-1 5 6123411-1 1 2-1 3 4-1 5 6-1 7 8157-1 9 1078911
Output101048
2 seconds
256 megabytes
['dp', 'games', 'greedy', 'trees', '*3200']
E. Flow Optimalitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a computer network consisting of n nodes numbered 1 through n. There are links in the network that connect pairs of nodes. A pair of nodes may have multiple links between them, but no node has a link to itself.Each link supports unlimited bandwidth (in either direction), however a link may only transmit in a single direction at any given time. The cost of sending data across a link is proportional to the square of the bandwidth. Specifically, each link has a positive weight, and the cost of sending data across the link is the weight times the square of the bandwidth.The network is connected (there is a series of links from any node to any other node), and furthermore designed to remain connected in the event of any single node failure.You needed to send data from node 1 to node n at a bandwidth of some positive number k. That is, you wish to assign a bandwidth to each link so that the bandwidth into a node minus the bandwidth out of a node is  - k for node 1, k for node n, and 0 for all other nodes. The individual bandwidths do not need to be integers.Wishing to minimize the total cost, you drew a diagram of the network, then gave the task to an intern to solve. The intern claimed to have solved the task and written the optimal bandwidths on your diagram, but then spilled coffee on it, rendering much of it unreadable (including parts of the original diagram, and the value of k).From the information available, determine if the intern's solution may have been optimal. That is, determine if there exists a valid network, total bandwidth, and optimal solution which is a superset of the given information. Furthermore, determine the efficiency of the intern's solution (if possible), where efficiency is defined as total cost divided by total bandwidth.InputInput will begin with two integers n and m (2 ≀ n ≀ 200000; 0 ≀ m ≀ 200000), the number of nodes and number of known links in the network, respectively. Following this are m lines with four integers each: f, t, w, b (1 ≀ f ≀ n;Β 1 ≀ t ≀ n;Β f ≠ t;Β 1 ≀ w ≀ 100;Β 0 ≀ b ≀ 100). This indicates there is a link between nodes f and t with weight w and carrying b bandwidth. The direction of bandwidth is from f to t.OutputIf the intern's solution is definitely not optimal, print "BAD x", where x is the first link in the input that violates the optimality of the solution. If the intern's solution may be optimal, print the efficiency of the solution if it can be determined rounded to the nearest integer, otherwise print "UNKNOWN".ExamplesInput4 51 2 1 21 3 4 12 3 2 12 4 4 13 4 1 2Output6Input5 52 3 1 13 4 1 14 2 1 11 5 1 11 5 100 100OutputBAD 3Input6 41 3 31 411 5 59 262 6 53 584 6 97 93OutputUNKNOWNInput7 51 7 2 12 3 1 14 5 1 06 1 10 01 3 1 1OutputBAD 4NoteAlthough the known weights and bandwidths happen to always be integers, the weights and bandwidths of the remaining links are not restricted to integers.
Input4 51 2 1 21 3 4 12 3 2 12 4 4 13 4 1 2
Output6
2 seconds
256 megabytes
['constructive algorithms', 'flows', 'math', '*3000']
D. Bingo!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m β‰₯ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then k distinct numbers between 1 and m will be called at random (called uniformly among all available sets of k numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).InputInput will consist of three integers n, m, k (1 ≀ n ≀ 300;Β n2 ≀ m ≀ 100000;Β n ≀ k ≀ m).OutputPrint the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10 - 9.ExamplesInput1 2 1Output2.5Input2 4 3Output4Input7 59164 40872Output3.1415926538
Input1 2 1
Output2.5
1 second
256 megabytes
['combinatorics', 'math', 'probabilities', '*2700']
C. Electionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.InputFirst line contains one integer n (1 ≀ n ≀ 105) β€” number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≀ ai ≀ 105;Β 0 ≀ bi ≀ 104) β€” number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).OutputPrint one integer β€” smallest amount of money you need to spend to win the elections.ExamplesInput51 21 21 22 10 0Output3Input41 21 22 10 0Output2Input1100000 0Output0
Input51 21 21 22 10 0
Output3
2 seconds
256 megabytes
['brute force', '*2100']
B. Distributed Jointime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.InputFirst line contains two integer numbers, m and n (1 ≀ m, n ≀ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≀ ai ≀ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≀ bi ≀ 109).OutputPrint one integer β€” minimal number of copy operations.ExamplesInput2 22 63 100Output11Input2 310 101 1 1Output6NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2Β·3 = 6 copy operations.
Input2 22 63 100
Output11
1 second
256 megabytes
['greedy', '*1900']
A. Golden Systemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.InputInput consists of two lines β€” one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.OutputPrint ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.ExamplesInput1000111Output<Input0010011Output=Input110101Output>NoteIn the first example first number equals to , while second number is approximately 1.6180339882 + 1.618033988 + 1β€‰β‰ˆβ€‰5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is β€‰β‰ˆβ€‰2.618.
Input1000111
Output<
1 second
256 megabytes
['math', 'meet-in-the-middle', '*1700']
B. Fedya and Mathstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n + 2n + 3n + 4n)Β modΒ 5for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).InputThe single line contains a single integer n (0 ≀ n ≀ 10105). The number doesn't contain any leading zeroes.OutputPrint the value of the expression without leading zeros.ExamplesInput4Output4Input124356983594583453458888889Output0NoteOperation xΒ modΒ y means taking remainder after division x by y.Note to the first sample:
Input4
Output4
1 second
256 megabytes
['math', 'number theory', '*1200']
A. Laptopstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops.Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality).All ai are distinct. All bi are distinct. OutputIf Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).ExamplesInput21 22 1OutputHappy Alex
Input21 22 1
OutputHappy Alex
1 second
256 megabytes
['sortings', '*1100']
E. Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSerega and Fedor play with functions. One day they came across a very interesting function. It looks like that: f(1, j) = a[j], 1 ≀ j ≀ n. f(i, j) = min(f(i - 1, j), f(i - 1, j - 1)) + a[j], 2 ≀ i ≀ n, i ≀ j ≀ n. Here a is an integer array of length n.Serega and Fedya want to know what values this function takes at some points. But they don't want to calculate the values manually. So they ask you to help them.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the length of array a. The next line contains n integers: a[1], a[2], ..., a[n] (0 ≀ a[i] ≀ 104).The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains two integers: xi, yi (1 ≀ xi ≀ yi ≀ n). Each line means that Fedor and Serega want to know the value of f(xi, yi).OutputPrint m lines β€” the answers to the guys' queries.ExamplesInput62 2 3 4 3 444 53 43 42 3Output12995Input71 3 2 3 4 0 244 52 31 44 6Output11430
Input62 2 3 4 3 444 53 43 42 3
Output12995
1 second
256 megabytes
['data structures', '*2900']
D. Serega and Funtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSerega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query problems. One day Fedor came up with such a problem.You are given an array a consisting of n positive integers and queries to it. The queries can be of two types: Make a unit cyclic shift to the right on the segment from l to r (both borders inclusive). That is rearrange elements of the array in the following manner:a[l], a[l + 1], ..., a[r - 1], a[r] → a[r], a[l], a[l + 1], ..., a[r - 1]. Count how many numbers equal to k are on the segment from l to r (both borders inclusive). Fedor hurried to see Serega enjoy the problem and Serega solved it really quickly. Let's see, can you solve it?InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of elements of the array. The second line contains n integers a[1], a[2], ..., a[n] (1 ≀ a[i] ≀ n).The third line contains a single integer q (1 ≀ q ≀ 105) β€” the number of queries. The next q lines contain the queries.As you need to respond to the queries online, the queries will be encoded. A query of the first type will be given in format: 1 l'i r'i. A query of the second type will be given in format: 2 l'i r'i k'i. All the number in input are integer. They satisfy the constraints: 1 ≀ l'i, r'i, k'i ≀ n.To decode the queries from the data given in input, you need to perform the following transformations:li = ((l'i + lastans - 1)Β modΒ n) + 1;Β ri = ((r'i + lastans - 1)Β modΒ n) + 1;Β ki = ((k'i + lastans - 1)Β modΒ n) + 1.Where lastans is the last reply to the query of the 2-nd type (initially, lastans = 0). If after transformation li is greater than ri, you must swap these values.OutputFor each query of the 2-nd type print the answer on a single line.ExamplesInput76 6 2 7 4 2 571 3 62 2 4 22 2 4 72 2 2 51 2 61 1 42 1 7 3Output2100Input88 4 2 2 7 7 8 881 8 82 8 1 71 8 11 7 32 8 8 31 1 41 2 71 4 5Output20
Input76 6 2 7 4 2 571 3 62 2 4 22 2 4 72 2 2 51 2 61 1 42 1 7 3
Output2100
4 seconds
256 megabytes
['data structures', '*2700']