question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.
Input: ['21 22 1'] Output:['2 02 0']
[ 0, 2 ]
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?
Input: ['5 20 4 5 1 0'] Output:['1']
[ 2 ]
One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found n test tubes with mercury numbered from 1 to n and decided to conduct an experiment.The experiment consists of q steps. On each step, one of the following actions occurs: Diana pours all the contents from tube number pi and then pours there exactly xi liters of mercury. Let's consider all the ways to add vi liters of water into the tubes; for each way let's count the volume of liquid (water and mercury) in the tube with water with maximum amount of liquid; finally let's find the minimum among counted maximums. That is the number the students want to count. At that, the students don't actually pour the mercury. They perform calculations without changing the contents of the tubes. Unfortunately, the calculations proved to be too complex and the students asked you to help them. Help them conduct the described experiment.
Input: ['3 31 2 02 21 2 12 3'] Output:['1.500001.66667']
[ 4, 4 ]
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input: ['1 1'] Output:['1']
[ 3, 4 ]
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory shower door. As soon as the shower opens, the first person from the line enters the shower. After a while the first person leaves the shower and the next person enters the shower. The process continues until everybody in the line has a shower.Having a shower takes some time, so the students in the line talk as they wait. At each moment of time the students talk in pairs: the (2i - 1)-th man in the line (for the current moment) talks with the (2i)-th one. Let's look at this process in more detail. Let's number the people from 1 to 5. Let's assume that the line initially looks as 23154 (person number 2 stands at the beginning of the line). Then, before the shower opens, 2 talks with 3, 1 talks with 5, 4 doesn't talk with anyone. Then 2 enters the shower. While 2 has a shower, 3 and 1 talk, 5 and 4 talk too. Then, 3 enters the shower. While 3 has a shower, 1 and 5 talk, 4 doesn't talk to anyone. Then 1 enters the shower and while he is there, 5 and 4 talk. Then 5 enters the shower, and then 4 enters the shower.We know that if students i and j talk, then the i-th student's happiness increases by gij and the j-th student's happiness increases by gji. Your task is to find such initial order of students in the line that the total happiness of all students will be maximum in the end. Please note that some pair of students may have a talk several times. In the example above students 1 and 5 talk while they wait for the shower to open and while 3 has a shower.
Input: ['0 0 0 0 90 0 0 0 00 0 0 0 00 0 0 0 07 0 0 0 0'] Output:['32']
[ 0 ]
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color. For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.
Input: ['6 2 21 1 2 2 1 1'] Output:['6']
[ 0 ]
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that each internal node (a node with at least one son) has at least two sons; node i has ci nodes in its subtree? Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes.
Input: ['41 1 1 4'] Output:['YES']
[ 2 ]
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station. The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input: ['3 61 2 3'] Output:['4']
[ 2, 3, 4 ]
Sereja has painted n distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number.
Input: ['50 00 22 02 21 1'] Output:['1']
[ 4 ]
Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h × w, then the component must contain exactly hw cells.A connected component of the same values is a set of cells of the table that meet the following conditions: every two cells of the set have the same value; the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table); it is impossible to add any cell to the set unless we violate the two previous conditions. Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?
Input: ['5 5 21 1 1 1 11 1 1 1 11 1 0 1 11 1 1 1 11 1 1 1 1'] Output:['1']
[ 2 ]
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:A swap operation is the following sequence of actions: choose two indexes i, j (i ≠ j); perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?
Input: ['10 210 -1 2 2 2 2 2 2 -1 10'] Output:['32']
[ 0 ]
Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.To construct a biathlon track a plot of land was allocated, which is a rectangle divided into n × m identical squares. Each of the squares has two coordinates: the number of the row (from 1 to n), where it is located, the number of the column (from 1 to m), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.The biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends tp seconds, an ascent takes tu seconds, a descent takes td seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to t seconds as possible. In other words, the difference between time ts of passing the selected track and t should be minimum.For a better understanding you can look at the first sample of the input data. In this sample n = 6, m = 7, and the administration wants the track covering time to be as close to t = 48 seconds as possible, also, tp = 3, tu = 6 and td = 2. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly 48 seconds. The upper left corner of this track is located in the square with the row number 4, column number 3 and the lower right corner is at square with row number 6, column number 7. Among other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.You are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them.
Input: ['6 7 483 6 25 4 8 3 3 7 94 1 6 8 7 1 11 6 4 6 4 8 67 2 6 1 6 9 41 9 8 6 3 9 24 5 6 8 4 3 7'] Output:['4 3 6 7']
[ 0, 4 ]
People in the Tomskaya region like magic formulas very much. You can see some of them below.Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:Here, "mod" means the operation of taking the residue after dividing.The expression means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal β€” by "xor".People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q.
Input: ['31 2 3'] Output:['3']
[ 3 ]
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input: ['4 9999981 1 12 2 13 3 12 -2 1'] Output:['2.8284271']
[ 2, 4 ]
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.
Input: ['4 22 31 41 42 1'] Output:['6']
[ 4 ]
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.
Input: ['1 1'] Output:['1']
[ 3 ]
A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer.
Input: ['2 2 1100 1 12100 2 11'] Output:['202']
[ 2 ]
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds.The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Each of the additional elimination rounds consists of d problems. The winner of the additional round is one person. Besides, k winners of the past finals are invited to the finals without elimination.As a result of all elimination rounds at least nΒ·m people should go to the finals. You need to organize elimination rounds in such a way, that at least nΒ·m people go to the finals, and the total amount of used problems in all rounds is as small as possible.
Input: ['1 107 21'] Output:['2']
[ 3 ]
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ​​may be unknown. Such values are represented by number -1.For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ​​-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ​​-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input: ['98 6 4 2 1 4 7 10 2'] Output:['3']
[ 2, 3 ]
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and pi β€” the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.Unfortunately, there only are k tables in the restaurant. For each table, we know ri β€” the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.
Input: ['310 502 1005 3034 6 9'] Output:['2 1302 13 2']
[ 2, 4 ]
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules: Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n); each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
Input: ['5 112345'] Output:['1 3 6 10 15 ']
[ 0 ]
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: Is it true that y is strictly larger than number x? Is it true that y is strictly smaller than number x? Is it true that y is larger than or equal to number x? Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".
Input: ['4>= 1 Y< 3 N<= -3 N> 55 N'] Output:['17']
[ 2 ]
Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.
Input: ['5 1 412 6 11 9 1'] Output:['0 2 3 1 1 ']
[ 2, 3, 4 ]
Mashmokh is playing a new game. In the beginning he has k liters of water and p coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of m vertices. Each vertex of the tree contains a water tank that is empty in the beginning.The game begins with the fact that Mashmokh chooses some (no more than k) of these tanks (except the root) and pours into each of them exactly 1 liter of water. Then the following process is performed until there is no water remained in tanks. The process consists of several steps. At the beginning of each step Mashmokh opens doors of all tanks. Then Mashmokh closes doors of some tanks (he is not allowed to close door of tank in the root) for the duration of this move. Let's denote the number of liters in some tank with closed door as w, Mashmokh pays w coins for the closing of that tank during this move. Let's denote by x1, x2, ..., xm as the list of vertices of the tree sorted (nondecreasing) by their depth. The vertices from this list should be considered one by one in the order. Firstly vertex x1 (which is the root itself) is emptied. Then for each vertex xi (i > 1), if its door is closed then skip the vertex else move all the water from the tank of vertex xi to the tank of its father (even if the tank of the father is closed). Suppose l moves were made until the tree became empty. Let's denote the amount of water inside the tank of the root after the i-th move by wi then Mashmokh will win max(w1, w2, ..., wl) dollars. Mashmokh wanted to know what is the maximum amount of dollars he can win by playing the above game. He asked you to find this value for him.
Input: ['10 2 11 21 33 43 52 66 86 79 88 10'] Output:['2']
[ 2, 4 ]
'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.
Input: ['4 11 3 7 53'] Output:['18']
[ 2, 3 ]
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?
Input: ['3 240 20 30'] Output:['30']
[ 2 ]
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
Input: ['2 2R1'] Output:['PRINT 1LEFTPRINT R']
[ 2 ]
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input: ['5 14'] Output:['19']
[ 0 ]
You've got an array consisting of n integers: a[1], a[2], ..., a[n]. Moreover, there are m queries, each query can be described by three integers li, ri, ki. Query li, ri, ki means that we should add to each element a[j], where li ≀ j ≀ ri.Record means the binomial coefficient, or the number of combinations from y elements into groups of x elements.You need to fulfil consecutively all queries and then print the final array.
Input: ['5 10 0 0 0 01 5 0'] Output:['1 1 1 1 1']
[ 0, 3 ]
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input: ['1 1'] Output:['NO']
[ 0, 3 ]
Little Chris is having a nightmare. Even in dreams all he thinks about is math.Chris dreams about m binary strings of length n, indexed with numbers from 1 to m. The most horrifying part is that the bits of each string are ordered in either ascending or descending order. For example, Chris could be dreaming about the following 4 strings of length 5: The Hamming distance H(a, b) between two strings a and b of length n is the number of positions at which the corresponding symbols are different. Π‘hris thinks that each three strings with different indices constitute a single triple. Chris's delusion is that he will wake up only if he counts the number of such string triples a, b, c that the sum H(a, b) + H(b, c) + H(c, a) is maximal among all the string triples constructed from the dreamed strings.Help Chris wake up from this nightmare!
Input: ['5 40 30 51 41 5'] Output:['3']
[ 3 ]
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds: "Are you kidding me?", asks Chris.For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7. However, now Chris has exactly s = 106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!
Input: ['31 4 5'] Output:['2999993 1000000']
[ 2, 3 ]
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1Β·1 + 1Β·0 + 1Β·1) + (0Β·1 + 1Β·1 + 1Β·0) + (1Β·1 + 0Β·1 + 0Β·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input: ['31 1 10 1 11 0 01232 332 22 21 3331 22 11 13'] Output:['01001']
[ 3 ]
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the n columns after the gravity switch!
Input: ['43 2 1 2'] Output:['1 2 2 3 ']
[ 2 ]
Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot.The robot has instructions β€” the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move.Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once β€” at its last move. Moreover, the latter move cannot be skipped.Let's assume that k is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose k obstacles and the finishing cell so that the robot is able to complete the instructions successfully.
Input: ['RR'] Output:['1']
[ 2, 4 ]
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2Β·d, ..., nΒ·d meters.
Input: ['2 52'] Output:['1.0000000000 2.00000000002.0000000000 0.0000000000']
[ 3 ]
You have matrix a of size n × n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions: for any numbers i, j (1 ≀ i, j ≀ n) the following inequality holds: aij β‰₯ 0; . Matrix b is strictly positive, if for any numbers i, j (1 ≀ i, j ≀ n) the inequality bij > 0 holds. You task is to determine if there is such integer k β‰₯ 1, that matrix ak is strictly positive.
Input: ['21 00 1'] Output:['NO']
[ 3 ]
You have an array of positive integers a[1], a[2], ..., a[n] and a set of bad prime numbers b1, b2, ..., bm. The prime numbers that do not occur in the set b are considered good. The beauty of array a is the sum , where function f(s) is determined as follows: f(1) = 0; Let's assume that p is the minimum prime divisor of s. If p is a good prime, then , otherwise . You are allowed to perform an arbitrary (probably zero) number of operations to improve array a. The operation of improvement is the following sequence of actions: Choose some number r (1 ≀ r ≀ n) and calculate the value g = GCD(a[1], a[2], ..., a[r]). Apply the assignments: , , ..., . What is the maximum beauty of the array you can get?
Input: ['5 24 20 34 10 102 5'] Output:['-2']
[ 2, 3 ]
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: the graph contains exactly 2n + p edges; the graph doesn't contain self-loops and multiple edges; for any integer k (1 ≀ k ≀ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.
Input: ['16 0'] Output:['1 21 31 41 51 62 32 42 52 63 43 53 6']
[ 0 ]
The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≀ i ≀ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≀ i < n), ai + 1 - ai = k, where k is the number the Queen chose.Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?
Input: ['4 11 2 1 5'] Output:['2+ 3 2- 4 1']
[ 0 ]
You have a nuts and lots of boxes. The boxes have a wonderful feature: if you put x (x β‰₯ 0) divisors (the spacial bars that can divide a box) to it, you get a box, divided into x + 1 sections.You are minimalist. Therefore, on the one hand, you are against dividing some box into more than k sections. On the other hand, you are against putting more than v nuts into some section of the box. What is the minimum number of boxes you have to use if you want to put all the nuts in boxes, and you have b divisors?Please note that you need to minimize the number of used boxes, not sections. You do not have to minimize the number of used divisors.
Input: ['3 10 3 3'] Output:['2']
[ 2, 3 ]
This problem was deleted from the contest, because it was used previously at another competition.
Input: ['1 11 2 100'] Output:['6']
[ 3 ]
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number n, modulo m.Number x is considered close to number n modulo m, if: it can be obtained by rearranging the digits of number n, it doesn't have any leading zeroes, the remainder after dividing number x by m equals 0. Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.
Input: ['104 2'] Output:['3']
[ 0 ]
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that: there wouldn't be a pair of any side-adjacent cards with zeroes in a row; there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
Input: ['1 2'] Output:['101']
[ 2 ]
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier β€” a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.
Input: ['3 22 12 2'] Output:['0 0']
[ 2, 3 ]
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.
Input: ['3 2-1 1 2'] Output:['1']
[ 3 ]
Inna is fed up with jokes about female logic. So she started using binary logic instead.Inna has an array of n elements a1[1], a1[2], ..., a1[n]. Girl likes to train in her binary logic, so she does an exercise consisting of n stages: on the first stage Inna writes out all numbers from array a1, on the i-th (i β‰₯ 2) stage girl writes all elements of array ai, which consists of n - i + 1 integers; the k-th integer of array ai is defined as follows: ai[k] = ai - 1[k] AND ai - 1[k + 1]. Here AND is bit-wise binary logical operation.Dima decided to check Inna's skill. He asks Inna to change array, perform the exercise and say the sum of all elements she wrote out during the current exercise.Help Inna to answer the questions!
Input: ['3 41 1 11 12 23 21 2'] Output:['64712']
[ 4 ]
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns β€” from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!
Input: ['3 3 3 1 1 91 11 21 32 12 22 33 13 23 3'] Output:['1 31 21 12 32 22 13 33 23 1']
[ 3 ]
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs: some dwarf in one of the chosen lines is located in the rightmost cell of his row; some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.
Input: ['3 4*G*SG**S*G*S'] Output:['2']
[ 0 ]
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity β€” he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission β€” ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket β€” because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≀ x ≀ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
Input: ['25 2 36 4 5'] Output:['YesNo']
[ 3 ]
Of course, many of you can calculate Ο†(n) β€” the number of positive integers that are less than or equal to n, that are coprime with n. But what if we need to calculate Ο†(Ο†(...Ο†(n))), where function Ο† is taken k times and n is given in the canonical decomposition into prime factors? You are given n and k, calculate the value of Ο†(Ο†(...Ο†(n))). Print the result in the canonical decomposition into prime factors.
Input: ['17 11'] Output:['22 13 1']
[ 3 ]
You are given a permutation p. Calculate the total number of inversions in all permutations that lexicographically do not exceed the given one.As this number can be very large, print it modulo 1000000007 (109 + 7).
Input: ['22 1'] Output:['1']
[ 3 ]
Let's assume that v(n) is the largest prime number, that does not exceed n; u(n) is the smallest prime number strictly greater than n. Find .
Input: ['223'] Output:['1/67/30']
[ 3 ]
You are given an integer m as a product of integers a1, a2, ... an . Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers.Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo 1000000007 (109 + 7).
Input: ['115'] Output:['1']
[ 3 ]
The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum.Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression.
Input: ['5-3 -4 -2 -3 3'] Output:['2-3 1']
[ 0, 3 ]
During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes.The teacher responded instantly at our request. He put nm dominoes on the table as an n × 2m rectangle so that each of the n rows contained m dominoes arranged horizontally. Each half of each domino contained number (0 or 1).We were taken aback, and the teacher smiled and said: "Consider some arrangement of dominoes in an n × 2m matrix. Let's count for each column of the matrix the sum of numbers in this column. Then among all such sums find the maximum one. Can you rearrange the dominoes in the matrix in such a way that the maximum sum will be minimum possible? Note that it is prohibited to change the orientation of the dominoes, they all need to stay horizontal, nevertheless dominoes are allowed to rotate by 180 degrees. As a reward I will give you all my dominoes".We got even more taken aback. And while we are wondering what was going on, help us make an optimal matrix of dominoes.
Input: ['2 301 11 0000 01 11'] Output:['11 11 1000 00 01']
[ 2 ]
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input: ['6 5'] Output:['142857']
[ 3 ]
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? β€” That's right, using counting sticks! An here's our new task: An expression of counting sticks is an expression of type:[ A sticks][sign +][B sticks][sign =][C sticks] (1 ≀ A, B, C). Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if A + B = C.We've got an expression that looks like A + B = C given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.We really aren't fabulous at arithmetics. Can you help us?
Input: ['||+|=|||||'] Output:['|||+|=||||']
[ 0 ]
Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation: F1 = 1, F2 = 2, Fi = Fi - 1 + Fi - 2 (i > 2).We'll define a new number sequence Ai(k) by the formula: Ai(k) = Fi × ik (i β‰₯ 1).In this problem, your task is to calculate the following sum: A1(k) + A2(k) + ... + An(k). The answer can be very large, so print it modulo 1000000007 (109 + 7).
Input: ['1 1'] Output:['1']
[ 3 ]
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if: the Euclidean distance between A and B is one unit and neither A nor B is blocked; or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B. Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
Input: ['1'] Output:['4']
[ 3 ]
This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points.Manao has developed a model to predict the stock price of a company over the next n days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions: It only allows owning either zero or one shares of stock at a time; It only allows buying or selling a share of this stock once per day; It allows a maximum of k buy orders over the next n days; For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day i, then holding the stock until some day j > i at which point the share is sold. To restate the above constraints, Manao is permitted to make at most k non-overlapping trades during the course of an n-day trading period for which Manao's model has predictions about the stock price.Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to k times until n days have passed.Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the n-day trading period subject to the above constraints.
Input: ['10 22739879719'] Output:['15']
[ 2 ]
This problem consists of two subproblems: for solving subproblem D1 you will receive 3 points, and for solving subproblem D2 you will receive 16 points.Manao is the chief architect involved in planning a new supercollider. He has to identify a plot of land where the largest possible supercollider can be built. The supercollider he is building requires four-way orthogonal collisions of particles traveling at the same speed, so it will consist of four accelerating chambers and be shaped like a plus sign (i.e., +). Each of the four accelerating chambers must be the same length and must be aligned with the Earth's magnetic field (parallel or orthogonal) to minimize interference.The accelerating chambers need to be laid down across long flat stretches of land to keep costs under control. Thus, Manao has already commissioned a topographical study that has identified all possible maximal length tracts of land available for building accelerating chambers that are either parallel or orthogonal to the Earth's magnetic field. To build the largest possible supercollider, Manao must identify the largest symmetric plus shape from among these candidate tracts. That is, he must find the two tracts of land that form an axis-aligned plus shape with the largest distance from the center of the plus to the tip of the shortest of the four arms of the plus. Note that the collider need not use the entire length of the tracts identified (see the example in the notes).
Input: ['1 24 0 91 1 81 2 7'] Output:['2']
[ 0 ]
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points.Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort.After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
Input: ['3 21 11 42 2'] Output:['3']
[ 2 ]
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points.Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort.After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
Input: ['3 21 11 42 2'] Output:['3']
[ 0 ]
You will receive 5 points for solving this problem.Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity.We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings:"ABCDEF|GHIJK" | "A|BCDEFGHIJK" | "AB|RACA|DAB|RA" | "X|XXXXX|X|X|XXXXXX" | | | XXXXXX KJIHG | KJIHGFEDCB | AR | X ABCDEF | A | DAB | X | | ACAR | XXXXX | | AB | XOne last example for "ABCD|EFGH|IJ|K": KIJHGFEABCDManao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both.
Input: ['ABRACADABRA'] Output:['3']
[ 0 ]
Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.Please, tell Ciel if she can draw the crosses in the described way.
Input: ['5.#...####..####...#......'] Output:['YES']
[ 2 ]
Fox Ciel is playing a game with numbers now. Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible.Please help Ciel to find this minimal sum.
Input: ['21 2'] Output:['2']
[ 2, 3 ]
Fox Ciel studies number theory.She thinks a non-empty set S contains non-negative integers is perfect if and only if for any (a can be equal to b), . Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or).Please calculate the number of perfect sets consisting of integers not greater than k. The answer can be very large, so print it modulo 1000000007 (109 + 7).
Input: ['1'] Output:['2']
[ 3 ]
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.Suppose Ciel and Jiro play optimally, what is the score of the game?
Input: ['21 1002 1 10'] Output:['101 10']
[ 2 ]
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input: ['2'] Output:['4NNYYNNYYYYNNYYNN']
[ 3 ]
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than xi boxes on the top of i-th box. What is the minimal number of piles she needs to construct?
Input: ['30 0 10'] Output:['2']
[ 2 ]
George is a cat, so he loves playing very much.Vitaly put n cards in a row in front of George. Each card has one integer written on it. All cards had distinct numbers written on them. Let's number the cards from the left to the right with integers from 1 to n. Then the i-th card from the left contains number pi (1 ≀ pi ≀ n). Vitaly wants the row to have exactly k cards left. He also wants the i-th card from left to have number bi written on it. Vitaly gave a task to George, to get the required sequence of cards using the remove operation n - k times.In one remove operation George can choose w (1 ≀ w; w is not greater than the current number of cards in the row) contiguous cards (contiguous subsegment of cards). Let's denote the numbers written on these card as x1, x2, ..., xw (from the left to the right). After that, George can remove the card xi, such that xi ≀ xj for each j (1 ≀ j ≀ w). After the described operation George gets w pieces of sausage.George wondered: what maximum number of pieces of sausage will he get in total if he reaches his goal and acts optimally well? Help George, find an answer to his question!
Input: ['3 22 1 31 3'] Output:['1']
[ 4 ]
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence of actions: Choose two distinct indexes i and j (1 ≀ i, j ≀ |b|; i ≠ j), such that bi β‰₯ bj. Get number v = concat(bi, bj), where concat(x, y) is a number obtained by adding number y to the end of the decimal record of number x. For example, concat(500, 10) = 50010, concat(2, 2) = 22. Add number v to the end of the array. The length of the array will increase by one. Remove from the array numbers with indexes i and j. The length of the array will decrease by two, and elements of the array will become re-numbered from 1 to current length of the array. George played for a long time with his array b and received from array b an array consisting of exactly one number p. Now George wants to know: what is the maximum number of elements array b could contain originally? Help him find this number. Note that originally the array could contain only positive integers.
Input: ['9555'] Output:['4']
[ 2 ]
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c β‰₯ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
Input: ['3 51 2 31 2 2 3 3'] Output:['0']
[ 0, 2 ]
Everyone loves a freebie. Especially students.It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam.In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input: ['64 1 7 8 3 81'] Output:['3']
[ 0, 4 ]
Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains growing raspberry, at that, the cell (x, y) of the field contains x + y raspberry bushes.The bear came out to walk across the field. At the beginning of the walk his speed is (dx, dy). Then the bear spends exactly t seconds on the field. Each second the following takes place: Let's suppose that at the current moment the bear is in cell (x, y). First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from k bushes, he increases each component of his speed by k. In other words, if before eating the k bushes of raspberry his speed was (dx, dy), then after eating the berry his speed equals (dx + k, dy + k). Let's denote the current speed of the bear (dx, dy) (it was increased after the previous step). Then the bear moves from cell (x, y) to cell (((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1). Then one additional raspberry bush grows in each cell of the field. You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell (sx, sy). Assume that each bush has infinitely much raspberry and the bear will never eat all of it.
Input: ['5 1 2 0 1 2'] Output:['3 1']
[ 3 ]
Recently, the bear started studying data structures and faced the following problem.You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li, ri is the sum: , where S(li, ri) is a set of prime numbers from segment [li, ri] (both borders are included in the segment).Help the bear cope with the problem.
Input: ['65 5 7 10 14 1532 113 124 4'] Output:['970']
[ 0, 3, 4 ]
The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≀ i ≀ j ≀ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≀ k ≀ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.
Input: ['bearbtear'] Output:['6']
[ 0, 2, 3 ]
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≀ i ≀ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for c kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day d (1 ≀ d < n), lent a barrel of honey and immediately (on day d) sell it according to a daily exchange rate. The next day (d + 1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day d + 1) give his friend the borrowed barrel of honey as well as c kilograms of raspberry for renting the barrel.The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
Input: ['5 15 10 7 3 20'] Output:['3']
[ 0, 2 ]
Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.Iahub can choose a pair of distinct indices i and j (1 ≀ i, j ≀ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position i is strictly greater than the value at position j.Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the n arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most (at most pairs). Help Iahub, find any suitable array.
Input: ['2 5 01 3 2 5 41 4 3 2 5'] Output:['32 42 34 5']
[ 2 ]
Iahub got lost in a very big desert. The desert can be represented as a n × n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 ≀ i, j ≀ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1). Also, there are m cells that are occupied by volcanoes, which Iahub cannot enter. Iahub is initially at cell (1, 1) and he needs to travel to cell (n, n). Knowing that Iahub needs 1 second to travel from one cell to another, find the minimum time in which he can arrive in cell (n, n).
Input: ['4 21 31 4'] Output:['6']
[ 4 ]
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
Input: ['40 0 1 0'] Output:['1']
[ 2 ]
Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers a, b, w, x (0 ≀ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: c = c - 1. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if b β‰₯ x, perform the assignment b = b - x, if b < x, then perform two consecutive assignments a = a - 1; b = w - (x - b).You've got numbers a, b, w, x, c. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if c ≀ a.
Input: ['4 2 3 1 6'] Output:['2']
[ 3, 4 ]
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium. The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
Input: ['AC|TL'] Output:['AC|TL']
[ 2 ]
Sereja loves integer sequences very much. He especially likes stairs.Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≀ i ≀ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?
Input: ['51 2 3 4 5'] Output:['55 4 3 2 1']
[ 2 ]
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
Input: ['44 1 2 10'] Output:['12 5']
[ 2 ]
The cinema theater hall in Sereja's city is n seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for n = 4. Today it's the premiere of a movie called "Dry Hard". The tickets for all the seats have been sold. There is a very strict controller at the entrance to the theater, so all n people will come into the hall one by one. As soon as a person enters a cinema hall, he immediately (momentarily) takes his seat and occupies all empty slots to the left and to the right from him. If there are no empty slots, the man gets really upset and leaves.People are not very constant, so it's hard to predict the order in which the viewers will enter the hall. For some seats, Sereja knows the number of the viewer (his number in the entering queue of the viewers) that will come and take this seat. For others, it can be any order. Being a programmer and a mathematician, Sereja wonders: how many ways are there for the people to enter the hall, such that nobody gets upset? As the number can be quite large, print it modulo 1000000007 (109 + 7).
Input: ['110 0 0 0 0 0 0 0 0 0 0'] Output:['1024']
[ 3 ]
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1, a2, ..., an, then after we apply the described operation, the sequence transforms into a1, a2, ..., an[, a1, a2, ..., al] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
Input: ['61 11 22 2 11 32 5 21 4161 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16'] Output:['1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4']
[ 0, 4 ]
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input: ['3 2 2 2'] Output:['ACAC']
[ 0 ]
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.
Input: ['35 1 1'] Output:['5 1 2']
[ 2 ]
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.The first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
Input: ['2 5'] Output:['3 0 3']
[ 0 ]
Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get ci 'passes' in his subjects (regardless of the volume of his work).Bugs, like students, are not the same: every bug is characterized by complexity aj, and every student has the level of his abilities bi. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: bi β‰₯ aj, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.
Input: ['3 4 91 3 1 22 1 34 3 6'] Output:['YES2 3 2 3']
[ 2, 4 ]
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.The decoding of the lever description is given below. If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar. If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar. If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input: ['=^=='] Output:['balance']
[ 3 ]
You have a weighted tree, consisting of n vertices. Each vertex is either painted black or is painted red. A red and black tree is called beautiful, if for any its vertex we can find a black vertex at distance at most x.The distance between two nodes is the shortest path between them.You have a red and black tree. Your task is to make it beautiful in the minimum number of color swap operations. In one color swap operation, you can choose two vertices of different colors and paint each of them the other color. In other words, if you choose a red vertex p and a black vertex q, then in one operation you are allowed to paint p black and paint q red.Print the minimum number of required actions.
Input: ['3 21 0 01 2 22 3 2'] Output:['1']
[ 3 ]
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
Input: ['1689'] Output:['1869']
[ 3 ]
Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies". The babies playing board is an infinite plane containing n blue babies and m red ones. Each baby is a segment that grows in time. At time moment t the blue baby (x, y) is a blue segment with ends at points (x - t, y + t), (x + t, y - t). Similarly, at time t the red baby (x, y) is a red segment with ends at points (x + t, y + t), (x - t, y - t) of the plane. Initially, at time t = 0 all babies are points on the plane.The goal of the game is to find the first integer moment of time when the plane contains a rectangle of a non-zero area which sides are fully covered by some babies. A side may be covered by multiple babies. More formally, each point of each side of the rectangle should be covered by at least one baby of any color. At that, you must assume that the babies are closed segments, that is, they contain their endpoints.You are given the positions of all babies β€” help Inna and Dima to find the required moment of time.
Input: ['2 22 25 53 75 1'] Output:['3']
[ 4 ]
Dima's spent much time thinking what present to give to Inna and gave her an empty sequence w. Now they want to fill sequence w with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses m integers a1, a2, ..., am (1 ≀ a1 < a2 < ... < am). Then Inna and Dima start playing, that is, adding numbers to sequence w. Each new number they choose is added to the end of the sequence. At some moments of time Dima feels that the game is going to end too soon (and he wants to play with Inna as long as possible), so he hits a table hard with his fist. At that the a1-th, a2-th, a3-th, ..., ak-th numbers from the beginning simultaneously fall out of the sequence (the sequence gets k numbers less). Here k is such maximum number that value ak doesn't exceed the current length of the sequence. If number a1 is larger than the current length of w, then nothing falls out of the sequence.You are given the chronological sequence of events in the game. Each event is either adding a number to the end of sequence w or Dima's hit on the table. Calculate the sequence w after all these events happen.
Input: ['10 31 3 6-11100-101-11'] Output:['011']
[ 4 ]
Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.
Input: ['369727'] Output:['2']
[ 2 ]
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b.Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types: move the candy from position (x, y) on the board to position (x - a, y - b); move the candy from position (x, y) on the board to position (x + a, y - b); move the candy from position (x, y) on the board to position (x - a, y + b); move the candy from position (x, y) on the board to position (x + a, y + b). Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task!
Input: ['5 7 1 3 2 2'] Output:['2']
[ 2 ]
We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)Β·k to add the number n to the sequence.You can spend a cost up to w, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.
Input: ['9 1 1'] Output:['9']
[ 3, 4 ]