question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
In Berland each high school student is characterized by academic performance β integer value between 1 and 5.In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known β integer value between 1 and 5.The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class A and one student of class B. After that, they both change their groups.Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance. | Input: ['45 4 4 45 5 4 5'] Output:['1'] | [
3
] |
Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters.Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his languages which is called broom. Broom is rooted tree with edges marked with letters. Initially broom is represented by the only vertex β the root of the broom. When Peterson wants to add new word to the language he stands at the root and processes the letters of new word one by one. Consider that Peterson stands at the vertex u. If there is an edge from u marked with current letter, Peterson goes through this edge. Otherwise Peterson adds new edge from u to the new vertex v, marks it with the current letter and goes through the new edge. Size of broom is the number of vertices in it.In the evening after working day Peterson can't understand the language he made this morning. It is too difficult for bored Peterson and he tries to make it simpler. Simplification of the language is the process of erasing some letters from some words of this language. Formally, Peterson takes some positive integer p and erases p-th letter from all the words of this language having length at least p. Letters in words are indexed starting by 1. Peterson considers that simplification should change at least one word, i.e. there has to be at least one word of length at least p. Peterson tries to make his language as simple as possible, so he wants to choose p such that the size of the broom for his simplified language is as small as possible.Peterson is pretty annoyed with this task so he asks you for help. Write a program to find the smallest possible size of the broom and integer p. | Input: ['51 2 c2 3 a3 4 t2 5 t'] Output:['32'] | [
0
] |
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. | Input: ['3 3a := 101b := 011c := ? XOR b'] Output:['011100'] | [
0
] |
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if tβ=β"nastya" and aβ=β[4,β1,β5,β3,β2,β6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t. | Input: ['ababcbaabb5 3 4 1 7 6 2'] Output:['3'] | [
2,
4
] |
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied: Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bjββ€βbi. Rings should not fall one into the the other. That means one can place ring j on the ring i only if bjβ>βai. The total height of all rings used should be maximum possible. | Input: ['31 5 12 6 23 7 3'] Output:['6'] | [
0,
2
] |
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. | Input: ['3#book#bigtown#big'] Output:['#b#big#big'] | [
2,
4
] |
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.Now she has a table filled with integers. The table consists of n rows and m columns. By ai,βj we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai,βjββ€βaiβ+β1,βj for all i from 1 to nβ-β1.Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai,βjββ€βaiβ+β1,βj for all i from l to rβ-β1 inclusive.Alyona is too small to deal with this task and asks you to help! | Input: ['5 41 2 3 53 1 3 24 5 2 35 5 3 24 4 3 461 12 54 53 51 31 5'] Output:['YesNoYesYesYesNo'] | [
2,
4
] |
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if nβ=β3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies. | Input: ['3123321'] Output:['02'] | [
2
] |
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly n movements were made by the operator and the ball was under shell x at the end. Now he wonders, what was the initial position of the ball? | Input: ['42'] Output:['1'] | [
3
] |
The Holmes children are fighting over who amongst them is the cleverest.Mycroft asked Sherlock and Eurus to find value of f(n), where f(1)β=β1 and for nββ₯β2, f(n) is the number of distinct ordered positive integer pairs (x,βy) that satisfy xβ+βyβ=βn and gcd(x,βy)β=β1. The integer gcd(a,βb) is the greatest common divisor of a and b.Sherlock said that solving this was child's play and asked Mycroft to instead get the value of . Summation is done over all positive integers d that divide n.Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.She defined a k-composite function Fk(n) recursively as follows:She wants them to tell the value of Fk(n) modulo 1000000007. | Input: ['7 1'] Output:['6'] | [
3
] |
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.Help her to do so in finding the total number of such segments. | Input: ['4 22 2 2 2'] Output:['8'] | [
0,
3,
4
] |
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern. | Input: ['ross rachel4ross joeyrachel phoebephoebe monicamonica chandler'] Output:['ross racheljoey racheljoey phoebejoey monicajoey chandler'] | [
0
] |
Polycarp's workday lasts exactly n minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has k bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that k is strictly greater than 1.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute x and the next bar in the minute y (x < y). Then the break time is equal to y - x - 1 minutes. It is not necessary for Polycarp to eat all bars he has. | Input: ['3 3010'] Output:['1'] | [
4
] |
Stepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (nβ+β1)-th day again he uses the pen number 1, on the (nβ+β2)-th β he uses the pen number 2 and so on.On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day. Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above. | Input: ['33 3 3'] Output:['2'] | [
4
] |
Stepan has a very big positive integer.Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m. | Input: ['5213'] Output:['2'] | [
3
] |
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer. | Input: ['2'] Output:['1'] | [
2
] |
Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β its significance ci and width wi.Stepan decided to expose some of his cups on a shelf with width d in such a way, that: there is at least one Physics cup and at least one Informatics cup on the shelf, the total width of the exposed cups does not exceed d, from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups. | Input: ['3 1 84 25 54 23 2'] Output:['8'] | [
4
] |
Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1β+βc2Β·(xβ-β1)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group. | Input: ['3 4 1011'] Output:['8'] | [
4
] |
Test data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness.For example, consider a problem from an old Codeforces round. Its input format looks roughly as follows:The first line contains a single integer n (1ββ€βnββ€βmaxn) β the size of the set. The second line contains n distinct integers a1,βa2,β...,βan (1ββ€βaiββ€βmaxa) β the elements of the set in increasing order.If you don't pay attention to the problem solution, it looks fairly easy to generate a good test case for this problem. Let nβ=βmaxn, take random distinct ai from 1 to maxa, sort them... Soon you understand that it's not that easy.Here is the actual problem solution. Let g be the greatest common divisor of a1,βa2,β...,βan. Let xβ=βanβ/βgβ-βn. Then the correct solution outputs "Alice" if x is odd, and "Bob" if x is even.Consider two wrong solutions to this problem which differ from the correct one only in the formula for calculating x.The first wrong solution calculates x as xβ=βanβ/βg (without subtracting n).The second wrong solution calculates x as xβ=βanβ-βn (without dividing by g).A test case is interesting if it makes both wrong solutions output an incorrect answer.Given maxn, maxa and q, find the number of interesting test cases satisfying the constraints, and output it modulo q. | Input: ['3 6 100000'] Output:['4'] | [
3
] |
It can be shown that any positive integer x can be uniquely represented as xβ=β1β+β2β+β4β+β...β+β2kβ-β1β+βr, where k and r are integers, kββ₯β0, 0β<βrββ€β2k. Let's call that representation prairie partition of x.For example, the prairie partitions of 12, 17, 7 and 1 are: 12β=β1β+β2β+β4β+β5,17β=β1β+β2β+β4β+β8β+β2,7β=β1β+β2β+β4,1β=β1. Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options! | Input: ['81 1 2 2 3 4 5 8'] Output:['2 '] | [
2,
3,
4
] |
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1β/β4, and the problem's maximum point value is equal to 1500.If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses xβ/β250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000Β·(1β-β40β/β250)β=β1680 points for this problem.There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.Unfortunately, Vasya is a cheater. He has registered 109β+β7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal. | Input: ['25 15 40 70 11550 45 40 30 15'] Output:['2'] | [
0,
2
] |
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to xβ/βy.Your favorite rational number in the [0;1] range is pβ/βq. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be pβ/βq? | Input: ['43 10 1 27 14 3 820 70 2 75 6 1 1'] Output:['4100-1'] | [
3,
4
] |
This is an interactive problem.The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2nβ-β1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.A question consists of printing the label of three distinct leaves a1,βa2,βa3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a,βb) denote the node with maximum depth that is a common ancestor of the nodes a and b.Consider Xβ=βLCA(a1,βa2),βYβ=βLCA(a2,βa3),βZβ=βLCA(a3,βa1). The judge will tell you which one of X,βY,βZ has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties. More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively). You may only ask at most 10Β·n questions. | Input: ['5XZYYX'] Output:['1 4 21 2 42 4 12 3 52 4 3-1-1 1 1 2 2 3 3 6 6'] | [
4
] |
You are given an integer m, and a list of n distinct integers between 0 and mβ-β1.You would like to construct a sequence satisfying the properties: Each element is an integer between 0 and mβ-β1, inclusive. All prefix products of the sequence modulo m are distinct. No prefix product modulo m appears as an element of the input list. The length of the sequence is maximized. Construct any sequence satisfying the properties above. | Input: ['0 5'] Output:['51 2 4 3 0'] | [
3
] |
You have n devices that you want to use simultaneously.The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power. | Input: ['2 12 22 1000'] Output:['2.0000000000'] | [
3,
4
] |
Limak has a grid that consists of 2 rows and n columns. The j-th cell in the i-th row contains an integer ti,βj which can be positive, negative or zero.A non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to 0.Limak wants to choose some nice rectangles and give them to his friends, as gifts. No two chosen rectangles should share a cell. What is the maximum possible number of nice rectangles Limak can choose? | Input: ['670 70 70 70 70 -1590 -60 -30 30 -30 15'] Output:['3'] | [
2
] |
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | Input: ['8 3NO NO YES YES YES NO'] Output:['Adam Bob Bob Cpqepqwer Limak Adam Bob Adam'] | [
2
] |
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. | Input: ['100'] Output:['99'] | [
3
] |
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if kβ=β2, the pair of integers xβ=β5 and yβ=β3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that iβ<βj and the pair of integers ai and aj is k-interesting. Your task is to help Vasya and determine this number. | Input: ['4 10 3 2 1'] Output:['4'] | [
0
] |
The Robot is in a rectangular maze of size nβΓβm. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above. | Input: ['2 3 2.**X..'] Output:['RL'] | [
2
] |
Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai β the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that: the student i sends no more than ai messages (for all i from 1 to n); all students knew the news about the credit (initially only Polycarp knew it); the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above. | Input: ['41 2 1 0'] Output:['31 22 42 3'] | [
2
] |
Given a rooted tree with n nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest.The root of a tree in the forest is the node in that tree which does not have a parent. We define the strength of the forest as the size of largest tree in forest.Jon Snow wants to minimize the strength of the forest. To do this he can perform the following operation at most once.He removes the edge between a node and its parent and inserts a new edge between this node and any other node in forest such that the total number of trees in forest remain same.For each node v you need to find the minimum value of strength of the forest formed when node v is removed. | Input: ['100 11 21 31 42 52 63 74 84 95 10'] Output:['3455599999'] | [
4
] |
Tarly has two different type of items, food boxes and wine barrels. There are f food boxes and w wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two stacks of wine barrels are together.The height of a stack is defined as the number of items in the stack. Two stacks are considered different if either their heights are different or one of them contains food and other contains wine.Jon Snow doesn't like an arrangement if any stack of wine barrels has height less than or equal to h. What is the probability that Jon Snow will like the arrangement if all arrangement are equiprobably?Two arrangement of stacks are considered different if exists such i, that i-th stack of one arrangement is different from the i-th stack of the other arrangement. | Input: ['1 1 1'] Output:['0'] | [
0,
3
] |
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where Ξ΅β<β10β-β7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help. | Input: ['1 11'] Output:['1'] | [
3
] |
Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number x, he might get soldiers of high strength. So, he decided to do the following operation k times: Arrange all the rangers in a straight line in the order of increasing strengths. Take the bitwise XOR (is written as ) of the strength of each alternate ranger with x and update it's strength. Suppose, Jon has 5 rangers with strengths [9,β7,β11,β15,β5] and he performs the operation 1 time with xβ=β2. He first arranges them in the order of their strengths, [5,β7,β9,β11,β15]. Then he does the following: The strength of first ranger is updated to , i.e. 7. The strength of second ranger remains the same, i.e. 7. The strength of third ranger is updated to , i.e. 11. The strength of fourth ranger remains the same, i.e. 11. The strength of fifth ranger is updated to , i.e. 13. The new strengths of the 5 rangers are [7,β7,β11,β11,β13]Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations k times. He wants your help for this task. Can you help him? | Input: ['5 1 29 7 11 15 5'] Output:['13 7'] | [
0
] |
Student Arseny likes to plan his life for n days ahead. He visits a canteen every day and he has already decided what he will order in each of the following n days. Prices in the canteen do not change and that means Arseny will spend ci rubles during the i-th day.There are 1-ruble coins and 100-ruble notes in circulation. At this moment, Arseny has m coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards.Cashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny x notes and coins on the i-th day, his dissatisfaction for this day equals xΒ·wi. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this. "Caution! Angry cashier" Arseny wants to pay in such a way that the total dissatisfaction of the cashier for n days would be as small as possible. Help him to find out how he needs to pay in each of the n days!Note that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days. | Input: ['5 42117 71 150 243 2001 1 1 1 1'] Output:['791 171 02 02 432 0'] | [
2
] |
Olya likes milk very much. She drinks k cartons of milk each day if she has at least k and drinks all of them if she doesn't. But there's an issue β expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's fridge contains a carton past its expiry date, she throws it away.Olya hates throwing out cartons, so when she drinks a carton, she chooses the one which expires the fastest. It's easy to understand that this strategy minimizes the amount of cartons thrown out and lets her avoid it if it's even possible. Milk. Best before: 20.02.2017. The main issue Olya has is the one of buying new cartons. Currently, there are n cartons of milk in Olya's fridge, for each one an expiration date is known (how soon does it expire, measured in days). In the shop that Olya visited there are m cartons, and the expiration date is known for each of those cartons as well.Find the maximum number of cartons Olya can buy so that she wouldn't have to throw away any cartons. Assume that Olya drank no cartons today. | Input: ['3 6 21 0 12 0 2 0 0 2'] Output:['31 2 3'] | [
2,
4
] |
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp. Help Dima to find a suitable way to cut the garland, or determine that this is impossible.While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer. | Input: ['62 40 54 22 11 14 2'] Output:['1 4'] | [
2
] |
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.He knows that the receptionist starts working after ts minutes have passed after midnight and closes after tf minutes have passed after midnight (so that (tfβ-β1) is the last minute when the receptionist is still working). The receptionist spends exactly t minutes on each person in the queue. If the receptionist would stop working within t minutes, he stops serving visitors (other than the one he already serves). Vasya also knows that exactly n visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately. "Reception 1" For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him! | Input: ['10 15 2210 13'] Output:['12'] | [
0,
2
] |
Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by nβ-β1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is , where is bitwise xor operation.Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities. | Input: ['31 2 31 22 3'] Output:['10'] | [
3
] |
Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1β=β2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1β=β2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions: How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109β+β7. What is the maximum length of a substring that can appear in some valid splitting? What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa". | Input: ['3aab2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'] Output:['322'] | [
0,
2
] |
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area. | Input: ['51 5 3 2 4'] Output:['YES'] | [
2,
3
] |
If you have gone that far, you'll probably skip unnecessary legends anyway...You are given a binary string and an integer . Find the number of integers k, 0ββ€βkβ<βN, such that for all iβ=β0, 1, ..., mβ-β1 Print the answer modulo 109β+β7. | Input: ['122 13 1'] Output:['2'] | [
0,
3
] |
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0β=βv, a1, ..., ak, and b0β=βv, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. | Input: ['61 22 32 44 51 6'] Output:['3'] | [
2
] |
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.Let [n] denote the set {1,β...,βn}. We will also write f:β[x]βββ[y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.Now then, you are given a function f:β[n]βββ[n]. Your task is to find a positive integer m, and two functions g:β[n]βββ[m], h:β[m]βββ[n], such that g(h(x))β=βx for all , and h(g(x))β=βf(x) for all , or determine that finding these is impossible. | Input: ['31 2 3'] Output:['31 2 31 2 3'] | [
3
] |
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.Note that the game consisted of several complete sets. | Input: ['11 11 5'] Output:['1'] | [
3
] |
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation. | Input: ['abacaba'] Output:['YES'] | [
2
] |
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: this list contains all Jinotega's flights in this year (in arbitrary order), Jinotega has only flown from his hometown to a snooker contest and back, after each competition Jinotega flies back home (though they may attend a competition in one place several times), and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! | Input: ['4SVOSVO->CDGLHR->SVOSVO->LHRCDG->SVO'] Output:['home'] | [
3
] |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1,β2,β...,βz. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute. | Input: ['1 1 10'] Output:['10'] | [
0,
3
] |
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.One of his birthday presents was a sequence of distinct integers a1,βa2,β...,βan. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x,βxβ+βd,βxβ+β2d,β...,βxβ+β(nβ-β1)Β·d, each taken modulo m. | Input: ['17 50 2 4 13 15'] Output:['13 2'] | [
0,
3
] |
In the lattice points of the coordinate line there are n radio stations, the i-th of which is described by three integers: xi β the coordinate of the i-th station on the line, ri β the broadcasting range of the i-th station, fi β the broadcasting frequency of the i-th station. We will say that two radio stations with numbers i and j reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words min(ri,βrj)ββ₯β|xiβ-βxj|.Let's call a pair of radio stations (i,βj) bad if iβ<βj, stations i and j reach each other and they are close in frequency, that is, |fiβ-βfj|ββ€βk.Find the number of bad pairs of radio stations. | Input: ['3 21 3 103 2 54 10 8'] Output:['1'] | [
4
] |
You are given a rectangular table 3βΓβn. Each cell contains an integer. You can move from one cell to another if they share a side.Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible. | Input: ['31 1 11 -1 11 1 1'] Output:['7'] | [
2
] |
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s. | Input: ['hibob'] Output:['-'] | [
4
] |
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some β only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy. | Input: ['2 1 145 USB6 PS/23 PS/27 PS/2'] Output:['3 14'] | [
2
] |
You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist.Divisor of n is any such natural number, that n can be divided by it without remainder. | Input: ['4 2'] Output:['2'] | [
3
] |
Dasha decided to have a rest after solving the problem D and began to look photos from previous competitions.Let's call photos as the matrix with the size nβΓβm, which consists of lowercase English letters.Some k photos especially interested her, because they can be received from photo-template by painting a rectangular area in a certain color. Let's call such photos special. More formally the i-th special photo is received from the photo-template by replacing all characters on some rectangle with upper left corner of the cell with coordinates (ai,βbi) and lower right corner in the cell with coordinates (ci,βdi) to the symbol ei.Dasha asks you to find the special photo so that the total distance from it to all other special photos is minimum. And calculate this distance.Determine the distance between two photos as the sum of distances between all corresponding letters. The distance between two letters is the difference module of their positions in the alphabet. For example, the distance between letters 'h' and 'm' equals |8β-β13|β=β5, because the letter 'h' is the 8-th in the alphabet, the letter 'm' is the 13-th. | Input: ['3 3 2aaaaaaaaa1 1 2 2 b2 2 3 3 c'] Output:['10'] | [
0
] |
Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity β origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are nβ-β1 edges in a tree with n vertices.The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane.It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value. | Input: ['71 21 32 42 53 63 7'] Output:['YES0 01 00 12 01 -1-1 10 2'] | [
2
] |
Dasha logged into the system and began to solve problems. One of them is as follows:Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ciβ=βbiβ-βai.About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: lββ€βaiββ€βr and lββ€βbiββ€βr. About sequence c we know that all its elements are distinct. Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence cβ=β[250,β200,β300,β100,β50] the compressed sequence will be pβ=β[4,β3,β5,β2,β1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct. | Input: ['5 1 51 1 1 1 13 1 5 4 2'] Output:['3 1 5 4 2 '] | [
0,
2,
4
] |
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: There is at least one digit in the string, There is at least one lowercase (small) letter of the Latin alphabet in the string, There is at least one of three listed symbols in the string: '#', '*', '&'. Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. | Input: ['3 41**2a3*0c4**'] Output:['1'] | [
0
] |
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track. Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the n barriers. Thus, each of them wrote n integers in the ascending order, each of them was between 0 and Lβ-β1, inclusively. Consider an example. Let Lβ=β8, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence [2,β4,β6], and Sasha writes down [1,β5,β7]. There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks. Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction β counterclockwise, if you look on a track from above. | Input: ['3 82 4 61 5 7'] Output:['YES'] | [
0,
3
] |
On her way to programming school tiger Dasha faced her first test β a huge staircase! The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values β the number of steps with even and odd numbers. You need to check whether there is an interval of steps from the l-th to the r-th (1ββ€βlββ€βr), for which values that Dasha has found are correct. | Input: ['2 3'] Output:['YES'] | [
0,
3
] |
n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (nββ€βm). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have. Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt? | Input: ['4 6 2'] Output:['2'] | [
2,
4
] |
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap. | Input: ['1 7'] Output:['6'] | [
3
] |
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: lββ€βaiββ€βr and aiββ βaj , where a1,βa2,β...,βan is the geometrical progression, 1ββ€βi,βjββ€βn and iββ βj.Geometrical progression is a sequence of numbers a1,βa2,β...,βan where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4,β6,β9, common ratio is .Two progressions a1,βa2,β...,βan and b1,βb2,β...,βbn are considered different, if there is such i (1ββ€βiββ€βn) that aiββ βbi. | Input: ['1 1 10'] Output:['10'] | [
0,
3
] |
You are given a tree that has n vertices, which are numbered from 1 to n, where the vertex number one is the root. Each edge has weight wi and strength pi.Botanist Innokentiy, who is the only member of the jury of the Olympiad in Informatics, doesn't like broken trees. The tree is broken if there is such an edge the strength of which is less than the sum of weight of subtree's edges to which it leads.It is allowed to reduce weight of any edge by arbitrary integer value, but then the strength of its edge is reduced by the same value. It means if the weight of the edge is 10, and the strength is 12, then by the reducing the weight by 7 its weight will equal 3, and the strength will equal 5. It is not allowed to increase the weight of the edge.Your task is to get the tree, which is not broken, by reducing the weight of edges of the given tree, and also all edged should have the positive weight, moreover, the total weight of all edges should be as large as possible.It is obvious that the strength of edges can not be negative, however it can equal zero if the weight of the subtree equals zero. | Input: ['31 3 5 73 2 4 3'] Output:['31 3 5 73 2 4 3'] | [
2
] |
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets 11311 (475β=β1Β·162β+β13Β·161β+β11Β·160). Alexander lived calmly until he tried to convert the number back to the decimal number system.Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base n he will get the number k. | Input: ['1312'] Output:['12'] | [
2,
3
] |
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others.Seating in the class looks like a rectangle, where n rows with m pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the 1-st row, the 2-nd row, ..., the nβ-β1-st row, the n-th row, the nβ-β1-st row, ..., the 2-nd row, the 1-st row, the 2-nd row, ...The order of asking of pupils on the same row is always the same: the 1-st pupil, the 2-nd pupil, ..., the m-th pupil.During the lesson the teacher managed to ask exactly k questions from pupils in order described above. Sergei seats on the x-th row, on the y-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values: the maximum number of questions a particular pupil is asked, the minimum number of questions a particular pupil is asked, how many times the teacher asked Sergei. If there is only one row in the class, then the teacher always asks children from this row. | Input: ['1 3 8 1 1'] Output:['3 2 3'] | [
3,
4
] |
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' β red, 'B' β blue, 'Y' β yellow, 'G' β green.Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors. | Input: ['RYBGRYBGR'] Output:['0 0 0 0'] | [
0
] |
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them. | Input: ['50 1 2 3 4'] Output:['10'] | [
3
] |
Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.Bash defines a function f0(n), which denotes the number of ways of factoring n into two factors p and q such that gcd(p,βq)β=β1. In other words, f0(n) is the number of ordered pairs of positive integers (p,βq) such that pΒ·qβ=βn and gcd(p,βq)β=β1.But Bash felt that it was too easy to calculate this function. So he defined a series of functions, where frβ+β1 is defined as:Where (u,βv) is any ordered pair of positive integers, they need not to be co-prime.Now Bash wants to know the value of fr(n) for different r and n. Since the value could be huge, he would like to know the value modulo 109β+β7. Help him! | Input: ['50 301 253 652 54 48'] Output:['85254630'] | [
0
] |
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of kβ>β1 Pokemon with strengths {s1,βs2,βs3,β...,βsk} tend to fight among each other if gcd(s1,βs2,βs3,β...,βsk)β=β1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself. | Input: ['32 3 4'] Output:['2'] | [
2,
3
] |
Consider the following grammar: <expression> ::= <term> | <expression> '+' <term> <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')' <number> ::= <pos_digit> | <number> <digit> <digit> ::= '0' | <pos_digit> <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'This grammar describes a number in decimal system using the following rules: <number> describes itself, <number>-<number> (l-r, lββ€βr) describes integer which is concatenation of all integers from l to r, written without leading zeros. For example, 8-11 describes 891011, <number>(<expression>) describes integer which is concatenation of <number> copies of integer described by <expression>, <expression>+<term> describes integer which is concatenation of integers described by <expression> and <term>.For example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717.You are given an expression in the given grammar. Print the integer described by it modulo 109β+β7. | Input: ['8-11'] Output:['891011'] | [
3
] |
There are n types of coins in Byteland. Conveniently, the denomination of the coin type k divides the denomination of the coin type kβ+β1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types kβ+β1 and k equals ak. It is known that for each x there are at most 20 coin types of denomination x.Byteasar has bk coins of type k with him, and he needs to pay exactly m tugricks. It is known that Byteasar never has more than 3Β·105 coins with him. Byteasar want to know how many ways there are to pay exactly m tugricks. Two ways are different if there is an integer k such that the amount of coins of type k differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo 109β+β7. | Input: ['142'] Output:['1'] | [
3
] |
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1βββ2), the resulting population is "bbbb"; 2βββ1, the result is "aabb"; 2βββ3, the result is "baab"; 3βββ2, the result is "bbbb" (note that the result is the same as the first option); 3βββ4 or 4βββ3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109β+β7. | Input: ['3aaa'] Output:['1'] | [
0
] |
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.The fare is constructed in the following manner. There are three types of tickets: a ticket for one trip costs 20 byteland rubles, a ticket for 90 minutes costs 50 byteland rubles, a ticket for one day (1440 minutes) costs 120 byteland rubles. Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to tβ+βxβ-β1, inclusive. Assume that all trips take exactly one minute.To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum aβ-βb.You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip. | Input: ['3102030'] Output:['202010'] | [
4
] |
PolandBall is standing in a row with Many Other Balls. More precisely, there are exactly n Balls. Balls are proud of their home land β and they want to prove that it's strong.The Balls decided to start with selecting exactly m groups of Balls, each consisting either of single Ball or two neighboring Balls. Each Ball can join no more than one group.The Balls really want to impress their Enemies. They kindly asked you to calculate number of such divisions for all m where 1ββ€βmββ€βk. Output all these values modulo 998244353, the Enemies will be impressed anyway. | Input: ['3 3'] Output:['5 5 1 '] | [
3
] |
It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are n Balls overall. Each Ball has someone for whom he should bring a present according to some permutation p, piββ βi for all i.Unfortunately, Balls are quite clumsy. We know earlier that exactly k of them will forget to bring their gift. A Ball number i will get his present if the following two constraints will hold: Ball number i will bring the present he should give. Ball x such that pxβ=βi will bring his present. What is minimum and maximum possible number of kids who will not get their present if exactly k Balls will forget theirs? | Input: ['5 23 4 1 5 2'] Output:['2 4'] | [
2
] |
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally? | Input: ['5 1polandballisacoolcharacternope'] Output:['YES'] | [
2,
4
] |
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number nΒ·mβ+β1 is a prime number".Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any n. | Input: ['3'] Output:['1'] | [
0,
3
] |
Dasha is fond of challenging puzzles: Rubik's Cube 3βΓβ3βΓβ3, 4βΓβ4βΓβ4, 5βΓβ5βΓβ5 and so on. This time she has a cyclic table of size nβΓβm, and each cell of the table contains a lowercase English letter. Each cell has coordinates (i,βj) (0ββ€βiβ<βn, 0ββ€βjβ<βm). The table is cyclic means that to the right of cell (i,βj) there is the cell , and to the down there is the cell .Dasha has a pattern as well. A pattern is a non-cyclic table of size rβΓβc. Each cell is either a lowercase English letter or a question mark. Each cell has coordinates (i,βj) (0ββ€βiβ<βr, 0ββ€βjβ<βc).The goal of the puzzle is to find all the appearance positions of the pattern in the cyclic table.We say that the cell (i,βj) of cyclic table is an appearance position, if for every pair (x,βy) such that 0ββ€βxβ<βr and 0ββ€βyβ<βc one of the following conditions holds: There is a question mark in the cell (x,βy) of the pattern, or The cell of the cyclic table equals to the cell (x,βy) of the pattern. Dasha solved this puzzle in no time, as well as all the others she ever tried. Can you solve it?. | Input: ['5 7qcezchshhedywqwikywqyqckrqztbqexcxz3 2??yw?q'] Output:['00001000001001000000000000000000000'] | [
0
] |
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor! | Input: ['4 21 10040 70120 130125 180'] Output:['311 2 '] | [
2,
4
] |
Recently Vladik discovered a new entertainment β coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats! | Input: ['12Vladik netman2?: Hello, Vladik!?: Hi'] Output:['netman: Hello, Vladik!Vladik: Hi'] | [
0
] |
Ilya is an experienced player in tic-tac-toe on the 4βΓβ4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not. The rules of tic-tac-toe on the 4βΓβ4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal). | Input: ['xx...oo.x...oox.'] Output:['YES'] | [
0
] |
One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A.Lesha is tired now so he asked you to split the array. Help Lesha! | Input: ['31 2 -3'] Output:['YES21 23 3'] | [
2
] |
The only difference from the previous problem is the constraint on the number of requests. In this problem your program should guess the answer doing at most 7 requests.This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java β call System.out.flush(), and in Pascal β flush(output).Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers β the number of "bulls" and the number of "cows". A try can contain equal digits.More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1ββ€βiββ€β4) where s[i]β=βx[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i]β=βc), x contains c, but x[i]ββ βc.For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons β the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).Your program is allowed to do at most 7 queries.You can hack solutions of other participants providing a 4-digit string containing distinct digits β the secret string. | Input: ['0 12 01 10 42 14 0'] Output:['800001793159321001120123'] | [
0
] |
This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java β call System.out.flush(), and in Pascal β flush(output).Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers β the number of "bulls" and the number of "cows". A try can contain equal digits.More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1ββ€βiββ€β4) where s[i]β=βx[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i]β=βc), x contains c, but x[i]ββ βc.For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons β the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).Your program is allowed to do at most 50 queries.You can hack solutions of other participants providing a 4-digit string containing distinct digits β the secret string. | Input: ['0 12 01 10 42 14 0'] Output:['800001793159321001120123'] | [
0
] |
Santa Claus has n candies, he dreams to give them as gifts to children.What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has. | Input: ['5'] Output:['22 3'] | [
2,
3
] |
The New Year tree is an infinite perfect binary tree rooted in the node 1. Each node v has two children: nodes indexed (2Β·v) and (2Β·vβ+β1). Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nodes. Though he was given an opportunity to pick the pair himself! Now he wants to know the number of unordered pairs of indices (u,βv) (uββ€βv), such that the sum of indices of all nodes along the simple path between u and v (including endpoints) is equal to s. Can you help him and count this value? | Input: ['10'] Output:['4'] | [
0
] |
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on.Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1,βt2,β...,βtn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2nβ-β1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time β it is allowed and such parts do not crash.Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells? | Input: ['44 2 2 3'] Output:['39'] | [
0
] |
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible". | Input: ['3-7 15 28 2'] Output:['1907'] | [
2,
3,
4
] |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th problem.Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, where he will participate in the contest first.How many problems can Limak solve if he wants to make it to the party? | Input: ['3 222'] Output:['2'] | [
0,
3,
4
] |
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai,βbi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning biβ<βbiβ+β1 for all iβ<βn. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. aiββ βaiβ+β1 for all iβ<βn.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them. | Input: ['61 102 1003 10001 100002 1000003 100000031 32 2 32 1 2'] Output:['2 1000001 103 1000'] | [
4
] |
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated: Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting). When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote. | Input: ['5DDRRR'] Output:['D'] | [
2
] |
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwise traversal.Alex had very nice test for this problem, but is somehow happened that the last line of the input was lost and now he has only three out of four points of the original parallelogram. He remembers that test was so good that he asks you to restore it given only these three points. | Input: ['0 01 00 1'] Output:['31 -1-1 11 1'] | [
0
] |
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors β 1 and k. | Input: ['5'] Output:['22 3'] | [
2,
3
] |
Santa Claus has n tangerines, and the i-th of them consists of exactly ai slices. Santa Claus came to a school which has k pupils. Santa decided to treat them with tangerines.However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice.Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa.Let bi be the number of slices the i-th pupil has in the end. Let Santa's joy be the minimum among all bi's.Your task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts). | Input: ['3 25 9 3'] Output:['5'] | [
2,
4
] |
Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative β that means that Santa doesn't find this string beautiful at all.Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n.Recall that a palindrome is a string that doesn't change after one reverses it.Since the empty string is a palindrome too, the answer can't be negative. Even if all ai's are negative, Santa can obtain the empty string. | Input: ['7 3abb 2aaa -3bba -1zyz -4abb 5aaa 7xyx 4'] Output:['12'] | [
2
] |
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1,βp2,β...,βpm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence. | Input: ['4RURD'] Output:['2'] | [
3
] |
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numbered from 1 to m starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).The organizers numbered all the working places from 1 to 2nm. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. The picture illustrates the first and the second samples. Santa Clause knows that his place has number k. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right! | Input: ['4 3 9'] Output:['2 2 L'] | [
3
] |
Igor likes hexadecimal notation and considers positive integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than t times. For example, if tβ=β3, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not interesting.Your task is to find the k-th smallest interesting for Igor integer in the hexadecimal notation. The integer should not contain leading zeros. | Input: ['17 1'] Output:['12'] | [
0,
3
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.