question_text
stringlengths
2
3.82k
input_outputs
stringlengths
23
941
algo_tags
sequence
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all 26 lowercase Latin letters will be arranged in some order.Polycarp uses the same password s on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in s, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in s, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?
Input: ['5', 'ababa', 'codedoca', 'abcda', 'zxzytyz', 'abcdefghijklmnopqrstuvwxyza', ''] Output:['YES', 'bacdefghijklmnopqrstuvwxyz', 'YES', 'edocabfghijklmnpqrstuvwxyz', 'NO', 'YES', 'xzytabcdefghijklmnopqrsuvw', 'NO', '']
[ 2 ]
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are g days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next b days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again g good days, b bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1, 2, ..., g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n = 5 then at least 3 units of the highway should have high quality; if n = 4 then at least 2 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?
Input: ['3', '5 1 1', '8 10 10', '1000000 1 1000000', ''] Output:['5', '8', '499999500000', '']
[ 3 ]
This is an unusual problem in an unusual contest, here is the announcement: http://codeforces.com/blog/entry/73543You have the safe lock which consists of 5 decimal digits. If you rotate some digit, it increases by one, except 9 which becomes 0.Initially, the lock contains number x. To unlock the safe you must do the following operations in order (and be careful, don't mix up if and else statements).If sum of digits on positions 1 and 4 is greater than 10, rotate digit on position 1 by 3 times, else rotate digit on position 4 by 8 times.If sum of digits on positions 3 and 2 is greater than 8, rotate digit on position 4 by 9 times, else rotate digit on position 5 by 8 times.If digit on position 3 is odd, rotate digit on position 3 by 3 times, else rotate digit on position 3 by 4 times.If digit on position 5 is greater than digit on position 2, rotate digit on position 4 by 1 times, else rotate digit on position 2 by 7 times.If digit on position 1 is odd, rotate digit on position 1 by 3 times, else rotate digit on position 3 by 5 times.If digit on position 4 is odd, rotate digit on position 4 by 7 times, else rotate digit on position 1 by 9 times.If digit on position 4 is greater than digit on position 1, rotate digit on position 4 by 9 times, else rotate digit on position 4 by 2 times.If digit on position 1 is greater than digit on position 3, rotate digit on position 2 by 1 times, else rotate digit on position 3 by 1 times.If digit on position 5 is greater than digit on position 3, rotate digit on position 4 by 5 times, else rotate digit on position 5 by 8 times.If sum of digits on positions 1 and 3 is greater than 8, rotate digit on position 4 by 5 times, else rotate digit on position 2 by 5 times.If digit on position 1 is greater than digit on position 4, rotate digit on position 4 by 3 times, else rotate digit on position 2 by 3 times.If sum of digits on positions 3 and 1 is greater than 9, rotate digit on position 2 by 9 times, else rotate digit on position 2 by 2 times.If sum of digits on positions 4 and 3 is greater than 10, rotate digit on position 4 by 7 times, else rotate digit on position 5 by 7 times.If digit on position 3 is greater than digit on position 2, rotate digit on position 3 by 2 times, else rotate digit on position 4 by 6 times.If digit on position 1 is greater than digit on position 3, rotate digit on position 1 by 9 times, else rotate digit on position 2 by 9 times.If digit on position 3 is odd, rotate digit on position 3 by 9 times, else rotate digit on position 1 by 5 times.If sum of digits on positions 3 and 5 is greater than 9, rotate digit on position 3 by 4 times, else rotate digit on position 3 by 9 times.If digit on position 3 is greater than digit on position 1, rotate digit on position 5 by 1 times, else rotate digit on position 5 by 7 times.If digit on position 1 is greater than digit on position 3, rotate digit on position 2 by 9 times, else rotate digit on position 4 by 6 times.If sum of digits on positions 2 and 3 is greater than 10, rotate digit on position 2 by 2 times, else rotate digit on position 3 by 6 times.
Input: ['00000', ''] Output:['61376', '']
[ 0 ]
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0.Warawreh couldn't find the best option himself so he asked you for help, can you help him?
Input: ['5 5 5', 'RRGGB', 'RRGGY', 'YYBBG', 'YYBBR', 'RBBRG', '1 1 5 5', '2 2 5 5', '2 2 3 3', '1 1 3 5', '4 4 5 5', ''] Output:['16', '4', '4', '4', '0', '']
[ 4 ]
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 <=q l <=q r <=q |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, ..., s_r is equal to "1". For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input: ['5', '3 1', '3 2', '3 3', '4 0', '5 2', ''] Output:['4', '5', '6', '0', '12', '']
[ 2, 3, 4 ]
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer k (0 <=q k <=q 10^{9}) and replaces all missing elements in the array a with k.Let m be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |a_i - a_{i+1}| for all 1 <=q i <=q n - 1) in the array a after Dark replaces all missing elements with k.Dark should choose an integer k so that m is minimized. Can you help him?
Input: ['7', '5', '-1 10 -1 12 -1', '5', '-1 40 35 -1 35', '6', '-1 -1 9 -1 3 -1', '2', '-1 -1', '2', '0 -1', '4', '1 -1 3 -1', '7', '1 -1 7 5 2 -1 5', ''] Output:['1 11', '5 35', '3 6', '0 42', '0 0', '1 2', '3 4', '']
[ 2, 4, 4 ]
Reminder: the median of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}.There are 2n students, the i-th student has skill level a_i. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 2 classes such that each class has odd number of students (not divisible by 2). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?
Input: ['3', '1', '1 1', '3', '6 5 4 1 2 3', '5', '13 4 20 13 2 5 8 3 17 16', ''] Output:['0', '1', '5', '']
[ 2 ]
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 <= i <= n) and do a_i := a_i + 1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a_1 + a_2 + ... + a_n!=0 and a_1 \cdot a_2 \cdot ... \cdot a_n!=0.
Input: ['4', '3', '2 -1 -1', '4', '-1 0 0 1', '2', '-1 2', '3', '0 -2 1', ''] Output:['1', '2', '0', '2', '']
[ 3 ]
This problem is interactive.We have hidden a permutation p_1, p_2, ..., p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries:? k a_1 a_2 ... a_k.In response, you will learn if the average of elements with indexes a_1, a_2, ..., a_k is an integer. In other words, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. You have to guess the permutation. You can ask not more than 18n queries.Note that permutations [p_1, p_2, ..., p_k] and [n + 1 - p_1, n + 1 - p_2, ..., n + 1 - p_k] are indistinguishable. Therefore, you are guaranteed that p_1 <= \frac{n}{2}.Note that the permutation p is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.
Input: ['2', '1 2', ''] Output:['? 1 2', '? 1 1', '! 1 2 ', '']
[ 3 ]
Guy-Manuel and Thomas are planning 144 trips around the world.You are given a simple weighted undirected connected graph with n vertexes and m edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 3 which passes through the vertex 1. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 0 aren't exciting. You may choose any subset of edges incident to the vertex 1 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 0 which passes through the vertex 1 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 10^9+7.
Input: ['6 8', '1 2 0', '2 3 1', '2 4 3', '2 6 2', '3 4 8', '3 5 4', '5 4 5', '5 6 6', ''] Output:['2', '']
[ 3 ]
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.You can perform the following operation: choose some subsegment [l, r] (1<= l <= r <= n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b.
Input: ['4', '7 5 5 7', ''] Output:['5.666666667', '5.666666667', '5.666666667', '7.000000000', '']
[ 2 ]
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the bitwise OR operation. For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input: ['4', '4 0 11 6', ''] Output:['11 6 4 0']
[ 0, 2, 3 ]
For a given positive integer m, a positive number is called a m-number if the product of its digits is m. For example, the beginning of a series of 24-numbers are as follows: 38, 46, 64, 83, 138, 146, 164, 183, 226 ...You are given a positive integer m and k. Print k-th among m-numbers if all m-numbers are sorted in ascending order.
Input: ['24 9', ''] Output:['226', '']
[ 3 ]
Recently, Polycarp has been a fan of cinema novelties and is trying not to miss them!In the near future, n new movies will be released: the i-th of them will be airing from the day a_i and to the day b_i. This means that if Polycarp wants to watch the i-th movie in the cinema, he must do so in the period from a_i to b_i inclusive.If perhaps Polycarp will not have the opportunity to watch a movie in a cinema, he can then do it after day b_i by watching it using an online service. Of course, this is an undesirable outcome for Polycarp because the whole world will have time to discuss this movie on social networks!Polycarp can watch no more than m movies per day. Help Polycarp find a movie-watching schedule such that every movie will be watched in the cinema. If such a schedule does not exist, then Polycarp wants to watch movies so that: for each movie that he doesn't have time to watch in the cinema, we will find the number of days between the end of its airing and the day when Polycarpus watches the movie, the maximum of the values from the previous point should be as small as possible.
Input: ['3', '7 2', '1 2', '1 3', '2 2', '2 3', '1 1', '2 3', '1 2', '5 3', '1 1', '1 1', '1 1', '1 1', '1 1', '6 1', '13 13', '31 31', '25 25', '12 12', '14 14', '10 10', ''] Output:['1', '1 3 2 3 1 4 2 ', '1', '1 1 1 2 2 ', '0', '13 31 25 12 14 10 ', '']
[ 2 ]
For the first time, Polycarp's startup ended the year with a profit! Now he is about to distribute k burles as a bonus among n employees.It is known that the current salary of the i-th employee is a_i and all the values of a_i in the company are different.Polycarp wants to distribute the k burles between n employees so this month the i-th employee will be paid not a_i, but a_i+d_i (d_i >= 0, d_i is an integer), where d_i is the bonus for the i-th employee. Of course, d_1+d_2+...+d_n=k.Polycarp will follow two rules for choosing the values d_i: the relative order of the salaries should not be changed: the employee with originally the highest salary (a_i is the maximum) should have the highest total payment after receiving their bonus (a_i+d_i is also the maximum), the employee whose salary was originally the second-largest should receive the second-largest total payment after receiving their bonus and so on. to emphasize that annual profit is a group effort, Polycarp wants to minimize the maximum total payment to an employee (i.e minimize the maximum value of a_i+d_i). Help Polycarp decide the non-negative integer bonuses d_i such that: their sum is k, for each employee, the number of those who receive strictly more than them remains unchanged (that is, if you sort employees by a_i and by a_i+d_i, you get the same order of employees), all a_i + d_i are different, the maximum of the values a_i+d_i is the minimum possible. Help Polycarp and print any of the possible answers d_1, d_2, ..., d_n.
Input: ['5', '4 1', '3 1 4 2', '2 3', '10 2', '4 1000000000', '987654321 1000000000 999999999 500000000', '8 9', '5 6 1 8 3 4 2 7', '6 1', '6 3 1 8 5 9', ''] Output:['0 0 1 0 ', '0 3 ', '134259259 121913582 121913582 621913577 ', '2 2 0 2 0 1 0 2 ', '1 0 0 0 0 0 ', '']
[ 2, 4 ]
Polycarp is the project manager in the IT-company. Right now, he needs to choose developers for his team to start a new project. The company has n developers "on the bench" (i.e not involved in other projects). Polycarp assessed the skills of each of them: a_i (-10^4 <= a_i <= 10^4) — an integer characteristic of the i-th developer. This value can be either positive, zero or even negative (some developers cause distractions).After Polycarp chooses a subset of developers for his team, the strength of the team will be determined by the sum of a_i values for all selected developers.Polycarp fears that if he chooses a team in such a way that maximizes the sum of the characteristics of a_i, other managers may find this unacceptable. For this reason, he plans to create such a team that the sum of the a_i values for it is strictly less than the maximum possible value.Help Polycarp choose any team that: the sum of the characteristics a_i for all members of the selected team is strictly less than the maximum value that can be achieved by choosing the team in some other way and at the same time, the sum of the characteristics of a_i for all members of the selected team is the greatest possible. If, following the requirements above, you can select a team in several ways, then just find any of them. It's guaranteed that the sum of the characteristics in the desired subset is strictly positive (i.e. Polycarp can always choose a non-empty team).
Input: ['5', '5', '1 -1 1 -1 1', '2', '11 1', '3', '5 -3 4', '3', '5 3 -4', '5', '-1 0 3 -3 0', ''] Output:['2', '11101', '11', '10', '6', '111', '5', '100', '2', '10100', '']
[ 2 ]
There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive.You asked m passengers some questions: the j-th one told you three values: his departure station a_j; his arrival station b_j; minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist.
Input: ['4', '1 2', '3 2', '3 4', '2', '1 2 5', '1 3 3', ''] Output:['5 3 5', '']
[ 2 ]
This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string s consisting of n lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in s).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.
Input: ['9', 'abacbecfd', ''] Output:['YES', '001010101', '']
[ 2 ]
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 0.The fight with a monster happens in turns. You hit the monster by a hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by b hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most k times in total (for example, if there are two monsters and k=4, then you can use the technique 2 times on the first monster and 1 time on the second monster, but not 2 times on the first monster and 3 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.
Input: ['6 2 3 3', '7 10 50 12 1 8', ''] Output:['5', '']
[ 2 ]
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 <= x <= s, buy food that costs exactly x burles and obtain \lfloor\frac{x}{10}\rfloor burles as a cashback (in other words, Mishka spends x burles and obtains \lfloor\frac{x}{10}\rfloor back). The operation \lfloor\frac{a}{b}\rfloor means a divided by b rounded down.It is guaranteed that you can always buy some food that costs x for any possible value of x.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19 burles then the maximum number of burles he can spend is 21. Firstly, he can spend x=10 burles, obtain 1 burle as a cashback. Now he has s=10 burles, so can spend x=10 burles, obtain 1 burle as a cashback and spend it too.You have to answer t independent test cases.
Input: ['6', '1', '10', '19', '9876', '12345', '1000000000', ''] Output:['1', '11', '21', '10973', '13716', '1111111111', '']
[ 3 ]
You are given an array a consisting of n integers.In one move, you can choose two indices 1 <= i, j <= n such that i!=j and set a_i := a_j. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose i and j and replace a_i with a_j).Your task is to say if it is possible to obtain an array with an odd (not divisible by 2) sum of elements.You have to answer t independent test cases.
Input: ['5', '2', '2 3', '4', '2 2 8 8', '3', '3 3 3', '4', '5 5 5 5', '4', '1 1 1 1', ''] Output:['YES', 'NO', 'YES', 'NO', 'NO', '']
[ 3 ]
You are given two integers a and m. Calculate the number of integers x such that 0 <= x < m and \gcd(a, m) = \gcd(a + x, m).Note: \gcd(a, b) is the greatest common divisor of a and b.
Input: ['3', '4 9', '5 10', '42 9999999967', ''] Output:['6', '1', '9999999966', '']
[ 3 ]
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z = ac, s = abcde, you may turn z into following strings in one operation: z = acace (if we choose subsequence ace); z = acbcd (if we choose subsequence bcd); z = acbce (if we choose subsequence bce). Note that after this operation string s doesn't change.Calculate the minimum number of such operations to turn string z into string t.
Input: ['3', 'aabce', 'ace', 'abacaba', 'aax', 'ty', 'yyt', ''] Output:['1', '-1', '3', '']
[ 2 ]
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss ... For example, if s = 10010, then t = 100101001010010...Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal to cnt_{0, q} - cnt_{1, q}, where cnt_{0, q} is the number of occurrences of 0 in q, and cnt_{1, q} is the number of occurrences of 1 in q. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
Input: ['4', '6 10', '010010', '5 3', '10101', '1 0', '0', '2 0', '01', ''] Output:['3', '0', '1', '-1', '']
[ 3 ]
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 10 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 1, you have to turn on 2 segments of the screen, and if you want to display 8, all 7 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than n segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than n segments.Your program should be able to process t different test cases.
Input: ['2', '3', '4', ''] Output:['7', '11', '']
[ 2 ]
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.
Input: ['8', '1 2', '2 3', '3 4', '4 5', '4 6', '3 7', '3 8', ''] Output:['5', '1 8 6', '']
[ 2 ]
You are given a rectangular matrix of size n * m consisting of integers from 1 to 2 \cdot 10^5.In one move, you can: choose any element of the matrix and change its value to any integer between 1 and n \cdot m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some j (1 <= j <= m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n \cdot m (i.e. a_{i, j} = (i - 1) \cdot m + j) with the minimum number of moves performed.
Input: ['3 3', '3 2 1', '1 2 3', '4 5 6', ''] Output:['6', '']
[ 2, 3 ]
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array; for the array [1, 2, 3, 4] MEX equals to 0 because 0 is the minimum non-negative integer not presented in the array; for the array [0, 1, 4, 3] MEX equals to 2 because 2 is the minimum non-negative integer not presented in the array. You are given an empty array a=[] (in other words, a zero-length array). You are also given a positive integer x.You are also given q queries. The j-th query consists of one integer y_j and means that you have to append one element y_j to the array. The array length increases by 1 after a query.In one move, you can choose any index i and set a_i := a_i + x or a_i := a_i - x (i.e. increase or decrease any element of the array by x). The only restriction is that a_i cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of q queries (i.e. the j-th answer corresponds to the array of length j).Operations are discarded before each query. I.e. the array a after the j-th query equals to [y_1, y_2, ..., y_j].
Input: ['7 3', '0', '1', '2', '2', '0', '0', '10', ''] Output:['1', '2', '3', '3', '4', '4', '7', '']
[ 2, 3 ]
You are given one integer number n. Find three distinct integers a, b, c such that 2 <= a, b, c and a \cdot b \cdot c = n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer t independent test cases.
Input: ['5', '64', '32', '97', '2', '12345', ''] Output:['YES', '2 4 8 ', 'NO', 'NO', 'NO', 'YES', '3 5 823 ', '']
[ 2, 3 ]
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.He wants to distribute all these n coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives A coins to Alice, B coins to Barbara and C coins to Cerene (A+B+C=n), then a + A = b + B = c + C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all n coins between sisters in a way described above.You have to answer t independent test cases.
Input: ['5', '5 3 2 8', '100 101 102 105', '3 2 1 100000000', '10 20 15 14', '101 101 101 3', ''] Output:['YES', 'YES', 'NO', 'NO', 'YES', '']
[ 3 ]
3R2 - Standby for ActionOur dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are s (s > 0) opponents remaining and t (0 <= t <= s) of them make a mistake on it, JOE receives \displaystyle\frac{t}{s} dollars, and consequently there will be s - t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?
Input: ['1', ''] Output:['1.000000000000', '']
[ 2, 3 ]
Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor s of the building. On each floor (including floor s, of course), there is a restaurant offering meals. However, due to renovations being in progress, k of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
Input: ['5', '5 2 3', '1 2 3', '4 3 3', '4 1 2', '10 2 6', '1 2 3 4 5 7', '2 1 1', '2', '100 76 8', '76 75 36 67 41 74 10 77', ''] Output:['2', '0', '4', '0', '2', '']
[ 0, 4 ]
MisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string p. From the unencrypted papers included, Rin already knows the length n of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string s of an arbitrary length into the artifact's terminal, and it will return every starting position of s as a substring of p.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains \frac{7}{5} units of energy. For each time Rin inputs a string s of length t, the artifact consumes \frac{1}{t^2} units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?
Input: ['1', '4', '', '2 1 2', '', '1 2', '', '0', '', '1'] Output:['', '', '? C', '', '? CH', '', '? CCHO', '', '! CCHH', '', '']
[ 2, 3 ]
Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1, 2, 3, ...). The node with a number x (x > 1), is directly connected with a node with number \frac{x}{f(x)}, with f(x) being the lowest prime divisor of x.Vanessa's mind is divided into n fragments. Due to more than 500 years of coma, the fragments have been scattered: the i-th fragment is now located at the node with a number k_i! (a factorial of k_i).To maximize the chance of successful awakening, Ivy decides to place the samples in a node P, so that the total length of paths from each fragment to P is smallest possible. If there are multiple fragments located at the same node, the path from that node to P needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node P.
Input: ['3', '2 1 4', ''] Output:['5', '']
[ 2, 3 ]
INSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of n small gangs. This network contains exactly n - 1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 0 to n - 2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass S password layers, with S being defined by the following formula:S = \sum_{1 <=q u < v <=q n} mex(u, v)Here, mex(u, v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang u to gang v.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of S, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible S before he returns?
Input: ['3', '1 2', '2 3', ''] Output:['3', '']
[ 2 ]
THE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 0, with their coordinates defined as follows: The coordinates of the 0-th node is (x_0, y_0) For i > 0, the coordinates of i-th node is (a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y) Initially Aroma stands at the point (x_s, y_s). She can stay in OS space for at most t seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (x_s, y_s) to warp home.While within the OS space, Aroma can do the following actions: From the point (x, y), Aroma can move to one of the following points: (x-1, y), (x+1, y), (x, y-1) or (x, y+1). This action requires 1 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 0 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within t seconds?
Input: ['1 1 2 3 1 0', '2 4 20', ''] Output:['3']
[ 0, 2 ]
You're given an array a_1, ..., a_n of n non-negative integers.Let's call it sharpened if and only if there exists an integer 1 <= k <= n such that a_1 < a_2 < ... < a_k and a_k > a_{k+1} > ... > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4], [0, 1], [12, 10, 8] and [3, 11, 15, 9, 7, 4] are sharpened; The arrays [2, 8, 2, 8, 6, 5], [0, 1, 1, 0] and [2, 5, 6, 9, 8, 8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any i (1 <= i <= n) such that a_i>0 and assign a_i := a_i - 1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.
Input: ['10', '1', '248618', '3', '12 10 8', '6', '100 11 15 9 7 8', '4', '0 1 1 0', '2', '0 0', '2', '0 1', '2', '1 0', '2', '1 1', '3', '0 1 0', '3', '1 0 1', ''] Output:['Yes', 'Yes', 'Yes', 'No', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'No', '']
[ 2 ]
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer s, consisting of n digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 0 (do not delete any digits at all) and n-1.For example, if you are given s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \rightarrow 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 70 and is divisible by 2, but number itself is not divisible by 2: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
Input: ['4', '4', '1227', '1', '0', '6', '177013', '24', '222373204424185217171912', ''] Output:['1227', '-1', '17703', '2237344218521717191', '']
[ 2, 3 ]
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k >= 2 and 2k non-empty strings s_1, t_1, s_2, t_2, ..., s_k, t_k that satisfy the following conditions: If we write the strings s_1, s_2, ..., s_k in order, the resulting string will be equal to s; If we write the strings t_1, t_2, ..., t_k in order, the resulting string will be equal to t; For all integers i between 1 and k inclusive, s_i and t_i are anagrams of each other. If such strings don't exist, then t is said to be an irreducible anagram of s. Note that these notions are only defined when s and t are anagrams of each other.For example, consider the string s = "gamegame". Then the string t = "megamage" is a reducible anagram of s, we may choose for example s_1 = "game", s_2 = "gam", s_3 = "e" and t_1 = "mega", t_2 = "mag", t_3 = "e": On the other hand, we can prove that t = "memegaga" is an irreducible anagram of s.You will be given a string s and q queries, represented by two integers 1 <= l <= r <= |s| (where |s| is equal to the length of the string s). For each query, you should find if the substring of s formed by characters from the l-th to the r-th has at least one irreducible anagram.
Input: ['aaaaa', '3', '1 1', '2 4', '5 5', ''] Output:['Yes', 'No', 'Yes', '']
[ 4 ]
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the m-th position in the line. Before the process starts, you may choose up to k different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer x such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to x?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.
Input: ['4', '6 4 2', '2 9 2 3 8 5', '4 4 1', '2 13 60 4', '4 1 3', '1 2 2 1', '2 2 0', '1 2', ''] Output:['8', '4', '1', '1', '']
[ 0 ]
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.You have to choose two arrays a_i and a_j (1 <= i, j <= n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k \in [1, m] b_k = \max(a_{i, k}, a_{j, k}).Your goal is to choose i and j so that the value of \min \limits_{k = 1}^{m} b_k is maximum possible.
Input: ['6 5', '5 0 3 1 2', '1 8 9 1 3', '1 2 3 4 5', '9 1 0 3 7', '2 3 0 6 3', '6 4 1 7 0', ''] Output:['1 5', '']
[ 4 ]
You are given two integers A and B, calculate the number of pairs (a, b) such that 1 <= a <= A, 1 <= b <= B, and the equation a \cdot b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11) = 10011). a and b should not contain leading zeroes.
Input: ['31 114 2191 31415926'] Output:['1', '0', '1337', '']
[ 3 ]
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days optimizing the program, he will make the program run in <=ft\lceil \frac{d}{x + 1} \right\rceil days (<=ft\lceil a \right\rceil is the ceiling function: <=ft\lceil 2.4 \right\rceil = 3, <=ft\lceil 2 \right\rceil = 2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x + <=ft\lceil \frac{d}{x + 1} \right\rceil.Will Adilbek be able to provide the generated results in no more than n days?
Input: ['3', '1 1', '4 5', '5 11', ''] Output:['YES', 'YES', 'NO', '']
[ 0, 3, 4, 4 ]
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are n cards with k features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k = 4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.
Input: ['3 3', 'SET', 'ETS', 'TSE', ''] Output:['1']
[ 0 ]
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index i in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.
Input: ['1', '4', 'PPAP', ''] Output:['1', '']
[ 2 ]
To defeat Lord Voldemort, Harry needs to destroy all horcruxes first. The last horcrux is an array a of n integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations: choose an index i (1 <= i <= n), an integer x, and subtract x from a_i. choose two indices i and j (1 <= i, j <= n; i!=j), an integer x, and subtract x from a_i and x + 1 from a_j. Note that x does not have to be positive.Harry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.
Input: ['3', '1 10 100', ''] Output:['3', '']
[ 0, 3 ]
An infinitely long Line Chillland Collider (LCC) was built in Chillland. There are n pipes with coordinates x_i that are connected to LCC. When the experiment starts at time 0, i-th proton flies from the i-th pipe with speed v_i. It flies to the right with probability p_i and flies to the left with probability (1 - p_i). The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.Find the expected value of the duration of the experiment.Illustration for the first example
Input: ['2', '1 1 100', '3 1 0', ''] Output:['1', '']
[ 3 ]
This problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 3 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed <=ft\lceil 0.777(n+1)^2 \right\rceil (\lceil x \rceil is x rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.
Input: ['4', '', 'a', 'aa', 'a', '', 'cb', 'b', 'c', '', 'c'] Output:['? 1 2', '', '? 3 4', '', '? 4 4', '', '! aabc']
[ 0, 3 ]
This problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 3 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)^2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.
Input: ['4', '', 'a', 'aa', 'a', '', 'cb', 'b', 'c', '', 'c'] Output:['? 1 2', '', '? 3 4', '', '? 4 4', '', '! aabc']
[ 0, 3 ]
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. Illustration for the second example, the first integer is a_i and the integer in parentheses is c_iAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.Help him to restore initial integers!
Input: ['3', '2 0', '0 2', '2 0', ''] Output:['YES', '1 2 1 ']
[ 2 ]
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 2). For example, the complexity of 1 4 2 3 5 is 2 and the complexity of 1 3 5 7 6 4 2 is 1.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.
Input: ['5', '0 5 0 2 3', ''] Output:['2', '']
[ 2 ]
Given an array a, consisting of n integers, find:\max\limits_{1 <= i < j <= n} LCM(a_i,a_j),where LCM(x, y) is the smallest positive integer that is divisible by both x and y. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
Input: ['3', '13 35 77', ''] Output:['1001']
[ 4 ]
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l <= x <= r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100]; if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then: erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union; erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union; erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union; erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union. Thus, you are required to erase the third segment to get answer 2.Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input: ['3', '4', '1 4', '2 3', '3 6', '5 7', '3', '5 5', '5 5', '5 5', '6', '3 3', '1 1', '5 5', '1 5', '2 2', '4 4', ''] Output:['2', '1', '5', '']
[ 0 ]
Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, ..., a_n and challenged him to choose an integer X such that the value \underset{1 <=q i <=q n}{\max} (a_i \oplus X) is minimum possible, where \oplus denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of \underset{1 <=q i <=q n}{\max} (a_i \oplus X).
Input: ['3', '1 2 3', ''] Output:['2', '']
[ 0, 2 ]
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?
Input: ['2', ''] Output:['1 2', '']
[ 0, 3 ]
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l, r] (1 <= l <= r <= n) that does not include all of cupcakes (he can't choose [l, r] = [1, n]) and buy exactly one cupcake of each of types l, l + 1, ..., r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7, 4, -1]. Yasser will buy all of them, the total tastiness will be 7 + 4 - 1 = 10. Adel can choose segments [7], [4], [-1], [7, 4] or [4, -1], their total tastinesses are 7, 4, -1, 11 and 3, respectively. Adel can choose segment with tastiness 11, and as 10 is not strictly greater than 11, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.
Input: ['3', '4', '1 2 3 4', '3', '7 4 -1', '3', '5 -5 5', ''] Output:['YES', 'NO', 'NO', '']
[ 2 ]
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: 'L' (Left) sets the position x: =x - 1; 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position x doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 0; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 0 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position -2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.
Input: ['4', 'LRLR', ''] Output:['5', '']
[ 3 ]
Donghyun's new social network service (SNS) contains n users numbered 1, 2, ..., n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1.To prevent a possible server breakdown, Donghyun created a backup network T_2, which also connects the same n users via a tree graph. If a system breaks down, exactly one edge e \in T_1 becomes unusable. In this case, Donghyun will protect the edge e by picking another edge f \in T_2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f \in T_2 for as many edges e \in T_1 as possible. However, since the backup network T_2 is fragile, f \in T_2 can be assigned as the replacement edge for at most one edge in T_1. With this restriction, Donghyun wants to protect as many edges in T_1 as possible.Formally, let E(T) be an edge set of the tree T. We consider a bipartite graph with two parts E(T_1) and E(T_2). For e \in E(T_1), f \in E(T_2), there is an edge connecting \{e, f\} if and only if graph T_1 - \{e\} + \{f\} is a tree. You should find a maximum matching in this bipartite graph.
Input: ['4', '1 2', '2 3', '4 3', '1 3', '2 4', '1 4', ''] Output:['3', '3 2 4 2', '2 1 1 3', '4 3 1 4', '']
[ 3 ]
Kiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle, which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s = \{(x_1, y_1), (x_2, y_2), ..., (x_n, y_n)\} consisting of n distinct points. In the set s, no three distinct points lie on a single line. For a point p \in s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 4 vertices) that strictly encloses the point p (i.e. the point p is strictly inside a quadrilateral). Kiwon is interested in the number of 4-point subsets of s that can be used to build a castle protecting p. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p) be the number of 4-point subsets that can enclose the point p. Please compute the sum of f(p) for all points p \in s.
Input: ['5', '-1 0', '1 0', '-10 -1', '10 -1', '0 3', ''] Output:['2']
[ 3 ]
Filled with optimism, Hyunuk will host a conference about how great this new year will be!The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i <= ea_i) and [sb_i, eb_i] (sb_i <= eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if \max(x, u) <= \min(y, v).We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input: ['2', '1 2 3 6', '3 4 7 8', ''] Output:['YES', '']
[ 4 ]
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).A sequence a is a subsegment of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l, r], where l, r are two integers with 1 <= l <= r <= n. This indicates the subsegment where l-1 elements from the beginning and n-r elements from the end are deleted from the sequence.For a permutation p_1, p_2, ..., p_n, we define a framed segment as a subsegment [l,r] where \max\{p_l, p_{l+1}, ..., p_r\} - \min\{p_l, p_{l+1}, ..., p_r\} = r - l. For example, for the permutation (6, 7, 1, 8, 5, 3, 2, 4) some of its framed segments are: [1, 2], [5, 8], [6, 7], [3, 3], [8, 8]. In particular, a subsegment [i,i] is always a framed segments for any i between 1 and n, inclusive.We define the happiness of a permutation p as the number of pairs (l, r) such that 1 <= l <= r <= n, and [l, r] is a framed segment. For example, the permutation [3, 1, 2] has happiness 5: all segments except [1, 2] are framed segments.Given integers n and m, Jongwon wants to compute the sum of happiness for all permutations of length n, modulo the prime number m. Note that there exist n! (factorial of n) different permutations of length n.
Input: ['1 993244853', ''] Output:['1', '']
[ 3 ]
A sequence a = [a_1, a_2, ..., a_l] of length l has an ascent if there exists a pair of indices (i, j) such that 1 <= i < j <= l and a_i < a_j. For example, the sequence [0, 2, 0, 2, 0] has an ascent because of the pair (1, 4), but the sequence [4, 3, 3, 3, 1] doesn't have an ascent.Let's call a concatenation of sequences p and q the sequence that is obtained by writing down sequences p and q one right after another without changing the order. For example, the concatenation of the [0, 2, 0, 2, 0] and [4, 3, 3, 3, 1] is the sequence [0, 2, 0, 2, 0, 4, 3, 3, 3, 1]. The concatenation of sequences p and q is denoted as p+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has n sequences s_1, s_2, ..., s_n which may have different lengths. Gyeonggeun will consider all n^2 pairs of sequences s_x and s_y (1 <= x, y <= n), and will check if its concatenation s_x + s_y has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x, y) of sequences s_1, s_2, ..., s_n whose concatenation s_x + s_y contains an ascent.
Input: ['5', '1 1', '1 1', '1 2', '1 4', '1 3', ''] Output:['9', '']
[ 4 ]
Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of n lamps and n - 1 wires. Exactly one lamp will be connected to power grid, and power will be transmitted from it to other lamps by the wires. Each wire connectes exactly two lamps; one lamp is called the main lamp for this wire (the one that gets power from some other wire and transmits it to this wire), the other one is called the auxiliary lamp (the one that gets power from this wire). Obviously, each lamp has at most one wire that brings power to it (and this lamp is the auxiliary lamp for this wire, and the main lamp for all other wires connected directly to it).Each lamp has a brightness value associated with it, the i-th lamp has brightness 2^i. We define the importance of the wire as the sum of brightness values over all lamps that become disconnected from the grid if the wire is cut (and all other wires are still working).Polycarp has drawn the scheme of the garland he wants to make (the scheme depicts all n lamp and n - 1 wires, and the lamp that will be connected directly to the grid is marked; the wires are placed in such a way that the power can be transmitted to each lamp). After that, Polycarp calculated the importance of each wire, enumerated them from 1 to n - 1 in descending order of their importance, and then wrote the index of the main lamp for each wire (in the order from the first wire to the last one).The following day Polycarp bought all required components of the garland and decided to solder it — but he could not find the scheme. Fortunately, Polycarp found the list of indices of main lamps for all wires. Can you help him restore the original scheme?
Input: ['6', '3 6 3 1 5', ''] Output:['3', '6 3', '6 5', '1 3', '1 4', '5 2', '']
[ 2 ]
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.For all friends 1 <= x_i <= n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
Input: ['4', '1 2 4 4', ''] Output:['2 4', '']
[ 2 ]
There are n Christmas trees on an infinite number line. The i-th tree grows at the position x_i. All x_i are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are m people who want to celebrate Christmas. Let y_1, y_2, ..., y_m be the positions of people (note that all values x_1, x_2, ..., x_n, y_1, y_2, ..., y_m should be distinct and all y_j should be integer). You want to find such an arrangement of people that the value \sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j| is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let d_j be the distance from the j-th human to the nearest Christmas tree (d_j = \min\limits_{i=1}^{n} |y_j - x_i|). Then you need to choose such positions y_1, y_2, ..., y_m that \sum\limits_{j=1}^{m} d_j is the minimum possible.
Input: ['2 6', '1 5', ''] Output:['8', '-1 2 6 4 0 3 ', '']
[ 2 ]
There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or 1 <= f_i <= n if the i-th friend wants to give the gift to the friend f_i.You want to fill in the unknown values (f_i = 0) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.
Input: ['5', '5 0 0 2 4', ''] Output:['5 3 1 2 4 ', '']
[ 3 ]
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time: b - a <= 1 (it means b = a or b = a + 1); the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed \lfloor\frac{k}{2}\rfloor (less than or equal to \lfloor\frac{k}{2}\rfloor). \lfloor\frac{k}{2}\rfloor is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then \lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer t independent test cases.
Input: ['5', '5 2', '19 4', '12 7', '6 2', '100000 50010', ''] Output:['5', '18', '10', '6', '75015', '']
[ 3 ]
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 <= hh < 24 and 0 <= mm < 60. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows 0 hours and 0 minutes.You have to answer t independent test cases.
Input: ['5', '23 55', '23 0', '0 1', '4 20', '23 59', ''] Output:['5', '60', '1439', '1180', '1', '']
[ 3 ]
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0 to T, inclusive.All problems are divided into two types: easy problems — Petya takes exactly a minutes to solve any easy problem; hard problems — Petya takes exactly b minutes (b > a) to solve any hard problem. Thus, if Petya starts solving an easy problem at time x, then it will be solved at time x+a. Similarly, if at a time x Petya starts to solve a hard problem, then it will be solved at time x+b.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time t_i (0 <= t_i <= T) at which it will become mandatory (required). If Petya leaves the exam at time s and there is such a problem i that t_i <= s and he didn't solve it, then he will receive 0 points for the whole exam. Otherwise (i.e if he has solved all such problems for which t_i <= s) he will receive a number of points equal to the number of solved problems. Note that leaving at time s Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if n=2, T=5, a=2, b=3, the first problem is hard and t_1=3 and the second problem is easy and t_2=2. Then: if he leaves at time s=0, then he will receive 0 points since he will not have time to solve any problems; if he leaves at time s=1, he will receive 0 points since he will not have time to solve any problems; if he leaves at time s=2, then he can get a 1 point by solving the problem with the number 2 (it must be solved in the range from 0 to 2); if he leaves at time s=3, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time s=4, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time s=5, then he can get 2 points by solving all problems. Thus, the answer to this test is 2.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
Input: ['10', '3 5 1 3', '0 0 1', '2 1 4', '2 5 2 3', '1 0', '3 2', '1 20 2 4', '0', '16', '6 20 2 5', '1 1 0 1 0 0', '0 8 2 9 11 6', '4 16 3 6', '1 0 1 1', '8 3 5 6', '6 20 3 6', '0 1 0 0 1 0', '20 11 3 20 16 17', '7 17 1 6', '1 1 0 1 0 0 0', '1 7 0 11 10 15 10', '6 17 2 6', '0 0 1 0 0 1', '7 6 3 7 10 12', '5 17 2 5', '1 1 1 1 0', '17 11 10 6 4', '1 1 1 2', '0', '1', ''] Output:['3', '2', '1', '0', '1', '4', '0', '1', '2', '1', '']
[ 2 ]
This is the hard version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: 2 <= k <= n.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store.Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by a_i — the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index i if he currently has enough coins (i.e p >= a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i). Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p >= a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i). Please note that each good can be bought no more than once.For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.
Input: ['8', '5 6 2', '2 4 3 5 7', '5 11 2', '2 4 3 5 7', '3 2 3', '4 2 6', '5 2 3', '10 1 3 9 2', '2 10000 2', '10000 10000', '2 9999 2', '10000 10000', '4 6 4', '3 2 3 2', '5 5 3', '1 2 2 1 2', ''] Output:['3', '4', '1', '1', '2', '0', '4', '5', '']
[ 2 ]
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store. Remember, that in this problem k=2.Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by a_i — the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index i if he currently has enough coins (i.e p >= a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i). Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p >= a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i). Please note that each good can be bought no more than once.For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.
Input: ['6', '5 6 2', '2 4 3 5 7', '5 11 2', '2 4 3 5 7', '2 10000 2', '10000 10000', '2 9999 2', '10000 10000', '5 13 2', '8 2 8 2 5', '3 18 2', '1 2 3', ''] Output:['3', '4', '2', '0', '4', '3', '']
[ 2 ]
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a distance less than or equal to r from the point x=c, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from x=a to x=b. His speed — one unit of distance per minute.
Input: ['9', '1 10 7 1', '3 3 3 0', '8 2 10 4', '8 2 10 100', '-10 20 -17 2', '-3 2 2 0', '-3 1 2 0', '2 3 2 3', '-1 3 -2 2', ''] Output:['7', '0', '4', '0', '30', '5', '4', '0', '3', '']
[ 3 ]
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string s representing Jeff's product name and the string c representing his competitor's product name, find a way to swap at most one pair of characters in s (that is, find two distinct indices i and j and swap s_i and s_j) such that the resulting new name becomes strictly lexicographically smaller than c, or determine that it is impossible.Note: String a is strictly lexicographically smaller than string b if and only if one of the following holds: a is a proper prefix of b, that is, a is a prefix of b such that a \neq b; There exists an integer 1 <= i <= \min{(|a|, |b|)} such that a_i < b_i and a_j = b_j for 1 <= j < i.
Input: ['3', 'AZAMON APPLE', 'AZAMON AAAAAAAAAAALIBABA', 'APPLE BANANA', ''] Output:['AMAZON', '---', 'APPLE', '']
[ 2 ]
You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 * (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1.In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so.
Input: ['2', '3', '1 2 3 5 6 E 7', '8 9 10 4 11 12 13', '11', '34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1', 'E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3', ''] Output:['SURGERY COMPLETE', 'IR', 'R SrS', 'S rr', 'I lldll', 'DONE', 'SURGERY FAILED', '']
[ 3 ]
Your friend Kirchhoff is shocked with the current state of electronics design."Ohmygosh! Watt is wrong with the field? All these circuits are inefficient! There's so much capacity for improvement. The electrical engineers must not conduct their classes very well. It's absolutely revolting" he said.The negativity just keeps flowing out of him, but even after complaining so many times he still hasn't lepton the chance to directly change anything."These circuits have too much total resistance. Wire they designed this way? It's just causing a massive loss of resistors! Their entire field could conserve so much money if they just maximized the potential of their designs. Why can't they just try alternative ideas?"The frequency of his protests about the electrical engineering department hertz your soul, so you have decided to take charge and help them yourself. You plan to create a program that will optimize the circuits while keeping the same circuit layout and maintaining the same effective resistance.A circuit has two endpoints, and is associated with a certain constant, R, called its effective resistance. The circuits we'll consider will be formed from individual resistors joined together in series or in parallel, forming more complex circuits. The following image illustrates combining circuits in series or parallel. According to your friend Kirchhoff, the effective resistance can be calculated quite easily when joining circuits this way: When joining k circuits in series with effective resistances R_1, R_2, ..., R_k, the effective resistance R of the resulting circuit is the sum R = R_1 + R_2 + ... + R_k. When joining k circuits in parallel with effective resistances R_1, R_2, ..., R_k, the effective resistance R of the resulting circuit is found by solving for R in \frac{1}{R} = \frac{1}{R_1} + \frac{1}{R_2} + ... + \frac{1}{R_k}, assuming all R_i > 0; if at least one R_i = 0, then the effective resistance of the whole circuit is simply R = 0. Circuits will be represented by strings. Individual resistors are represented by an asterisk, "*". For more complex circuits, suppose s_1, s_2, ..., s_k represent k >= 2 circuits. Then: "(s_1 S s_2 S ... S s_k)" represents their series circuit; "(s_1 P s_2 P ... P s_k)" represents their parallel circuit. For example, "(* P (* S *) P *)" represents the following circuit: Given a circuit, your task is to assign the resistances of the individual resistors such that they satisfy the following requirements: Each individual resistor has a nonnegative integer resistance value; The effective resistance of the whole circuit is r; The sum of the resistances of the individual resistors is minimized. If there are n individual resistors, then you need to output the list r_1, r_2, ..., r_n (0 <= r_i, and r_i is an integer), where r_i is the resistance assigned to the i-th individual resistor that appears in the input (from left to right). If it is impossible to accomplish the task, you must say so as well.If it is possible, then it is guaranteed that the minimum sum of resistances is at most 10^{18}.
Input: ['3', '5 *', '1 (* S *)', '1 (* P (* S *))', ''] Output:['REVOLTING 5', 'REVOLTING 1 0', 'REVOLTING 2 1 1', '']
[ 3 ]
The Oak has n nesting places, numbered with integers from 1 to n. Nesting place i is home to b_i bees and w_i wasps.Some nesting places are connected by branches. We call two nesting places adjacent if there exists a branch between them. A simple path from nesting place x to y is given by a sequence s_0, ..., s_p of distinct nesting places, where p is a non-negative integer, s_0 = x, s_p = y, and s_{i-1} and s_{i} are adjacent for each i = 1, ..., p. The branches of The Oak are set up in such a way that for any two pairs of nesting places x and y, there exists a unique simple path from x to y. Because of this, biologists and computer scientists agree that The Oak is in fact, a tree.A village is a nonempty set V of nesting places such that for any two x and y in V, there exists a simple path from x to y whose intermediate nesting places all lie in V. A set of villages \cal P is called a partition if each of the n nesting places is contained in exactly one of the villages in \cal P. In other words, no two villages in \cal P share any common nesting place, and altogether, they contain all n nesting places.The Oak holds its annual Miss Punyverse beauty pageant. The two contestants this year are Ugly Wasp and Pretty Bee. The winner of the beauty pageant is determined by voting, which we will now explain. Suppose \mathcal{P} is a partition of the nesting places into m villages V_1, ..., V_m. There is a local election in each village. Each of the insects in this village vote for their favorite contestant. If there are strictly more votes for Ugly Wasp than Pretty Bee, then Ugly Wasp is said to win in that village. Otherwise, Pretty Bee wins. Whoever wins in the most number of villages wins.As it always goes with these pageants, bees always vote for the bee (which is Pretty Bee this year) and wasps always vote for the wasp (which is Ugly Wasp this year). Unlike their general elections, no one abstains from voting for Miss Punyverse as everyone takes it very seriously.Mayor Waspacito, and his assistant Alexwasp, wants Ugly Wasp to win. He has the power to choose how to partition The Oak into exactly m villages. If he chooses the partition optimally, determine the maximum number of villages in which Ugly Wasp wins.
Input: ['2', '4 3', '10 160 70 50', '70 111 111 0', '1 2', '2 3', '3 4', '2 1', '143 420', '214 349', '2 1', ''] Output:['2', '0', '']
[ 2 ]
Welcome! Everything is fine.You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B?
Input: ['2', '3', '1 2 3', '3 2 4', '2 4 3', '4 5 6', '5 6 5', '2', '1 2 1', '1 3 2', '1 4 3', ''] Output:['15 33', '6 6', '']
[ 2 ]
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r * c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.In particular, a single use of your power is this: You choose a horizontal 1 * x subgrid or a vertical x * 1 subgrid. That value of x is up to you; You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number s of steps; You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 * 4 subgrid, the direction NORTH, and s = 2 steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input: ['4', '7 8', 'AAPAAAAA', 'PPPPAAAA', 'PPPPAAAA', 'APAAPPPP', 'APAPPAPP', 'AAAAPPAP', 'AAAAPPAA', '6 5', 'AAAAA', 'AAAAA', 'AAPAA', 'AAPAP', 'AAAPP', 'AAAPP', '4 4', 'PPPP', 'PPPP', 'PPPP', 'PPPP', '3 4', 'PPPP', 'PAAP', 'PPPP', ''] Output:['2', '1', 'MORTAL', '4', '']
[ 3 ]
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location \ell is denoted by an integer in \{0, ..., |s|\}, with the following meaning: If \ell = 0, then the cursor is located before the first character of s. If \ell = |s|, then the cursor is located right after the last character of s. If 0 < \ell < |s|, then the cursor is located between s_\ell and s_{\ell+1}. We denote by s_\text{left} the string to the left of the cursor and s_\text{right} the string to the right of the cursor. We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions: The Move action. Move the cursor one step to the right. This increments \ell once. The Cut action. Set c <=ftarrow s_\text{right}, then set s <=ftarrow s_\text{left}. The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c. The cursor initially starts at \ell = 0. Then, we perform the following procedure: Perform the Move action once. Perform the Cut action once. Perform the Paste action s_\ell times. If \ell = x, stop. Otherwise, return to step 1. You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7. It is guaranteed that \ell <= |s| at any time.
Input: ['4', '5', '231', '7', '2323', '6', '333', '24', '133321333', ''] Output:['25', '1438', '1101', '686531475', '']
[ 3 ]
New Year is getting near. So it's time to change handles on codeforces. Mishka wants to change his handle but in such a way that people would not forget who he is.To make it work, he only allowed to change letters case. More formally, during one handle change he can choose any segment of his handle [i; i + l - 1] and apply tolower or toupper to all letters of his handle on this segment (more fomally, replace all uppercase letters with corresponding lowercase or vice versa). The length l is fixed for all changes.Because it is not allowed to change codeforces handle too often, Mishka can perform at most k such operations. What is the minimum value of min(lower, upper) (where lower is the number of lowercase letters, and upper is the number of uppercase letters) can be obtained after optimal sequence of changes?
Input: ['7 1 4', 'PikMike', ''] Output:['0', '']
[ 4 ]
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following: choose one kid x equiprobably among all n kids; choose some item y equiprobably among all k_x items kid x wants; choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot. If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input: ['2', '2 2 1', '1 1', ''] Output:['124780545', '']
[ 3 ]
New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly — the part which takes a_2 seconds, and so on. After reciting the verse, Vasya will get the number of presents equal to the number of parts he fully recited.Vasya can skip at most one part of the verse while reciting it (if he skips more than one part, then Santa will definitely notice it).Santa will listen to Vasya's verse for no more than s seconds. For example, if s = 10, a = [100, 9, 1, 1], and Vasya skips the first part of verse, then he gets two presents.Note that it is possible to recite the whole verse (if there is enough time). Determine which part Vasya needs to skip to obtain the maximum possible number of gifts. If Vasya shouldn't skip anything, print 0. If there are multiple answers, print any of them.You have to process t test cases.
Input: ['3', '7 11', '2 9 1 3 18 1 4', '4 35', '11 9 10 7', '1 8', '5', ''] Output:['2', '1', '0', '']
[ 0, 4 ]
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input: ['3', '3 3 3', '1 10 2', '2 1 1', ''] Output:['Yes', 'No', 'Yes', '']
[ 3 ]
Consider the following experiment. You have a deck of m cards, and exactly one card is a joker. n times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.Let x be the number of times you have taken the joker out of the deck during this experiment. Assuming that every time you shuffle the deck, all m! possible permutations of cards are equiprobable, what is the expected value of x^k? Print the answer modulo 998244353.
Input: ['1 1 1', ''] Output:['1', '']
[ 3 ]
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were 2n jars of strawberry and blueberry jam.All the 2n jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly n jars to his left and n jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten 1 jar to his left and then 5 jars to his right. There remained exactly 3 full jars of both strawberry and blueberry jam. Jars are numbered from 1 to 2n from left to right, so Karlsson initially stands between jars n and n+1.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer t independent test cases.
Input: ['4', '6', '1 1 1 2 2 1 2 1 2 1 1 2', '2', '1 2 1 2', '3', '1 1 1 1 1 1', '2', '2 1 1 1', ''] Output:['6', '0', '6', '2', '']
[ 2 ]
You are given two integers a and b. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by 1; during the second operation you choose one of these numbers and increase it by 2, and so on. You choose the number of these operations yourself.For example, if a = 1 and b = 3, you can perform the following sequence of three operations: add 1 to a, then a = 2 and b = 3; add 2 to b, then a = 2 and b = 5; add 3 to a, then a = 5 and b = 5. Calculate the minimum number of operations required to make a and b equal.
Input: ['3', '1 3', '11 11', '30 20', ''] Output:['3', '0', '4', '']
[ 2, 3 ]
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm: take the password p, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain p' (p' can still be equal to p); generate two random strings, consisting of lowercase Latin letters, s_1 and s_2 (any of these strings can be empty); the resulting hash h = s_1 + p' + s_2, where addition is string concatenation. For example, let the password p = "abacaba". Then p' can be equal to "aabcaab". Random strings s1 = "zyx" and s2 = "kjh". Then h = "zyxaabcaabkjh".Note that no letters could be deleted or added to p to obtain p', only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password p and the hash h, check that h can be the hash for the password p.Your program should answer t independent test cases.
Input: ['5', 'abacaba', 'zyxaabcaabkjh', 'onetwothree', 'threetwoone', 'one', 'zzonneyy', 'one', 'none', 'twenty', 'ten', ''] Output:['YES', 'YES', 'NO', 'YES', 'NO', '']
[ 0 ]
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that: the final set of n words still contains different words (i.e. all words are unique); there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.
Input: ['4', '4', '0001', '1000', '0011', '0111', '3', '010', '101', '0', '2', '00000', '00001', '4', '01', '001', '0001', '00001', ''] Output:['1', '3 ', '-1', '0', '', '2', '1 2 ', '']
[ 3 ]
There are n positive integers a_1, a_2, ..., a_n. For the one move you can choose any even value c and divide by two all elements that equal c.For example, if a=[6,8,12,6,3,12] and you choose c=6, and a is transformed into a=[3,8,12,3,3,12] after the move.You need to find the minimal number of moves for transforming a to an array of only odd integers (each element shouldn't be divisible by 2).
Input: ['4', '6', '40 6 40 3 20 1', '1', '1024', '4', '2 4 8 16', '3', '3 1 7', ''] Output:['4', '10', '4', '0', '']
[ 2 ]
You are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen.A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.
Input: ['12', '3 1 4 1 5 9 2 6 5 3 5 8', ''] Output:['12', '3 4', '1 2 3 5', '3 1 5 4', '5 6 8 9', '']
[ 0, 2, 3 ]
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j (1 <= j <= n-2), that s_{j}s_{j+1}s_{j+2}="one" or s_{j}s_{j+1}s_{j+2}="two".For example: Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"), Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like s="onetwone", then if Polycarp selects two indices 3 and 6, then "onetwone" will be selected and the result is "ontwne".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?
Input: ['4', 'onetwone', 'testme', 'oneoneone', 'twotwo', ''] Output:['2', '6 3', '0', '', '3', '4 1 7 ', '2', '1 4', '']
[ 2 ]
Это интерактивная задача.Когда данных становится слишком много и они не помещаются на один сервер, их приходится шардировать. Рассмотрим систему хранения постов пользователей, которая расположена на S серверах, нумеруемых с единицы. Каждый раз когда пользователь пишет пост, ему выдается уникальный идентификатор в пределах от 1 до 10^{18} и сохраняется на случайный сервер. Чем позже был создан пост, тем больше его id. Иногда посты удаляются, поэтому на серверах может лежать существенно разное количество постов.Рассмотрим все неудаленные id постов пользователя и отсортируем их по возрастанию. Вам хочется узнать k-й из них. Для этого вы можете послать не более 100 дополнительных запросов. Каждый запрос имеет формат «? i j». В ответ вы получите идентификатор j-го по возрастанию поста пользователя среди хранящихся на i-м сервере. Когда вы считаете, что знаете k-й по возрастанию идентификатор, вместо запроса необходимо вывести ответ в формате «! id».
Input: ['1 2', '3 2', '3', '', '3', '', '5', '', '10'] Output:['? 1 2', '', '? 2 1', '', '? 1 3', '', '! 5', '']
[ 4 ]
You are given an array a consisting of n integers.You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input: ['5', '1 2 5 3 4', ''] Output:['4', '']
[ 0 ]
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to (x - 1, y); if the current instruction is 'R', then the robot can move to the right to (x + 1, y); if the current instruction is 'U', then the robot can move to the top to (x, y + 1); if the current instruction is 'D', then the robot can move to the bottom to (x, y - 1). You've noticed the warning on the last page of the manual: if the robot visits some cell (except (0, 0)) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell (0, 0), performs the given instructions, visits no cell other than (0, 0) two or more times and ends the path in the cell (0, 0). Also cell (0, 0) should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not (0, 0)) and "UUDD" (the cell (0, 1) is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).You have to answer q independent test cases.
Input: ['6', 'LRU', 'DURLDRUDRULRDURDDL', 'LRUDDLRUDRUL', 'LLLLRRRR', 'URDUR', 'LLL', ''] Output:['2', 'LR', '14', 'RUURDDDDLLLUUR', '12', 'ULDDDRRRUULL', '2', 'LR', '2', 'UD', '0', '', '']
[ 2 ]
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer q independent test cases.
Input: ['8', '3 3 4', '10 20 30', '5 5 5', '2 4 3', '1 1000000000 1000000000', '1 1000000000 999999999', '3 2 5', '3 2 6', ''] Output:['0', '36', '0', '0', '1999999994', '1999999994', '2', '4', '']
[ 0, 2, 3 ]
Recently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-year students of the computer science faculty.There are t new groups belonging to this faculty. Students have to attend classes on three different subjects — maths, programming and P. E. All classes are held in different places according to the subject — maths classes are held in auditoriums, programming classes are held in computer labs, and P. E. classes are held in gyms.Each group should be divided into two subgroups so that there is enough space in every auditorium, lab or gym for all students of the subgroup. For the first subgroup of the i-th group, maths classes are held in an auditorium with capacity of a_{i, 1} students; programming classes are held in a lab that accomodates up to b_{i, 1} students; and P. E. classes are held in a gym having enough place for c_{i, 1} students. Analogically, the auditorium, lab and gym for the second subgroup can accept no more than a_{i, 2}, b_{i, 2} and c_{i, 2} students, respectively.As usual, some students skip some classes. Each student considers some number of subjects (from 0 to 3) to be useless — that means, he skips all classes on these subjects (and attends all other classes). This data is given to you as follows — the i-th group consists of: d_{i, 1} students which attend all classes; d_{i, 2} students which attend all classes, except for P. E.; d_{i, 3} students which attend all classes, except for programming; d_{i, 4} students which attend only maths classes; d_{i, 5} students which attend all classes, except for maths; d_{i, 6} students which attend only programming classes; d_{i, 7} students which attend only P. E. There is one more type of students — those who don't attend any classes at all (but they, obviously, don't need any place in auditoriums, labs or gyms, so the number of those students is insignificant in this problem).Your task is to divide each group into two subgroups so that every auditorium (or lab, or gym) assigned to each subgroup has enough place for all students from this subgroup attending the corresponding classes (if it is possible). Each student of the i-th group should belong to exactly one subgroup of the i-th group; it is forbidden to move students between groups.
Input: ['3', '9 4 13', '1 10 3', '1 2 3 4 5 6 7', '9 4 13', '1 10 3', '2 1 3 4 5 6 7', '1 2 3', '4 5 6', '0 0 0 0 0 0 0', ''] Output:['1 1 3 4 2 0 7', '-1', '0 0 0 0 0 0 0', '']
[ 0 ]
At first, let's define function f(x) as follows: \begin{matrix} f(x) & = & <=ft\{ \begin{matrix} \frac{x}{2} & \mbox{if } x \text{ is even} \\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} We can see that if we choose some value v and will apply function f to it, then apply f to f(v), and so on, we'll eventually get 1. Let's write down all values we get in this process in a list and denote this list as path(v). For example, path(1) = [1], path(15) = [15, 14, 7, 6, 3, 2, 1], path(32) = [32, 16, 8, 4, 2, 1].Let's write all lists path(x) for every x from 1 to n. The question is next: what is the maximum value y such that y is contained in at least k different lists path(x)?Formally speaking, you need to find maximum y such that <=ft| \{ x ~|~ 1 <= x <= n, y \in path(x) \} \right| >= k.
Input: ['11 3', ''] Output:['5', '']
[ 3, 4 ]
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle: if you are currently in the castle i, you may leave one warrior to defend castle i; there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v. Obviously, when you order your warrior to defend some castle, he leaves your army.You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it — your score will be calculated afterwards).Can you determine an optimal strategy of capturing and defending the castles?
Input: ['4 3 7', '7 4 17', '3 0 8', '11 2 0', '13 3 5', '3 1', '2 1', '4 3', ''] Output:['5', '']
[ 2 ]
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.The main school of the capital is located in (s_x, s_y). There are n students attending this school, the i-th of them lives in the house located in (x_i, y_i). It is possible that some students live in the same house, but no student lives in (s_x, s_y).After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the i-th student goes from the school to his house is |s_x - x_i| + |s_y - y_i|.The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the i-th student will buy a shawarma if at least one of the shortest paths from the school to the i-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.
Input: ['4 3 2', '1 3', '4 2', '5 1', '4 1', ''] Output:['3', '4 2', '']
[ 0, 2 ]
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 \cdot n. If it is impossible to find such a sequence of operations, you need to report it.
Input: ['8', 'BWWWWWWB', ''] Output:['3', '6 2 4', '']
[ 2, 3 ]