question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit. | Input: ['5 6.....#S....#.#.....#.......E..333300012'] Output:['1'] | [
0
] |
Your friend has n cards.You know that each card has a lowercase English letter on one side and a digit on the other.Currently, your friend has laid out the cards on a table so only one side of each card is visible.You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. | Input: ['ee'] Output:['2'] | [
0
] |
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if aββ€βb, he or she likes it if and only if he can climb into this car and 2aββ₯βb.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars. | Input: ['50 30 10 10'] Output:['503010'] | [
0
] |
Priests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from kβ-β1 rocks, possesses power p and we want to add the rock charged with power wk then value of power of a new tower will be {wk}p. Rocks are added from the last to the first. That is for sequence w1,β...,βwm value of power will beAfter tower is built, its power may be extremely large. But still priests want to get some information about it, namely they want to know a number called cumulative power which is the true value of power taken modulo m. Priests have n rocks numbered from 1 to n. They ask you to calculate which value of cumulative power will the tower possess if they will build it from rocks numbered l,βlβ+β1,β...,βr. | Input: ['6 10000000001 2 2 3 3 381 11 62 22 32 44 44 54 6'] Output:['1124256327597484987'] | [
3
] |
Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it. | Input: ['5 61 21 32 32 53 44 5'] Output:['22 3 '] | [
0
] |
Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.Let's enumerate students from 1 to nΒ·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (iβ-β1)Β·mβ+βj. You have to find a matrix with n rows and m columns in which all numbers from 1 to nΒ·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix. | Input: ['2 4'] Output:['YES5 4 7 2 3 6 1 8 '] | [
0,
3
] |
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1,βs2,β...,βsk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).You are given k strings s1,βs2,β...,βsk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, kΒ·nββ€β5000). | Input: ['3 4abaccaabacba'] Output:['acab'] | [
0
] |
Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai,βaj) over all pairs (i,βj) such that 1ββ€βiββ€βjββ€βn. | Input: ['51 2 3 1 3'] Output:['4'] | [
3
] |
Mishka has got n empty boxes. For every i (1ββ€βiββ€βn), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met: i-th box is not put into another box; j-th box doesn't contain any other boxes; box i is smaller than box j (aiβ<βaj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes! | Input: ['31 2 3'] Output:['1'] | [
2
] |
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1β>βa2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win. | Input: ['10 6 10017 5'] Output:['4STRIKEHEALSTRIKESTRIKE'] | [
2
] |
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one β 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount of chicken.Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a small portions and b large ones contain exactly x chunks.Help Ivan to answer this question for several values of x! | Input: ['265'] Output:['YESNO'] | [
2
] |
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cvβ=β0.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cuβ=βx.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory). | Input: ['61 2 2 1 52 1 1 1 1 1'] Output:['3'] | [
2
] |
Pig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x;βy], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car. | Input: ['3 50 22 43 5'] Output:['YES'] | [
2
] |
Senor Vorpal Kickass'o invented an innovative method to encrypt integer sequences of length n. To encrypt a sequence, one has to choose a secret sequence , that acts as a key.Vorpal is very selective, so the key should be such a sequence bi, that its cyclic shifts are linearly independent, that is, there is no non-zero set of coefficients x0,βx1,β...,βxnβ-β1, such that for all k at the same time.After that for a sequence you should build the following cipher:In other words, you are to compute the quadratic deviation between each cyclic shift of bi and the sequence ai. The resulting sequence is the Kickass's cipher. The cipher is in development right now and Vorpal wants to decipher a sequence after it has been encrypted. You are to solve this problem for him. You are given sequences ci and bi. You are to find all suitable sequences ai. | Input: ['110'] Output:['11'] | [
3
] |
You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n. You have to answer q queries. Each query is described by a segment of vertices [l;βr], and you have to count the number of its subsegments [x;βy] (lββ€βxββ€βyββ€βr), such that if we delete all vertices except the segment of vertices [x;βy] (including x and y) and edges between them, the resulting graph is bipartite. | Input: ['6 61 22 33 14 55 66 431 34 61 6'] Output:['5514'] | [
4
] |
Suppose you have two polynomials and . Then polynomial can be uniquely represented in the following way:This can be done using long division. Here, denotes the degree of polynomial P(x). is called the remainder of division of polynomial by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair to pair . | Input: ['1'] Output:['10 101'] | [
3
] |
Count the number of distinct sequences a1,βa2,β...,βan (1ββ€βai) consisting of positive integers such that gcd(a1,βa2,β...,βan)β=βx and . As this number could be large, print the answer modulo 109β+β7.gcd here means the greatest common divisor. | Input: ['3 9'] Output:['3'] | [
3
] |
You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1,βa2,β...,βak the element ai is a record if for every integer j (1ββ€βjβ<βi) the following holds: ajβ<βai. | Input: ['11'] Output:['1'] | [
0,
3
] |
You have a fraction . You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point. | Input: ['1 2 0'] Output:['2'] | [
3
] |
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines.You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other. | Input: ['7'] Output:['3'] | [
3
] |
Petya has n integers: 1,β2,β3,β...,βn. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. | Input: ['4'] Output:['02 1 4 '] | [
3
] |
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. | Input: ['41 1 2 1'] Output:['1'] | [
2,
3
] |
A correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that: character'+' is placed on the left of character '=', characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle part β b and the right part β c), all the three parts a, b and c do not contain leading zeros, it is true that a+b=c. It is guaranteed that in given tests answer always exists. | Input: ['12345168'] Output:['123+45=168'] | [
0,
3
] |
Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly nβ/β2 piles contain number of candies that is a square of some integer and exactly nβ/β2 piles contain number of candies that is not a square of any integer. | Input: ['412 14 30 4'] Output:['2'] | [
2
] |
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai β number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on. | Input: ['3 3 23 5 1'] Output:['1'] | [
2
] |
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and xΒ·aβ+βyΒ·bβ=βn or tell that it's impossible. | Input: ['723'] Output:['YES2 1'] | [
0
] |
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.For example, if nβ=β4722 answer is 4720. If nβ=β5 Vasya can round it to 0 or to 10. Both ways are correct.For given n find out to which integer will Vasya round it. | Input: ['5'] Output:['0'] | [
3
] |
β Thanks a lot for today.β I experienced so many great things.β You gave me memories like dreams... But I have to leave now...β One last request, can you...β Help me solve a Codeforces problem?β ......β What?Chtholly has been thinking about a problem for days:If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help! | Input: ['2 100'] Output:['33'] | [
0
] |
Lakhesh loves to make movies, so Nephren helps her run a cinema. We may call it No. 68 Cinema.However, one day, the No. 68 Cinema runs out of changes (they don't have 50-yuan notes currently), but Nephren still wants to start their business. (Assume that yuan is a kind of currency in Regulu Ere.)There are three types of customers: some of them bring exactly a 50-yuan note; some of them bring a 100-yuan note and Nephren needs to give a 50-yuan note back to him/her; some of them bring VIP cards so that they don't need to pay for the ticket.Now n customers are waiting outside in queue. Nephren wants to know how many possible queues are there that they are able to run smoothly (i.e. every customer can receive his/her change), and that the number of 50-yuan notes they have after selling tickets to all these customers is between l and r, inclusive. Two queues are considered different if there exists a customer whose type is different in two queues. As the number can be large, please output the answer modulo p. | Input: ['4 97 2 3'] Output:['13'] | [
3
] |
This is an interactive problem. Refer to the Interaction section below for better understanding.Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number. | Input: ['2 4 4213'] Output:['122'] | [
2,
4
] |
What are you doing at the end of the world? Are you busy? Will you save us?Nephren is playing a game with little leprechauns.She gives them an infinite array of strings, f0... β.f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".She wants to let more people know about it, so she defines fiβ=β "What are you doing while sending "fiβ-β1"? Are you busy? Will you send "fiβ-β1"?" for all iββ₯β1.For example, f1 is"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1.It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces.Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes).Can you answer her queries? | Input: ['31 11 21 111111111111'] Output:['Wh.'] | [
4
] |
At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.2) String a is lexicographically smaller than c.3) String c is lexicographically smaller than b.For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1β=βy1,βx2β=βy2,β...,βxiβ-β1β=βyiβ-β1,βxiβ<βyi.Since the answer can be very large, you need to find answer modulo 109β+β7. | Input: ['abcddd'] Output:['5'] | [
3
] |
Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.Two ways are considered different if sets of indexes of elements chosen by these ways are different.Since the answer can be very large, you should find the answer modulo 109β+β7. | Input: ['41 1 1 1'] Output:['15'] | [
3
] |
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i,βj) such that aiββ€βaj and there are exactly k integers y such that aiββ€βyββ€βaj and y is divisible by x.In this problem it is meant that pair (i,βj) is equal to (j,βi) only if i is equal to j. For example pair (1,β2) is not the same as (2,β1). | Input: ['4 2 11 3 5 7'] Output:['3'] | [
3,
4
] |
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty. | Input: ['490 90 90 90'] Output:['0'] | [
0
] |
Ralph is in the Binary Country. The Binary Country consists of n cities and (nβ-β1) bidirectional roads connecting the cities. The roads are numbered from 1 to (nβ-β1), the i-th road connects the city labeled (here β xβ denotes the x rounded down to the nearest integer) and the city labeled (iβ+β1), and the length of the i-th road is Li.Now Ralph gives you m queries. In each query he tells you some city Ai and an integer Hi. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including Ai) as the terminal city for a tour. He gains happiness (Hiβ-βL) during a tour, where L is the distance between the city Ai and the terminal city.Ralph is interested in tours from Ai in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour. | Input: ['2 251 82 4'] Output:['114'] | [
0
] |
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1,βa2,β...,βan. He remembered that he calculated gcd(ai,βaiβ+β1,β...,βaj) for every 1ββ€βiββ€βjββ€βn and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1. | Input: ['42 4 6 12'] Output:['34 6 12'] | [
3
] |
Ralph has a magic field which is divided into nβΓβm blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007β=β109β+β7.Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity. | Input: ['1 1 -1'] Output:['1'] | [
3
] |
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). illustration by η«ε± https://twitter.com/nekoyaliu Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. | Input: ['QAQAQYSYIOIWIN'] Output:['4'] | [
0
] |
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: There are y elements in F, and all of them are integer numbers; . You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1ββ€βiββ€βy) such that Aiββ βBi. Since the answer can be very large, print it modulo 109β+β7. | Input: ['26 34 2'] Output:['366'] | [
3
] |
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If aiβ>β0, then ai bourles are deposited to Luba's account. If aiβ<β0, then ai bourles are withdrawn. And if aiβ=β0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when aiβ=β0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her! | Input: ['5 10-1 5 0 -5 3'] Output:['0'] | [
2
] |
Vova promised himself that he would never play computer games... But recently Firestorm β a well-known game developing company β published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely. | Input: ['5 22 5 3 4 81 44 5'] Output:['10'] | [
2
] |
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of kβ+β1 consecutive ones, and then k consecutive zeroes.Some examples of beautiful numbers: 12 (110); 1102 (610); 11110002 (12010); 1111100002 (49610). More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2kβ-β1)β*β(2kβ-β1).Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it! | Input: ['3'] Output:['1'] | [
0
] |
Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | Input: ['40 1 0 10'] Output:['1'] | [
2
] |
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai ββ€β bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not! | Input: ['23 53 6'] Output:['YES'] | [
2
] |
A false witness that speaketh lies!You are given a sequence containing n integers. There is a variable res that is equal to 0 initially. The following process repeats k times.Choose an index from 1 to n uniformly at random. Name it x. Add to res the multiply of all ai's such that 1ββ€βiββ€βn, but iββ βx. Then, subtract ax by 1.You have to find expected value of res at the end of the process. It can be proved that the expected value of res can be represented as an irreducible fraction . You have to find . | Input: ['2 15 5'] Output:['5'] | [
3
] |
You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices Sβ=β{x1,βx2,β...,βxk} (1ββ€βxiββ€βn, 0β<βkβ<βn) the sums of elements on that positions in a and b are different, i. e. | Input: ['21 2'] Output:['2 1 '] | [
2
] |
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x,βy), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1? | Input: ['52 2 3 4 6'] Output:['5'] | [
0,
2,
3
] |
You are given a sequence of integers a1,βa2,β...,βan. Let , and for 1ββ€βiβ<βn. Here, denotes the modulus operation. Find the maximum value of f(x,β1) over all nonnegative integers x. | Input: ['210 5'] Output:['13'] | [
3,
4
] |
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.Let's call a permutation an almost identity permutation iff there exist at least nβ-βk indices i (1ββ€βiββ€βn) such that piβ=βi.Your task is to count the number of almost identity permutations for given numbers n and k. | Input: ['4 1'] Output:['1'] | [
3
] |
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.You have to find minimum k such that there exists at least one k-dominant character. | Input: ['abacaba'] Output:['2'] | [
4
] |
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0,β0). The robot can process commands. There are four types of commands it can perform: U β move from the cell (x,βy) to (x,βyβ+β1); D β move from (x,βy) to (x,βyβ-β1); L β move from (x,βy) to (xβ-β1,βy); R β move from (x,βy) to (xβ+β1,βy). Ivan entered a sequence of n commands, and the robot processed it. After this sequence the robot ended up in the starting cell (0,β0), but Ivan doubts that the sequence is such that after performing it correctly the robot ends up in the same cell. He thinks that some commands were ignored by robot. To acknowledge whether the robot is severely bugged, he needs to calculate the maximum possible number of commands that were performed correctly. Help Ivan to do the calculations! | Input: ['4LDUR'] Output:['4'] | [
2
] |
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, aiβ<βaiβ-β1 and aiβ<βaiβ+β1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, aiβ>βaiβ-β1 and aiβ>βaiβ+β1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima.An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array. | Input: ['31 2 3'] Output:['0'] | [
0
] |
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it. Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc). She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella. | Input: ['5 42 3 5 2 5'] Output:['NO'] | [
2
] |
Masha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister. Masha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing.At first, the line going through two points, that brother drew, doesn't intersect or touch any circle.Also, no two circles intersect or touch, and there is no pair of circles such that one circle is located inside another.Moreover, for each circle, Masha drew a square of the minimal area with sides parallel axis such that this circle is located inside the square and noticed that there is no two squares intersect or touch and there is no pair of squares such that one square is located inside other.Now Masha wants to draw circle of minimal possible radius such that it goes through two points that brother drew and doesn't intersect any other circle, but other circles can touch Masha's circle and can be located inside it.It's guaranteed, that answer won't exceed 1012. It should be held for hacks as well. | Input: ['2 4 7 1333 0 112 4 2-4 14 2'] Output:['5.1478150705'] | [
4
] |
During the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2.It's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation of one face of the cube in any direction.To check her answers she wants to use a program which will for some state of cube tell if it's possible to solve it using one rotation, described above.Cube is called solved if for each face of cube all squares on it has the same color.https://en.wikipedia.org/wiki/Rubik's_Cube | Input: ['2 5 4 6 1 3 6 2 5 5 1 2 3 5 3 1 1 2 4 6 6 4 3 4'] Output:['NO'] | [
0
] |
Absent-minded Masha got set of n cubes for her birthday.At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x.To make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number.The number can't contain leading zeros. It's not required to use all cubes to build a number.Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations. | Input: ['30 1 2 3 4 56 7 8 9 0 12 3 4 5 6 7'] Output:['87'] | [
0
] |
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code:int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans;}That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer.Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109β+β7. | Input: ['5 2'] Output:['22'] | [
3
] |
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? | Input: ['20 0'] Output:['2'] | [
2
] |
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.After practice competition, participant number i got a score of ai. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question. | Input: ['1 3 2 1 2 1'] Output:['YES'] | [
0
] |
A string a of length m is called antipalindromic iff m is even, and for each i (1ββ€βiββ€βm) aiββ βamβ-βiβ+β1.Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the beauty of t as the sum of bi among all indices i such that siβ=βti.Help Ivan to determine maximum possible beauty of t he can get. | Input: ['8abacabac1 1 1 1 1 1 1 1'] Output:['8'] | [
2
] |
Ivan has n different boxes. The first of them contains some balls of n different colors.Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1ββ€βiββ€βn) i-th box will contain all balls with color i.In order to do this, Ivan will make some turns. Each turn he does the following: Ivan chooses any non-empty box and takes all balls from this box; Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either kβ=β2 or kβ=β3. The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.Help Ivan to determine the minimum possible penalty of the game! | Input: ['31 2 3'] Output:['6'] | [
2
] |
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | Input: ['32 1 3'] Output:['9'] | [
2,
3
] |
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: start the race from some point of a field, go around the flag, close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x1,βy1) and the coordinates of the point where the flag is situated (x2,βy2). Polycarpβs quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (x,βy) to any of four points: (xβ-β1,βy), (xβ+β1,βy), (x,βyβ-β1) or (x,βyβ+β1).Thus the quadcopter path is a closed cycle starting and finishing in (x1,βy1) and containing the point (x2,βy2) strictly inside. The picture corresponds to the first example: the starting (and finishing) point is in (1,β5) and the flag is in (5,β2). What is the minimal length of the quadcopter path? | Input: ['1 55 2'] Output:['18'] | [
2,
3
] |
Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road si and width of lawn gi. For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer xi (0ββ€βxiββ€βgi). After it new road width of the i-th part will be equal to s'iβ=βsiβ+βxi and new lawn width will be equal to g'iβ=βgiβ-βxi.On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1ββ€βiβ<βn) the inequation |s'iβ+β1β-βs'i|ββ€β1 should hold. Initially this condition might not be true.You need to find the the total width of lawns the Mayor will destroy according to his plan. | Input: ['34 54 54 10'] Output:['169 9 10 '] | [
2
] |
The mayor of the Berland city S sees the beauty differently than other city-dwellers. In particular, he does not understand at all, how antique houses can be nice-looking. So the mayor wants to demolish all ancient buildings in the city.The city S is going to host the football championship very soon. In order to make the city beautiful, every month the Berland government provides mayor a money tranche. The money has to be spent on ancient buildings renovation.There are n months before the championship and the i-th month tranche equals to ai burles. The city S has m antique buildings and the renovation cost of the j-th building is bj burles.The mayor has his own plans for spending the money. As he doesn't like antique buildings he wants to demolish as much of them as possible. For the j-th building he calculated its demolishing cost pj.The mayor decided to act according to the following plan.Each month he chooses several (possibly zero) of m buildings to demolish in such a way that renovation cost of each of them separately is not greater than the money tranche ai of this month (bjββ€βai) β it will allow to deceive city-dwellers that exactly this building will be renovated.Then the mayor has to demolish all selected buildings during the current month as otherwise the dwellers will realize the deception and the plan will fail. Definitely the total demolishing cost can not exceed amount of money the mayor currently has. The mayor is not obliged to spend all the money on demolishing. If some money is left, the mayor puts it to the bank account and can use it in any subsequent month. Moreover, at any month he may choose not to demolish any buildings at all (in this case all the tranche will remain untouched and will be saved in the bank).Your task is to calculate the maximal number of buildings the mayor can demolish. | Input: ['2 32 46 2 31 3 2'] Output:['2'] | [
2
] |
Evlampiy has found one more cool application to process photos. However the application has certain limitations.Each photo i has a contrast vi. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible.Evlampiy already knows the contrast vi for each of his n photos. Now he wants to split the photos into groups, so that each group contains at least k photos. As a result, each photo must belong to exactly one group.He considers a processing time of the j-th group to be the difference between the maximum and minimum values of vi in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups.Split n photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible. | Input: ['5 250 110 130 40 120'] Output:['20'] | [
4
] |
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings. | Input: ['6aabaac'] Output:['2aba aca '] | [
0
] |
Game field is represented by a line of n square cells. In some cells there are packmen, in some cells there are asterisks and the rest of the cells are empty. Packmen eat asterisks.Before the game starts you can choose a movement direction, left or right, for each packman. Once the game begins all the packmen simultaneously start moving according their directions. A packman can't change the given direction.Once a packman enters a cell containing an asterisk, packman immediately eats the asterisk. Once the packman leaves the cell it becomes empty. Each packman moves at speed 1 cell per second. If a packman enters a border cell, the packman stops. 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 assign a direction to each packman so that they eat the maximal number of asterisks. If there are multiple ways to assign directions to eat the maximal number of asterisks, you should choose the way which minimizes the time to do that. | Input: ['6*.P*P*'] Output:['3 4'] | [
3,
4
] |
Only T milliseconds left before the start of well-known online programming contest Codehorses Round 2017.Polycarp needs to download B++ compiler to take part in the contest. The size of the file is f bytes.Polycarp's internet tariff allows to download data at the rate of one byte per t0 milliseconds. This tariff is already prepaid, and its use does not incur any expense for Polycarp. In addition, the Internet service provider offers two additional packages: download a1 bytes at the rate of one byte per t1 milliseconds, paying p1 burles for the package; download a2 bytes at the rate of one byte per t2 milliseconds, paying p2 burles for the package. Polycarp can buy any package many times. When buying a package, its price (p1 or p2) is prepaid before usage. Once a package is bought it replaces the regular tariff until package data limit is completely used. After a package is consumed Polycarp can immediately buy a new package or switch to the regular tariff without loosing any time. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.Find the minimum amount of money Polycarp has to spend to download an f bytes file no more than in T milliseconds.Note that because of technical reasons Polycarp can download only integer number of bytes using regular tariff and both packages. I.e. in each of three downloading modes the number of downloaded bytes will be integer. It means that Polycarp can't download a byte partially using the regular tariff or/and both packages. | Input: ['120 964 2026 8 813 10 4'] Output:['40'] | [
4
] |
There are n military men in the Berland army. Some of them have given orders to other military men by now. Given m pairs (xi, yi), meaning that the military man xi gave the i-th order to another military man yi.It is time for reform! The Berland Ministry of Defence plans to introduce ranks in the Berland army. Each military man should be assigned a rank β integer number between 1 and k, inclusive. Some of them have been already assigned a rank, but the rest of them should get a rank soon.Help the ministry to assign ranks to the rest of the army so that: for each of m orders it is true that the rank of a person giving the order (military man xi) is strictly greater than the rank of a person receiving the order (military man yi); for each rank from 1 to k there is at least one military man with this rank. | Input: ['5 3 30 3 0 0 22 43 43 5'] Output:['1 3 3 2 2 '] | [
2
] |
One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? | Input: ['abba'] Output:['4'] | [
0
] |
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset. | Input: ['3 2 31 8 4'] Output:['Yes1 4 '] | [
3
] |
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters.For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. | Input: ['3231'] Output:['3'] | [
3
] |
In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his n sons-princes marry the brides with as big dowry as possible.In search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with m unmarried princesses. Receiving guests, Karl learned that the dowry of the i th princess is wi of golden coins. Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.Help the king to organize the marriage of his sons in the most profitable way for the treasury. | Input: ['2 31 2 51 2 12 1 10'] Output:['15'] | [
2
] |
Petya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the point with the coordinate s2, and the clients are at the points x1,βx2,β...,βxn in the order of the required visit.The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the i-th client is delivered, the one who delivers the package to the (iβ+β1)-st client is sent to the path (it can be the same person who went to the point xi, or the other). The friend who is not busy in delivering the current package, is standing still.To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules. | Input: ['2 0 105 6'] Output:['10'] | [
4
] |
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :)Rick and Morty like to go to the ridge High Cry for crying loudly β there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them. Bitwise OR is a binary operation which is determined the following way. Consider representation of numbers x and y in binary numeric system (probably with leading zeroes) xβ=βxk... x1x0 and yβ=βyk... y1y0. Then zβ=βx | y is defined following way: zβ=βzk... z1z0, where ziβ=β1, if xiβ=β1 or yiβ=β1, and ziβ=β0 otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers 10β=β10102 and 9β=β10012 equals 11β=β10112. In programming languages C/C++/Java/Python this operation is defined as Β«|Β», and in Pascal as Β«orΒ».Help Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs l and r (1ββ€βlβ<βrββ€βn) such that bitwise OR of heights of all mountains between l and r (inclusive) is larger than the height of any mountain at this interval. | Input: ['53 2 1 6 5'] Output:['8'] | [
4
] |
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system.Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova. | Input: ['21'] Output:['115'] | [
0,
3
] |
Alexey recently held a programming contest for students from Berland. n students participated in a contest, i-th of them solved ai problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degree, or won't receive any diplomas at all. Let cntx be the number of students that are awarded with diplomas of degree x (1ββ€βxββ€β3). The following conditions must hold: For each x (1ββ€βxββ€β3) cntxβ>β0; For any two degrees x and y cntxββ€β2Β·cnty. Of course, there are a lot of ways to distribute the diplomas. Let bi be the degree of diploma i-th student will receive (or β-β1 if i-th student won't receive any diplomas). Also for any x such that 1ββ€βxββ€β3 let cx be the maximum number of problems solved by a student that receives a diploma of degree x, and dx be the minimum number of problems solved by a student that receives a diploma of degree x. Alexey wants to distribute the diplomas in such a way that: If student i solved more problems than student j, then he has to be awarded not worse than student j (it's impossible that student j receives a diploma and i doesn't receive any, and also it's impossible that both of them receive a diploma, but bjβ<βbi); d1β-βc2 is maximum possible; Among all ways that maximize the previous expression, d2β-βc3 is maximum possible; Among all ways that correspond to the two previous conditions, d3β-βcβ-β1 is maximum possible, where cβ-β1 is the maximum number of problems solved by a student that doesn't receive any diploma (or 0 if each student is awarded with some diploma). Help Alexey to find a way to award the contestants! | Input: ['41 2 3 4'] Output:['3 3 2 1 '] | [
0
] |
Ivan is playing a strange game.He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows: Initially Ivan's score is 0; In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that ai,βjβ=β1). If there are no 1's in the column, this column is skipped; Ivan will look at the next min(k,βnβ-βiβ+β1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score. | Input: ['4 3 20 1 01 0 10 1 01 1 1'] Output:['4 1'] | [
2
] |
Petya had a tree consisting of n vertices numbered with integers from 1 to n. Accidentally he lost his tree. Petya remembers information about k vertices: distances from each of them to each of the n tree vertices.Your task is to restore any tree that satisfies the information that Petya remembers or report that such tree doesn't exist. | Input: ['5 20 1 2 3 22 1 0 1 2'] Output:['2 13 24 35 2'] | [
2
] |
This is an interactive problem.Jury has hidden a permutation p of integers from 0 to nβ-β1. You know only the length n. Remind that in permutation all integers are distinct.Let b be the inverse permutation for p, i.e. pbiβ=βi for all i. The only thing you can do is to ask xor of elements pi and bj, printing two indices i and j (not necessarily distinct). As a result of the query with indices i and j you'll get the value , where denotes the xor operation. You can find the description of xor operation in notes.Note that some permutations can remain indistinguishable from the hidden one, even if you make all possible n2 queries. You have to compute the number of permutations indistinguishable from the hidden one, and print one of such permutations, making no more than 2n queries.The hidden permutation does not depend on your queries. | Input: ['3003232'] Output:['? 0 0? 1 1? 1 2? 0 2? 2 1? 2 0!10 1 2'] | [
0
] |
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself. | Input: ['112'] Output:['3'] | [
2,
3
] |
You are given an array a1,βa2,β...,βan consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes. | Input: ['5 21 2 3 4 5'] Output:['5'] | [
2
] |
You are given two lists of non-zero digits.Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? | Input: ['2 34 25 7 6'] Output:['25'] | [
0
] |
The fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor.The Cinderswarm Bee. Koyomi knows it.The bees, according to their nature, live in a tree. To be more specific, a complete binary tree with n nodes numbered from 1 to n. The node numbered 1 is the root, and the parent of the i-th (2ββ€βiββ€βn) node is . Note that, however, all edges in the tree are undirected.Koyomi adds m extra undirected edges to the tree, creating more complication to trick the bees. And you're here to count the number of simple paths in the resulting graph, modulo 109β+β7. A simple path is an alternating sequence of adjacent nodes and undirected edges, which begins and ends with nodes and does not contain any node more than once. Do note that a single node is also considered a valid simple path under this definition. Please refer to the examples and notes below for instances. | Input: ['3 0'] Output:['9'] | [
0
] |
β This is not playing but duty as allies of justice, Nii-chan!β Not allies but justice itself, Onii-chan!With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters β Karen and Tsukihi β is heading for somewhere they've never reached β water-surrounded islands!There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of a, b and c distinct islands respectively.Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster.The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998β244β353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other. | Input: ['1 1 1'] Output:['8'] | [
3
] |
Even if the world is full of counterfeits, I still regard it as wonderful.Pile up herbs and incense, and arise again from the flames and ashes of its predecessor β as is known to many, the phoenix does it like this.The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes the factorial of integer a, that is, a!β=β1βΓβ2βΓβ...βΓβa. Specifically, 0!β=β1.Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of b! years, that is, . Note that when bββ₯βa this value is always integer.As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge. | Input: ['2 4'] Output:['2'] | [
3
] |
Rock... Paper!After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted by x1,βx2,β...,βxn and y1,βy2,β...,βyn respectively. They reveal their sequences, and repeat until all of 2n integers become distinct, which is the only final state to be kept and considered.Then they count the number of ordered pairs (i,βj) (1ββ€βi,βjββ€βn) such that the value xi xor yj equals to one of the 2n integers. Here xor means the bitwise exclusive or operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game. | Input: ['31 2 34 5 6'] Output:['Karen'] | [
0
] |
The prehistoric caves of El Toll are located in MoiΓ (Barcelona). You have heard that there is a treasure hidden in one of n possible spots in the caves. You assume that each of the spots has probability 1β/βn to contain a treasure.You cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly k distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability 1β/β2, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot x times is 1β/β2x).What is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo 109β+β7. Formally, let the answer be an irreducible fraction Pβ/βQ, then you have to output . It is guaranteed that Q is not divisible by 109β+β7. | Input: ['31 12 13 2'] Output:['2500000007777777786'] | [
3
] |
You are given n strings s1,βs2,β...,βsn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string snβ+βi (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0. | Input: ['5011010111111031 26 54 4'] Output:['120'] | [
0
] |
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset! | Input: ['5 31 0 11 1 01 0 01 0 01 0 0'] Output:['NO'] | [
0
] |
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. | Input: ['ya4ahoytoha'] Output:['YES'] | [
0
] |
It's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates.The flower shop has F different types of flowers available. The i-th type of flower always has exactly pi petals. Pieguy has decided to buy a bouquet consisting of exactly N flowers. He may buy the same type of flower multiple times. The N flowers are then arranged into a bouquet. The position of the flowers within a bouquet matters. You can think of a bouquet as an ordered list of flower types.The chocolate shop sells chocolates in boxes. There are B different types of boxes available. The i-th type of box contains ci pieces of chocolate. Pieguy can buy any number of boxes, and can buy the same type of box multiple times. He will then place these boxes into a basket. The position of the boxes within the basket matters. You can think of the basket as an ordered list of box types.Pieguy knows that Piegirl likes to pluck a petal from a flower before eating each piece of chocolate. He would like to ensure that she eats the last piece of chocolate from the last box just after plucking the last petal from the last flower. That is, the total number of petals on all the flowers in the bouquet should equal the total number of pieces of chocolate in all the boxes in the basket.How many different bouquet+basket combinations can Pieguy buy? The answer may be very large, so compute it modulo 1000000007β=β109β+β7. | Input: ['2 3 33 510 3 7'] Output:['17'] | [
3
] |
The game of Egg Roulette is played between two players. Initially 2R raw eggs and 2C cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg was cooked, not much happens, but if the egg was raw, it will make quite the mess. This continues until one player has broken R raw eggs, at which point that player is declared the loser and the other player wins.The order in which players take turns can be described as a string of 'A' and 'B' characters, where the i-th character tells which player should choose the i-th egg. Traditionally, players take turns going one after the other. That is, they follow the ordering "ABABAB...". This isn't very fair though, because the second player will win more often than the first. We'd like you to find a better ordering for the players to take their turns. Let's define the unfairness of an ordering as the absolute difference between the first player's win probability and the second player's win probability. We're interested in orderings that minimize the unfairness. We only consider an ordering valid if it contains the same number of 'A's as 'B's.You will also be given a string S of length 2(Rβ+βC) containing only 'A', 'B', and '?' characters. An ordering is said to match S if it only differs from S in positions where S contains a '?'. Of the valid orderings that minimize unfairness, how many match S? | Input: ['1 1??BB'] Output:['0'] | [
0,
3
] |
Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string, nor the length of the string, but may have permuted the digits arbitrarily. For example, if the original string was 0abc they may have changed it to a0cb or 0bca, but not abc or 0abb.Unfortunately you don't have access to the original string nor the copied string, but you do know the length of the strings and their numerical absolute difference. You will be given this difference as a hexadecimal string S, which has been zero-extended to be equal in length to the original and copied strings. Determine the smallest possible numerical value of the original string. | Input: ['f1e'] Output:['NO'] | [
0
] |
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible. | Input: ['910 5 4 7 9 12 6 2 10'] Output:['20'] | [
2
] |
You're trying to set the record on your favorite video game. The game consists of N levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the i-th level in either Fi seconds or Si seconds, where Fiβ<βSi, and there's a Pi percent chance of completing it in Fi seconds. After completing a level, you may decide to either continue the game and play the next level, or reset the game and start again from the first level. Both the decision and the action are instant.Your goal is to complete all the levels sequentially in at most R total seconds. You want to minimize the expected amount of time playing before achieving that goal. If you continue and reset optimally, how much total time can you expect to spend playing? | Input: ['1 82 8 81'] Output:['3.14'] | [
4
] |
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved? | Input: ['3 123 5 74 6 75 9 5'] Output:['84'] | [
4,
4
] |
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal β compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if xiβ<βyi, where i is the first index in which the permutations x and y differ.Determine the array Ivan will obtain after performing all the changes. | Input: ['43 2 2 3'] Output:['21 2 4 3 '] | [
2,
3
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.