question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
There is a tree consisting of n vertices. The vertices are numbered from 1 to n.Let's define the length of an interval [l, r] as the value r - l + 1. The score of a subtree of this tree is the maximum length of such an interval [l, r] that, the vertices with numbers l, l + 1, ..., r belong to the subtree.Considering all subtrees of the tree whose size is at most k, return the maximum score of the subtree. Note, that in this problem tree is not rooted, so a subtree β€” is an arbitrary connected subgraph of the tree.
Input: ['10 64 1010 62 99 68 57 14 77 31 8'] Output:['3']
[ 4 ]
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1.In the festival m fireworks will be launched. The i-th (1 ≀ i ≀ m) launching is on time ti at section ai. If you are at section x (1 ≀ x ≀ n) at the time of i-th launching, you'll gain happiness value bi - |ai - x| (note that the happiness value might be a negative value).You can move up to d length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness.Note that two or more fireworks can be launched at the same time.
Input: ['50 3 149 1 126 1 46 1 10'] Output:['-31']
[ 3 ]
There is an n × m rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the i-th row and the j-th column as (i, j).Let's define a "rectangle" as four integers a, b, c, d (1 ≀ a ≀ c ≀ n; 1 ≀ b ≀ d ≀ m). Rectangle denotes a set of cells of the grid {(x, y) :  a ≀ x ≀ c, b ≀ y ≀ d}. Let's define a "good rectangle" as a rectangle that includes only the cells with zeros.You should answer the following q queries: calculate the number of good rectangles all of which cells are in the given rectangle.
Input: ['5 5 500101000000000101000000011 2 2 44 5 4 51 2 5 22 2 4 54 2 5 3'] Output:['1017345']
[ 0 ]
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
Input: ['825769842'] Output:['5']
[ 2, 4 ]
Berland is going through tough times β€” the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
Input: ['31 100 1012'] Output:['2 3 ']
[ 2, 3 ]
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) ΠΈ 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "Π’SCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.Polycarpus has nb pieces of bread, ns pieces of sausage and nc pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are pb rubles for a piece of bread, ps for a piece of sausage and pc for a piece of cheese.Polycarpus has r rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.
Input: ['BBBSSC6 4 11 2 34'] Output:['2']
[ 0, 4 ]
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal". The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.
Input: ['15 20'] Output:['3']
[ 3 ]
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly times consecutively. In other words, array a is k-periodic, if it has period of length k.For example, any array is n-periodic, where n is the array length. Array [2, 1, 2, 1, 2, 1] is at the same time 2-periodic and 6-periodic and array [1, 2, 1, 1, 2, 1, 1, 2, 1] is at the same time 3-periodic and 9-periodic.For the given array a, consisting only of numbers one and two, find the minimum number of elements to change to make the array k-periodic. If the array already is k-periodic, then the required value equals 0.
Input: ['6 22 1 2 2 2 1'] Output:['1']
[ 2, 3 ]
At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer.As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the list are numbered starting from 1 and Vasya was reading them in the order they go in the list. Vasya never reads a new book until he finishes reading the previous one. Unfortunately, Vasya wasn't accurate and some days he forgot to note the number of the book and the notes for those days remained empty.As Vasya knows that the literature teacher will want to check the Reader's Diary, so he needs to restore the lost records. Help him do it and fill all the blanks. Vasya is sure that he spends at least two and at most five days for each book. Vasya finished reading all the books he had started. Assume that the reading list contained many books. So many, in fact, that it is impossible to read all of them in a summer. If there are multiple valid ways to restore the diary records, Vasya prefers the one that shows the maximum number of read books.
Input: ['70 1 0 0 0 3 0'] Output:['31 1 2 2 3 3 3 ']
[ 2 ]
Innocentius has a problem β€” his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention".Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that: the frame's width is 1 pixel, the frame doesn't go beyond the borders of the screen, all white pixels of the monitor are located on the frame, of all frames that satisfy the previous three conditions, the required frame must have the smallest size. Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is d = 3, then it consists of 8 pixels, if its size is d = 2, then it contains 4 pixels and if d = 1, then the frame is reduced to a single pixel.
Input: ['4 8..w..w....................w..w..'] Output:['..w++w....+..+....+..+....w++w..']
[ 0, 2 ]
A Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th child has both mittens of color ci.The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children.The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.
Input: ['6 31 3 2 2 1 1'] Output:['62 11 22 11 31 23 1']
[ 2 ]
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) β€” the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules: A rook moves any number of fields horizontally or vertically. A bishop moves any number of fields diagonally. A king moves one field in any direction β€” horizontally, vertically or diagonally. The pieces move like that Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (r1, c1) to field (r2, c2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.
Input: ['4 3 1 6'] Output:['2 1 3']
[ 3 ]
Valera loves segments. He has recently come up with one interesting problem.The Ox axis of coordinates has n segments, the i-th segment starts in position li and ends in position ri (we will mark it as [li, ri]). Your task is to process m queries, each consists of number cnti and a set of cnti coordinates of points located on the Ox axis. The answer to the query is the number of segments, such that each of them contains at least one point from the query. Segment [l, r] contains point q, if l ≀ q ≀ r.Valera found the solution of this problem too difficult. So he asked you to help him. Help Valera.
Input: ['3 31 34 56 73 1 4 72 4 51 8'] Output:['310']
[ 4 ]
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 β‰₯ a2 β‰₯ ... β‰₯ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
Input: ['5 3 1 3 13 9'] Output:['2 3 2 3 3 ']
[ 3 ]
Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.
Input: ['3 1 11 2 1'] Output:['1']
[ 2 ]
Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property: consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a; for each pair x, y must exist some position j (1 ≀ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x. Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.Help Sereja, find the maximum amount of money he can pay to Dima.
Input: ['5 21 22 3'] Output:['5']
[ 2 ]
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.
Input: ['5 3 11 2 3 2 11 2 3'] Output:['21 3']
[ 4 ]
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as aij. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that aij = apq at (i, j) ≠ (p, q).Dima has already written a song β€” a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).We'll represent a way to play a song as a sequence of pairs (xi, yi) (1 ≀ i ≀ s), such that the xi-th string on the yi-th fret produces the i-th note from the song. The complexity of moving between pairs (x1, y1) and (x2, y2) equals + . The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!
Input: ['4 6 5 73 1 2 2 3 13 2 2 2 5 54 2 2 2 5 33 2 2 1 4 32 3 1 4 1 5 1'] Output:['8']
[ 0, 3 ]
Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal...Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node.A trap graph is an undirected graph consisting of n nodes and m edges. For edge number k, Dima denoted a range of integers from lk to rk (lk ≀ rk). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it x), then Seryozha must go some way from the starting node with number 1 to the final node with number n. At that, Seryozha can go along edge k only if lk ≀ x ≀ rk.Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the n-th one as the number of integers x, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible!
Input: ['4 41 2 1 102 4 3 51 3 1 52 4 2 7'] Output:['6']
[ 4 ]
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
Input: ['6 23 2 1 6 5 4'] Output:['1']
[ 0 ]
John Doe offered his sister Jane Doe find the gcd of some set of numbers a.Gcd is a positive integer g, such that all number from the set are evenly divisible by g and there isn't such g' (g' > g), that all numbers of the set are evenly divisible by g'.Unfortunately Jane couldn't cope with the task and John offered her to find the ghd of the same subset of numbers.Ghd is a positive integer g, such that at least half of numbers from the set are evenly divisible by g and there isn't such g' (g' > g) that at least half of the numbers from the set are evenly divisible by g'.Jane coped with the task for two hours. Please try it, too.
Input: ['66 2 3 4 5 6'] Output:['3']
[ 0, 3 ]
We'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if , then . In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.Your task is to find any beautiful set, where the number of elements is equal to k and each element doesn't exceed 2k2.
Input: ['10'] Output:['16 18 24 27 36 48 54 72 108 144 ']
[ 0 ]
Let's assume that we are given an n × m table filled by integers. We'll mark a cell in the i-th row and j-th column as (i, j). Thus, (1, 1) is the upper left cell of the table and (n, m) is the lower right cell. We'll assume that a circle of radius r with the center in cell (i0, j0) is a set of such cells (i, j) that . We'll consider only the circles that do not go beyond the limits of the table, that is, for which r + 1 ≀ i0 ≀ n - r and r + 1 ≀ j0 ≀ m - r. A circle of radius 3 with the center at (4, 5). Find two such non-intersecting circles of the given radius r that the sum of numbers in the cells that belong to these circles is maximum. Two circles intersect if there is a cell that belongs to both circles. As there can be more than one way to choose a pair of circles with the maximum sum, we will also be interested in the number of such pairs. Calculate the number of unordered pairs of circles, for instance, a pair of circles of radius 2 with centers at (3, 4) and (7, 7) is the same pair as the pair of circles of radius 2 with centers at (7, 7) and (3, 4).
Input: ['2 2 01 22 4'] Output:['6 2']
[ 0 ]
A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?
Input: ['2 2 105 57 6'] Output:['2 3']
[ 2, 4 ]
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
Input: ['helloo'] Output:['hello']
[ 2 ]
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights. Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
Input: ['7 31 2 6 1 1 7 1'] Output:['3']
[ 0 ]
You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of n cities, some pairs of cities are connected by bidirectional roads, each road is described by its length li.The fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly p new roads in the country. Constructing a road goes like this: We choose a pair of distinct cities u, v that will be connected by a new road (at that, it is possible that there already is a road between these cities). We define the length of the new road: if cities u, v belong to distinct regions, then the length is calculated as min(109, S + 1) (S β€” the total length of all roads that exist in the linked regions), otherwise we assume that the length equals 1000. We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region. Vasily wants the road constructing process to result in the country that consists exactly of q regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads.
Input: ['9 6 2 21 2 23 2 14 6 201 3 87 8 35 7 2'] Output:['YES9 51 9']
[ 2 ]
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1){ int j = i; while (j > 0 && a[j] < a[j - 1]) { swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1] j = j - 1; }}Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.
Input: ['54 0 3 1 2'] Output:['3 2']
[ 3 ]
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
Input: ['2......................#.K..##..#.......#...##..#......#.K.........................#.......#..#....####.....##...............K#K#'] Output:['YESNO']
[ 2, 3 ]
Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.
Input: ['4 2'] Output:['2 4 3 1']
[ 3 ]
Levko loves sports pathfinding competitions in his city very much. In order to boost his performance, Levko spends his spare time practicing. The practice is a game.The city consists of n intersections connected by m + k directed roads. Two or more roads can connect the same pair of intersections. Besides, there can be roads leading from an intersection to itself. Levko and Zenyk are playing a game. First Levko stands on intersection s1, and Zenyk stands on intersection s2. They both want to get to intersection f. The person who does it quicker wins. If they get there at the same time, the game ends with a draw. By agreement both players start simultaneously and move with the same speed.Levko wants to win very much. He knows the lengths of all the roads in the city. Also he knows that he can change the lengths of some roads (there are k such roads at all) if he pays the government. So, the government can change the length of the i-th road to any integer value in the segment [li, ri] (both borders inclusive). Levko wondered if he can reconstruct the roads so as to win the game and whether he can hope for the draw if he cannot win.You should consider that both players play optimally well. It is guaranteed that we can get from intersections s1 and s2 to intersection f.
Input: ['4 1 31 3 43 2 21 2 1 32 4 1 33 4 1 3'] Output:['WIN1 1 3 ']
[ 2 ]
Levko has an array that consists of integers: a1, a2, ... , an. But he doesn’t like this array at all.Levko thinks that the beauty of the array a directly depends on value c(a), which can be calculated by the formula: The less value c(a) is, the more beautiful the array is.It’s time to change the world and Levko is going to change his array for the better. To be exact, Levko wants to change the values of at most k array elements (it is allowed to replace the values by any integers). Of course, the changes should make the array as beautiful as possible.Help Levko and calculate what minimum number c(a) he can reach.
Input: ['5 24 7 4 7 4'] Output:['0']
[ 4 ]
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types: Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li ≀ j ≀ ri. Find the maximum of elements from li to ri. That is, calculate the value . Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input: ['4 51 2 3 12 1 2 82 3 4 71 1 3 32 3 4 8'] Output:['YES4 7 4 7']
[ 2 ]
Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≀ l ≀ r ≀ n), such that the following conditions hold: there is integer j (l ≀ j ≀ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.
Input: ['54 6 9 3 6'] Output:['1 32 ']
[ 0, 3, 4 ]
Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7).
Input: ['2 22 2'] Output:['8']
[ 3 ]
A permutation p is an ordered group of numbers p1,   p2,   ...,   pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1,   p2,   ...,   pn.Simon has a positive integer n and a non-negative integer k, such that 2k ≀ n. Help him find permutation a of length 2n, such that it meets this equation: .
Input: ['1 0'] Output:['1 2']
[ 3 ]
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
Input: ['3 30 0 00 1 00 0 0'] Output:['4']
[ 2 ]
Dima is a good person. In fact, he's great. But all good things come to an end...Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle n × m consisting of unit squares.For the beginning, Seryozha put Dima in a center of some square. Then he started to kick Dima (it is known, that he kicks Dima at least once). Each time when Dima is kicked he flyes up and moves into one of four directions (up, left, right, down). On each move Dima passes k (k > 1) unit of the length in the corresponding direction. Seryozha is really kind, so he kicks Dima in such way that Dima never meets the walls (in other words, Dima never leave the room's space). Seryozha is also dynamic character so Dima never flies above the same segment, connecting a pair of adjacent squares, twice.Seryozha kicks Dima for a long time, but Dima is not vindictive β€” Dima writes. Dima marked all squares in which he was staying or above which he was flying. Thanks to kicks, Dima does not remember the k value, so he asks you to find all possible values which matches to the Dima's records.
Input: ['5 51 1 1 1 11 0 0 0 11 0 0 0 11 0 0 0 11 1 1 1 1'] Output:['2 4']
[ 0 ]
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
Input: ['41 2 3 44 3 2 10 1 1 0'] Output:['13']
[ 2 ]
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!
Input: ['100101201230'] Output:['0pushStack1 popStackpushStackpushQueue2 popStack popQueuepushStackpushQueuepushFront3 popStack popQueue popFront']
[ 2 ]
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
Input: ['3iloveyou<3i<3love<23you<3'] Output:['yes']
[ 0 ]
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the n-th point. Two points with coordinates (x1, 0) and (x2, 0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any). Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.
Input: ['40 10 5 15'] Output:['yes']
[ 0 ]
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 point, c2 children got 2 points, ..., cm children got m points. Now you need to set the passing rate k (integer from 1 to m): all schoolchildren who got less than k points go to the beginner group and those who get at strictly least k points go to the intermediate group. We know that if the size of a group is more than y, then the university won't find a room for them. We also know that if a group has less than x schoolchildren, then it is too small and there's no point in having classes with it. So, you need to split all schoolchildren into two groups so that the size of each group was from x to y, inclusive. Help the university pick the passing rate in a way that meets these requirements.
Input: ['53 4 3 2 16 8'] Output:['3']
[ 0, 2 ]
When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions: A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible? The answer is quite simple. The third bag contains a coin and two other bags. This problem is a generalization of the childhood puzzle. You have n bags. You know that the first bag contains a1 coins, the second bag contains a2 coins, ..., the n-th bag contains an coins. In total, there are s coins. Find the way to arrange the bags and coins so that they match the described scenario or else state that it is impossible to do.
Input: ['3 31 3 1'] Output:['1 01 2 3 11 0']
[ 2 ]
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students.
Input: ['51 2 2 4 3'] Output:['2']
[ 2 ]
Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance.The Hamming distance between two strings s = s1s2... sn and t = t1t2... tn of equal length n is value . Record [si ≠ ti] is the Iverson notation and represents the following: if si ≠ ti, it is one, otherwise β€” zero.Now Xenia wants to calculate the Hamming distance between two long strings a and b. The first string a is the concatenation of n copies of string x, that is, . The second string b is the concatenation of m copies of string y. Help Xenia, calculate the required Hamming distance, given n, x, m, y.
Input: ['100 10aaaaaaaaaaa'] Output:['0']
[ 3 ]
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
Input: ['1 3 7 192 32 54 4 4'] Output:['12']
[ 2 ]
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).The seller can obtain array b from array a if the following conditions hold: bi > 0; 0 ≀ ai - bi ≀ k for all 1 ≀ i ≀ n.Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).
Input: ['6 13 6 10 12 13 16'] Output:['3']
[ 0 ]
Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms β€” the left one and the right one. The robot can consecutively perform the following actions: Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.
Input: ['3 4 4 19 142 3 99'] Output:['576']
[ 0, 2, 3 ]
You have a directed acyclic graph G, consisting of n vertexes, numbered from 0 to n - 1. The graph contains n edges numbered from 0 to n - 1. An edge with number i connects vertexes i and (i + 1) mod n, and it can be directed in either direction (from i to (i + 1) mod n, or vise versa).Operation x mod y means taking the remainder after dividing number x by number y.Let's call two vertexes u and v in graph G comparable if the graph contains a path either from u to v or from v to u. We'll assume that an antichain is a set of vertexes of graph G, where any two distinct vertexes are not comparable. The size of an antichain is the number of vertexes in the corresponding set. An antichain is maximum if the graph doesn't have antichains of a larger size.Your task is to find the size of the maximum antichain in graph G.
Input: ['001'] Output:['1']
[ 2 ]
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≀ x ≀ m.
Input: ['23 810'] Output:['3']
[ 3 ]
Valera has 2Β·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer β€” the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?
Input: ['110 99'] Output:['12 1 ']
[ 2, 3 ]
Valera has got n domino pieces in a row. Each piece consists of two halves β€” the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
Input: ['24 26 4'] Output:['0']
[ 3 ]
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
Input: ['45 0 5 0'] Output:['0']
[ 0, 3 ]
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≀ i < j ≀ n), such that an inequality ai > aj holds.Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
Input: ['22 1'] Output:['0']
[ 2 ]
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: choose indexes i and j (i ≠ j) that haven't been chosen yet; round element ai to the nearest integer that isn't more than ai (assign to ai: ⌊ ai βŒ‹); round element aj to the nearest integer that isn't less than aj (assign to aj: ⌈ aj βŒ‰). Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
Input: ['30.000 0.500 0.750 1.000 2.000 3.000'] Output:['0.250']
[ 2, 3 ]
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.Valera's code is given below.ans[i][j] // the shortest distance for a pair of vertexes i, ja[i] // vertexes, marked by Valerafor(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) { if (i == j) ans[i][j] = 0; else ans[i][j] = INF; //INF is a very large number }} for(i = 1; i <= m; i++) { read a pair of vertexes u, v that have a non-directed edge between them; ans[u][v] = 1; ans[v][u] = 1;}for (i = 1; i <= k; i++) { v = a[i]; for(j = 1; j <= n; j++) for(r = 1; r <= n; r++) ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);}Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
Input: ['3 2 21 2'] Output:['1 32 3']
[ 0 ]
Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain n distinct segments and m distinct circles. We will consider the segments indexed from 1 to n in some way and the circles β€” indexed from 1 to m in some way. Palpatine defines an owl as a set of a pair of distinct circles (i, j) (i < j) and one segment k, such that: circles i and j are symmetrical relatively to the straight line containing segment k; circles i and j don't have any common points; circles i and j have the same radius; segment k intersects the segment that connects the centers of circles i and j. Help Palpatine, count the number of distinct owls on the picture.
Input: ['1 23 2 3 -20 0 26 0 2'] Output:['1']
[ 4 ]
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (xi, yi). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinates (0, 0). Also, let's mark the robot's current position as (x, y). In order to destroy all the bombs, the robot can perform three types of operations: Operation has format "1 k dir". To perform the operation robot have to move in direction dir k (k β‰₯ 1) times. There are only 4 directions the robot can move in: "R", "L", "U", "D". During one move the robot can move from the current point to one of following points: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) (corresponding to directions). It is forbidden to move from point (x, y), if at least one point on the path (besides the destination point) contains a bomb. Operation has format "2". To perform the operation robot have to pick a bomb at point (x, y) and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point (x, y) has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container. Operation has format "3". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point (0, 0). It is forbidden to perform the operation if the container has no bomb. Help the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.
Input: ['21 1-1 -1'] Output:['121 1 R1 1 U21 1 L1 1 D31 1 L1 1 D21 1 R1 1 U3']
[ 2 ]
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≀ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met: v is a positive integer; all correct solutions pass the system testing; at least one correct solution passes the system testing with some "extra" time; all wrong solutions do not pass the system testing; value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.
Input: ['3 64 5 28 9 6 10 7 11'] Output:['5']
[ 0, 2 ]
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.
Input: ['55 4 3 2 1 2 3 4 5'] Output:['55555']
[ 2 ]
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
Input: ['425 25 50 50'] Output:['YES']
[ 2 ]
You are given an array a1, a2, ..., an and m sets S1, S2, ..., Sm of indices of elements of this array. Let's denote Sk = {Sk, i} (1 ≀ i ≀ |Sk|). In other words, Sk, i is some element from set Sk.In this problem you have to answer q queries of the two types: Find the sum of elements with indices from set Sk: . The query format is "? k". Add number x to all elements at indices from set Sk: aSk, i is replaced by aSk, i + x for all i (1 ≀ i ≀ |Sk|). The query format is "+ k x". After each first type query print the required sum.
Input: ['5 3 55 -5 5 1 -42 1 24 2 1 4 52 2 5? 2+ 3 4? 1+ 2 1? 2'] Output:['-349']
[ 0 ]
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
Input: ['33 2 2'] Output:['4']
[ 3, 4 ]
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
Input: ['50 1 3 4 2'] Output:['3']
[ 0, 3 ]
In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. β€” Wikipedia. It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to the limits of its jumping ability. Consider the following problem.There are n platforms. The height of the x-th (1 ≀ x ≀ n) platform is aΒ·x mod p, where a and p are positive co-prime integers. The maximum possible height of a Doodler's jump is h. That is, it can jump from height h1 to height h2 (h1 < h2) if h2 - h1 ≀ h. Initially, the Doodler is on the ground, the height of which is 0. The question is whether it can reach the highest platform or not.For example, when a = 7, n = 4, p = 12, h = 2, the heights of the platforms are 7, 2, 9, 4 as in the picture below. With the first jump the Doodler can jump to the platform at height 2, with the second one the Doodler can jump to the platform at height 4, but then it can't jump to any of the higher platforms. So, it can't reach the highest platform. User xiaodao thought about the problem for a long time but didn't solve it, so she asks you for help. Also, she has a lot of instances of the problem. Your task is solve all of these instances.
Input: ['37 4 12 27 1 9 47 4 12 3'] Output:['NONOYES']
[ 3 ]
You are given a sequence of positive integers x1, x2, ..., xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves: subtract 1 from the current a; subtract a mod xi (1 ≀ i ≀ n) from the current a. Operation a mod xi means taking the remainder after division of number a by number xi.Now you want to know the minimum number of moves needed to transform a into b.
Input: ['33 4 530 17'] Output:['6']
[ 2, 3 ]
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
Input: ['22 3'] Output:['Alice']
[ 3 ]
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number β€” the number of bonds the atom must form with other atoms. An atom can form one or multiple bonds with any other atom, but it cannot form a bond with itself. The number of bonds of an atom in the molecule must be equal to its valence number. Mike knows valence numbers of the three atoms. Find a molecule that can be built from these atoms according to the stated rules, or determine that it is impossible.
Input: ['1 1 2'] Output:['0 1 1']
[ 0, 3 ]
Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations.The system consists of n pumping stations, which are numbered by integers from 1 to n. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a time). For each pipe you know its bandwidth β€” the maximum number of liters of water that can flow through it in one hour. Each pumping station can pump incoming water from some stations to other stations through the pipes, provided that in one hour the total influx of water to the station is equal to the total outflux of water from the station.It is Mike's responsibility to pump water between stations. From station a to station b through the pipes (possibly through other stations) within one hour one can transmit a certain number of liters of water according to the rules described above. During this time, water from other stations can not flow into station a, and can not flow out of the station b. However, any amount of water can flow out of station a or in station b. If a total of x litres of water flows out of the station a in an hour, then Mike gets x bollars more to his salary.To get paid, Mike needs to work for n - 1 days, according to the contract. On the first day he selects two stations v1 and v2, and within one hour he pumps a certain amount of water from v1 to v2. Next, on the i-th day Mike chooses a station vi + 1 that has been never selected before, and pumps a certain amount of water out of the station vi to station vi + 1 for one hour. The quantity of water he pumps on the i-th day does not depend on the amount of water pumped on the (i - 1)-th day.Mike needs to earn as much bollars as he can for his projects. Help Mike find such a permutation of station numbers v1, v2, ..., vn so Mike will be able to earn the highest possible salary.
Input: ['6 111 2 101 6 82 3 42 5 22 6 33 4 53 5 43 6 24 5 74 6 25 6 3'] Output:['776 2 1 5 3 4 ']
[ 0, 2 ]
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number hi. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h1, h2, ..., hn have been read at the beginning of the operation. Mike needs to read the data on m distinct tracks with numbers p1, p2, ..., pm. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.
Input: ['3 42 5 61 3 6 8'] Output:['2']
[ 2, 4 ]
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.
Input: ['-++-'] Output:['Yes']
[ 2 ]
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements: one resistor; an element and one resistor plugged in sequence; an element and one resistor plugged in parallel. With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals . In this case Re equals the resistance of the element being connected.Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element.
Input: ['1 1'] Output:['1']
[ 3 ]
Xenia the vigorous detective faced n (n β‰₯ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≀ li ≀ ri ≀ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).
Input: ['3 5 1 31 1 22 2 33 3 34 1 110 1 3'] Output:['XXRR']
[ 0, 2 ]
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held: a < b < c; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist.
Input: ['61 1 1 2 2 2'] Output:['-1']
[ 2 ]
Iahub is playing an uncommon game. Initially, he has n boxes, numbered 1, 2, 3, ..., n. Each box has some number of candies in it, described by a sequence a1, a2, ..., an. The number ak represents the number of candies in box k. The goal of the game is to move all candies into exactly two boxes. The rest of n - 2 boxes must contain zero candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes i and j, such that ai ≀ aj. Then, Iahub moves from box j to box i exactly ai candies. Obviously, when two boxes have equal number of candies, box number j becomes empty.Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.
Input: ['33 6 9'] Output:['22 31 3']
[ 2 ]
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).
Input: ['5-1 -1 4 3 -1'] Output:['2']
[ 3 ]
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph() build a graph G with n vertices and 0 edges repeat swapped = false for i = 1 to n - 1 inclusive do: if a[i] > a[i + 1] then add an undirected edge in G between a[i] and a[i + 1] swap( a[i], a[i + 1] ) swapped = true end if end for until not swapped /* repeat the algorithm as long as swapped value is true. */ end procedureFor a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input: ['33 1 2'] Output:['2']
[ 4 ]
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
Input: ['32 3 5'] Output:['22 3']
[ 3 ]
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.
Input: ['50 00 44 04 42 3'] Output:['16.000000']
[ 0 ]
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on. Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-th one. That is, he'll paint bricks x, 2Β·x, 3Β·x and so on red. Similarly, Floyd skips y - 1 consecutive bricks, then he paints the y-th one. Hence he'll paint bricks y, 2Β·y, 3Β·y and so on pink.After painting the wall all day, the boys observed that some bricks are painted both red and pink. Iahub has a lucky number a and Floyd has a lucky number b. Boys wonder how many bricks numbered no less than a and no greater than b are painted both red and pink. This is exactly your task: compute and print the answer to the question.
Input: ['2 3 6 18'] Output:['3']
[ 3 ]
Xenia the horse breeder has n (n > 1) horses that stand in a row. Each horse has its own unique number. Initially, the i-th left horse has number i. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, ..., n.Xenia trains horses before the performance. During the practice sessions, she consistently gives them commands. Each command is a pair of numbers l, r (1 ≀ l < r ≀ n). The command l, r means that the horses that are on the l-th, (l + 1)-th, (l + 2)-th, ..., r-th places from the left must be rearranged. The horses that initially stand on the l-th and r-th places will swap. The horses on the (l + 1)-th and (r - 1)-th places will swap. The horses on the (l + 2)-th and (r - 2)-th places will swap and so on. In other words, the horses that were on the segment [l, r] change their order to the reverse one.For example, if Xenia commanded l = 2, r = 5, and the sequence of numbers of horses before the command looked as (2, 1, 3, 4, 5, 6), then after the command the sequence will be (2, 5, 4, 3, 1, 6).We know that during the practice Xenia gave at most three commands of the described form. You have got the final sequence of numbers of horses by the end of the practice. Find what commands Xenia gave during the practice. Note that you do not need to minimize the number of commands in the solution, find any valid sequence of at most three commands.
Input: ['51 4 3 2 5'] Output:['12 4']
[ 2 ]
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≀ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on ​​the scales or to say that it can't be done.
Input: ['00000001013'] Output:['YES8 10 8']
[ 2 ]
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input: ['3+2+1'] Output:['1+2+3']
[ 2 ]
Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≀ i ≀ n, 1 ≀ j ≀ m. GCD(a, b) is the greatest common divisor of numbers a and b.You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1 ≀ i ≀ n and 1 ≀ j ≀ m - k + 1 should exist that G(i, j + l - 1) = al for all 1 ≀ l ≀ k.Determine if the sequence a occurs in table G.
Input: ['100 100 55 2 1 2 1'] Output:['YES']
[ 3 ]
A divisor tree is a rooted tree that meets the following conditions: Each vertex of the tree contains a positive integer number. The numbers written in the leaves of the tree are prime numbers. For any inner vertex, the number within it is equal to the product of the numbers written in its children. Manao has n distinct integers a1, a2, ..., an. He tries to build a divisor tree which contains each of these numbers. That is, for each ai, there should be at least one vertex in the tree which contains ai. Manao loves compact style, but his trees are too large. Help Manao determine the minimum possible number of vertices in the divisor tree sought.
Input: ['26 10'] Output:['7']
[ 0 ]
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9).
Input: ['5 3 2'] Output:['3']
[ 2, 3, 4 ]
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction p / q.
Input: ['1 1 3 2'] Output:['1/3']
[ 2, 3 ]
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f1 pieces, the second one consists of f2 pieces and so on.Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B.
Input: ['4 610 12 10 7 5 22'] Output:['5']
[ 2 ]
Vasily the Bear loves beautiful strings. String s is beautiful if it meets the following criteria: String s only consists of characters 0 and 1, at that character 0 must occur in string s exactly n times, and character 1 must occur exactly m times. We can obtain character g from string s with some (possibly, zero) number of modifications. The character g equals either zero or one. A modification of string with length at least two is the following operation: we replace two last characters from the string by exactly one other character. This character equals one if it replaces two zeros, otherwise it equals zero. For example, one modification transforms string "01010" into string "0100", two modifications transform it to "011". It is forbidden to modify a string with length less than two.Help the Bear, count the number of beautiful strings. As the number of beautiful strings can be rather large, print the remainder after dividing the number by 1000000007 (109 + 7).
Input: ['1 1 0'] Output:['2']
[ 3 ]
Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal β€” by "and".
Input: ['51 2 3 4 5'] Output:['24 5']
[ 0, 2 ]
One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively. Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2 - 1, inclusive. On the day number i the following things happened: The fly arrived at the coordinate plane at the center of the circle with number ( is the result of dividing number x by number y, rounded down to an integer). The fly went along the coordinate plane to the center of the circle number ( is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction. Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days.
Input: ['1 1'] Output:['2.0000000000']
[ 3 ]
Vasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you to find two points A = (x1, y1) and C = (x2, y2), such that the following conditions hold: the coordinates of points: x1, x2, y1, y2 are integers. Besides, the following inequation holds: x1 < x2; the triangle formed by point A, B and C is rectangular and isosceles ( is right); all points of the favorite rectangle are located inside or on the border of triangle ABC; the area of triangle ABC is as small as possible. Help the bear, find the required points. It is not so hard to proof that these points are unique.
Input: ['10 5'] Output:['0 15 15 0']
[ 3 ]
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
Input: ['63 4 5 3 4 5'] Output:['14']
[ 2 ]
A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height i having probability 2 - i for all positive integers i. The floors of a skyscraper with height i are numbered 0 through i - 1.To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the i-th floor of one skyscraper with the i-th floor of another skyscraper if and only if there are no skyscrapers between them that have an i-th floor.Alice and Bob decide to count the number of skyscrapers.Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than h due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds 2i to his counter, where i is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.Consider the following example. There are 6 buildings, with heights 1, 4, 3, 4, 1, 2 from left to right, and h = 2. Alice begins with her counter at 1 and then adds 1 five times for a result of 6. Bob begins with his counter at 1, then he adds 1, 4, 4, and 2, in order, for a result of 12. Note that Bob ignores the highest zip line because of his fear of heights (h = 2). Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter.
Input: ['Alice3 1'] Output:['3.500000000']
[ 3 ]
You are given n rectangles, labeled 1 through n. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).Your task is to determine if there's a non-empty subset of the rectangles that forms a square. That is, determine if there exists a subset of the rectangles and some square for which every point that belongs to the interior or the border of that square belongs to the interior or the border of at least one of the rectangles in the subset, and every point that belongs to the interior or the border of at least one rectangle in the subset belongs to the interior or the border of that square.
Input: ['90 0 1 91 0 9 11 8 9 98 1 9 82 2 3 63 2 7 32 6 7 75 3 7 63 3 5 6'] Output:['YES 55 6 7 8 9']
[ 0 ]
Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.
Input: ['banana4'] Output:['2baan']
[ 2, 4 ]
Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a plane. The circles must not interfere with each other (but they may touch each other). He can choose the centers of the circles only from the n options granted by the Company. He is free to choose the radius of the circles himself (all three radiuses must be equal), but please note that the larger the radius is, the more he gets paid. Help Gerald earn as much as possible.
Input: ['30 11 01 1'] Output:['0.50000000000000000000']
[ 0, 4 ]
Gerald found a table consisting of n rows and m columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value β€” it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.
Input: ['2 21 23 4'] Output:['1']
[ 0, 4 ]
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores k-lucky tickets.Pollard sais that a ticket is k-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., "+", "-", " × ") and brackets so as to obtain the correct arithmetic expression whose value would equal k. For example, ticket "224201016" is 1000-lucky as ( - 2 - (2 + 4)) × (2 + 0) + 1016 = 1000.Pollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for m days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram k-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these m days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly m distinct k-lucky tickets.
Input: ['0 3'] Output:['000000000000000100000002']
[ 0 ]