📜 ⬆️ ⬇️

Yandex. Blitz. 12 algorithmic problems of the qualifying round and their analysis

At the end of September, we told us that we decided to try to hold a contest, where anyone can practice in solving problems as close as possible to “combat”. So the participants can understand what format the tasks are received by the developers at the interviews in Yandex (many people are interested in this), and most importantly - what they encounter while working on the Search. A typical task at the interview is to create an algorithm, prove its correctness, suggest ways of optimization. If a person understands the algorithms, then he will quickly be able to implement them in any available language.


In Blitz, you can use Java, C ++, C # or Python. In addition, participation in the contest gives you the opportunity to test your knowledge. If in the end you understand that they should be tightened - this is also the result. By the way, then specialization on the Algorithms and Data Structures cursor, in the creation of which Yandex participated, may be useful to you.


image


Let's now analyze the tasks that were proposed in the qualifying round. We had several variants of the same complexity, each of which contained six tasks. We will analyze one set of tasks completely, as well as the most interesting tasks from other sets. By the way, out of 1,762 participants in the qualifying round, only 263 passed to the final. So the tasks were not the easiest.


"A game"


Condition


Petya and Vasya play a game: they take turns taking cards from the deck, on which are written non-recurring positive numbers (Petya always takes the first card). Players take cards one by one from the top of the deck. After that, they compare the values ​​recorded on the cards: the player who has less pulls another card and leaves it. When all the cards end, Petya and Vasya count the sum of the values ​​written on these cards. Loses one who has the amount obtained is less than that of another player.


They are tired of manually drawing cards and comparing values. They asked you to write a program that, according to the initial set of cards, will determine the winner.


It is guaranteed that for any test the winner can be determined unequivocally.


Extra options

Input Format


The first line of the input contains an integer n a multiple of three is the total number of cards (3 leqn leq999) .


The next line contains n different positive integers ai - values ​​written on cards in the order in which Petya and Vasya will distribute them (1 leqai leq1000) .


Output format


In the only line print Petya, if Petya wins the game, or Vasya, if Vasya wins the game.


Examples


InputConclusion
  3
 1 2 3 
  Petya 
InputConclusion
  3
 1 4 2 
  Vasya 

Time limit: 2 seconds


Memory Limit: 64 MB


Decision


Perhaps the easiest way to solve this problem is to simulate a game on a given sequence of numbers. As long as we still have input data, we’ll get three numbers from the input stream, add the first number to Peti’s total points, and the second one to Vasya’s total points. After that, compare two numbers taken from the input stream. If the first is less than the second, then we will add the third number to Petit's points, and if the second is less than the first, we will add the third to Vasya's points. When the input data is finished, let's compare the total number of points scored and find the winner. The solution of the problem is simplified by the fact that all the input data is correct and so-called border situations cannot arise when, for example, the number of points on the cards stretched by the players is the same or when both participants score the same number of points at the end of the game.


“Complicated Numbers”


Condition


Denote by S(n) sum of digits of a natural number n .


Let's say that a natural number n complex if there is no such natural number k, what


n= frac3kS(k)2.


Find the smallest complex number.


Decision


Here you can come up with a mathematical solution, but all we have to do is find the smallest number that satisfies the condition of the problem. At the same time, neither the proof nor the code need to be written, and we do not have much time for the remaining tasks. Therefore, instead of searching for an informed solution, you can use brute force. Here is one of the choices: search the value of the function for all k from 1 to a certain limit (for example, to a million) and, if it is an integer, remember what a number is n definitely will not be difficult. Then, we derive the smallest positive integer that we did not remember in the process of calculating our function. In our example, this will be the number 61.


"Standings"


Condition


Many programmers love to play football. Some even like to hold their tournaments. But they do not want to keep track of who scored points and how many places they took, they just want to add the results of the matches to the database, and then get the standings with the number of points scored and the final position.


One of these groups of programmers asked you to help them and, while they are assembling teams and conducting their own tournament, write a program that will build the final standings.


Extra options

Input Format


Input data is a set of lines, each line describes exactly one match played. Each line contains the names of teams playing with each other and the result of the match. The names and the result are separated by a dash, which is broken off on both sides by spaces. Each name consists only of Latin letters, begins with a capital letter, all other letters are lowercase, it is guaranteed that the length of each name does not exceed 30 characters. The score is recorded as A: B, where A is the number of goals scored by the first team, and B is the number of goals scored by the second team. The winning team is scored more goals. If the same number of goals is scored, the result of the match is considered a draw. For winning the team is awarded three points, for a draw - one, for defeat - zero.


It is guaranteed that there is not a single pair of teams with the same name, that no pair of teams played each other more than once. The total number of participating teams does not exceed 100. More than one hundred goals were not scored in any match.


Output format


You need to build a standings with the results.


Each row of the table is a presentation of the results of each of the commands; commands must be ordered in lexicographical order. The first column contains the ordinal number of the command, the second - the name. Followed by n columns, each of which contains information about games with other teams: in case of victory, the letter W must be present in the cell, in case of defeat - L, in case of a draw - D, if participants did not play with each other - a space, if the match cell is filled the player with himself, then there should put the character X.


The last two columns should be written out the number of points scored by the team and the final place. Team A takes a higher place than Team B if it scored more points, or they both scored the same number of points, but Team A scored more victories than Team B. If the same number of points and number of wins the teams have is the same, they take same place. For ease of rewarding is required to award only places from first to third.


All columns must have the smallest possible width to fit the data in each row. For columns containing ordinal numbers, the number of points scored and occupied places, all data are right aligned, all titles are aligned to the left, after each name there must be a space in the table.


Making the table, focus on examples.


Examples


InputConclusion
  Linux - Gentoo - 1: 0
 Gentoo - Windows - 2: 1
 Linux - Windows - 0: 2 
  + - + -------- + - + - + - + - + - +
 | 1 | Gentoo | X | L | W | 3 | 1 |
 + - + -------- + - + - + - + - + - +
 | 2 | Linux | W | X | L | 3 | 1 |
 + - + -------- + - + - + - + - + - +
 | 3 | Windows | L | W | X | 3 | 1 |
 + - + -------- + - + - + - + - + - + 

InputConclusion
  Cplusplus - C - 1: 0
 Cplusplus - Php - 2: 0
 Java - Php - 1: 0
 Java - C - 2: 2
 Java - Perl - 1: 1
 Java - Haskell - 1: 1 
  + - + ---------- + - + - + - + - + - + - + - + - +
 | 1 | C | X | L |  | D |  |  | 1 | 3 |
 + - + ---------- + - + - + - + - + - + - + - + - +
 | 2 | Cplusplus | W | X |  |  |  | W | 6 | 1 |
 + - + ---------- + - + - + - + - + - + - + - + - +
 | 3 | Haskell |  |  | X | D |  |  | 1 | 3 |
 + - + ---------- + - + - + - + - + - + - + - + - +
 | 4 | Java | D |  | D | X | D | W | 6 | 2 |
 + - + ---------- + - + - + - + - + - + - + - + - +
 | 5 | Perl |  |  |  | D | X |  | 1 | 3 |
 + - + ---------- + - + - + - + - + - + - + - + - +
 | 6 | Php |  | L |  | L |  | X | 0 |  |
 + - + ---------- + - + - + - + - + - + - + - + - + 

Time limit: 2 seconds


Memory Limit: 64 MB


Decision


In the programmer's work, such tasks are often encountered when it is necessary to obtain data that has some pre-negotiated format, and to give the result in the form in which the next element of the conveyor waits for it to enter. This task is about correct data processing and their output in the right format. The main difficulty here is to write the input parser and storage. The parser accepts a string as input and saves the results of the game between two teams, and the repository contains the names of the teams and the results.


Due to the rather small amount of input data, it is possible to use not complex structures, but standard mechanisms of any of the available languages. For example, when using C ++, the std::map container is suitable. The key in the container will be the name of the team, and the value will be information about it: the number of points scored, the number of victories and the results of games with other teams. The results can also be stored in std::map , where the key is the name of the opponent, and the value is the result of the match.


Divide each of the rows of the input stream and update the information about each of the participants. std::map , chosen as the repository, allows us to store all the names in lexicographical order, so for the formation of the final table we just need to iterate over the repository elements. When the entire input stream is processed, we calculate the final position of each of the participants: select all pairs of the type “number of points - the number of wins” and arrange them in descending order, arranging the corresponding places for the first three results. In addition, during post-processing, we can calculate the required number of characters for each of the columns of the resulting table, and then carefully implement the output of the table to the output stream.


"Wallets and coins"


Condition


Programmer Peter loves to put all his money in wallets and record how much money is in each wallet. To do this, he saves in the file a set of positive integers - the amount of money that lies in each of his wallets (Peter doesn’t like it when at least one of his wallets is empty). Peter keeps all the money in coins, the denomination of each coin is 1 conventional unit.


Once, Peter had a block of magnetic heads broken and he had to recover data from a hard disk. He wants to check whether the data has been correctly restored, and asks you to make sure that the amount of money he had can be decomposed into all of his wallets so that the same numbers as in the recovered file are obtained.


Extra options

Input Format


The first line of the output contains a natural number n(1 leqn leq100) - The number of wallets in Petit.


The second line contains the data from the recovered file separated by a space: n natural numbers ai each of which means how much money lies in i the purse of Petit (1 leqai leq100) .


The third line contains a natural number. m(1 leqm leq104) - The total amount of money that Petya had before he laid it out in purses.


Output format


If there is no error in the restored file, and the initial amount can be expanded into purses with the specified configuration, output Yes. If such a configuration cannot exist, output No.


Examples


InputConclusion
  2
 2 3
 five 
  Yes 

InputConclusion
  2
 2 3
 four 
  No 

InputConclusion
  2
 2 3
 3 
  Yes 

Notes


In the first example, Petit has two purses, in the first one there are two coins, in the second - three. The configuration given in the second example cannot exist, therefore the file was not correctly restored. In the third example, the proposed configuration is possible: in the second wallet there is one coin and the first wallet, inside which there are two coins.


Time limit: 2 seconds


Memory Limit: 64 MB


Decision


It was necessary to understand that several other wallets may lie in the wallet, where, in turn, there are coins. One of the test examples clearly showed the possibility of such a situation. With this in mind, the task is quite easily reduced to the well-known problem of a backpack , which is solved by the method of dynamic programming. Take the most roomy wallet and fill it with coins. If this cannot be done (that is, the number of coins is less than it is necessary to put in the largest wallet) - there is no way to put the coins into wallets. If we managed to fill the biggest wallet - take all the remaining coins and try to find a way to expand them on the remaining wallets. Here we are - just like in the task about the backpack - we make a choice. Only there we would choose whether to put another item in a backpack.


Restrictions allow us to allocate memory for an array whose size is equal to the remaining number of coins. Then check each remaining wallet to see if we can fill it with the remaining number of coins. If there is a way to distribute coins over a certain subset of wallets, then we will put all unused wallets into the largest one, after having transferred the necessary amount of coins from them to it. If the remaining coins cannot be distributed among a subset of the remaining wallets, there is no successful configuration.


"Good Sequence"


Condition


A sequence of points on a plane is called trivial if it is strictly ordered in ascending or descending order of distance to one of the points of this sequence.


A sequence of points in three-dimensional space is called good if none of the sequences obtained by taking the original projection on one of the base planes (Oxy,Oyz and Oxz), not trivial.


Given a sequence of n points with integer coordinates in three-dimensional space. It is necessary to find such an odd permutation of its indices, that after its application the sequence becomes good.


It is guaranteed that a solution exists.


Extra options

Input Format


The first line of the input contains an integer n(3 leqn leq1000) in the following n lines separated by a space of three integer coordinates xi,yi,zi(104 leqxi,yi,zi leq104) each of the points.


It is guaranteed that the projections of all points on any of the base planes are different.


Output format


Output n numbers: the desired permutation of indices from 1 to n . If there are several solutions, output any of them. Numbers in the string should be separated by spaces.


Examples


InputConclusion
  four
 1 1 1
 2 4 16
 3 9 81
 4 16 256 
  1 2 4 3 

Notes


Inversion permutation p order n called every pair of indices (i,j) such that 1 leqi<j leqn and pi>pj . The parity of the number of inversions in a permutation determines the parity of the permutation.


Time limit: 2 seconds


Memory Limit: 64 MB


Decision


For the correct solution of the problem, it is quite enough for us to estimate how many trivial permutations exist. In each of the planes their number is proportional to O(n) where n - the total number of points. So, everything in their space will be O(n3) . In this case, the total number of permutations, which can serve as a correct answer, is equal to n!/2 (the division is due to the fact that we only need odd permutations). It turns out that unsuitable answers are much less than those that suit us. Therefore, we can simply iterate through the odd permutations. The answer will be the first permutation, which is not trivial when constructing its projection on any of the three planes.


"An interesting journey"


Condition


It is no secret that some programmers love to travel. Well-known programmer Petya also enjoys traveling, visiting museums and seeing the sights of other cities.


To move from city to city, he prefers to use the car. At the same time, it refuels only at stations in cities, but not at stations along the way. Therefore, he very carefully selects the routes so that the car does not stall on the road. And Petya is a very important team member, so he cannot afford to travel for too long. He decided to write a program that will help him with the choice of the next trip. But since he now has too many other tasks, he asked you to help him.


The distance between two cities is calculated as the sum of the difference modules for each of the coordinates. Roads are between all pairs of cities.


Extra options

Input Format


The first line of the input data contains the number of cities. n ( 2 leqn leq1000 ). In the following n The lines contain two integers: the coordinates of each city, not exceeding in magnitude a billion. All cities are numbered from 1 to n in record order in the input.


The next line contains a positive integer. k , not exceeding two billion, is the maximum distance between cities that Petya can overcome without refueling the car.


The last line contains two different numbers - the number of the city where Peter comes from, and the number of the city where he goes.


Output format


If there are paths that meet the conditions described above, then output the minimum number of roads that you need to go to get from the starting point of the route to the final one. If the path does not exist, output -1.


Examples


InputConclusion
  7
 0 0
 0 2
 2 2
 0 -2
 2 -2
 2 -1
 2 1
 2
 13 
  2 

InputConclusion
  four
 0 0
 ten
 0 1
 eleven
 2
 14 
  one 

InputConclusion
  four
 0 0
 20
 0 2
 2 2
 one
 14 
  -one 

Time limit: 1 second


Memory Limit: 64 MB


Decision


First, from the existing points you need to build a graph. To do this, let's iterate through all pairs of points and, if the distance between them is less than the specified limit, add an edge between the vertices to the graph. After constructing the graph, we will launch a search wide from the city, from where Peter begins his journey. As soon as it reaches the destination point, we complete our algorithm and derive the number of edges we have passed. If the algorithm is completed, and we have not reached the destination, then it is not reachable from the source city, so you should output -1. The total complexity of the described algorithm is O(n2) where n - the number of cities.


"Splitting number"


Condition


Given the number n . Break decimal notation n to the maximum possible number of different numbers.


Using numbers with insignificant zeros is not allowed.


Extra options

Input Format


The only input line is a number n ( 0 leqn leq1019 ).


Output format


Print the split number n into different parts. Between parts put a sign "-". If there are several possible partitions, output any.


Examples


InputConclusion
  0 
  0 

InputConclusion
  101 
  10-1 

InputConclusion
  102 
  1-0-2 

InputConclusion
  eleven 
  eleven 

Time limit: 2 seconds


Memory Limit: 64 MB


Decision


Despite the fact that the initial number can be very large, the number of ways to break it apart depends not on the value, but on the number of characters in the number. In the worst case, the number consists of 18 decimal places (we don’t consider option 10 19 - there’s only one partitioning option). Hence, the “-” sign can only be put in 17 different positions. In each of these positions, we can both put a sign and lower it. In other words, there are only 2 17 ways to choose a partition for the largest numbers. These are about 10 5 options. We will sort them all, cut off those that do not suit us (that is, which give the same numbers), and choose the variant containing the largest number of parts.


“Maximum damage”


Condition


Programmer Igor loves to play computer games. Most of all, Igor likes strategies, especially those moments when he sends groups of his units to attack enemy bases. Igor has been playing strategy for a long time, so he has a well-developed plan of action for the attack: he breaks up all his units into groups and sends them to the attack in turn. At the same time, Igor believes that the total damage that will be inflicted in the attack is equal to the product of the size of the groups. He tries to split his units into groups so as to maximize total damage.


Recently, Igor began to often lose. He is sure that the problem is that in one of the groups, after splitting, an unlucky number of units is obtained. He is trying to remake his partitioning algorithm and asked you to calculate what maximum total damage his group can inflict if there is not one among them containing an unlucky number of units.


Extra options

Input Format


The single line of the input data contains natural numbers separated by spaces. n and a(1 leqn,a leq106,n neqa) - the number of units that Igor has and the number of units in the group that Igor considers unlucky.


Output format


Output the maximum possible total damage modulo 10 9 + 7.


Examples


InputConclusion
  8 2 
  sixteen 

InputConclusion
  9 3 
  20 

Notes


In the first example, in order to maximize the total damage, the units should be divided into two groups of 4 units each, in the second example into two groups: in the first 4 units, in the second - 5.


Time limit: 2 seconds


Memory Limit: 64 MB


Decision


If it were not for an additional ban on the use of groups of a certain size, which in the condition is called unlucky, then the product would be maximal when splitting the original number into groups of 3 units. If the total number of units is divided into 3, we simply divide them into groups of 3 units. If the remainder of dividing by 3 is 1, then we separate a group of four units (unless, of course, initially we have more than one unit), and in the other groups we define 3 units each. And finally, if the remainder of dividing by 3 is 2, we separate a group of two units, and in the rest we define 3 units each.


We prove that such a partition is correct. Let's try to prove it by the opposite. Suppose first that there are numbers in our partition x ≥ 5. But then we can replace x two numbers: x -3 and 3. The total amount of the replacement will not affect, and the product of the numbers 3 and x -3 is always more than x at x ≥ 5. So numbers that are greater than or equal to 5 in our sequence cannot exist. Suppose it has the number 4, but we can replace it with two deuces without affecting the values ​​of the sum and the product, so let's do it. Further, in our sequence there can be no more than two twos, otherwise we could replace any three of them with two triples. The value of the sum of this would not change, and the value of the product would increase (8 = 2⋅2⋅2 <3⋅3 = 9). Consequently, three or more twos cannot be either. Well, and besides, we can not have units (only if the initial amount itself is not equal to one). Thus, our resulting sequence can consist only of triples and no more than two twos, as we showed above.


Let us return to the restriction on the unlucky size of the group. If it exceeds the value of 3 - our solution will remain exactly the same. If it is 3, then, going through the small sizes of groups manually, we will divide the sequence into groups of size 2. If the number of units is initially odd, then we additionally take a group consisting of 5 units (since one group of size 5 will provide a greater final value than 2 groups 2 units each and one group of one unit). If group sizes equal to 2 are excluded, then we use the algorithm of division into groups of 3 units. Finally, if their initial number is not divisible by 3, we take as the size of additional groups not 2, but 4 units.


"Red-black trees"


Condition


A red-ebony tree is a tree, in which all the vertices are painted red or black and there are additional properties:



Find the number of non-isomorphic red-black trees with a given number of vertices. Two red-black trees T1 and T2 are isomorphic if there is a bijection between the vertices of the trees f:V(T1) rightarrowV(T2) satisfying the conditions:



Extra options

Input Format


The first line contains the number of tree vertices. n ( 1 leqn leq1000 ).


Output format


Print the number of non-isomorphic red-black trees with n vertices modulo 10 9 + 7.


Examples


InputConclusion
  five 
  one 

InputConclusion
  7 
  2 

InputConclusion
  6 
  0 

Time limit: 2 seconds


Memory Limit: 256 MB


Decision


The problem can be solved by dynamic programming, but it is a bit more complicated than the tasks that we solved by the same method above.


Denote as Countblack[n][h] the number of different black-root red-black trees up to isomorphism, which consist of N vertices and in which the number of black vertices from root to leaf is H . Behind Countred[n][h] we denote the same trees with a red root. This will violate the black root property of red-black trees, but we need this assumption to calculate the result.


How to calculate the value Countblack[n][h] ? The root of it can be any number. i from 1 to N . Then the left subtree will contain i1 top, and in the right - j=Ni vertices. How many subtrees can be in the left subtree? If its root is black, then the number of subtrees is CountBlack[i1][H1] , and if red, then CountRed[i1][H1] . : CountBlack[j][H1] , , CountRed[j][H1] , . , : CountLeft=CountBlack[i1][H1]+CountRed[i1][H1] and CountRight=CountBlack[j][H1]+CountRed[j][H1]. , i . , i1j . If a i1<j , CountBlack[N][H] : CountLeftCountRight . ( i1=j ), CountLeft(CountLeft+1)/2 .


CountRed[N][H] , . -, , . -, , . , i , CountBlack[i1][H] , — CountBlack[j][H] . .


, CountBlack[N][H] H . . , , H=2log(N)20 . H 1 20 CountBlack[N][H] . .


« »


Condition


k n , m .


, k , .


Extra options


n and m ( 1n1000 , 1m100 ).


m n numbers i - , i - .


k ( 1k5104 ). k 1 m — .



k , .


Examples


Conclusion
  3 2
1 3 2
2 3 1
 3
1 2 1 
  3
 one
 2 

Conclusion
  2 2
 12
 2 1
 3
1 2 1 
  2
 one
 2 

Conclusion
  eleven
 one
 one
 one 
  one 

: 2


: 128


Decision


prefix[i] , i - , k permutations. Behind suffix[i] , , , i - k -. , , prefix[i1] , prefix[i] , prefix[i1]i - . — O(n) where n — . , prefix[i] for i 1 k O(nk) . suffix[i] , , suffix[i] suffix[i+1] to i - . , , j - , prefix[j1] suffix[j+1] . prefix[0] and suffix[k+1] j 1 k , . j O(n) , — O(nk) .


« »


Condition


n .


. , , , , .


, .


Extra options


n(1n100000) — . n i - xi,yi(|xi|109,|yi|109) . .



, .


Examples


Conclusion
  one
 -eleven 
  one 

Conclusion
  3
 -eleven
 0 0
 eleven 
  2 

Conclusion
  five
 0 1
1 0
 eleven
 2 1
 3 2 
  2 

: 2


: 64


Decision


. , , . 4 , — . , . , . .


« »


Condition


n a1,a2,,an . , : .


?


Extra options


n ( 1n1000 ). n ai ( 1ai109 ).



, .


Examples


Conclusion
  2
 eleven 
  0 

Conclusion
  3
9 6 3 
  3 

Conclusion
  6
1000000000 1000000000 1000000000 1000000000 1000000000 1 
 4999999995 

: 2


: 64


Decision


Let be a — . , , 2a , . , , , 2a . a, , 2a , , , 2a . , 2a , , . , . . S . Then S2na , aS/(2n) . , 11/(2n) time. O(nlog(Mn)) , M — .


')

Source: https://habr.com/ru/post/340784/


All Articles