question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from x = 0 to x = a and back. Moving from the point x = 0 to x = a or from the point x = a to x = 0 is called a bus journey. In total, the bus must make k journeys.The petrol tank of the bus can hold b liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.There is a gas station in point x = f. This point is between points x = 0 and x = a. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain b liters of gasoline.What is the minimum number of times the bus needs to refuel at the point x = f to make k journeys? The first journey starts in the point x = 0.
Input: ['6 9 2 4'] Output:['4']
[ 2, 3 ]
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.Let A be a set of positions in the string. Let's call it pretty if following conditions are met: letters on positions from A in the string are all distinct and lowercase; there are no uppercase letters in the string which are situated between positions from A (i.e. there is no such j that s[j] is an uppercase letter, and a1 < j < a2 for some a1 and a2 from A). Write a program that will determine the maximum number of elements in a pretty set of positions.
Input: ['11aaaaBaabAbA'] Output:['2']
[ 0 ]
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking β€” if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.Help the party to determine minimum possible total instability!
Input: ['21 2 3 4'] Output:['1']
[ 0, 2 ]
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left.For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.You are given some integer number x. Check if it's a quasi-palindromic number.
Input: ['131'] Output:['YES']
[ 0 ]
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≀ j ≀ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, . Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer xi to all elements in a in range [li;ri] i.e. they should add xi to ali, ali + 1, ... , ari and then they should calculate the minimum value of f(j) for all valid j.Please help Mahmoud and Ehab.
Input: ['5 6 31 2 3 4 51 2 3 4 5 61 1 101 1 -91 5 -1'] Output:['0900']
[ 4 ]
Mahmoud and Ehab are in the fourth stage now.Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length n, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.Help Mahmoud and Ehab find these two positions.You will get Wrong Answer verdict if Your queries doesn't satisfy interaction protocol described below. You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query. Your final answer is not correct. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .
Input: ['3213210'] Output:['? 000? 001? 010? 011? 100? 101! 2 1']
[ 4 ]
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?
Input: ['5 30 4 5 6 7'] Output:['2']
[ 2 ]
n evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number k. Then you may repeatedly select a set of 2 or more points which are evenly spaced, and either increase all numbers at points in the set by k or decrease all numbers at points in the set by k. You would like to eventually end up with all numbers equal to 0. Is it possible?A set of 2 points is considered evenly spaced if they are diametrically opposed, and a set of 3 or more points is considered evenly spaced if they form a regular polygon.
Input: ['30000100000100000110000000001100'] Output:['YES']
[ 3 ]
It's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top C contestants are going to be awarded T-shirts, but we obviously don't know which contestants that will be. The plan is to get the T-Shirt sizes of all contestants before the actual competition, and then order enough T-shirts so that no matter who is in the top C we'll have T-shirts available in order to award them.In order to get the T-shirt sizes of the contestants, we will send out a survey. The survey will allow contestants to either specify a single desired T-shirt size, or two adjacent T-shirt sizes. If a contestant specifies two sizes, it means that they can be awarded either size.As you can probably tell, this plan could require ordering a lot of unnecessary T-shirts. We'd like your help to determine the minimum number of T-shirts we'll need to order to ensure that we'll be able to award T-shirts no matter the outcome of the competition.
Input: ['2 200100 250 100'] Output:['200']
[ 2 ]
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
Input: ['4'] Output:['8']
[ 0, 3 ]
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.After the qualifying round completes, you know K of the onsite finalists, as well as their qualifying ranks (which start at 1, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.
Input: ['252 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28'] Output:['3']
[ 2 ]
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests.Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples; all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests.
Input: ['501 02 12extra 03 199 0'] Output:['4move 3 1move 01 5move 2extra 4move 99 3']
[ 2 ]
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example: the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.
Input: ['hellno'] Output:['hell no ']
[ 2 ]
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.Given this information, is it possible to restore the exact floor for flat n?
Input: ['10 36 22 17 3'] Output:['4']
[ 0 ]
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.For example, 4-rounding of 375 is 375Β·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.Write a program that will perform the k-rounding of n.
Input: ['375 4'] Output:['30000']
[ 0, 3 ]
Vasya and Petya are playing an online game. As most online games, it has hero progress system that allows players to gain experience that make their heroes stronger. Of course, Vasya would like to get as many experience points as possible. After careful study of experience points allocation, he found out that if he plays the game alone, he gets one experience point each second. However, if two players are playing together, and their current experience values differ by at most C points, they can boost their progress, and each of them gets 2 experience points each second.Since Vasya and Petya are middle school students, their parents don't allow them to play all the day around. Each of the friends has his own schedule: Vasya can only play during intervals [a1;b1], [a2;b2], ..., [an;bn], and Petya can only play during intervals [c1;d1], [c2;d2], ..., [cm;dm]. All time periods are given in seconds from the current moment. Vasya is good in math, so he has noticed that sometimes it can be profitable not to play alone, because experience difference could become too big, and progress would not be boosted even when played together.Now they would like to create such schedule of playing that Vasya's final experience was greatest possible. The current players experience is the same. Petya is not so concerned about his experience, so he is ready to cooperate and play when needed to maximize Vasya's experience.
Input: ['2 1 51 710 2010 20'] Output:['25']
[ 2 ]
It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number ai written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 × 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
Input: ['421 131 31 12312345 67 8491 2 3 4 5 6 7 8 9'] Output:['22231680']
[ 3 ]
Masha and Grisha like studying sets of positive integers.One day Grisha has written a set A containing n different integers ai on a blackboard. Now he asks Masha to create a set B containing n different integers bj such that all n2 integers that can be obtained by summing up ai and bj for all possible pairs of i and j are different.Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 106, and all numbers in B must also be in the same range.Help Masha to create the set B that satisfies Grisha's requirement.
Input: ['331 10 1001122 4'] Output:['YES1 2 3 YES1 YES1 2 ']
[ 0 ]
Nagini, being a horcrux You-know-who created with the murder of Bertha Jorkins, has accumulated its army of snakes and is launching an attack on Hogwarts school. Hogwarts' entrance can be imagined as a straight line (x-axis) from 1 to 105. Nagini is launching various snakes at the Hogwarts entrance. Each snake lands parallel to the entrance, covering a segment at a distance k from x = l to x = r. Formally, each snake can be imagined as being a line segment between points (l, k) and (r, k). Note that k can be both positive and negative, but not 0.Let, at some x-coordinate x = i, there be snakes at point (i, y1) and point (i, y2), such that y1 > 0 and y2 < 0. Then, if for any point (i, y3) containing a snake such that y3 > 0, y1 ≀ y3 holds and for any point (i, y4) containing a snake such that y4 < 0, |y2| ≀ |y4| holds, then the danger value at coordinate x = i is y1 + |y2|. If no such y1 and y2 exist, danger value is 0. Harry wants to calculate the danger value of various segments of the Hogwarts entrance. Danger value for a segment [l, r) of the entrance can be calculated by taking the sum of danger values for each integer x-coordinate present in the segment.Formally, you have to implement two types of queries: 1 l r k: a snake is added parallel to entrance from x = l to x = r at y-coordinate y = k (l inclusive, r exclusive). 2 l r: you have to calculate the danger value of segment l to r (l inclusive, r exclusive).
Input: ['31 1 10 101 2 4 -72 1 10'] Output:['34']
[ 4 ]
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 ≀ i ≀ j ≀ k ≀ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input: ['5 1 2 31 2 3 4 5'] Output:['30']
[ 0 ]
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes).
Input: ['6tomluciusginnyharryginnyharry'] Output:['NONONONOYESYES']
[ 0 ]
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly k already inhabited apartments, but he doesn't know their indices yet.Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.
Input: ['6 3'] Output:['1 3']
[ 3 ]
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ( + ) instead of division button (Γ·) and got sum of numerator and denominator that was equal to n instead of the expected decimal notation. Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction such that sum of its numerator and denominator equals n. Help Petya deal with this problem.
Input: ['3'] Output:['1 2']
[ 0, 3 ]
Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.Michael's day starts from charging his electric car for getting to the work and back. He spends 1000 burles on charge if he goes to the first job, and 2000 burles if he goes to the second job.On a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of x burles, he is allowed to pay an amount of y (0 ≀ y ≀ x) burles that does not exceed the bonus card balance with bonus burles. In this case he pays x - y burles with cash, and the balance on the bonus card is decreased by y bonus burles. If customer pays whole price with cash (i.e., y = 0) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by bonus burles. Initially the bonus card balance is equal to 0 bonus burles.Michael has planned next n days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.
Input: ['31000 2000 1000'] Output:['3700']
[ 2, 4 ]
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input: ['2 6 51 1 0 50003 2 0 55002 2 0 600015 0 2 90009 0 1 70008 0 2 6500'] Output:['24500']
[ 2 ]
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input: ['5 24 2 1 10 2'] Output:['203 6 7 4 5 ']
[ 2 ]
This story is happening in a town named BubbleLand. There are n houses in BubbleLand. In each of these n houses lives a boy or a girl. People there really love numbers and everyone has their favorite number f. That means that the boy or girl that lives in the i-th house has favorite number equal to fi.The houses are numerated with numbers 1 to n.The houses are connected with n - 1 bidirectional roads and you can travel from any house to any other house in the town. There is exactly one path between every pair of houses.A new dating had agency opened their offices in this mysterious town and the citizens were very excited. They immediately sent q questions to the agency and each question was of the following format: a b β€” asking how many ways are there to choose a couple (boy and girl) that have the same favorite number and live in one of the houses on the unique path from house a to house b. Help the dating agency to answer the questions and grow their business.
Input: ['71 0 0 1 0 1 09 2 9 2 2 9 92 61 24 26 53 67 421 37 5'] Output:['23']
[ 0 ]
Consider an array A with N elements, all being the same integer a.Define the product transformation as a simultaneous update Ai = AiΒ·Ai + 1, that is multiplying each element to the element right to it for , with the last number AN remaining the same. For example, if we start with an array A with a = 2 and N = 4, then after one product transformation A = [4,  4,  4,  2], and after two product transformations A = [16,  16,  8,  2].Your simple task is to calculate the array A after M product transformations. Since the numbers can get quite big you should output them modulo Q.
Input: ['2 2 2 7'] Output:['1 2 ']
[ 3 ]
The competitors of Bubble Cup X gathered after the competition and discussed what is the best way to get to know the host country and its cities.After exploring the map of Serbia for a while, the competitors came up with the following facts: the country has V cities which are indexed with numbers from 1 to V, and there are E bi-directional roads that connect the cites. Each road has a weight (the time needed to cross that road). There are N teams at the Bubble Cup and the competitors came up with the following plan: each of the N teams will start their journey in one of the V cities, and some of the teams share the starting position.They want to find the shortest time T, such that every team can move in these T minutes, and the number of different cities they end up in is at least K (because they will only get to know the cities they end up in). A team doesn't have to be on the move all the time, if they like it in a particular city, they can stay there and wait for the time to pass.Please help the competitors to determine the shortest time T so it's possible for them to end up in at least K different cities or print -1 if that is impossible no matter how they move.Note that there can exist multiple roads between some cities.
Input: ['6 7 5 45 5 2 2 51 3 31 5 21 6 52 5 42 6 73 4 113 5 3'] Output:['3']
[ 4 ]
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n,  A2n =  A0, with sides of the exactly 1 meter in length. Court rules for removing part of his property are as follows: Split every edge Ak Ak + 1,  k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1 On every edge A2k A2k + 1,  k = 0... n - 1 court will choose one point B2k =  Pi for some i = 0, ...,  n - 1 such that On every edge A2k + 1A2k + 2,  k = 0...n - 1 Bill will choose one point B2k + 1 =  Pi for some i = 0, ...,  n - 1 such that Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1 Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
Input: ['30 1 2'] Output:['0 2 1']
[ 2 ]
John gave Jack a very hard problem. He wrote a very big positive integer A0 on a piece of paper. The number is less than 10200000 . In each step, Jack is allowed to put ' + ' signs in between some of the digits (maybe none) of the current number and calculate the sum of the expression. He can perform the same procedure on that sum and so on. The resulting sums can be labeled respectively by A1, A2 etc. His task is to get to a single digit number.The problem is that there is not much blank space on the paper. There are only three lines of space, so he can't perform more than three steps. Since he wants to fill up the paper completely, he will perform exactly three steps.Jack must not add leading zeros to intermediate results, but he can put ' + ' signs in front of digit 0. For example, if the current number is 1000100, 10 + 001 + 00 is a valid step, resulting in number 11.
Input: ['11'] Output:['111']
[ 0, 3 ]
Arpa is taking a geometry exam. Here is the last problem of the exam.You are given three points a, b, c.Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.
Input: ['0 1 1 1 1 0'] Output:['Yes']
[ 3 ]
Arpa is researching the Mexican wave.There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. At time 1, the first spectator stands. At time 2, the second spectator stands. ... At time k, the k-th spectator stands. At time k + 1, the (k + 1)-th spectator stands and the first spectator sits. At time k + 2, the (k + 2)-th spectator stands and the second spectator sits. ... At time n, the n-th spectator stands and the (n - k)-th spectator sits. At time n + 1, the (n + 1 - k)-th spectator sits. ... At time n + k, the n-th spectator sits. Arpa wants to know how many spectators are standing at time t.
Input: ['10 5 3'] Output:['3']
[ 3 ]
You have a bag of balls of n different colors. You have ai balls of the i-th color.While there are at least two different colored balls in the bag, perform the following steps: Take out two random balls without replacement one by one. These balls might be the same color. Color the second ball to the color of the first ball. You are not allowed to switch the order of the balls in this step. Place both balls back in the bag. All these actions take exactly one second. Let M = 109 + 7. It can be proven that the expected amount of time needed before you stop can be represented as a rational number , where P and Q are coprime integers and where Q is not divisible by M. Return the value .
Input: ['21 1'] Output:['1']
[ 3 ]
The presidential election is coming in Bearland next year! Everybody is so excited about this!So far, there are three candidates, Alice, Bob, and Charlie. There are n citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, each of n citizens will choose one of six orders of preference between Alice, Bob and Charlie uniformly at random, independently from other voters.The government of Bearland has devised a function to help determine the outcome of the election given the voters preferences. More specifically, the function is (takes n boolean numbers and returns a boolean number). The function also obeys the following property: f(1 - x1, 1 - x2, ..., 1 - xn) = 1 - f(x1, x2, ..., xn).Three rounds will be run between each pair of candidates: Alice and Bob, Bob and Charlie, Charlie and Alice. In each round, xi will be equal to 1, if i-th citizen prefers the first candidate to second in this round, and 0 otherwise. After this, y = f(x1, x2, ..., xn) will be calculated. If y = 1, the first candidate will be declared as winner in this round. If y = 0, the second will be the winner, respectively.Define the probability that there is a candidate who won two rounds as p. pΒ·6n is always an integer. Print the value of this integer modulo 109 + 7 = 1 000 000 007.
Input: ['301010101'] Output:['216']
[ 0, 3 ]
Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex. Yesterday Ivan learned Landau's criterion: there is tournament with scores d1 ≀ d2 ≀ ... ≀ dn if and only if for all 1 ≀ k < n and .Now, Ivan wanna solve following problem: given a set of numbers S = {a1, a2, ..., am}, is there a tournament with given set of scores? I.e. is there tournament with sequence of scores d1, d2, ..., dn such that if we remove duplicates in scores, we obtain the required set {a1, a2, ..., am}? Find a tournament with minimum possible number of vertices.
Input: ['21 2'] Output:['40011100101000010']
[ 2, 3 ]
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors and is acute (i.e. strictly less than ). Otherwise, the point is called good.The angle between vectors and in 5-dimensional space is defined as , where is the scalar product and is length of .Given the list of points, print the indices of the good points in ascending order.
Input: ['60 0 0 0 01 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1'] Output:['11']
[ 0, 3 ]
Connect the countless points with lines, till we reach the faraway yonder.There are n points on a coordinate plane, the i-th of which being (i, yi).Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.
Input: ['57 5 8 6 9'] Output:['Yes']
[ 0 ]
The Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days.On the rim of the Floral Clock are 2n flowers, numbered from 1 to 2n clockwise, each of which has a colour among all n possible ones. For each colour, there are exactly two flowers with it, the distance between which either is less than or equal to 2, or equals n. Additionally, if flowers u and v are of the same colour, then flowers opposite to u and opposite to v should be of the same colour as well β€” symmetry is beautiful!Formally, the distance between two flowers is 1 plus the number of flowers on the minor arc (or semicircle) between them. Below is a possible arrangement with n = 6 that cover all possibilities. The beauty of an arrangement is defined to be the product of the lengths of flower segments separated by all opposite flowers of the same colour. In other words, in order to compute the beauty, we remove from the circle all flowers that have the same colour as flowers opposite to them. Then, the beauty is the product of lengths of all remaining segments. Note that we include segments of length 0 in this product. If there are no flowers that have the same colour as flower opposite to them, the beauty equals 0. For instance, the beauty of the above arrangement equals 1 × 3 × 1 × 3 = 9 β€” the segments are {2}, {4, 5, 6}, {8} and {10, 11, 12}.While keeping the constraints satisfied, there may be lots of different arrangements. Find out the sum of beauty over all possible arrangements, modulo 998 244 353. Two arrangements are considered different, if a pair (u, v) (1 ≀ u, v ≀ 2n) exists such that flowers u and v are of the same colour in one of them, but not in the other.
Input: ['3'] Output:['24']
[ 3 ]
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral.Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the first term equals to the average temperature on the first day, the second term equals to the average temperature on the second day and so on, then the average temperature of the next (n + 1)-th day will be equal to the next term of the arithmetic progression. Otherwise, according to Vasya's method, the temperature of the (n + 1)-th day will be equal to the temperature of the n-th day.Your task is to help Vasya predict the average temperature for tomorrow, i. e. for the (n + 1)-th day.
Input: ['510 5 0 -5 -10'] Output:['-15']
[ 3 ]
In the evening Polycarp decided to analyze his today's travel expenses on public transport.The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.For example, if Polycarp made three consecutive trips: "BerBank" "University", "University" "BerMall", "University" "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards?
Input: ['3 5 3 1 8BerBank UniversityUniversity BerMallUniversity BerBank'] Output:['11']
[ 2 ]
Soon the first year students will be initiated into students at the University of Berland. The organizers of the initiation come up with a program for this holiday. In their opinion, it would be good if the first-year students presented small souvenirs to each other. When they voiced this idea to the first-year students, they found out the following: some pairs of the new students already know each other; each new student agrees to give souvenirs only to those with whom they are already familiar; each new student does not want to present too many souvenirs. The organizers have written down all the pairs of first-year friends who are familiar with each other and now want to determine for each new student, whom they should give souvenirs to. In their opinion, in each pair of familiar students exactly one student must present a souvenir to another student.First year students already decided to call the unluckiest the one who will have to present the greatest number of souvenirs. The organizers in return promised that the unluckiest will be unlucky to the minimum possible degree: of course, they will have to present the greatest number of souvenirs compared to the other students, but this number will be as small as possible.Organizers are very busy, and they asked you to determine for each pair of first-year friends who and to whom should present a souvenir.
Input: ['5 42 11 32 32 5'] Output:['11 22 33 15 2']
[ 4 ]
The Berland's capital has the form of a rectangle with sizes n × m quarters. All quarters are divided into three types: regular (labeled with the character '.') β€” such quarters do not produce the noise but are not obstacles to the propagation of the noise; sources of noise (labeled with an uppercase Latin letter from 'A' to 'Z') β€” such quarters are noise sources and are not obstacles to the propagation of the noise; heavily built-up (labeled with the character '*') β€” such quarters are soundproofed, the noise does not penetrate into them and they themselves are obstacles to the propagation of noise. A quarter labeled with letter 'A' produces q units of noise. A quarter labeled with letter 'B' produces 2Β·q units of noise. And so on, up to a quarter labeled with letter 'Z', which produces 26Β·q units of noise. There can be any number of quarters labeled with each letter in the city.When propagating from the source of the noise, the noise level is halved when moving from one quarter to a quarter that shares a side with it (when an odd number is to be halved, it's rounded down). The noise spreads along the chain. For example, if some quarter is located at a distance 2 from the noise source, then the value of noise which will reach the quarter is divided by 4. So the noise level that comes from the source to the quarter is determined solely by the length of the shortest path between them. Heavily built-up quarters are obstacles, the noise does not penetrate into them. The values in the cells of the table on the right show the total noise level in the respective quarters for q = 100, the first term in each sum is the noise from the quarter 'A', the second β€” the noise from the quarter 'B'. The noise level in quarter is defined as the sum of the noise from all sources. To assess the quality of life of the population of the capital of Berland, it is required to find the number of quarters whose noise level exceeds the allowed level p.
Input: ['3 3 100 140...A*..B.'] Output:['3']
[ 3 ]
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send ai requests.Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n.
Input: ['51 4 3 2 5'] Output:['6']
[ 2 ]
The elections to Berland parliament are happening today. Voting is in full swing!Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 ≀ k ≀ n) top candidates will take seats in the parliament.After the end of the voting the number of votes for each candidate is calculated. In the resulting table the candidates are ordered by the number of votes. In case of tie (equal number of votes) they are ordered by the time of the last vote given. The candidate with ealier last vote stands higher in the resulting table.So in the resulting table candidates are sorted by the number of votes (more votes stand for the higher place) and if two candidates have equal number of votes they are sorted by the time of last vote (earlier last vote stands for the higher place).There is no way for a candidate with zero votes to take a seat in the parliament. So it is possible that less than k candidates will take a seat in the parliament.In Berland there are m citizens who can vote. Each of them will vote for some candidate. Each citizen will give a vote to exactly one of n candidates. There is no option "against everyone" on the elections. It is not accepted to spoil bulletins or not to go to elections. So each of m citizens will vote for exactly one of n candidates.At the moment a citizens have voted already (1 ≀ a ≀ m). This is an open election, so for each citizen it is known the candidate for which the citizen has voted. Formally, the j-th citizen voted for the candidate gj. The citizens who already voted are numbered in chronological order; i.e. the (j + 1)-th citizen voted after the j-th.The remaining m - a citizens will vote before the end of elections, each of them will vote for one of n candidates.Your task is to determine for each of n candidates one of the three possible outcomes: a candidate will be elected to the parliament regardless of votes of the remaining m - a citizens; a candidate has chance to be elected to the parliament after all n citizens have voted; a candidate has no chances to be elected to the parliament regardless of votes of the remaining m - a citizens.
Input: ['3 1 5 41 2 1 3'] Output:['1 3 3 ']
[ 2 ]
A game field is a strip of 1 × n square cells. In some cells there are Packmen, in some cells β€” asterisks, other cells are empty.Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.In the initial moment of time all Packmen begin to move. Each Packman can change direction of its move unlimited number of times, but it is not allowed to go beyond the boundaries of the game field. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.Your task is to determine minimum possible time after which Packmen can eat all the asterisks.
Input: ['7*..P*P*'] Output:['3']
[ 4 ]
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!On the show a dog needs to eat as many bowls of dog food as possible (bottomless stomach helps here). Dogs compete separately of each other and the rules are as follows:At the start of the show the dog and the bowls are located on a line. The dog starts at position x = 0 and n bowls are located at positions x = 1, x = 2, ..., x = n. The bowls are numbered from 1 to n from left to right. After the show starts the dog immediately begins to run to the right to the first bowl.The food inside bowls is not ready for eating at the start because it is too hot (dog's self-preservation instinct prevents eating). More formally, the dog can eat from the i-th bowl after ti seconds from the start of the show or later.It takes dog 1 second to move from the position x to the position x + 1. The dog is not allowed to move to the left, the dog runs only to the right with the constant speed 1 distance unit per second. When the dog reaches a bowl (say, the bowl i), the following cases are possible: the food had cooled down (i.e. it passed at least ti seconds from the show start): the dog immediately eats the food and runs to the right without any stop, the food is hot (i.e. it passed less than ti seconds from the show start): the dog has two options: to wait for the i-th bowl, eat the food and continue to run at the moment ti or to skip the i-th bowl and continue to run to the right without any stop. After T seconds from the start the show ends. If the dog reaches a bowl of food at moment T the dog can not eat it. The show stops before T seconds if the dog had run to the right of the last bowl.You need to help your dog create a strategy with which the maximum possible number of bowls of food will be eaten in T seconds.
Input: ['3 51 5 3'] Output:['2']
[ 2 ]
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.Ivan represent his array with increasing sequences with help of the following algorithm.While there is at least one unused number in array Ivan repeats the following procedure: iterate through array from the left to the right; Ivan only looks at unused numbers on current iteration; if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down. For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one β€” [2, 4].Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.
Input: ['51 3 2 5 4'] Output:['1 3 5 2 4 ']
[ 4 ]
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).
Input: ['21 2'] Output:['1.500000']
[ 3 ]
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 ≀ i ≀ n) there exist two numbers xi and ki that denote a possible transformation: ki kilograms of material xi can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material xi. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.For each i (1 ≀ i ≀ n) Igor knows that the experiment requires ai kilograms of material i, and the laboratory contains bi kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?
Input: ['31 2 33 2 11 11 1'] Output:['YES']
[ 2 ]
Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).
Input: ['2 3 2 52 1 82 2 81 2 11 3 42 3 2'] Output:['8']
[ 4 ]
You are given an array of n integer numbers. Let sum(l, r) be the sum of all numbers on positions from l to r non-inclusive (l-th element is counted, r-th element is not counted). For indices l and r holds 0 ≀ l ≀ r ≀ n. Indices in array are numbered from 0. For example, if a = [ - 5, 3, 9, 4], then sum(0, 1) =  - 5, sum(0, 2) =  - 2, sum(1, 4) = 16 and sum(i, i) = 0 for each i from 0 to 4.Choose the indices of three delimiters delim0, delim1, delim2 (0 ≀ delim0 ≀ delim1 ≀ delim2 ≀ n) and divide the array in such a way that the value of res = sum(0, delim0) - sum(delim0, delim1) + sum(delim1, delim2) - sum(delim2, n) is maximal. Note that some of the expressions sum(l, r) can correspond to empty segments (if l = r for some segment).
Input: ['3-1 2 3'] Output:['0 1 3']
[ 0 ]
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him tj minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all k of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is k + 1.Polycarp has M minutes of time. What is the maximum number of points he can earn?
Input: ['3 4 111 2 3 4'] Output:['6']
[ 0, 2 ]
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.More formally, you are given an array s1, s2, ..., sn of zeros and ones. Zero corresponds to an unsuccessful game, one β€” to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.
Input: ['41 1 0 1'] Output:['3']
[ 0 ]
You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex 1 and vertex n.Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.
Input: ['3 31 2 31 3 23 2 0'] Output:['2']
[ 3 ]
The capital of Berland looks like a rectangle of size n × m of the square blocks of same size.Fire!It is known that k + 1 blocks got caught on fire (k + 1 ≀ nΒ·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct.The fire goes the following way: during the zero minute of fire only these k + 1 centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner.Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of k blocks (centers of ignition) are known and (k + 1)-th can be positioned in any other block.Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.
Input: ['7 7 31 22 15 5'] Output:['3']
[ 4 ]
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. speed limit: this sign comes with a positive integer number β€” maximal speed of the car after the sign (cancel the action of the previous sign of this type); overtake is allowed: this sign means that after some car meets it, it can overtake any other car; no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.In the beginning of the ride overtake is allowed and there is no speed limit.You are given the sequence of events in chronological order β€” events which happened to Polycarp during the ride. There are events of following types: Polycarp changes the speed of his car to specified (this event comes with a positive integer number); Polycarp's car overtakes the other car; Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); Polycarp's car goes past the "overtake is allowed" sign; Polycarp's car goes past the "no speed limit"; Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
Input: ['111 1003 70423 12053 12061 15043 300'] Output:['2']
[ 2 ]
Polycarp is a great fan of television.He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.Polycarp wants to check out all n shows. Are two TVs enough to do so?
Input: ['31 22 34 5'] Output:['YES']
[ 2 ]
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.
Input: ['000000'] Output:['0']
[ 0, 2 ]
You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: All cells in a set have the same color. Every two cells in a set share row or column.
Input: ['1 10'] Output:['1']
[ 3 ]
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
Input: ['yandex6'] Output:['0']
[ 2 ]
You are given a tree with n vertices and you are allowed to perform no more than 2n transformations on it. Transformation is defined by three vertices x, y, y' and consists of deleting edge (x, y) and adding edge (x, y'). Transformation x, y, y' could be performed if all the following conditions are satisfied: There is an edge (x, y) in the current tree. After the transformation the graph remains a tree. After the deletion of edge (x, y) the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex x by Vx, and the set of nodes in the component containing vertex y by Vy. Then condition |Vx| > |Vy| should be satisfied, i.e. the size of the component with x should be strictly larger than the size of the component with y. You should minimize the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than 2n transformations and output any sequence of transformations leading initial tree to such state.Note that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.
Input: ['33 21 3'] Output:['0']
[ 3 ]
This is an interactive problem.You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the integer value in this element, and nexti that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if nexti ≠  - 1, then valuenexti > valuei.You are given the number of elements in the list n, the index of the first element start, and the integer x.You can make up to 2000 queries of the following two types: ? i (1 ≀ i ≀ n) β€” ask the values valuei and nexti, ! ans β€” give the answer for the problem: the minimum integer, greater than or equal to x, or ! -1, if there are no such integers. Your program should terminate after this query. Write a program that solves this problem.
Input: ['5 3 8097 -158 516 281 179 4'] Output:['? 1? 2? 3? 4? 5! 81']
[ 0 ]
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
Input: ['63 2 1 6 5 4'] Output:['42 1 31 22 4 61 5']
[ 3 ]
Nikita plays a new computer game. There are m levels in this game. In the beginning of each level a new class appears in the game; this class is a child-class of the class yi (and yi is called parent-class for this new class). Thus, the classes form a tree. Initially there is only one class with index 1.Changing the class to its neighbour (child-class or parent-class) in the tree costs 1 coin. You can not change the class back. The cost of changing the class a to the class b is equal to the total cost of class changes on the path from a to b in the class tree.Suppose that at i -th level the maximum cost of changing one class to another is x. For each level output the number of classes such that for each of these classes there exists some other class y, and the distance from this class to y is exactly x.
Input: ['41121'] Output:['2223']
[ 4 ]
Today at the lesson Vitya learned a very interesting function β€” mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.Vitya quickly understood all tasks of the teacher, but can you do the same?You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps: Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x. Find mex of the resulting array. Note that after each query the array changes.
Input: ['2 21 313'] Output:['10']
[ 4 ]
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai.Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.For each vertex the answer must be considered independently.The beauty of the root equals to number written on it.
Input: ['26 21 2'] Output:['6 6 ']
[ 3 ]
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers β€” amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.For each two integer numbers a and b such that l ≀ a ≀ r and x ≀ b ≀ y there is a potion with experience a and cost b in the store (that is, there are (r - l + 1)Β·(y - x + 1) potions).Kirill wants to buy a potion which has efficiency k. Will he be able to do this?
Input: ['1 10 1 10 1'] Output:['YES']
[ 0 ]
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?
Input: ['41 3 2 3'] Output:['First']
[ 3 ]
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si β€” lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset β€” print Β«YESΒ», if he can, and Β«NOΒ», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input: ['4 2aabb'] Output:['YES']
[ 0 ]
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β€” mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≀ i, j ≀ m the condition Ai β‰₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum is maximally possible, where A' is already rearranged array.
Input: ['57 3 5 3 42 1 3 2 3'] Output:['4 7 3 5 3']
[ 2, 3 ]
There are n castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself. Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has k liters of a strange liquid. He wants to distribute that liquid among the castles, so each castle may contain some liquid (possibly zero or non-integer number of liters). After that the stability of a wall is defined as follows: if the wall connects two castles a and b, and they contain x and y liters of that liquid, respectively, then the strength of that wall is xΒ·y.Your task is to print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.
Input: ['3 10 1 01 0 00 0 0'] Output:['0.250000000000']
[ 0, 3 ]
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan if i1 < i2 < i3 < ... < ik and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan kΒ·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans.Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7).Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.
Input: ['33 3 1'] Output:['12']
[ 3 ]
Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1, 2}, {3, 4}, {4, 5}, {5, 6} or {7, 8}. A row in the airplane Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.
Input: ['2 25 8'] Output:['YES']
[ 0, 2 ]
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.This airplane has an entrance at the very front and very back of the plane.Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input: ['3 3'] Output:['128']
[ 3 ]
You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.
Input: ['3 5001001011011001'] Output:['5']
[ 0 ]
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≀ i ≀ m).You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i β‰₯ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input: ['2 21 1'] Output:['1']
[ 0, 3, 4 ]
Vasya is studying number theory. He has denoted a function f(a, b) such that: f(a, 0) = 0; f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b. Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.
Input: ['3 5'] Output:['3']
[ 3, 4 ]
Let's call the roundness of the number the number of zeros to which it ends.You have an array of n numbers. You need to choose a subset of exactly k numbers so that the roundness of the product of the selected numbers will be maximum possible.
Input: ['3 250 4 20'] Output:['3']
[ 3 ]
One very important person has a piece of paper in the form of a rectangle a × b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?
Input: ['2 2 21 22 1'] Output:['4']
[ 0 ]
The flag of Berland is such rectangular field n × m that satisfies following conditions: Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color. Each color should be used in exactly one stripe. You are given a field n × m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input: ['6 5RRRRRRRRRRBBBBBBBBBBGGGGGGGGGG'] Output:['YES']
[ 0 ]
Pay attention: this problem is interactive.Penguin Xoriy came up with a new game recently. He has n icicles numbered from 1 to n. Each icicle has a temperature β€” an integer from 1 to 109. Exactly two of these icicles are special: their temperature is y, while a temperature of all the others is x ≠ y. You have to find those special icicles. You can choose a non-empty subset of icicles and ask the penguin what is the bitwise exclusive OR (XOR) of the temperatures of the icicles in this subset. Note that you can't ask more than 19 questions.You are to find the special icicles.
Input: ['4 2 1211'] Output:['? 3 1 2 3? 1 1? 1 3! 1 3']
[ 4 ]
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k > 1) if and only if: Its left half equals to its right half. Its left and right halfs are non-empty (k - 1)-palindromes. The left half of string t is its prefix of length ⌊|t| / 2βŒ‹, and right half β€” the suffix of the same length. ⌊|t| / 2βŒ‹ denotes the length of string t divided by 2, rounded down.Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.
Input: ['abba'] Output:['6 1 0 0 ']
[ 0 ]
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.
Input: ['311'] Output:['1']
[ 2 ]
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 milliseconds.If connection ping (delay) is t milliseconds, the competition passes for a participant as follows: Exactly after t milliseconds after the start of the competition the participant receives the text to be entered. Right after that he starts to type it. Exactly t milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.Given the length of the text and the information about participants, determine the result of the game.
Input: ['5 1 2 1 2'] Output:['First']
[ 3 ]
Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail.For example, if Krakozyabra is to have the number 57040 for dinner, its inedible tail would be the number 457.Slastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from L to R, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner.
Input: ['1 10'] Output:['9']
[ 0, 2, 3 ]
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Input: ['4 11 2 2 1'] Output:['2']
[ 4 ]
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input: ['62 475 458 816 16247 9941000000000 1000000'] Output:['YesYesYesNoNoYes']
[ 3 ]
n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed.You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed.The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray.You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106.
Input: ['2 999400000 1 2500000 1 1'] Output:['500000.000000000000000000000000000000']
[ 3, 4 ]
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
Input: ['1 1'] Output:['YES']
[ 3 ]
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≀ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
Input: ['4 1-5 5 0 2010'] Output:['3']
[ 0 ]
Developer Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way.Each element has one controller that can be set to any non-negative real value. If a controller is set on some value x, then the controller consumes x2 energy units per second. At the same time, any two elements connected by a wire produce yΒ·z energy units per second, where y and z are the values set on their controllers.Petr has only a limited number of wires, so he has already built some scheme of elements and wires, and is now interested if it's possible to set the controllers in such a way that the system produces at least as much power as it consumes, and at least one controller is set on the value different from 0. Help him check this, and if it's possible, find the required integer values that should be set.It is guaranteed that if there exist controllers' settings satisfying the above conditions, then there exist required integer values not greater than 106.
Input: ['4\xa04 41 22 33 44 2\xa03 22 33 1\xa04 61 23 44 21 41 33 2\xa010 92 13 25 26 22 72 82 92 104 2'] Output:['YES1 2 2 1NOYES1 1 1 1YES1 5 1 1 1 1 1 1 1 1']
[ 3 ]
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?
Input: ['3 41 3 5'] Output:['3']
[ 0, 3 ]
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.
Input: ['2 4 5020 10060 10 40 80'] Output:['50']
[ 0, 2, 4 ]
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length n and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to?A period of a string is such an integer d from 1 to the length of the string that if we put the string shifted by d positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of "VKKVK".
Input: ['3\xa05V??VK\xa06??????\xa04?VK?'] Output:['23 561 2 3 4 5 632 3 4']
[ 3 ]
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input: ['3 2'] Output:['21 22 3']
[ 2 ]
Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.
Input: ['3a 4 1 3 5 7ab 2 1 5ca 1 4'] Output:['abacaba']
[ 2 ]
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.You should assign labels to all vertices in such a way that: Labels form a valid permutation of length n β€” an integer sequence such that each integer from 1 to n appears exactly once in it. If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu. Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions.
Input: ['3 31 21 33 2'] Output:['1 3 2 ']
[ 2 ]
You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters. Suitability of string s is calculated by following metric:Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings s, you choose the one with the largest number of non-intersecting occurrences of string t. Suitability is this number of occurrences.You should replace all '?' characters with small Latin letters in such a way that the suitability of string s is maximal.
Input: ['?aa?ab'] Output:['baab']
[ 2, 4 ]
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β€” a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty (no matter on what online judge was it).Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.
Input: ['3 32 1 9'] Output:['1']
[ 2 ]