question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers.Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.
Input: ['2 21 2 3 41 5 3 4'] Output:['1']
[ 0 ]
Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were n shamans in total enumerated with integers from 1 to n in the order they lived. Also, each shaman had a magic power which can now be expressed as an integer.The chronicle includes a list of powers of the n shamans. Also, some shamans can be king-shamans, if they gathered all the power of their predecessors, i.e. their power is exactly the sum of powers of all previous shamans. Nastya is interested in whether there was at least one king-shaman in Byteland.Unfortunately many of the powers are unreadable in the list, so Nastya is doing the following: Initially she supposes some power for each shaman. After that she changes the power of some shaman q times (the shamans can differ) and after that wants to check if there is at least one king-shaman in the list. If yes, she wants to know the index of any king-shaman. Unfortunately the list is too large and Nastya wants you to help her.
Input: ['2 11 31 2'] Output:['-1']
[ 4 ]
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that , where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments. Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input: ['1 11'] Output:['1']
[ 0, 3 ]
Nastya received a gift on New Year β€” a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year. Nastya owns x dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for k + 1 months.Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 109 + 7, because it is easy to see that it is always integer.
Input: ['2 0'] Output:['4']
[ 3 ]
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the greatest common divisor of a and b, and LCM(a, b) denotes the least common multiple of a and b.You are given two integers x and y. You are to find the number of good pairs of integers (a, b) such that l ≀ a, b ≀ r. Note that pairs (a, b) and (b, a) are considered different if a ≠ b.
Input: ['1 2 1 2'] Output:['2']
[ 3 ]
Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important β€” factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the number at the first glance. Could it be shortened? For example, instead of 1000000 you could write 10^{6}, instead of 1000000000 β€”10^{9}, instead of 1000000007 β€” 10^{9}+7.Vasya decided that, to be concise, the notation should follow several rules: the notation should only consist of numbers, operations of addition ("+"), multiplication ("*") and exponentiation ("^"), in particular, the use of braces is forbidden; the use of several exponentiation operations in a row is forbidden, for example, writing "2^3^4" is unacceptable; the value of the resulting expression equals to the initial number; the notation should consist of the minimal amount of symbols. Given n, find the equivalent concise notation for it.
Input: ['2018'] Output:['2018']
[ 0, 2, 3 ]
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either β€” although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number n.In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.Given n, determine the total number of possible bus number variants.
Input: ['97'] Output:['2']
[ 0, 3 ]
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states: XX XX .X X.X. .X XX XX Bishwocks don't attack any squares and can even occupy on the adjacent squares as long as they don't occupy the same square. Vasya has a board with 2* n squares onto which he wants to put some bishwocks. To his dismay, several squares on this board are already occupied by pawns and Vasya can't put bishwocks there. However, pawns also don't attack bishwocks and they can occupy adjacent squares peacefully.Knowing the positions of pawns on the board, help Vasya to determine the maximum amount of bishwocks he can put onto the board so that they wouldn't occupy the same squares and wouldn't occupy squares with pawns.
Input: ['0000'] Output:['1']
[ 2 ]
After passing a test, Vasya got himself a box of n candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.This means the process of eating candies is the following: in the beginning Vasya chooses a single integer k, same for all days. After that, in the morning he eats k candies from the box (if there are less than k candies in the box, he eats them all), then in the evening Petya eats 10\% of the candies remaining in the box. If there are still candies left in the box, the process repeats β€” next day Vasya eats k candies again, and Petya β€” 10\% of the candies left in a box, and so on.If the amount of candies in the box is not divisible by 10, Petya rounds the amount he takes from the box down. For example, if there were 97 candies in the box, Petya would eat only 9 of them. In particular, if there are less than 10 candies in a box, Petya won't eat any at all.Your task is to find out the minimal amount of k that can be chosen by Vasya so that he would eat at least half of the n candies he initially got. Note that the number k must be integer.
Input: ['68'] Output:['3']
[ 4 ]
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically β€” he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student β€” 4.5 would be rounded up to 5 (as in example 3), but 4.4 would be rounded down to 4.This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than 5 (maybe even the dreaded 2). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get 5 for the course. Of course, Vasya will get 5 for the lab works he chooses to redo.Help Vasya β€” calculate the minimum amount of lab works Vasya has to redo.
Input: ['34 4 4'] Output:['2']
[ 2 ]
You have to handle a very complex water distribution system. The system consists of n junctions and m pipes, i-th pipe connects junctions x_i and y_i.The only thing you can do is adjusting the pipes. You have to choose m integer numbers f_1, f_2, ..., f_m and use them as pipe settings. i-th pipe will distribute f_i units of water per second from junction x_i to junction y_i (if f_i is negative, then the pipe will distribute |f_i| units of water per second from junction y_i to junction x_i). It is allowed to set f_i to any integer from -2 \cdot 10^9 to 2 \cdot 10^9.In order for the system to work properly, there are some constraints: for every i \in [1, n], i-th junction has a number s_i associated with it meaning that the difference between incoming and outcoming flow for i-th junction must be exactly s_i (if s_i is not negative, then i-th junction must receive s_i units of water per second; if it is negative, then i-th junction must transfer |s_i| units of water per second to other junctions).Can you choose the integers f_1, f_2, ..., f_m in such a way that all requirements on incoming and outcoming flows are satisfied?
Input: ['43 -10 6 151 23 22 43 43 1'] Output:['Possible4-68-77']
[ 2 ]
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked and no post lamp can be placed there.There are post lamps of different types which differ only by their power. When placed in position x, post lamp of power l illuminates the segment [x; x + l]. The power of each post lamp is always a positive integer number.The post lamp shop provides an infinite amount of lamps of each type from power 1 to power k. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power l cost a_l each.What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power 3 in position n - 1 (even though its illumination zone doesn't completely belong to segment [0; n]).
Input: ['6 2 31 31 2 3'] Output:['6']
[ 0, 2 ]
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constant K.The i-th bacteria can swallow the j-th bacteria if and only if a_i > a_j and a_i <= a_j + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria i can swallow any bacteria j if a_i > a_j and a_i <= a_j + K. The swallow operations go one after another.For example, the sequence of bacteria sizes a=[101, 53, 42, 102, 101, 55, 54] and K=1. The one of possible sequences of swallows is: [101, 53, 42, 102, \underline{101}, 55, 54] \to [101, \underline{53}, 42, 102, 55, 54] \to [\underline{101}, 42, 102, 55, 54] \to [42, 102, 55, \underline{54}] \to [42, 102, 55]. In total there are 3 bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.
Input: ['7 1101 53 42 102 101 55 54'] Output:['3']
[ 2 ]
Berland Football Cup starts really soon! Commentators from all over the world come to the event.Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.If n is not divisible by m, it is impossible to distribute the boxes to the delegations at the moment.Organizers can build a new commentary box paying a burles and demolish a commentary box paying b burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by m)?
Input: ['9 7 3 8'] Output:['15']
[ 3 ]
Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river."To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino."See? The clouds are coming." Kanno gazes into the distance."That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is 0.There are n clouds floating in the sky. Each cloud has the same length l. The i-th initially covers the range of (x_i, x_i + l) (endpoints excluded). Initially, it moves at a velocity of v_i, which equals either 1 or -1.Furthermore, no pair of clouds intersect initially, that is, for all 1 <=q i \lt j <=q n, \lvert x_i - x_j \rvert >=q l.With a wind velocity of w, the velocity of the i-th cloud becomes v_i + w. That is, its coordinate increases by v_i + w during each unit of time. Note that the wind can be strong and clouds can change their direction.You are to help Mino count the number of pairs (i, j) (i < j), such that with a proper choice of wind velocity w not exceeding w_\mathrm{max} in absolute value (possibly negative and/or fractional), the i-th and j-th clouds both cover the moon at the same future moment. This w doesn't need to be the same across different pairs.
Input: ['5 1 2-2 12 13 -15 -17 -1'] Output:['4']
[ 3, 4 ]
You are given an integer n from 1 to 10^{18} without leading zeroes.In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.What is the minimum number of moves you have to make to obtain a number that is divisible by 25? Print -1 if it is impossible to obtain a number that is divisible by 25.
Input: ['5071'] Output:['4']
[ 0, 2 ]
There are n distinct points on a coordinate line, the coordinate of i-th point equals to x_i. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points x_{i_1}, x_{i_2}, ..., x_{i_m} such that for each pair x_{i_j}, x_{i_k} it is true that |x_{i_j} - x_{i_k}| = 2^d where d is some non-negative integer number (not necessarily the same for each pair of points).
Input: ['63 5 4 7 10 12'] Output:['37 3 5']
[ 0, 3 ]
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 <= k <= n) such that the ratings of all team members are distinct.If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print k distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
Input: ['5 315 13 15 15 12'] Output:['YES1 2 5 ']
[ 0 ]
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are n displays placed along a road, and the i-th of them can display a text with font size s_i only. Maria Stepanovna wants to rent such three displays with indices i < j < k that the font size increases if you move along the road in a particular direction. Namely, the condition s_i < s_j < s_k should be held.The rent cost is for the i-th display is c_i. Please determine the smallest cost Maria Stepanovna should pay.
Input: ['52 4 5 4 1040 30 20 10 40'] Output:['90']
[ 0 ]
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him.
Input: ['5 8'] Output:['>']
[ 3 ]
Surely you have seen insane videos by South Korean rapper PSY, such as "Gangnam Style", "Gentleman" and "Daddy". You might also hear that PSY has been recording video "Oppa Funcan Style" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find original description here):On the ground there are n platforms, which are numbered with integers from 1 to n, on i-th platform there is a dancer with number i. Further, every second all the dancers standing on the platform with number i jump to the platform with the number f(i). The moving rule f is selected in advance and is not changed throughout the clip.The duration of the clip was k seconds and the rule f was chosen in such a way that after k seconds all dancers were in their initial positions (i.e. the i-th dancer stood on the platform with the number i). That allowed to loop the clip and collect even more likes.PSY knows that enhanced versions of old artworks become more and more popular every day. So he decided to release a remastered-version of his video.In his case "enhanced version" means even more insanity, so the number of platforms can be up to 10^{18}! But the video director said that if some dancer stays on the same platform all the time, then the viewer will get bored and will turn off the video immediately. Therefore, for all x from 1 to n f(x) \neq x must hold.Big part of classic video's success was in that looping, so in the remastered version all dancers should return to their initial positions in the end of the clip as well.PSY hasn't decided on the exact number of platforms and video duration yet, so he asks you to check if there is a good rule f for different options.
Input: ['37 73 85 6'] Output:['YESNOYES']
[ 3 ]
Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem.You are given a tree with n vertices.In each vertex v there is positive integer a_{v}.You have to answer q queries.Each query has a from u v x.You have to calculate \prod_{w \in P} gcd(x, a_{w}) \mod (10^{9} + 7), where P is a set of vertices on path from u to v. In other words, you are to calculate the product of gcd(x, a_{w}) for all vertices w on the path from u to v. As it might be large, compute it modulo 10^9+7. Here gcd(s, t) denotes the greatest common divisor of s and t.Note that the numbers in vertices do not change after queries.I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them.
Input: ['41 21 31 46 4 9 532 3 62 3 23 4 7'] Output:['3641']
[ 0, 3 ]
You are working as an analyst in a company working on a new system for big data storage. This system will store n different objects. Each object should have a unique ID.To create the system, you choose the parameters of the system β€” integers m >= 1 and b_{1}, b_{2}, ..., b_{m}. With these parameters an ID of some object in the system is an array of integers [a_{1}, a_{2}, ..., a_{m}] where 1 <= a_{i} <= b_{i} holds for every 1 <= i <= m.Developers say that production costs are proportional to \sum_{i=1}^{m} b_{i}. You are asked to choose parameters m and b_{i} so that the system will be able to assign unique IDs to n different objects and production costs are minimized. Note that you don't have to use all available IDs.
Input: ['36'] Output:['10']
[ 3 ]
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.
Input: ['52 4 5 1 3'] Output:['Petr']
[ 3 ]
Some company is going to hold a fair in Byteland. There are n towns in Byteland and m two-way roads between towns. Of course, you can reach any town from any other town using roads.There are k types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least s different types of goods. It costs d(u,v) coins to bring goods from town u to town v where d(u,v) is the length of the shortest path from u to v. Length of a path is the number of roads in this path.The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of n towns.
Input: ['5 5 4 31 2 4 3 21 22 33 44 14 5'] Output:['2 2 2 2 3 ']
[ 2 ]
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers β€” saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that: Each pencil belongs to exactly one box; Each non-empty box has at least k pencils in it; If pencils i and j belong to the same box, then |ai - aj| ≀ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| ≀ d and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".
Input: ['6 3 107 2 7 7 4 2'] Output:['YES']
[ 2, 4 ]
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: h1 ≀ H: no sand from the leftmost spot should go over the fence; For any |hi - hi + 1| ≀ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; : you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.
Input: ['5 2'] Output:['3']
[ 3, 4 ]
You have m = nΒ·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.Let volume vj of barrel j be equal to the length of the minimal stave in it. You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |vx - vy| ≀ l for any 1 ≀ x ≀ n and 1 ≀ y ≀ n.Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.
Input: ['4 2 12 2 1 2 3 2 2 3'] Output:['7']
[ 2 ]
In the NN country, there are n cities, numbered from 1 to n, and n - 1 roads, connecting them. There is a roads path between any two cities.There are m bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by bus, you can travel from any stop on the route to any other. You can travel between cities only by bus.You are interested in q questions: is it possible to get from one city to another and what is the minimum number of buses you need to use for it?
Input: ['71 1 1 4 5 644 25 41 36 764 53 57 24 53 25 3'] Output:['13-1123']
[ 4 ]
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input: ['26 12 104 3 10'] Output:['FiniteInfinite']
[ 3 ]
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer k that if the shark in some day traveled the distance strictly less than k, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to k; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least k.The shark never returned to the same location after it has moved from it. Thus, in the sequence of n days we can find consecutive nonempty segments when the shark traveled the distance less than k in each of the days: each such segment corresponds to one location. Max wants to choose such k that the lengths of all such segments are equal.Find such integer k, that the number of locations is as large as possible. If there are several such k, print the smallest one.
Input: ['81 2 7 3 4 8 5 6'] Output:['7']
[ 0 ]
You're given a tree with n vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
Input: ['42 44 13 1'] Output:['1']
[ 2 ]
In the Bus of Characters there are n rows of seat, each having 2 seats. The width of both seats in the i-th row is w_i centimeters. All integers w_i are distinct.Initially the bus is empty. On each of 2n stops one passenger enters the bus. There are two types of passengers: an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
Input: ['23 10011'] Output:['2 1 1 2 ']
[ 2 ]
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold: There are no neighbors adjacent to anyone seated. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones (0 means that the corresponding seat is empty, 1 β€” occupied). The goal is to determine whether this seating is "maximal".Note that the first and last seats are not adjacent (if n!=2).
Input: ['3101'] Output:['Yes']
[ 0 ]
You are given a tree of n vertices. You are to select k (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the latter set should be non-empty.Compute the number of ways to select k paths modulo 998244353.The paths are enumerated, in other words, two ways are considered distinct if there are such i (1 <=q i <=q k) and an edge that the i-th path contains the edge in one way and does not contain it in the other.
Input: ['3 21 22 3'] Output:['7']
[ 3 ]
It's marriage season in Ringland!Ringland has a form of a circle's boundary of length L. There are n bridegrooms and n brides, and bridegrooms decided to marry brides.Of course, each bridegroom should choose exactly one bride, and each bride should be chosen by exactly one bridegroom.All objects in Ringland are located on the boundary of the circle, including the capital, bridegrooms' castles and brides' palaces. The castle of the i-th bridegroom is located at the distance a_i from the capital in clockwise direction, and the palace of the i-th bride is located at the distance b_i from the capital in clockwise direction.Let's define the inconvenience of a marriage the maximum distance that some bride should walk along the circle from her palace to her bridegroom's castle in the shortest direction (in clockwise or counter-clockwise direction).Help the bridegrooms of Ringland to choose brides in such a way that the inconvenience of the marriage is the smallest possible.
Input: ['2 40 12 3'] Output:['1']
[ 2, 4 ]
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly k bookshelves. He decided that the beauty of the k shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on k shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
Input: ['10 49 14 28 1 7 13 15 29 2 31'] Output:['24']
[ 2 ]
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.A substring s[l ... r] (1 <=q l <=q r <=q |s|) of a string s = s_{1}s_{2} ... s_{|s|} is the string s_{l}s_{l + 1} ... s_{r}.Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word s is changed into its longest substring that is not a palindrome. If all the substrings of s are palindromes, she skips the word at all.Some time ago Ann read the word s. What is the word she changed it into?
Input: ['mew'] Output:['3']
[ 0 ]
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.The nation has n districts numbered from 1 to n, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district i is equal to 2^i.This year, the president decided to reduce the costs. He wants to remove k contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts. The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.Which contestants should the president remove?
Input: ['6 32 12 64 25 62 3'] Output:['1 3 4']
[ 2 ]
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive).
Input: ['25 5'] Output:['3 0']
[ 3 ]
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the i-th integer represents the color of the i-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than k, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing k to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.
Input: ['4 32 14 3 4'] Output:['0 12 3 3']
[ 2 ]
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts.Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them.Note that the final necklace should remain as one circular part of the same length as the initial necklace.
Input: ['-o-o--'] Output:['YES']
[ 3 ]
Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day.Sadly, he's going on a vacation for a day, and he isn't able to continue his solving streak on his own. As Katie is a reliable person, Kuro kindly asked her to come to his house on this day to play the game for him.Initally, there is an empty array a. The game consists of q tasks of two types. The first type asks Katie to add a number u_i to a. The second type asks Katie to find a number v existing in a such that k_i \mid GCD(x_i, v), x_i + v <=q s_i, and x_i \oplus v is maximized, where \oplus denotes the bitwise XOR operation, GCD(c, d) denotes the greatest common divisor of integers c and d, and y \mid x means x is divisible by y, or report -1 if no such numbers are found.Since you are a programmer, Katie needs you to automatically and accurately perform the tasks in the game to satisfy her dear friend Kuro. Let's help her!
Input: ['51 11 22 1 1 32 1 1 22 1 1 1'] Output:['21-1']
[ 0, 2, 4 ]
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of 7 because its subribbon a appears 7 times, and the ribbon abcdabc has the beauty of 2 because its subribbon abc appears twice.The rules are simple. The game will have n turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after n turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?
Input: ['3KurooShiroKatie'] Output:['Kuro']
[ 2 ]
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input: ['3'] Output:['2']
[ 3 ]
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.There are three values about each exam: s_i β€” the day, when questions for the i-th exam will be published, d_i β€” the day of the i-th exam (s_i < d_i), c_i β€” number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive. There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i <= j < d_i.It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input: ['5 21 3 11 5 1'] Output:['1 2 3 0 3 ']
[ 2 ]
In BerSoft n programmers work, the programmer i is characterized by a skill r_i.A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel.You are given the skills of each programmers and a list of k pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer i, find the number of programmers, for which the programmer i can be a mentor.
Input: ['4 210 4 10 151 24 3'] Output:['0 0 1 2 ']
[ 4 ]
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.If x is the number of passengers in a bus just before the current bus stop and y is the number of passengers in the bus just after current bus stop, the system records the number y-x. So the system records show how number of passengers changed.The test run was made for single bus and n bus stops. Thus, the system recorded the sequence of integers a_1, a_2, ..., a_n (exactly one number for each bus stop), where a_i is the record for the bus stop i. The bus stops are numbered from 1 to n in chronological order.Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to w (that is, at any time in the bus there should be from 0 to w passengers inclusive).
Input: ['3 52 1 -3'] Output:['3']
[ 3 ]
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 <= i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals 0.
Input: ['424 21 14 10'] Output:['3']
[ 0, 3 ]
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all n dormitories is written on an envelope. In this case, assume that all the rooms are numbered from 1 to a_1 + a_2 + ... + a_n and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case n=2, a_1=3 and a_2=5 an envelope can have any integer from 1 to 8 written on it. If the number 7 is written on an envelope, it means that the letter should be delivered to the room number 4 of the second dormitory.For each of m letters by the room number among all n dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.
Input: ['3 610 15 121 9 12 23 26 37'] Output:['1 11 92 22 133 13 12']
[ 4 ]
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by 1. For example, if you delete the character in the position 2 from the string "exxxii", then the resulting string is "exxii".
Input: ['6xxxiii'] Output:['1']
[ 2 ]
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: divide the number x by 3 (x must be divisible by 3); multiply the number x by 2. After each operation, Polycarp writes down the result on the board and replaces x by the result. So there will be n numbers on the board after all.You are given a sequence of length n β€” the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.
Input: ['64 8 6 3 12 9'] Output:['9 3 6 12 4 8 ']
[ 3 ]
Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:Max owns n creatures, i-th of them can be described with two numbers β€” its health hpi and its damage dmgi. Max also has two types of spells in stock: Doubles health of the creature (hpi := hpiΒ·2); Assigns value of health of the creature to its damage (dmgi := hpi). Spell of first type can be used no more than a times in total, of the second type β€” no more than b times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.
Input: ['2 1 110 156 1'] Output:['27']
[ 2 ]
You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1, r1] lies within segment [l2, r2] iff l1 β‰₯ l2 and r1 ≀ r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.
Input: ['51 102 93 92 32 9'] Output:['2 1']
[ 2 ]
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions.Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) β€” the bottom left corner. Then she starts moving in the snake fashion β€” all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2).Lara has already moved to a neighbouring cell k times. Can you determine her current position?
Input: ['4 3 0'] Output:['1 1']
[ 3 ]
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j} where V_{x} is its speed on the x-axis and V_{y} is on the y-axis.A ghost i has experience value EX_i, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind GX = \sum_{i=1}^{n} EX_i will never increase.Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time T, and magically all the ghosts were aligned on a line of the form y = a \cdot x + b. You have to compute what will be the experience index of the ghost kind GX in the indefinite future, this is your task for today.Note that when Tameem took the picture, GX may already be greater than 0, because many ghosts may have scared one another at any moment between [-\infty, T].
Input: ['4 1 11 -1 -12 1 13 1 14 -1 -1'] Output:['8']
[ 3 ]
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The first warrior leads the attack.Each attacker can take up to a_i arrows before he falls to the ground, where a_i is the i-th warrior's strength.Lagertha orders her warriors to shoot k_i arrows during the i-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute t, they will all be standing to fight at the end of minute t.The battle will last for q minutes, after each minute you should tell Ivar what is the number of his standing warriors.
Input: ['5 51 2 1 2 13 10 1 1 1'] Output:['35443']
[ 4 ]
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input: ['0 1 1 0 0 0 0 0 0 7 0 0 0 0'] Output:['4']
[ 0 ]
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole.Arkady can block some of the holes, and then pour A liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes s_1, s_2, ..., s_n. In other words, if the sum of sizes of non-blocked holes is S, and the i-th hole is not blocked, \frac{s_i \cdot A}{S} liters of water will flow out of it.What is the minimum number of holes Arkady should block to make at least B liters of water flow out of the first hole?
Input: ['4 10 32 2 2 2'] Output:['1']
[ 3 ]
Arkady's code contains n variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.A string a is a prefix of a string b if you can delete some (possibly none) characters from the end of b and obtain a.Please find this minimum possible total length of new names.
Input: ['3codeforcescodehorsescode'] Output:['6']
[ 2 ]
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input: ['10 50 0 1 0 2 0 0 1 0'] Output:['3']
[ 2, 4 ]
k people want to split n candies between them. Each candy should be given to exactly one of them or be thrown away.The people are numbered from 1 to k, and Arkady is the first of them. To split the candies, Arkady will choose an integer x and then give the first x candies to himself, the next x candies to the second person, the next x candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by x) will be thrown away.Arkady can't choose x greater than M as it is considered greedy. Also, he can't choose such a small x that some person will receive candies more than D times, as it is considered a slow splitting.Please find what is the maximum number of candies Arkady can receive by choosing some valid x.
Input: ['20 4 5 2'] Output:['8']
[ 3 ]
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes.A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each person should have enough sheets to make n airplanes. How many packs should they buy?
Input: ['5 3 2 3'] Output:['4']
[ 3 ]
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives CΒ·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.
Input: ['4 5 5 3 51 5 5 4'] Output:['20']
[ 3 ]
Let's define a split of n as a nonincreasing sequence of positive integers, the sum of which is n. For example, the following sequences are splits of 8: [4, 4], [3, 3, 2], [2, 2, 1, 1, 1, 1], [5, 2, 1].The following sequences aren't splits of 8: [1, 7], [5, 4], [11, -3], [1, 1, 4, 1, 1].The weight of a split is the number of elements in the split that are equal to the first element. For example, the weight of the split [1, 1, 1, 1, 1] is 5, the weight of the split [5, 5, 3, 3, 3] is 2 and the weight of the split [9] equals 1.For a given n, find out the number of different weights of its splits.
Input: ['7'] Output:['4']
[ 3 ]
A chip was placed on a field with coordinate system onto point (0, 0).Every second the chip moves randomly. If the chip is currently at a point (x, y), after a second it moves to the point (x - 1, y) with probability p1, to the point (x, y - 1) with probability p2, to the point (x + 1, y) with probability p3 and to the point (x, y + 1) with probability p4. It's guaranteed that p1 + p2 + p3 + p4 = 1. The moves are independent.Find out the expected time after which chip will move away from origin at a distance greater than R (i.e. will be satisfied).
Input: ['0 1 1 1 1'] Output:['1']
[ 3 ]
A rectangle with sides A and B is cut into rectangles with cuts parallel to its sides. For example, if p horizontal and q vertical cuts were made, (p + 1) \cdot (q + 1) rectangles were left after the cutting. After the cutting, rectangles were of n different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles a * b and b * a are considered different if a \neq b.For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.Calculate the amount of pairs (A; B) such as the given rectangles could be created by cutting the rectangle with sides of lengths A and B. Note that pairs (A; B) and (B; A) are considered different when A \neq B.
Input: ['11 1 9'] Output:['3']
[ 0, 3 ]
You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges).A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.Destroy all vertices in the given tree or determine that it is impossible.
Input: ['50 1 2 1 2'] Output:['YES12354']
[ 2 ]
You are given two integers a and b. Moreover, you are given a sequence s_0, s_1, ..., s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k <=q i <=q n it's satisfied that s_{i} = s_{i - k}.Find out the non-negative remainder of division of \sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i} by 10^{9} + 9.Note that the modulo is unusual!
Input: ['2 2 3 3+-+'] Output:['7']
[ 3 ]
The cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities: the cities of Byteland, the cities of Berland, disputed cities. Recently, the project BNET has been launched β€” a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.The countries agreed to connect the pairs of cities with BNET cables in such a way that: If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables. Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.Each city is a point on the line Ox. It is technically possible to connect the cities a and b with a cable so that the city c (a < c < b) is not connected to this cable, where a, b and c are simultaneously coordinates of the cities a, b and c.
Input: ['4-5 R0 P3 P7 B'] Output:['12']
[ 2 ]
You are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.Determine the minimum number of operations that you need to consistently apply to the given integer n to make from it the square of some positive integer or report that it is impossible.An integer x is the square of some positive integer if and only if x=y^2 for some positive integer y.
Input: ['8314'] Output:['2']
[ 0, 3 ]
There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
Input: ['5 1 1*...*'] Output:['2']
[ 2 ]
You are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as . The weight of some partition R of a given set into k subsets is (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 109 + 7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition.
Input: ['4 22 3 2 3'] Output:['160']
[ 3 ]
You are given a string s consisting of n lowercase Latin letters.Let's denote k-substring of s as a string subsk = sksk + 1..sn + 1 - k. Obviously, subs1 = s, and there are exactly such substrings.Let's call some string t an odd proper suprefix of a string T iff the following conditions are met: |T| > |t|; |t| is an odd number; t is simultaneously a prefix and a suffix of T.For evey k-substring () of s you have to calculate the maximum length of its odd proper suprefix.
Input: ['15bcabcabcabcabca'] Output:['9 7 5 3 1 -1 -1 -1']
[ 4 ]
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
Input: ['10010'] Output:['1']
[ 0 ]
Japate, while traveling through the forest of Mala, saw N bags of gold lying in a row. Each bag has some distinct weight of gold between 1 to N. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag.Initially, he starts with an empty bag (zero weight). He considers the bags in some order. If the current bag has a higher weight than the bag in his hand, he picks the current bag.Japate put the bags in some order. Japate realizes that he will pick A bags, if he starts picking bags from the front, and will pick B bags, if he starts picking bags from the back. By picking we mean replacing the bag in his hand with the current one.Now he wonders how many permutations of bags are possible, in which he picks A bags from the front and B bags from back using the above strategy.Since the answer can be very large, output it modulo 998244353.
Input: ['1 1 1'] Output:['1']
[ 3 ]
You have a full binary tree having infinite levels.Each node has an initial value. If a node has value x, then its left child has value 2Β·x and its right child has value 2Β·x + 1. The value of the root is 1. You need to answer Q queries. There are 3 types of queries: Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected). Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them). Print the value of every node encountered on the simple path from the node with value X to the root.Positive K implies right cyclic shift and negative K implies left cyclic shift. It is guaranteed that atleast one type 3 query is present.
Input: ['53 121 2 13 122 4 -13 8'] Output:['12 6 3 1 12 6 2 1 8 4 2 1 ']
[ 0 ]
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  β‰₯ dPikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print  - 1.
Input: ['10 5'] Output:['65 50 7 15 6 100']
[ 2 ]
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.
Input: ['2 0 01 22 3'] Output:['2']
[ 2 ]
Ehab has an array a of n integers. He likes the bitwise-xor operation and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?A subsequence can contain elements that are not neighboring.
Input: ['5 50 1 2 3 44 32 03 75 75 8'] Output:['42040']
[ 3 ]
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≀ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight (where is the bitwise-xor operation). Can you find the weight of the minimum spanning tree of that graph?You can read about complete graphs in https://en.wikipedia.org/wiki/Complete_graphYou can read about the minimum spanning tree in https://en.wikipedia.org/wiki/Minimum_spanning_treeThe weight of the minimum spanning tree is the sum of the weights on the edges included in it.
Input: ['4'] Output:['4']
[ 3 ]
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that: b is lexicographically greater than or equal to a. bi β‰₯ 2. b is pairwise coprime: for every 1 ≀ i < j ≀ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z. Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≀ j < i. An array x is equal to an array y if xi = yi for all 1 ≀ i ≀ n.
Input: ['52 3 5 4 13'] Output:['2 3 5 7 11 ']
[ 2, 3 ]
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.
Input: ['5 4 4i loser am the second100 1 1 5 101 11 32 2 51 4i am the second'] Output:['107']
[ 2 ]
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: 1 ≀ a ≀ n. If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has to be odd. If the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally?
Input: ['1'] Output:['Ehab']
[ 3 ]
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission. Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k1 knights with lightsabers of the first color, k2 knights with lightsabers of the second color, ..., km knights with lightsabers of the m-th color.However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.
Input: ['8 33 3 1 2 2 1 1 33 1 1'] Output:['1']
[ 4 ]
Princess Heidi decided to give orders to all her K Rebel ship commanders in person. Unfortunately, she is currently travelling through hyperspace, and will leave it only at N specific moments t1, t2, ..., tN. The meetings with commanders must therefore start and stop at those times. Namely, each commander will board her ship at some time ti and disembark at some later time tj. Of course, Heidi needs to meet with all commanders, and no two meetings can be held during the same time. Two commanders cannot even meet at the beginnings/endings of the hyperspace jumps, because too many ships in one position could give out their coordinates to the enemy. Your task is to find minimum time that Princess Heidi has to spend on meetings, with her schedule satisfying the conditions above.
Input: ['2 51 4 6 7 12'] Output:['4']
[ 2, 4 ]
The Rebel fleet is afraid that the Empire might want to strike back again. Princess Heidi needs to know if it is possible to assign R Rebel spaceships to guard B bases so that every base has exactly one guardian and each spaceship has exactly one assigned base (in other words, the assignment is a perfect matching). Since she knows how reckless her pilots are, she wants to be sure that any two (straight) paths – from a base to its assigned spaceship – do not intersect in the galaxy plane (that is, in 2D), and so there is no risk of collision.
Input: ['3 30 02 03 1-2 10 32 2'] Output:['Yes']
[ 0, 2, 3 ]
The Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independently come up with the coordinate to which that ship will jump. In the obsolete navigation system used by the Rebels, this coordinate is given as the value of an arithmetic expression of the form .To plan the future of the resistance movement, Princess Heidi needs to know, for each ship, how many ships are going to end up at the same coordinate after the jump. You are her only hope!
Input: ['4(99+98)/97(26+4)/10(12+33)/15(5+1)/7'] Output:['1 2 2 1 ']
[ 3 ]
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:Define the score of X to be the sum of the elements of X modulo p.Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that: Each part contains at least 1 element of A, and each part consists of contiguous elements of A. The two parts do not overlap. The total sum S of the scores of those two parts is maximized. This is the encryption code. Output the sum S, which is the encryption code.
Input: ['4 103 4 7 2'] Output:['16']
[ 0 ]
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
Input: ['31 22 3'] Output:['1 3 3 ']
[ 2 ]
Jenya has recently acquired quite a useful tool β€” k-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length k from an arbitrary string s (its length should be at least 2Β·k in order to perform this operation) and concatenating them afterwards (preserving the initial order). For example, with the help of 2-scissors you can cut ab and de out of abcde and concatenate them into abde, but not ab and bc since they're intersecting.It's a nice idea to test this tool before using it in practice. After looking through the papers, Jenya came up with two strings s and t. His question is whether it is possible to apply his scissors to string s such that the resulting concatenation contains t as a substring?
Input: ['7 4 3baabaabaaaa'] Output:['Yes1 5']
[ 0 ]
You're given Q queries of the form (L, R). For each query you have to find the number of such x that L ≀ x ≀ R and there exist integer numbers a > 0, p > 1 such that x = ap.
Input: ['61 49 95 712 29137 5911 1000000'] Output:['2103171111']
[ 3, 4 ]
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.
Input: ['19 00255 1 100 1'] Output:['25200.0000']
[ 2, 3 ]
Suppose you have two strings s and t, and their length is equal. You may perform the following operation any number of times: choose two different characters c1 and c2, and replace every occurence of c1 in both strings with c2. Let's denote the distance between strings s and t as the minimum number of operations required to make these strings equal. For example, if s is abcd and t is ddcb, the distance between them is 2 β€” we may replace every occurence of a with b, so s becomes bbcd, and then we may replace every occurence of b with d, so both strings become ddcd.You are given two strings S and T. For every substring of S consisting of |T| characters you have to determine the distance between this substring and T.
Input: ['abcdefaddcb'] Output:['2 3 3 3 ']
[ 3 ]
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≀ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input: ['5 0 65 4 3 4 9'] Output:['5']
[ 2, 4 ]
Consider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to ai ml per second (this amount may be a real number). The water delivered by i-th tap has temperature ti.If for every you set i-th tap to deliver exactly xi ml of water per second, then the resulting temperature of water will be (if , then to avoid division by zero we state that the resulting water temperature is 0).You have to set all the water taps in such a way that the resulting temperature is exactly T. What is the maximum amount of water you may get per second if its temperature has to be T?
Input: ['2 1003 1050 150'] Output:['6.000000000000000']
[ 2, 4 ]
InputThe input contains a single integer a (10 ≀ a ≀ 999).OutputOutput 0 or 1.ExamplesInput13Output1Input927Output1Input48Output0
Input: ['13'] Output:['1']
[ 3 ]
Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred through the network: if an archive consists of k files of sizes l1, l2, ..., lk bytes, then the i-th file is split to one or more blocks bi, 1, bi, 2, ..., bi, mi (here the total length of the blocks bi, 1 + bi, 2 + ... + bi, mi is equal to the length of the file li), and after that all blocks are transferred through the network, maintaining the order of files in the archive.Zhorik thinks that the two messages contain the same archive, because their total lengths are equal. However, each file can be split in blocks in different ways in the two messages.You are given the lengths of blocks in each of the two messages. Help Zhorik to determine what is the maximum number of files could be in the archive, if the Zhorik's assumption is correct.
Input: ['7 62 5 3 1 11 4 47 8 2 4 1 8'] Output:['3']
[ 2 ]
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.
Input: ['1 4 2'] Output:['6']
[ 3 ]
It is never too late to play the fancy "Binary Cards" game!There is an infinite amount of cards of positive and negative ranks that are used in the game. The absolute value of any card rank is a power of two, i.e. each card has a rank of either 2k or  - 2k for some integer k β‰₯ 0. There is an infinite amount of cards of any valid rank.At the beginning of the game player forms his deck that is some multiset (possibly empty) of cards. It is allowed to pick any number of cards of any rank but the small deck is considered to be a skill indicator. Game consists of n rounds. In the i-th round jury tells the player an integer ai. After that the player is obligated to draw such a subset of his deck that the sum of ranks of the chosen cards is equal to ai (it is allowed to not draw any cards, in which case the sum is considered to be equal to zero). If player fails to do so, he loses and the game is over. Otherwise, player takes back all of his cards into his deck and the game proceeds to the next round. Player is considered a winner if he is able to draw the suitable set of cards in each of the rounds.Somebody told you which numbers ai the jury is going to tell you in each round. Now you want to pick a deck consisting of the minimum number of cards that allows you to win the "Binary Cards" game.
Input: ['19'] Output:['21 8']
[ 0 ]