question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible. | Input: ['21 999999 1'] Output:['AG'] | [
2,
3
] |
You are given three positive integers x,βy,βn. Your task is to find the nearest fraction to fraction whose denominator is no more than n. Formally, you should find such pair of integers a,βb (1ββ€βbββ€βn; 0ββ€βa) that the value is as minimal as possible.If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator. | Input: ['3 7 6'] Output:['2/5'] | [
0
] |
You've got a non-decreasing sequence x1,βx2,β...,βxn (1ββ€βx1ββ€βx2ββ€β...ββ€βxnββ€βq). You've also got two integers a and b (aββ€βb; aΒ·(nβ-β1)β<βq).Your task is to transform sequence x1,βx2,β...,βxn into some sequence y1,βy2,β...,βyn (1ββ€βyiββ€βq; aββ€βyiβ+β1β-βyiββ€βb). The transformation price is the following sum: . Your task is to choose such sequence y that minimizes the described transformation price. | Input: ['3 6 2 21 4 6'] Output:['1.666667 3.666667 5.666667 0.666667'] | [
0,
3
] |
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game. | Input: ['21 2'] Output:['1.50000000000000000000'] | [
3
] |
Valera considers a number beautiful, if it equals 2k or -2k for some integer k (kββ₯β0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands. | Input: ['10'] Output:['1'] | [
2
] |
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number iβ+β1, then book number iβ+β2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read. | Input: ['4 53 1 2 1'] Output:['3'] | [
0,
4
] |
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0,β0),β(1,β0)], [(1,β0),β(1,β1)], [(1,β1),β(β-β1,β1)], [(β-β1,β1),β(β-β1,ββ-β1)], [(β-β1,ββ-β1),β(2,ββ-β1)], [(2,ββ-β1),β(2,β2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.Valera the horse lives on the plane at coordinates (0,β0). He wants to walk along the spiral to point (x,βy). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0,β0) to point (x,βy). | Input: ['0 0'] Output:['0'] | [
0
] |
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems β the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1ββ€βlββ€βrββ€β|s|) of string sβ=βs1s2... s|s| (where |s| is the length of string s) is string slslβ+β1... sr.String xβ=βx1x2... xp is lexicographically smaller than string yβ=βy1y2... yq, if either pβ<βq and x1β=βy1,βx2β=βy2,β... ,βxpβ=βyp, or there exists such number r (rβ<βp,βrβ<βq), that x1β=βy1,βx2β=βy2,β... ,βxrβ=βyr and xrβ+β1β<βyrβ+β1. The string characters are compared by their ASCII codes. | Input: ['5threehorsesgoodsubstringssecretprimematrixbeautifulyear'] Output:['j'] | [
0
] |
A little girl loves problems on bitwise operations very much. Here's one of them.You are given two integers l and r. Let's consider the values of for all pairs of integers a and b (lββ€βaββ€βbββ€βr). Your task is to find the maximum value among all considered ones.Expression means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as "^", in Pascal β as "xor". | Input: ['1 2'] Output:['3'] | [
2,
3
] |
The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 <= l_i <= r_i <= n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum. | Input: ['3 35 3 21 22 31 3'] Output:['25'] | [
2
] |
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β the one who moves first or the one who moves second. | Input: ['aba'] Output:['First'] | [
2
] |
Lenny had an nβΓβm matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix.Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. | Input: ['3 31 -1 -11 2 12 -1 1'] Output:['3 1 2 '] | [
2
] |
Luyi has n circles on the plane. The i-th circle is centered at (xi,βyi). At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time t (tβ>β0) is equal to t. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consists of several black and white regions. Note that the circles may overlap while growing. We define a hole as a closed, connected white region. For instance, the figure contains two holes shown by red border. During growing some holes may be created and it is easy to see that each created hole will disappear eventually. Luyi asks you to find moment of time such that the last hole disappears. In other words, you should find the first moment such that no hole can be seen after that. | Input: ['30 01 12 2'] Output:['-1'] | [
0
] |
A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | Input: ['31 21 31 -1 1'] Output:['3'] | [
2
] |
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (xβ<βy) from the set, such that yβ=βxΒ·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset. | Input: ['6 22 3 6 5 4 10'] Output:['3'] | [
2,
4
] |
Little Dima has two sequences of points with integer coordinates: sequence (a1,β1),β(a2,β2),β...,β(an,βn) and sequence (b1,β1),β(b2,β2),β...,β(bn,βn).Now Dima wants to count the number of distinct sequences of points of length 2Β·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.Dima considers two assembled sequences (p1,βq1),β(p2,βq2),β...,β(p2Β·n,βq2Β·n) and (x1,βy1),β(x2,βy2),β...,β(x2Β·n,βy2Β·n) distinct, if there is such i (1ββ€βiββ€β2Β·n), that (pi,βqi)ββ β(xi,βyi).As the answer can be rather large, print the remainder from dividing the answer by number m. | Input: ['1127'] Output:['1'] | [
3
] |
Dima got into number sequences. Now he's got sequence a1,βa2,β...,βan, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0)β=β0; f(2Β·x)β=βf(x); f(2Β·xβ+β1)β=βf(x)β+β1. Dima wonders, how many pairs of indexes (i,βj) (1ββ€βiβ<βjββ€βn) are there, such that f(ai)β=βf(aj). Help him, count the number of such pairs. | Input: ['31 2 4'] Output:['3'] | [
3
] |
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima. | Input: ['11'] Output:['3'] | [
3
] |
There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a,βb).Each of the three horses can paint the special cards. If you show an (a,βb) card to the gray horse, then the horse can paint a new (aβ+β1,βbβ+β1) card. If you show an (a,βb) card, such that a and b are even integers, to the white horse, then the horse can paint a new card. If you show two cards (a,βb) and (b,βc) to the gray-and-white horse, then he can paint a new (a,βc) card.Polycarpus really wants to get n special cards (1,βa1), (1,βa2), ..., (1,βan). For that he is going to the horse land. He can take exactly one (x,βy) card to the horse land, such that 1ββ€βxβ<βyββ€βm. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires. | Input: ['1 62'] Output:['11'] | [
3
] |
You've got an nβΓβm matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | Input: ['3 31 2 35 6 14 4 1'] Output:['1'] | [
0,
3,
4
] |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits. | Input: ['1987'] Output:['2013'] | [
0
] |
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a1, a2, ..., an. | Input: ['55 2 1 3 4'] Output:['2'] | [
2
] |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a? | Input: ['3306090'] Output:['NOYESYES'] | [
3
] |
Emuskald is an innovative musician and always tries to push the boundaries of music production. Now he has come up with an idea for a revolutionary musical instrument β a rectangular harp.A rectangular harp is a rectangle nβΓβm consisting of n rows and m columns. The rows are numbered 1 to n from top to bottom. Similarly the columns are numbered 1 to m from left to right. String pins are spaced evenly across every side, one per unit. Thus there are n pins on the left and right sides of the harp and m pins on its top and bottom. The harp has exactly nβ+βm different strings, each string connecting two different pins, each on a different side of the harp.Emuskald has ordered his apprentice to construct the first ever rectangular harp. However, he didn't mention that no two strings can cross, otherwise it would be impossible to play the harp. Two strings cross if the segments connecting their pins intersect. To fix the harp, Emuskald can perform operations of two types: pick two different columns and swap their pins on each side of the harp, not changing the pins that connect each string; pick two different rows and swap their pins on each side of the harp, not changing the pins that connect each string; In the following example, he can fix the harp by swapping two columns: Help Emuskald complete his creation and find the permutations how the rows and columns of the harp need to be rearranged, or tell that it is impossible to do so. He can detach and reattach each string to its pins, so the physical layout of the strings doesn't matter. | Input: ['3 4L T 1 3L B 2 2L B 3 3T R 1 2T B 2 1T R 4 1B R 4 3'] Output:['1 2 3 3 2 1 4 '] | [
3
] |
Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw β it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold: for each vertex v (1β<βvβ<βn), sum of ci of incoming edges is equal to the sum of ci of outcoming edges; vertex with number 1 has no incoming edges; the obtained directed graph does not have cycles. | Input: ['3 33 2 101 2 103 1 5'] Output:['101'] | [
2
] |
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.From the top view each magical box looks like a square with side length equal to 2k (k is an integer, kββ₯β0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2kβ-β1 into one box of side length 2k, or as in the following figure: Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes. | Input: ['20 31 5'] Output:['3'] | [
2,
3
] |
Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist: If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song. If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song. For example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following: Manao listens to A, he likes it, he remembers it. Manao listens to B, he does not like it, so he listens to A, again. Manao listens to C, he likes the song and he remembers it, too. Manao listens to D, but does not enjoy it and re-listens to songs A and C. That is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening.Manao has received n songs: the i-th of them is li seconds long and Manao may like it with a probability of pi percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist. | Input: ['3150 20150 50100 50'] Output:['537.500000000'] | [
3
] |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario. | Input: ['2'] Output:['3'] | [
3
] |
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.There are n teams taking part in the national championship. The championship consists of nΒ·(nβ-β1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question. | Input: ['31 22 43 4'] Output:['1'] | [
0
] |
Berland traffic is very different from traffic in other countries. The capital of Berland consists of n junctions and m roads. Each road connects a pair of junctions. There can be multiple roads between a pair of junctions. For each road we know its capacity: value ci is the maximum number of cars that can drive along a road in any direction per a unit of time. For each road, the cars can drive along it in one of two direction. That it, the cars can't simultaneously move in both directions. A road's traffic is the number of cars that goes along it per a unit of time. For road (ai,βbi) this value is negative, if the traffic moves from bi to ai. A road's traffic can be a non-integer number.The capital has two special junctions β the entrance to the city (junction 1) and the exit from the city (junction n). For all other junctions it is true that the traffic is not lost there. That is, for all junctions except for 1 and n the incoming traffic sum equals the outgoing traffic sum.Traffic has an unusual peculiarity in the capital of Berland β for any pair of junctions (x,βy) the sum of traffics along any path from x to y doesn't change depending on the choice of the path. Such sum includes traffic along all roads on the path (possible with the "minus" sign, if the traffic along the road is directed against the direction of the road on the path from x to y).Your task is to find the largest traffic that can pass trough the city per one unit of time as well as the corresponding traffic for each road. | Input: ['231 2 21 2 42 1 1000'] Output:['6.000002.000002.00000-2.00000'] | [
3
] |
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai,βbi). How many operations will be performed for each of them? | Input: ['24 177 987654321'] Output:['8141093479'] | [
3
] |
You've got an array, consisting of n integers: a1,βa2,β...,βan. Your task is to quickly run the queries of two types: Assign value x to all elements from l to r inclusive. After such query the values of the elements of array al,βalβ+β1,β...,βar become equal to x. Calculate and print sum , where k doesn't exceed 5. As the value of the sum can be rather large, you should print it modulo 1000000007 (109β+β7). | Input: ['4 55 10 2 1? 1 2 1= 2 2 0? 2 4 3= 1 4 1? 1 4 5'] Output:['25431300'] | [
3
] |
BerDonalds, a well-known fast food restaurant, is going to open a cafe in Bertown. The important thing is to choose the new restaurant's location so that it would be easy to get there. The Bertown road system is represented by n junctions, connected by m bidirectional roads. For each road we know its length. We also know that we can get from any junction to any other one, moving along the roads.Your task is to find such location of the restaurant, that the shortest distance along the roads from the cafe to the farthest junction would be minimum. Note that the restaurant can be located not only on the junction, but at any point of any road. | Input: ['2 11 2 1'] Output:['0.50'] | [
3
] |
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (nβ-β1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: Swap i-th and j-th rows of the matrix; Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if iβ>βj. | Input: ['21 2'] Output:['22 1 21 1 2'] | [
2,
3
] |
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1ββ€βiββ€βnβ-β1), she jumps to height h of the tree iβ+β1. This action can't be performed if hβ>βhiβ+β1. Compute the minimal time (in seconds) required to eat all nuts. | Input: ['212'] Output:['5'] | [
2
] |
You've got a table of size nβΓβm. On the intersection of the i-th row (1ββ€βiββ€βn) and the j-th column (1ββ€βjββ€βm) there is a non-negative integer ai,βj. Besides, you've got a non-negative integer k.Your task is to find such pair of integers (a,βb) that meets these conditions: kββ€βaββ€βnβ-βkβ+β1; kββ€βbββ€βmβ-βkβ+β1; let's denote the maximum of the function among all integers x and y, that satisfy the inequalities kββ€βxββ€βnβ-βkβ+β1 and kββ€βyββ€βmβ-βkβ+β1, as mval; for the required pair of numbers the following equation must hold f(a,βb)β=βmval. | Input: ['4 4 21 2 3 41 1 1 12 2 2 24 3 2 1'] Output:['3 2'] | [
0
] |
One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a,βb) (aββ βb), that are either each other's immediate neighbors in the circle, or there is number c, such that a and Ρ are immediate neighbors, and b and c are immediate neighbors. As you can easily deduce, in the end Vasya drew 2Β·n arcs.For example, if the numbers are written in the circle in the order 1,β2,β3,β4,β5 (in the clockwise direction), then the arcs will join pairs of integers (1,β2), (2,β3), (3,β4), (4,β5), (5,β1), (1,β3), (2,β4), (3,β5), (4,β1) and (5,β2).Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with 2Β·n written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs. | Input: ['51 22 33 44 55 11 32 43 54 15 2'] Output:['1 2 3 4 5 '] | [
0
] |
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0,β0) and (ai,βai) are the opposite corners of the i-th square.Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly k drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits. | Input: ['4 35 1 3 4'] Output:['2 1'] | [
2
] |
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes. | Input: ['3 2-1 -1 1'] Output:['3'] | [
2
] |
Maxim has got a calculator. The calculator has two integer cells. Initially, the first cell contains number 1, and the second cell contains number 0. In one move you can perform one of the following operations: Let's assume that at the current time the first cell contains number a, and the second cell contains number b. Write to the second cell number bβ+β1; Let's assume that at the current time the first cell contains number a, and the second cell contains number b. Write to the first cell number aΒ·b. Maxim is wondering, how many integers x (lββ€βxββ€βr) are there, such that we can write the number x to the first cell of the calculator, having performed at most p moves. | Input: ['2 10 3'] Output:['1'] | [
0
] |
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (mβ+β1)βΓβ(mβ+β1):Maxim asks you to count, how many numbers m (1ββ€βmββ€βn) are there, such that the sum of values in the cells in the row number mβ+β1 of the resulting matrix equals t.Expression (x xor y) means applying the operation of bitwise excluding "OR" to numbers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal β by "xor". | Input: ['1 1'] Output:['1'] | [
3
] |
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number. | Input: ['31 2 33'] Output:['1.3333333333'] | [
3
] |
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts. | Input: ['12450 50 100 100'] Output:['200'] | [
2
] |
A country called Flatland is an infinite two-dimensional plane. Flatland has n cities, each of them is a point on the plane.Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four distinct straight lines, such that two of them are parallel to the Ox axis, and two others are parallel to the Oy axis. At that, no straight line can go through any city. Thus, Flatland will be divided into 9 parts, and each son will be given exactly one of these parts. Circle IV thought a little, evaluated his sons' obedience and decided that the i-th son should get the part of Flatland that has exactly ai cities.Help Circle find such four straight lines that if we divide Flatland into 9 parts by these lines, the resulting parts can be given to the sons so that son number i got the part of Flatland which contains ai cities. | Input: ['91 11 21 32 12 22 33 13 23 31 1 1 1 1 1 1 1 1'] Output:['1.5000000000 2.50000000001.5000000000 2.5000000000'] | [
0,
4
] |
The board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer.A bad boy Vasya came up to the board and wrote number sv near each node v β the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board.Your task is to restore the original tree by the node colors and numbers sv. | Input: ['31 31 20 5'] Output:['3 1 33 2 2'] | [
2
] |
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers iβ+β1, iβ+β2, iβ+β3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If iβ=βn, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if iβ=β3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4,β1,β2,β3,β4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x β the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes. | Input: ['4 44 3 1 6'] Output:['3 2 5 4 '] | [
2
] |
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year. | Input: ['777-444---21-12-2013-12-2013-12-2013---444-777'] Output:['13-12-2013'] | [
0
] |
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times. | Input: ['5 4 5'] Output:['524848'] | [
3
] |
Little Elephant loves magic squares very much.A magic square is a 3βΓβ3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15. The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 105. Help the Little Elephant, restore the original magic square, given the Elephant's notes. | Input: ['0 1 11 0 11 1 0'] Output:['1 1 11 1 11 1 1'] | [
0
] |
The Little Elephant loves chess very much. One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8βΓβ8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation multiple times (or not run it at all).For example, if the first line of the board looks like that "BBBBBBWW" (the white cells of the line are marked with character "W", the black cells are marked with character "B"), then after one cyclic shift it will look like that "WBBBBBBW".Help the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard. | Input: ['WBWBWBWBBWBWBWBWBWBWBWBWBWBWBWBWWBWBWBWBWBWBWBWBBWBWBWBWWBWBWBWB'] Output:['YES'] | [
0
] |
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1,β2,β3,β...,βn.This time the Little Elephant has permutation p1,βp2,β...,βpn. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the ai-th and the bi-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements.Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed.We'll call a pair of integers i,βj (1ββ€βiβ<βjββ€βn) an inversion in permutatuon p1,βp2,β...,βpn, if the following inequality holds: piβ>βpj. | Input: ['2 11 21 2'] Output:['0.500000000'] | [
3
] |
The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of k positive integers x1,βx2,β...,βxk is the minimum positive integer that is divisible by each of numbers xi.Let's assume that there is a sequence of integers b1,βb2,β...,βbn. Let's denote their LCMs as lcm(b1,βb2,β...,βbn) and the maximum of them as max(b1,βb2,β...,βbn). The Little Elephant considers a sequence b good, if lcm(b1,βb2,β...,βbn)β=βmax(b1,βb2,β...,βbn).The Little Elephant has a sequence of integers a1,βa2,β...,βan. Help him find the number of good sequences of integers b1,βb2,β...,βbn, such that for all i (1ββ€βiββ€βn) the following condition fulfills: 1ββ€βbiββ€βai. As the answer can be rather large, print the remainder from dividing it by 1000000007 (109β+β7). | Input: ['41 4 3 2'] Output:['15'] | [
3,
4
] |
There have recently been elections in the zoo. Overall there were 7 main political parties: one of them is the Little Elephant Political Party, 6 other parties have less catchy names.Political parties find their number in the ballot highly important. Overall there are m possible numbers: 1,β2,β...,βm. Each of these 7 parties is going to be assigned in some way to exactly one number, at that, two distinct parties cannot receive the same number.The Little Elephant Political Party members believe in the lucky digits 4 and 7. They want to evaluate their chances in the elections. For that, they need to find out, how many correct assignments are there, such that the number of lucky digits in the Little Elephant Political Party ballot number is strictly larger than the total number of lucky digits in the ballot numbers of 6 other parties. Help the Little Elephant Political Party, calculate this number. As the answer can be rather large, print the remainder from dividing it by 1000000007 (109β+β7). | Input: ['7'] Output:['0'] | [
0
] |
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation. | Input: ['101'] Output:['11'] | [
2,
3
] |
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1,βa2,β...,βan. Vasya noticed that the following condition holds for the array aiββ€βaiβ+β1ββ€β2Β·ai for any positive integer i (iβ<βn).Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0ββ€βsββ€βa1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. | Input: ['41 2 3 5'] Output:['+++-'] | [
2,
3
] |
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you. | Input: ['22 00 2'] Output:['90.0000000000'] | [
0,
3
] |
Petya and Vasya decided to play a little. They found n red cubes and m blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have nβ+βm cubes). Petya moves first. Petya's task is to get as many pairs of neighbouring cubes of the same color as possible. Vasya's task is to get as many pairs of neighbouring cubes of different colors as possible. The number of Petya's points in the game is the number of pairs of neighboring cubes of the same color in the line, the number of Vasya's points in the game is the number of neighbouring cubes of the different color in the line. Your task is to calculate the score at the end of the game (Petya's and Vasya's points, correspondingly), if both boys are playing optimally well. To "play optimally well" first of all means to maximize the number of one's points, and second β to minimize the number of the opponent's points. | Input: ['3 1'] Output:['2 1'] | [
2
] |
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity. What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter. | Input: ['3 5 33 1 2'] Output:['1'] | [
2
] |
Furlo and Rublo play a game. The table has n piles of coins lying on it, the i-th pile has ai coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to: choose some pile, let's denote the current number of coins in it as x; choose some integer y (0ββ€βyβ<βx; x1β/β4ββ€βyββ€βx1β/β2) and decrease the number of coins in this pile to y. In other words, after the described move the pile will have y coins left. The player who can't make a move, loses. Your task is to find out, who wins in the given game if both Furlo and Rublo play optimally well. | Input: ['11'] Output:['Rublo'] | [
3
] |
Mr. Bender has a digital table of size nβΓβn, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.We'll consider the table rows numbered from top to bottom from 1 to n, and the columns β numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x,βy) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.For a cell with coordinates (x,βy) the side-adjacent cells are cells with coordinates (xβ-β1,βy), (xβ+β1,βy), (x,βyβ-β1), (x,βyβ+β1).In how many seconds will Mr. Bender get happy? | Input: ['6 4 3 1'] Output:['0'] | [
3,
4
] |
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: a1β=βp, where p is some integer; aiβ=βaiβ-β1β+β(β-β1)iβ+β1Β·q (iβ>β1), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.Sequence s1,ββs2,ββ...,ββsk is a subsequence of sequence b1,ββb2,ββ...,ββbn, if there is such increasing sequence of indexes i1,βi2,β...,βik (1βββ€ββi1ββ<ββi2ββ<β... ββ<ββikβββ€ββn), that bijββ=ββsj. In other words, sequence s can be obtained from b by crossing out some elements. | Input: ['23 5'] Output:['2'] | [
0
] |
Rats have bred to hundreds and hundreds in the basement of the store, owned by Vasily Petrovich. Vasily Petrovich may have not noticed their presence, but they got into the habit of sneaking into the warehouse and stealing food from there. Vasily Petrovich cannot put up with it anymore, he has to destroy the rats in the basement. Since mousetraps are outdated and do not help, and rat poison can poison inattentive people as well as rats, he chose a radical way: to blow up two grenades in the basement (he does not have more).In this problem, we will present the shop basement as a rectangular table of nβΓβm cells. Some of the cells are occupied by walls, and the rest of them are empty. Vasily has been watching the rats and he found out that at a certain time they go to sleep, and all the time they sleep in the same places. He wants to blow up a grenade when this convenient time comes. On the plan of his basement, he marked cells with sleeping rats in them. Naturally, these cells are not occupied by walls.Grenades can only blow up in a cell that is not occupied by a wall. The blast wave from a grenade distributes as follows. We assume that the grenade blast occurs at time 0. During this initial time only the cell where the grenade blew up gets 'clear'. If at time t some cell is clear, then at time tβ+β1 those side-neighbouring cells which are not occupied by the walls get clear too (some of them could have been cleared before). The blast wave distributes for exactly d seconds, then it dies immediately. An example of a distributing blast wave: Picture 1 shows the situation before the blast, and the following pictures show "clear" cells by time 0,1,2,3 and 4. Thus, the blast wave on the picture distributes for dβ=β4 seconds. Vasily Petrovich wonders, whether he can choose two cells to blast the grenades so as to clear all cells with sleeping rats. Write the program that finds it out. | Input: ['4 4 1XXXXXR.XX.RXXXXX'] Output:['2 2 2 3'] | [
0
] |
String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1β=βq1, p2β=βq2, ..., pkβ-β1β=βqkβ-β1, pkβ<βqk for some k (1ββ€βkββ€βn). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order. | Input: ['ABACBA'] Output:['1ABC'] | [
2
] |
In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time. | Input: ['25 23 1 23 13 2 3'] Output:['2'] | [
0
] |
Let's consider a network printer that functions like that. It starts working at time 0. In each second it can print one page of a text. At some moments of time the printer receives printing tasks. We know that a printer received n tasks. Let's number the tasks by consecutive integers from 1 to n. Then the task number i is characterised by three integers: ti is the time when the task came, si is the task's volume (in pages) and pi is the task's priority. The priorities of all tasks are distinct.When the printer receives a task, the task goes to the queue and remains there until all pages from this task are printed. The printer chooses a page to print each time when it either stops printing some page or when it is free and receives a new task. Among all tasks that are in the queue at this moment, the printer chooses the task with the highest priority and next second prints an unprinted page from this task. You can assume that a task goes to the queue immediately, that's why if a task has just arrived by time t, the printer can already choose it for printing.You are given full information about all tasks except for one: you don't know this task's priority. However, we know the time when the last page from this task was finished printing. Given this information, find the unknown priority value and determine the moments of time when the printer finished printing each task. | Input: ['34 3 -10 2 21 3 37'] Output:['47 8 4'] | [
4
] |
Vasya has recently started to learn English. Now he needs to remember how to write English letters. He isn't sure about some of them, so he decided to train a little.He found a sheet of squared paper and began writing arbitrary English letters there. In the end Vasya wrote n lines containing m characters each. Thus, he got a rectangular nβΓβm table, each cell of the table contained some English letter. Let's number the table rows from top to bottom with integers from 1 to n, and columns β from left to right with integers from 1 to m.After that Vasya looked at the resulting rectangular table and wondered, how many subtables are there, that matches both following conditions: the subtable contains at most k cells with "a" letter; all letters, located in all four corner cells of the subtable, are equal. Formally, a subtable's definition is as follows. It is defined by four integers x1,βy1,βx2,βy2 such that 1ββ€βx1β<βx2ββ€βn, 1ββ€βy1β<βy2ββ€βm. Then the subtable contains all such cells (x,βy) (x is the row number, y is the column number), for which the following inequality holds x1ββ€βxββ€βx2,βy1ββ€βyββ€βy2. The corner cells of the table are cells (x1,βy1), (x1,βy2), (x2,βy1), (x2,βy2).Vasya is already too tired after he's been writing letters to a piece of paper. That's why he asks you to count the value he is interested in. | Input: ['3 4 4aabbbaabbaab'] Output:['2'] | [
0
] |
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (kβ+β1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r,βc), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r,βc), then Vasya pushed key: "Up": if the cursor was located in the first line (rβ=β1), then it does not move. Otherwise, it moves to the previous line (with number rβ-β1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number rβ-β1; "Down": if the cursor was located in the last line (rβ=βn), then it does not move. Otherwise, it moves to the next line (with number rβ+β1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number rβ+β1; "Right": if the cursor can move to the right in this line (cβ<βarβ+β1), then it moves to the right (to position cβ+β1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (cβ>β1), then it moves to the left (to position cβ-β1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1,βc1) to position (r2,βc2). | Input: ['42 1 6 43 4 4 2'] Output:['3'] | [
2
] |
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality yββ€β2Β·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times. | Input: ['64 5 3 8 3 7'] Output:['2'] | [
4
] |
There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to nβ+βm. Then the number of integers i (1ββ€βiβ<βnβ+βm) such that positions with indexes i and iβ+β1 contain children of different genders (position i has a girl and position iβ+β1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line. | Input: ['3 3'] Output:['GBGBGB'] | [
2
] |
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions: a1ββ€βa2ββ€β...ββ€βan; a1ββ₯βa2ββ₯β...ββ₯βan. Help Petya find the two required positions to swap or else say that they do not exist. | Input: ['11'] Output:['-1'] | [
0
] |
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java. | Input: ['51 2 1 1 2'] Output:['3'] | [
0
] |
Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1β+βx2) must be as large as possible. If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java.Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0. | Input: ['61 2 3 4 5 6'] Output:['2 2 2 2 2 2'] | [
3
] |
Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer a. There's only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer b. Petya decided to turn his number a into the number b consecutively performing the operations of the following two types: Subtract 1 from his number. Choose any integer x from 2 to k, inclusive. Then subtract number (a mod x) from his number a. Operation a mod x means taking the remainder from division of number a by number x. Petya performs one operation per second. Each time he chooses an operation to perform during the current move, no matter what kind of operations he has performed by that moment. In particular, this implies that he can perform the same operation any number of times in a row.Now he wonders in what minimum number of seconds he could transform his number a into number b. Please note that numbers x in the operations of the second type are selected anew each time, independently of each other. | Input: ['10 1 4'] Output:['6'] | [
2
] |
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1,βq2,β...,βqn of length n.A permutation a of length n is a sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€βn), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: Before the beginning of the game Petya writes permutation 1,β2,β...,βn on the blackboard. After that Petya makes exactly k moves, which are described below. During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. Let's assume that the board contains permutation p1,βp2,β...,βpn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1,βpq2,β...,βpqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqiβ=βpi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1,βs2,β...,βsn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times.Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. | Input: ['4 12 3 4 11 2 3 4'] Output:['NO'] | [
3
] |
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter. | Input: ['4 31 2 3 4'] Output:['4'] | [
4
] |
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.Joe moves by a particular algorithm. Every second he makes one of the following actions: If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved. Otherwise consider the next cell in the current direction of the gaze. If the cell is empty, then Joe moves into it, the gaze direction is preserved. If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite. If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits). Joe calms down as soon as he reaches any cell of the first floor.The figure below shows an example Joe's movements around the house. Determine how many seconds Joe will need to calm down. | Input: ['3 5..+.##+..++.#+.'] Output:['14'] | [
0
] |
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.The river banks can be assumed to be vertical straight lines xβ=βa and xβ=βb (0β<βaβ<βb).The west village lies in a steppe at point Oβ=β(0,β0). There are n pathways leading from the village to the river, they end at points Aiβ=β(a,βyi). The villagers there are plain and simple, so their pathways are straight segments as well.The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are m twisted paths leading from this village to the river and ending at points Biβ=β(b,βy'i). The lengths of all these paths are known, the length of the path that leads from the eastern village to point Bi, equals li.The villagers want to choose exactly one point on the left bank of river Ai, exactly one point on the right bank Bj and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |OAi|β+β|AiBj|β+βlj, where |XY| is the Euclidean distance between points X and Y) were minimum. The Euclidean distance between points (x1,βy1) and (x2,βy2) equals .Help them and find the required pair of points. | Input: ['3 2 3 5-2 -1 4-1 27 3'] Output:['2 2'] | [
4
] |
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre β an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1,βa2,β...,βan at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1ββ€βxββ€βk), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum. | Input: ['10 31 1 2 3 2 3 3 1 1 3'] Output:['3'] | [
2
] |
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (aiβ<β0), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders. | Input: ['111 2 3 -4 -5 -6 5 -5 -6 -7 6'] Output:['35 3 3 '] | [
2
] |
A Russian space traveller Alisa Selezneva, like any other schoolgirl of the late 21 century, is interested in science. She has recently visited the MIT (Moscow Institute of Time), where its chairman and the co-inventor of the time machine academician Petrov told her about the construction of a time machine.During the demonstration of the time machine performance Alisa noticed that the machine does not have high speed and the girl got interested in the reason for such disadvantage. As it turns out on closer examination, one of the problems that should be solved for the time machine isn't solved by an optimal algorithm. If you find a way to solve this problem optimally, the time machine will run faster and use less energy.A task that none of the staff can solve optimally is as follows. There exists a matrix a, which is filled by the following rule:The cells are consecutive positive integers, starting with one. Besides, ai,βjβ<βat,βk (i,βj,βt,βkββ₯β1), if: max(i,βj)β<βmax(t,βk); max(i,βj)β=βmax(t,βk) and jβ<βk; max(i,βj)β=βmax(t,βk), jβ=βk and iβ>βt. So, after the first 36 numbers are inserted, matrix a will look as follows: To solve the problem, you should learn to find rather quickly for the given values of x1,βy1,βx2 and y2 (x1ββ€βx2,βy1ββ€βy2) the meaning of expression:As the meaning of this expression can be large enough, it is sufficient to know only the last 10 digits of the sought value.So, no one in MTI can solve the given task. Alice was brave enough to use the time machine and travel the past to help you.Your task is to write a program that uses the given values x1,βy1,βx2 and y2 finds the last 10 digits of the given expression. | Input: ['51 1 1 12 2 3 32 3 5 6100 87 288 20024 2 5 4'] Output:['124300...5679392764111'] | [
3
] |
In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis β up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles Ξ±1 and Ξ±2 to the OX axis. Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles Ξ±1 and Ξ±2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star. As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.Your task is to find the maximum number of stars m that the Donkey's chain can contain.Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain. | Input: ['151/3 2/13 16 24 22 54 56 63 41 62 17 49 35 31 315 512 4'] Output:['4'] | [
3
] |
Piglet has got a birthday today. His friend Winnie the Pooh wants to make the best present for him β a honey pot. Of course Winnie realizes that he won't manage to get the full pot to Piglet. In fact, he is likely to eat all the honey from the pot. And as soon as Winnie planned a snack on is way, the pot should initially have as much honey as possible. The day before Winnie the Pooh replenished his honey stocks. Winnie-the-Pooh has n shelves at home, each shelf contains some, perhaps zero number of honey pots. During the day Winnie came to the honey shelves q times; on the i-th time he came to some shelf ui, took from it some pots ki, tasted the honey from each pot and put all those pots on some shelf vi. As Winnie chose the pots, he followed his intuition. And that means that among all sets of ki pots on shelf ui, he equiprobably chooses one.Now Winnie remembers all actions he performed with the honey pots. He wants to take to the party the pot he didn't try the day before. For that he must know the mathematical expectation of the number m of shelves that don't have a single untasted pot. To evaluate his chances better, Winnie-the-Pooh wants to know the value m after each action he performs.Your task is to write a program that will find those values for him. | Input: ['32 2 351 2 12 1 21 2 23 1 13 2 2'] Output:['0.0000000000000.3333333333331.0000000000001.0000000000002.000000000000'] | [
3
] |
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"Dr. Suess, How The Grinch Stole ChristmasChristmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street.The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets).After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food.The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets.Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street.Your task is to write a program that will determine the minimum possible value of k. | Input: ['6 6HSHSHS'] Output:['1'] | [
2,
4
] |
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer β as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. In the given coordinate system you are given: y1, y2 β the y-coordinates of the side pillars of the goalposts of robo-Wallace's opponents; yw β the y-coordinate of the wall to which Robo-Wallace is aiming; xb, yb β the coordinates of the ball's position when it is hit; r β the radius of the ball. A goal is scored when the center of the ball crosses the OY axis in the given coordinate system between (0, y1) and (0, y2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius r. | Input: ['4 10 13 10 3 1'] Output:['4.3750000000'] | [
4
] |
Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros. | Input: ['1'] Output:['-1'] | [
3
] |
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (kβ>β1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (kβ-β1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, xβ>β0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi. | Input: ['6pasha 0gerald 1gerald 1valera 2igor 3olesya 151 11 21 33 16 1'] Output:['22010'] | [
4
] |
You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k)β=β{cu :β cuββ βk and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. | Input: ['6 61 1 2 3 5 81 23 21 44 34 54 6'] Output:['3'] | [
0
] |
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty. | Input: ['3 31 2 3'] Output:['1 11 22 3 2'] | [
0,
2
] |
Polycarpus has an array, consisting of n integers a1,βa2,β...,βan. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: he chooses two elements of the array ai, aj (iββ βj); he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes aiβ=βaiβ+β1 and ajβ=βajβ-β1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus. | Input: ['22 1'] Output:['1'] | [
2,
3
] |
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1,βa2,β...,βan in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number n and array a.loop integer variable i from 1 to nβ-β1 loop integer variable j from i to nβ-β1 if (ajβ>βajβ+β1), then swap the values of elements aj and ajβ+β1But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of n doesn't exist, print -1. | Input: ['1'] Output:['-1'] | [
2
] |
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as m username pairs ai,βbi (aiββ βbi). Each pair ai,βbi means that users ai and bi are friends. Friendship is symmetric, that is, if ai is friends with bi, then bi is also friends with ai. User y is a suggested friend for user x, if the following conditions are met: xββ βy; x and y aren't friends; among all network users who meet the first two conditions, user y has most of all common friends with user x. User z is a common friend of user x and user y (zββ βx,βzββ βy), if x and z are friends, and y and z are also friends. Your task is to help Polycarpus to implement a mechanism for determining suggested friends. | Input: ['5Mike GeraldKate MikeKate TankGerald TankGerald David'] Output:['5Mike 1Gerald 1Kate 1Tank 1David 2'] | [
0
] |
You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m. | Input: ['60 32012-03-16 16:15:25: Disk size is2012-03-16 16:15:25: Network failute2012-03-16 16:16:29: Cant write varlog2012-03-16 16:16:42: Unable to start process2012-03-16 16:16:43: Disk size is too small2012-03-16 16:16:53: Timeout detected'] Output:['2012-03-16 16:16:43'] | [
0,
4
] |
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times. | Input: ['+-+-+'] Output:['1'] | [
2
] |
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a1,βa2,β...,βan. He also wrote a square matrix b of size nβΓβn. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as bij) equals: the "bitwise AND" of numbers ai and aj (that is, bijβ=βai & aj), if iββ βj; -1, if iβ=βj. Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.Help Polycarpus, given matrix b, restore the sequence of numbers a1,βa2,β...,βan, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109. | Input: ['1-1'] Output:['0 '] | [
2
] |
Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2Β·xβ+β1ββ€βn) and take a coin from each chest with numbers x, 2Β·x, 2Β·xβ+β1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves. | Input: ['11'] Output:['-1'] | [
2
] |
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if xβ=β4, and yβ=β7, then numbers 47, 744, 4 are lucky.Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0ββ€βx,βyββ€β9), that the decimal representation of number a (without leading zeroes) contains only digits x and y.Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number. | Input: ['10'] Output:['10'] | [
0
] |
Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1,βa2,β...,βan. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute. | Input: ['5 52 34 11 55 32 11 1 2 0 2'] Output:['21 2'] | [
2
] |
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories. | Input: ['3 2 1 1'] Output:['32 13 13 2'] | [
0
] |
The Old City is a rectangular city represented as an mβΓβn grid of blocks. This city contains many buildings, straight two-way streets and junctions. Each junction and each building is exactly one block. All the streets have width of one block and are either vertical or horizontal. There is a junction on both sides of each street. We call two blocks adjacent if and only if they share a common side. No two blocks of different streets are adjacent and no two junctions are adjacent. There is an annual festival and as a part of it, The Old Peykan follows a special path in the city. This path starts from a block in a street, continues with many junctions and ends in a block of some street. For each street block, we know how much time it takes for the Old Peykan to go from this block to an adjacent block. Also the Old Peykan can go from each junction to its adjacent street blocks in one minute. Of course Old Peykan can't go to building blocks.We know the initial position of the Old Peykan and the sequence of junctions that it passes to reach its destination. After passing all the junctions and reaching the destination, it will stay there forever. Your task is to find out where will the Old Peykan be k minutes after it starts moving. Consider that The Old Peykan always follows the shortest path that passes through the given sequence of junctions and reaches the destination.Note that the Old Peykan may visit some blocks more than once. | Input: ['3 10 12###########z1a1111b###########2 3 ab 2 8'] Output:['2 8'] | [
0
] |
You have n friends and you want to take m pictures of them. Exactly two of your friends should appear in each picture and no two pictures should contain the same pair of your friends. So if you have nβ=β3 friends you can take 3 different pictures, each containing a pair of your friends.Each of your friends has an attractiveness level which is specified by the integer number ai for the i-th friend. You know that the attractiveness of a picture containing the i-th and the j-th friends is equal to the exclusive-or (xor operation) of integers ai and aj.You want to take pictures in a way that the total sum of attractiveness of your pictures is maximized. You have to calculate this value. Since the result may not fit in a 32-bit integer number, print it modulo 1000000007 (109β+β7). | Input: ['3 11 2 3'] Output:['3'] | [
3,
4
] |