question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
n ants are on a circle of length m. An ant travels one unit of distance per one unit of time. Initially, the ant number i is located at the position si and is facing in the direction di (which is either L or R). Positions are numbered in counterclockwise order starting from some point. Positions of the all ants are distinct.All the ants move simultaneously, and whenever two ants touch, they will both switch their directions. Note that it is possible for an ant to move in some direction for a half of a unit of time and in opposite direction for another half of a unit of time.Print the positions of the ants after t time units. | Input: ['2 4 81 R3 L'] Output:['1 3'] | [
3
] |
The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2β>βh1) on the same tree hung an apple and the caterpillar was crawling to the apple.Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night.In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm.Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple. | Input: ['10 302 1'] Output:['1'] | [
3
] |
There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1ββ€βiββ€βnβ-β1), such that aiβ+β1β>βai. | Input: ['520 30 10 50 40'] Output:['4'] | [
2
] |
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent. | Input: ['3 5'] Output:['6'] | [
2,
3
] |
My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment.I was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner.I see n contacts connected by nβ-β1 wires. Contacts are numbered with integers from 1 to n. Bomb has a security mechanism that ensures the following condition: if there exist kββ₯β2 contacts c1,βc2,β...,βck forming a circuit, i. e. there exist k distinct wires between contacts c1 and c2, c2 and c3, ..., ck and c1, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length 2. It is also prohibited to connect a contact with itself.On the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than nβ-β2 wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear.I know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused. | Input: ['31 22 31 33 2'] Output:['11 2 1 3'] | [
2
] |
Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them.It is known that the forest consists of n trees staying in a row numbered from left to right with integers from 1 to n. According to Vasya, the height of the i-th tree is equal to hi. The zip-line of length k should hang over k (1ββ€βkββ€βn) trees i1,βi2,β...,βik (i1β<βi2β<β...β<βik) such that their heights form an increasing sequence, that is hi1β<βhi2β<β...β<βhik.Petya had been in this forest together with Vasya, and he now has q assumptions about the mistake in Vasya's sequence h. His i-th assumption consists of two integers ai and bi indicating that, according to Petya, the height of the tree numbered ai is actually equal to bi. Note that Petya's assumptions are independent from each other.Your task is to find the maximum length of a zip-line that can be built over the trees under each of the q assumptions.In this problem the length of a zip line is considered equal to the number of trees that form this zip-line. | Input: ['4 41 2 3 41 11 44 34 5'] Output:['4334'] | [
4
] |
Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.Petya decided to compress tables. He is given a table a consisting of n rows and m columns that is filled with positive integers. He wants to build the table a' consisting of positive integers such that the relative order of the elements in each row and each column remains the same. That is, if in some row i of the initial table ai,βjβ<βai,βk, then in the resulting table a'i,βjβ<βa'i,βk, and if ai,βjβ=βai,βk then a'i,βjβ=βa'i,βk. Similarly, if in some column j of the initial table ai,βjβ<βap,βj then in compressed table a'i,βjβ<βa'p,βj and if ai,βjβ=βap,βj then a'i,βjβ=βa'p,βj. Because large values require more space to store them, the maximum value in a' should be as small as possible.Petya is good in theory, however, he needs your help to implement the algorithm. | Input: ['2 21 23 4'] Output:['1 22 3'] | [
2
] |
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.Help Vasya find the maximum number of photos he is able to watch during T seconds. | Input: ['4 2 3 10wwhw'] Output:['2'] | [
0,
4
] |
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi,βyi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xiβ-βxj|β+β|yiβ-βyj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i,βj) (1ββ€βiβ<βjββ€βn), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs. | Input: ['31 17 51 5'] Output:['2'] | [
3
] |
After a drawn-out mooclear arms race, Farmer John and the Mischievous Mess Makers have finally agreed to establish peace. They plan to divide the territory of Bovinia with a line passing through at least two of the n outposts scattered throughout the land. These outposts, remnants of the conflict, are located at the points (x1,βy1),β(x2,βy2),β...,β(xn,βyn).In order to find the optimal dividing line, Farmer John and Elsie have plotted a map of Bovinia on the coordinate plane. Farmer John's farm and the Mischievous Mess Makers' base are located at the points Pβ=β(a,β0) and Qβ=β(β-βa,β0), respectively. Because they seek a lasting peace, Farmer John and Elsie would like to minimize the maximum difference between the distances from any point on the line to P and Q.Formally, define the difference of a line relative to two points P and Q as the smallest real number d so that for all points X on line , |PXβ-βQX|ββ€βd. (It is guaranteed that d exists and is unique.) They wish to find the line passing through two distinct outposts (xi,βyi) and (xj,βyj) such that the difference of relative to P and Q is minimized. | Input: ['2 51 02 1'] Output:['7.2111025509'] | [
4
] |
In an attempt to make peace with the Mischievious Mess Makers, Bessie and Farmer John are planning to plant some flower gardens to complement the lush, grassy fields of Bovinia. As any good horticulturist knows, each garden they plant must have the exact same arrangement of flowers. Initially, Farmer John has n different species of flowers he can plant, with ai flowers of the i-th species.On each of the next q days, Farmer John will receive a batch of flowers of a new species. On day j, he will receive cj flowers of the same species, but of a different species from those Farmer John already has. Farmer John, knowing the right balance between extravagance and minimalism, wants exactly k species of flowers to be used. Furthermore, to reduce waste, each flower of the k species Farmer John chooses must be planted in some garden. And each of the gardens must be identical; that is to say that each of the k chosen species should have an equal number of flowers in each garden. As Farmer John is a proponent of national equality, he would like to create the greatest number of gardens possible.After receiving flowers on each of these q days, Farmer John would like to know the sum, over all possible choices of k species, of the maximum number of gardens he could create. Since this could be a large number, you should output your result modulo 109β+β7. | Input: ['3 3 246986'] Output:['516'] | [
3
] |
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of mβ+βn tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s|β=βmβ+βn) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1β<βp2β<β...β<βpq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts. | Input: ['1 3ac'] Output:['8'] | [
2
] |
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level. | Input: ['4 52 11 32 34 24 3'] Output:['4'] | [
4
] |
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of kβ+β1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |jβ-βi|. Help Farmer John protect his cows by calculating this minimum possible distance. | Input: ['7 20100100'] Output:['2'] | [
4
] |
It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his k minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute.Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the k minutes that they have. We denote as pi the label of the cow in the i-th stall. The messiness of an arrangement of cows is defined as the number of pairs (i,βj) such that iβ<βj and piβ>βpj. | Input: ['5 2'] Output:['10'] | [
2,
3
] |
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2βΓβ2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below: In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed. | Input: ['ABXCXBAC'] Output:['YES'] | [
0
] |
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where: <hostname> β server name (consists of words and maybe some dots separating them), /<path> β optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa β for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different. | Input: ['10http://abacaba.ru/testhttp://abacaba.ru/http://abacaba.comhttp://abacaba.com/testhttp://abacaba.de/http://abacaba.ru/testhttp://abacaba.de/testhttp://abacaba.com/http://abacaba.com/thttp://abacaba.com/test'] Output:['1http://abacaba.de http://abacaba.ru '] | [
4
] |
There are n bears in the inn and p places to sleep. Bears will party together for some number of nights (and days).Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.Each night, the following happens in this exact order: Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears. Each bear drinks a glass from each barrel he chose. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately. At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).Radewoosh wants to allow bears to win. He considers q scenarios. In the i-th scenario the party will last for i nights. Then, let Ri denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define . Your task is to find , where denotes the exclusive or (also denoted as XOR).Note that the same barrel may be chosen by many bears and all of them will go to sleep at once. | Input: ['5 1 3'] Output:['32'] | [
3
] |
Limak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index 1 and is a root of the tree.Sometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each of its edges is destroyed with probability , independently of other edges. Then, Limak gets the penalty β an integer equal to the height of the subtree after the attack. The height is defined as the maximum number of edges on the path between the root of the subtree and any vertex in the subtree.You must handle queries of two types. 1 v denotes a query of the first type. A new vertex appears and its parent is v. A new vertex has the next available index (so, new vertices will be numbered 2,β3,β...). 2 v denotes a query of the second type. For a moment let's assume that the game allows Limak to attack a subtree rooted in v. Then, what would be the expected value of the penalty Limak gets after the attack? In a query of the second type, Limak doesn't actually attack the subtree and thus the query doesn't affect next queries. | Input: ['71 11 12 11 21 32 22 1'] Output:['0.75000000000.50000000001.1875000000'] | [
3
] |
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.We throw both dices simultaneously and then calculate values max(a,βb) and min(a,βb), where a is equal to the outcome of the first dice, while b is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for max(a,βb) and min(a,βb). That is, for each x from 1 to n you know the probability that max(a,βb) would be equal to x and the probability that min(a,βb) would be equal to x. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists. | Input: ['20.25 0.750.75 0.25'] Output:['0.5 0.5 0.5 0.5 '] | [
3
] |
Little Artem is fond of dancing. Most of all dances Artem likes rueda β Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | Input: ['6 31 221 2'] Output:['4 3 6 5 2 1'] | [
0
] |
Limak is a big polar bear. He prepared n problems for an algorithmic contest. The i-th problem has initial score pi. Also, testers said that it takes ti minutes to solve the i-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it β Limak has already announced initial scores for problems. Though it's still possible to adjust the speed of losing points, denoted by c in this statement.Let T denote the total number of minutes needed to solve all problems (so, Tβ=βt1β+βt2β+β...β+βtn). The contest will last exactly T minutes. So it's just enough to solve all problems.Points given for solving a problem decrease linearly. Solving the i-th problem after x minutes gives exactly points, where is some real constant that Limak must choose.Let's assume that c is fixed. During a contest a participant chooses some order in which he or she solves problems. There are n! possible orders and each of them gives some total number of points, not necessarily integer. We say that an order is optimal if it gives the maximum number of points. In other words, the total number of points given by this order is greater or equal than the number of points given by any other order. It's obvious that there is at least one optimal order. However, there may be more than one optimal order.Limak assumes that every participant will properly estimate ti at the very beginning and will choose some optimal order. He also assumes that testers correctly predicted time needed to solve each problem.For two distinct problems i and j such that piβ<βpj Limak wouldn't be happy to see a participant with strictly more points for problem i than for problem j. He calls such a situation a paradox.It's not hard to prove that there will be no paradox for cβ=β0. The situation may be worse for bigger c. What is the maximum real value c (remember that ) for which there is no paradox possible, that is, there will be no paradox for any optimal order of solving problems?It can be proved that the answer (the maximum c as described) always exists. | Input: ['34 3 101 1 8'] Output:['0.62500000000'] | [
2,
3,
4
] |
Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution β an integer number, not necessarily positive. There are n registered users and the i-th of them has contribution ti.Limak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments. Limak can spend b minutes to read one blog and upvote it. Author's contribution will be increased by 5. Limak can spend c minutes to read one comment and upvote it. Author's contribution will be increased by 1. Note that it's possible that Limak reads blogs faster than comments.Limak likes ties. He thinks it would be awesome to see a tie between at least k registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value x that at least k registered users have contribution exactly x.How much time does Limak need to achieve his goal? | Input: ['4 3 100 3012 2 6 1'] Output:['220'] | [
2
] |
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:Let a0,βa1,β...,βan denote the coefficients, so . Then, a polynomial P(x) is valid if all the following conditions are satisfied: ai is integer for every i; |ai|ββ€βk for every i; anββ β0. Limak has recently got a valid polynomial P with coefficients a0,βa1,βa2,β...,βan. He noticed that P(2)ββ β0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2)β=β0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ. | Input: ['3 100000000010 -9 -3 5'] Output:['3'] | [
3
] |
A super computer has been built in the Turtle Academy of Sciences. The computer consists of nΒ·mΒ·k CPUs. The architecture was the paralellepiped of size nβΓβmβΓβk, split into 1βΓβ1βΓβ1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x,βy,βz) can send messages to CPUs (xβ+β1,βy,βz), (x,βyβ+β1,βz) and (x,βy,βzβ+β1) (of course, if they exist), there is no feedback, that is, CPUs (xβ+β1,βy,βz), (x,βyβ+β1,βz) and (x,βy,βzβ+β1) cannot send messages to CPU (x,βy,βz).Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a,βb,βc) controls CPU (d,βe,βf) , if there is a chain of CPUs (xi,βyi,βzi), such that (x1β=βa,βy1β=βb,βz1β=βc), (xpβ=βd,βypβ=βe,βzpβ=βf) (here and below p is the length of the chain) and the CPU in the chain with number i (iβ<βp) can send messages to CPU iβ+β1.Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x,βy,βz) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x,βy,βz) CPUs: (a,βb,βc) and (d,βe,βf), such that (a,βb,βc) controls (d,βe,βf) before (x,βy,βz) is turned off and stopped controlling it after the turning off. | Input: ['2 2 3000000111111'] Output:['2'] | [
0
] |
In Berland there are n cities and nβ-β1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. | Input: ['41 23 43 2'] Output:['22 2 11 3'] | [
2
] |
The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to nβ-β1 in the order from the beginning of the street to the end (in the picture: from left to right). The houses with even numbers are at the other side of the street and are numbered from 2 to n in the order from the end of the street to its beginning (in the picture: from right to left). The corresponding houses with even and odd numbers are strictly opposite each other, that is, house 1 is opposite house n, house 3 is opposite house nβ-β2, house 5 is opposite house nβ-β4 and so on. Vasya needs to get to house number a as quickly as possible. He starts driving from the beginning of the street and drives his car to house a. To get from the beginning of the street to houses number 1 and n, he spends exactly 1 second. He also spends exactly one second to drive the distance between two neighbouring houses. Vasya can park at any side of the road, so the distance between the beginning of the street at the houses that stand opposite one another should be considered the same.Your task is: find the minimum time Vasya needs to reach house a. | Input: ['4 2'] Output:['2'] | [
3
] |
A sportsman starts from point xstartβ=β0 and runs to point with coordinate xfinishβ=βm (on a straight line). Also, the sportsman can jump β to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.On the way of an athlete are n obstacles at coordinates x1,βx2,β...,βxn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point. | Input: ['3 10 1 33 4 7'] Output:['RUN 2JUMP 3RUN 1JUMP 2RUN 2'] | [
2
] |
During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, kβ=β0 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits. | Input: ['2000000999999'] Output:['2'] | [
0
] |
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | Input: ['4alexivanromanivan'] Output:['ivanromanalex'] | [
4
] |
Paul is at the orchestra. The string section is arranged in an rβΓβc rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.Two pictures are considered to be different if the coordinates of corresponding rectangles are different. | Input: ['2 2 1 11 2'] Output:['4'] | [
0
] |
Yash loves playing with trees and gets especially excited when they have something to do with prime numbers. On his 20th birthday he was granted with a rooted tree of n nodes to answer queries on. Hearing of prime numbers on trees, Yash gets too intoxicated with excitement and asks you to help out and answer queries on trees for him. Tree is rooted at node 1. Each node i has some value ai associated with it. Also, integer m is given.There are queries of two types: for given node v and integer value x, increase all ai in the subtree of node v by value x for given node v, find the number of prime numbers p less than m, for which there exists a node u in the subtree of v and a non-negative integer value k, such that auβ=βpβ+βmΒ·k. | Input: ['8 203 7 9 8 4 11 7 31 21 33 44 54 64 75 842 11 1 12 52 4'] Output:['311'] | [
3
] |
An e-commerce startup pitches to the investors to get funding. They have been functional for n weeks now and also have a website!For each week they know the number of unique visitors during this week vi and the revenue ci. To evaluate the potential of the startup at some range of weeks from l to r inclusive investors use the minimum among the maximum number of visitors multiplied by 100 and the minimum revenue during this period, that is: The truth is that investors have no idea how to efficiently evaluate the startup, so they are going to pick some k random distinct weeks li and give them to managers of the startup. For each li they should pick some riββ₯βli and report maximum number of visitors and minimum revenue during this period.Then, investors will calculate the potential of the startup for each of these ranges and take minimum value of p(li,βri) as the total evaluation grade of the startup. Assuming that managers of the startup always report the optimal values of ri for some particular li, i.e., the value such that the resulting grade of the startup is maximized, what is the expected resulting grade of the startup? | Input: ['3 23 2 1300 200 300'] Output:['133.3333333'] | [
4
] |
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fnβ+β2β=βfnβ+β1β+βfn for all nββ₯β0. You are given some sequence of integers a1,βa2,β...,βan. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | Input: ['31 2 -1'] Output:['3'] | [
0,
3
] |
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem? | Input: ['1'] Output:['55 6 7 8 9 '] | [
0,
3
] |
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots.For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of damage. In order to break the shield Dante has to deal exactly c units of damage. Find out if this is possible. | Input: ['4 6 15'] Output:['No'] | [
0,
3
] |
You're given a matrix A of size nβΓβn.Let's call the matrix with nonnegative elements magic if it is symmetric (so aijβ=βaji), aiiβ=β0 and aijββ€βmax(aik,βajk) for all triples i,βj,βk. Note that i,βj,βk do not need to be distinct.Determine if the matrix is magic.As the input/output can reach very huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | Input: ['30 1 21 0 22 2 0'] Output:['MAGIC'] | [
0
] |
A thief made his way to a shop.As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai.The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind).Find all the possible total costs of products the thief can nick into his knapsack. | Input: ['3 21 2 3'] Output:['2 3 4 5 6'] | [
3
] |
You are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value lββ€βm.A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase zero or all elements.The LCM of an empty array equals 1. | Input: ['7 86 2 9 2 7 2 3'] Output:['6 51 2 4 6 7'] | [
0,
3
] |
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.The way to split up game pieces is split into several steps: First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once. Alice will get all the pieces marked A and Bob will get all the pieces marked B. The strength of a player is then the sum of strengths of the pieces in the group.Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve. | Input: ['51 2 3 4 5ABABA'] Output:['11'] | [
0
] |
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.We define function f(x,βl,βr) as a bitwise OR of integers xl,βxlβ+β1,β...,βxr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a,βl,βr)β+βf(b,βl,βr) among all possible 1ββ€βlββ€βrββ€βn. | Input: ['51 2 4 3 22 3 3 12 1'] Output:['22'] | [
0
] |
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.The game is played on a square field consisting of nβΓβn cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.The professor have chosen the field size n and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally. | Input: ['1'] Output:['1'] | [
3
] |
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids β one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. | Input: ['2 5 3'] Output:['38.546168065709'] | [
3
] |
The Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one. | Input: ['1 30 200'] Output:['-10.000000000000000-20.000000000000000'] | [
3
] |
Vasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face.One of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget β a rotating camera β come up to it to see it better, look into it. And the camera takes their photo at that time. What could be better for high quality identification?But not everything is so simple. The pictures from camera appear rotated too (on clockwise camera rotation frame the content becomes rotated counter-clockwise). But the identification algorithm can work only with faces that are just slightly deviated from vertical.Vasya was entrusted to correct the situation β to rotate a captured image so that image would be minimally deviated from vertical. Requirements were severe. Firstly, the picture should be rotated only on angle divisible by 90 degrees to not lose a bit of information about the image. Secondly, the frames from the camera are so huge and FPS is so big that adequate rotation speed is provided by hardware FPGA solution only. And this solution can rotate only by 90 degrees clockwise. Of course, one can apply 90 degrees turn several times but for the sake of performance the number of turns should be minimized.Help Vasya implement the program that by the given rotation angle of the camera can determine the minimum number of 90 degrees clockwise turns necessary to get a picture in which up direction deviation from vertical is minimum.The next figure contains frames taken from an unrotated camera, then from rotated 90 degrees clockwise, then from rotated 90 degrees counter-clockwise. Arrows show direction to "true up". The next figure shows 90 degrees clockwise turn by FPGA hardware. | Input: ['60'] Output:['1'] | [
3
] |
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose β to show the developer the imperfection of their protection.The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.Vasya is going to write a keygen program implementing this algorithm. Can you do the same? | Input: ['12345'] Output:['71232'] | [
3
] |
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus.A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it. | Input: ['12'] Output:['2'] | [
3
] |
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer of this game gets a small bonus.A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it. | Input: ['3000'] Output:['1'] | [
3
] |
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.The parking lot before the office consists of one line of (2nβ-β2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly n successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way. | Input: ['3'] Output:['24'] | [
3
] |
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.Help the park administration count the number of ways to place the benches. | Input: ['5'] Output:['120'] | [
3
] |
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants. | Input: ['2'] Output:['24'] | [
3
] |
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate. | Input: ['7'] Output:['29'] | [
3
] |
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.More formally, if a game designer selected cells having coordinates (x1,βy1) and (x2,βy2), where x1ββ€βx2 and y1ββ€βy2, then all cells having center coordinates (x,βy) such that x1ββ€βxββ€βx2 and y1ββ€βyββ€βy2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x2β-βx1 is divisible by 2.Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.Help him implement counting of these units before painting. | Input: ['1 1 5 5'] Output:['13'] | [
3
] |
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell. | Input: ['2'] Output:['19'] | [
3
] |
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits. | Input: ['2'] Output:['6'] | [
3
] |
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times. | Input: ['1000 1000000'] Output:['1011.060722383550382782399454922040'] | [
3
] |
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party. | Input: ['4M 151 307F 343 352F 117 145M 24 128'] Output:['2'] | [
0
] |
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a nβΓβn square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column. | Input: ['3.CCC..C.C'] Output:['4'] | [
0
] |
Limak is a little polar bear. He likes nice strings β strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | Input: ['4 26bear'] Output:['roar'] | [
2
] |
A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.The tournament takes place in the following way (below, m is the number of the participants of the current round): let k be the maximal power of the number 2 such that kββ€βm, k participants compete in the current round and a half of them passes to the next round, the other mβ-βk participants pass to the next round directly, when only one participant remains, the tournament finishes. Each match requires b bottles of water for each participant and one bottle for the judge. Besides p towels are given to each participant for the whole tournament.Find the number of bottles and towels needed for the tournament.Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose). | Input: ['5 2 3'] Output:['20 15'] | [
3
] |
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first k nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum ai she finds among those k nodes.Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of each node in any order he likes. Help Jacob find the best grade he can get on this assignment.A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node v, the procedure does the following: Print v. Traverse the list of neighbors of the node v in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node u if you came to node v directly from u. | Input: ['5 33 6 1 4 21 22 42 51 3'] Output:['3'] | [
2,
4
] |
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery. | Input: ['10 4 43 55 86 38 4'] Output:['22'] | [
2
] |
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a,βb)? | Input: ['9 5'] Output:['4'] | [
3
] |
Johnny is at a carnival which has n raffles. Raffle i has a prize with value pi. Each participant can put tickets in whichever raffles they choose (they may have more than one ticket in a single raffle). At the end of the carnival, one ticket is selected at random from each raffle, and the owner of the ticket wins the associated prize. A single person can win multiple prizes from different raffles. However, county rules prevent any one participant from owning more than half the tickets in a single raffle, i.e. putting more tickets in the raffle than all the other participants combined. To help combat this (and possibly win some prizes), the organizers started by placing a single ticket in each raffle, which they will never remove.Johnny bought t tickets and is wondering where to place them. Currently, there are a total of li tickets in the i-th raffle. He watches as other participants place tickets and modify their decisions and, at every moment in time, wants to know how much he can possibly earn. Find the maximum possible expected value of Johnny's winnings at each moment if he distributes his tickets optimally. Johnny may redistribute all of his tickets arbitrarily between each update, but he may not place more than t tickets total or have more tickets in a single raffle than all other participants combined. | Input: ['2 1 34 51 21 11 22 1'] Output:['1.6666666671.3333333332.000000000'] | [
2,
3
] |
Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of n (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size. | Input: ['41 2 3 12'] Output:['31 2 12 '] | [
3,
4,
4
] |
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew? | Input: ['21 2'] Output:['0.0000000000'] | [
0
] |
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks.The students donβt want to use too many blocks, but they also want to be unique, so no two studentsβ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers. | Input: ['1 3'] Output:['9'] | [
0,
2,
3
] |
Catherine has a deck of n cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color. She repeats this process until there is only one card left. What are the possible colors for the final card? | Input: ['2RB'] Output:['G'] | [
3
] |
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. | Input: ['6URLLDR'] Output:['2'] | [
0
] |
Ostap Bender recently visited frog farm and was inspired to create his own frog game.Number of frogs are places on a cyclic gameboard, divided into m cells. Cells are numbered from 1 to m, but the board is cyclic, so cell number 1 goes right after the cell number m in the direction of movement. i-th frog during its turn can jump for ai cells.Frogs move in turns, game starts with a move by frog 1. On its turn i-th frog moves ai cells forward, knocking out all the frogs on its way. If there is a frog in the last cell of the path of the i-th frog, that frog is also knocked out. After this the value ai is decreased by the number of frogs that were knocked out during this turn. If ai is zero or goes negative, then i-th frog doesn't make moves anymore.After frog number 1 finishes its turn, frog number 2 starts to move, then frog number 3 and so on. After the frog number n makes its move, frog 1 starts to move again, then frog 2 and so on this process goes forever. If some frog was already knocked out from the board, we consider that it skips all its moves.Help Ostap to identify, what frogs will stay on the board at the end of a game? | Input: ['3 52 15 34 3'] Output:['13 '] | [
2
] |
Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that aβ+βarβ=βn or determine that such a doesn't exist. | Input: ['4'] Output:['2'] | [
3
] |
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string. | Input: ['intellecttell'] Output:['1'] | [
2
] |
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (cβ<βb) rubles back, but you cannot return plastic bottles.Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help. | Input: ['101198'] Output:['2'] | [
3
] |
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: the i-th letter occurs in the string no more than ai times; the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once. | Input: ['32 5 5'] Output:['11'] | [
2
] |
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other with speed v1 and v2, respectively. Luke has width d and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive. | Input: ['2 6 2 2'] Output:['1.00000000000000000000'] | [
3
] |
Let's define the transformation P of a sequence of integers a1,βa2,β...,βan as b1,βb2,β...,βbn, where biβ=βa1 | a2 | ... | ai for all iβ=β1,β2,β...,βn, where | is the bitwise OR operation.Vasya consequently applies the transformation P to all sequences of length n consisting of integers from 1 to 2kβ-β1 inclusive. He wants to know how many of these sequences have such property that their transformation is a strictly increasing sequence. Help him to calculate this number modulo 109β+β7. | Input: ['1 2'] Output:['3'] | [
3
] |
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. n friends came by, and after a typical party they decided to play blind man's buff.The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the i-th friend does not change between rounds and is equal to pi percent (as we know, it is directly proportional to the amount of alcohol consumed by the i-th friend) and p1β+βp2β+β...β+βpnβ=β100 holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins.The game ends when Misha guesses every friend at least once, that is, there exists such set of rounds k1,βk2,β...,βkn, that during round number ki Misha caught the i-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally. | Input: ['250 50'] Output:['5.0000000000'] | [
2,
3
] |
Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals.A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: axis X is positive and axis Y is negative.Experienced laboratory worker marked n points with integer coordinates (xi,βyi) on the plane and stopped the time. Sasha should use "atomic tweezers" to place elementary particles in these points. He has an unlimited number of electrons (negatively charged elementary particles) and protons (positively charged elementary particles). He can put either an electron or a proton at each marked point. As soon as all marked points are filled with particles, laboratory worker will turn on the time again and the particles will come in motion and after some time they will stabilize in equilibrium. The objective of the laboratory work is to arrange the particles in such a way, that the diameter of the resulting state (the maximum distance between the pairs of points of the set) is as small as possible.Since Sasha is a programmer, he naively thinks that all the particles will simply "fall" into their projections on the corresponding axes: electrons will fall on axis X, while protons will fall on axis Y. As we are programmers too, we will consider the same model as Sasha. That is, a particle gets from point (x,βy) to point (x,β0) if it is an electron and to point (0,βy) if it is a proton.As the laboratory has high background radiation and Sasha takes care of his laptop, he did not take it with him, and now he can't write a program that computes the minimum possible diameter of the resulting set. Therefore, you will have to do it for him.Print a square of the minimum possible diameter of the set. | Input: ['31 101 201 30'] Output:['0'] | [
4
] |
You are given array ai of length n. You may consecutively apply two operations to this array: remove some subsegment (continuous subsequence) of length mβ<βn and pay for it mΒ·a coins; change some elements of the array by at most 1, and pay b coins for each change. Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1. | Input: ['3 1 44 2 3'] Output:['1'] | [
2
] |
There are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees.Find the value of the sum modulo 109β+β7 (so you should find the remainder after dividing the answer by the value 109β+β7). | Input: ['4 1'] Output:['10'] | [
3
] |
Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. | Input: ['121 21 31 42 52 63 73 83 98 108 118 12'] Output:['6'] | [
2
] |
Consider the infinite sequence of integers: 1,β1,β2,β1,β2,β3,β1,β2,β3,β4,β1,β2,β3,β4,β5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).Find the number on the n-th position of the sequence. | Input: ['3'] Output:['2'] | [
3
] |
Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options: a1β=βxyz; a2β=βxzy; a3β=β(xy)z; a4β=β(xz)y; a5β=βyxz; a6β=βyzx; a7β=β(yx)z; a8β=β(yz)x; a9β=βzxy; a10β=βzyx; a11β=β(zx)y; a12β=β(zy)x. Let m be the maximum of all the ai, and c be the smallest index (from 1 to 12) such that acβ=βm. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that ac. | Input: ['1.1 3.4 2.5'] Output:['z^y^x'] | [
0,
3
] |
There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and iβ+β1 are neighbours for all i from 1 to nβ-β1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product siΒ·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value. | Input: ['3 21 2420 421420420 420421'] Output:['4500.0'] | [
3
] |
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value vβ=β|saβ-βsb|.In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5,β1,β3,β2,β4] and the array b is [3,β3,β2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2,β1,β3,β2,β4] and the new array b [3,β3,β5].Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b. | Input: ['55 4 3 2 141 1 1 1'] Output:['121 14 2'] | [
4
] |
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | Input: ['51 2 3 4 1'] Output:['11 5'] | [
2
] |
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1,βy1) and should go to the point (x2,βy2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position. | Input: ['0 04 5'] Output:['5'] | [
3
] |
Your friend recently gave you some slimes for your birthday. You have a very large amount of slimes with value 1 and 2, and you decide to invent a game using these slimes.You initialize a row with n empty spaces. You also choose a number p to be used in the game. Then, you will perform the following steps while the last space is empty. With probability , you will choose a slime with value 1, and with probability , you will choose a slime with value 2. You place the chosen slime on the last space of the board. You will push the slime to the left as far as possible. If it encounters another slime, and they have the same value v, you will merge the slimes together to create a single slime with value vβ+β1. This continues on until the slime reaches the end of the board, or encounters a slime with a different value than itself. You have played the game a few times, but have gotten bored of it. You are now wondering, what is the expected sum of all values of the slimes on the board after you finish the game. | Input: ['2 500000000'] Output:['3.562500000000000'] | [
3
] |
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly nβ-β1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once. | Input: ['5 2 31 21 33 45 3'] Output:['9'] | [
2
] |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(xβ>β0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house. | Input: ['5'] Output:['1'] | [
3
] |
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109β+β7 (the remainder when divided by 109β+β7).The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1. | Input: ['3 4'] Output:['4'] | [
3
] |
The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. | Input: ['5 51 2 3 4 5'] Output:['1 5'] | [
4
] |
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love. | Input: ['3 44 1 3 52 2 2 25 4 5 1'] Output:['2'] | [
2
] |
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined: Ayrat is searching through the field. He started at point (0,β0) and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after n moves. | Input: ['3'] Output:['-2 0'] | [
3,
4
] |
Ayrat has number n, represented as it's prime factorization pi of size m, i.e. nβ=βp1Β·p2Β·...Β·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109β+β7 is the password to the secret data base. Now he wants to calculate this value. | Input: ['22 3'] Output:['36'] | [
3
] |
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer. | Input: ['abccbaabc'] Output:['23 11 3'] | [
2
] |
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. | Input: ['35 10 1'] Output:['50'] | [
3
] |
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him! | Input: ['1 10 2'] Output:['1 2 4 8 '] | [
0
] |
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace. | Input: ['34 2 1'] Output:['1abacaba'] | [
3
] |
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β the current skill level. All skills have the same maximum level A.Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: The number of skills that a character has perfected (i.e., such that aiβ=βA), multiplied by coefficient cf. The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. | Input: ['3 5 10 1 51 3 1'] Output:['122 5 2 '] | [
0,
2,
4
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.