question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
Alex studied well and won the trip to student camp Alushta, located on the seashore. Unfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of nβ+β2 concrete blocks height and m blocks width.Every day there is a breeze blowing from the sea. Each block, except for the blocks of the upper and lower levers, such that there is no block to the left of it is destroyed with the probability . Similarly, each night the breeze blows in the direction to the sea. Thus, each block (again, except for the blocks of the upper and lower levers) such that there is no block to the right of it is destroyed with the same probability p. Note, that blocks of the upper and lower level are indestructible, so there are only nΒ·m blocks that can be destroyed.The period of the strong winds will last for k days and k nights. If during this period the building will split in at least two connected components, it will collapse and Alex will have to find another place to spend summer.Find the probability that Alex won't have to look for other opportunities and will be able to spend the summer in this camp. | Input: ['2 21 21'] Output:['937500007'] | [
3
] |
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed .You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement. | Input: ['31 22 3'] Output:['1 1 1 '] | [
2
] |
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x,βy}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1β000β000. | Input: ['1 2 3 4'] Output:['Impossible'] | [
2,
3
] |
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once? | Input: ['codeforces'] Output:['bncdenqbdr'] | [
2
] |
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3,β4,β5), (5,β12,β13) and (6,β8,β10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same? | Input: ['3'] Output:['4 5'] | [
3
] |
Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: "+ x" β add integer x to multiset A. "- x" β erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x" β you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed. | Input: ['10+ 8+ 9+ 11+ 6+ 1? 3- 8? 3? 8? 11'] Output:['11101413'] | [
4
] |
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola". | Input: ['53 10 8 6 114110311'] Output:['0415'] | [
4
] |
Vasiliy lives at point (a,βb) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi,βyi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars. | Input: ['0 022 0 10 2 2'] Output:['1.00000000000000000000'] | [
0
] |
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and xβ-βp vertices where 1ββ€βpβ<βx is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help. | Input: ['31 2 3'] Output:['211'] | [
3
] |
Steve Rogers is fascinated with new vibranium shields S.H.I.E.L.D gave him. They're all uncolored. There are n shields in total, the i-th shield is located at point (xi,βyi) of the coordinate plane. It's possible that two or more shields share the same location.Steve wants to paint all these shields. He paints each shield in either red or blue. Painting a shield in red costs r dollars while painting it in blue costs b dollars.Additionally, there are m constraints Steve wants to be satisfied. The i-th constraint is provided by three integers ti, li and di: If tiβ=β1, then the absolute difference between the number of red and blue shields on line xβ=βli should not exceed di. If tiβ=β2, then the absolute difference between the number of red and blue shields on line yβ=βli should not exceed di. Steve gave you the task of finding the painting that satisfies all the condition and the total cost is minimum. | Input: ['5 68 32 101 59 109 102 81 9 11 2 12 10 32 10 21 1 12 5 2'] Output:['25rbrbb'] | [
2
] |
Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi,βj are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi,βj are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1,βx2,β...,βxm and their negations. An XNF formula is 2-XNF-2 if: For each 1ββ€βiββ€βn, kiββ€β2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1,β...,βxm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109β+β7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | Input: ['6 72 4 -22 6 32 -7 12 -5 12 3 62 -2 -5'] Output:['48'] | [
3
] |
Scott Lang is at war with Darren Cross. There are n chairs in a hall where they are, numbered with 1,β2,β...,βn from left to right. The i-th chair is located at coordinate xi. Scott is on chair number s and Cross is on chair number e. Scott can jump to all other chairs (not only neighboring chairs). He wants to start at his position (chair number s), visit each chair exactly once and end up on chair number e with Cross. As we all know, Scott can shrink or grow big (grow big only to his normal size), so at any moment of time he can be either small or large (normal). The thing is, he can only shrink or grow big while being on a chair (not in the air while jumping to another chair). Jumping takes time, but shrinking and growing big takes no time. Jumping from chair number i to chair number j takes |xiβ-βxj| seconds. Also, jumping off a chair and landing on a chair takes extra amount of time. If Scott wants to jump to a chair on his left, he can only be small, and if he wants to jump to a chair on his right he should be large.Jumping off the i-th chair takes: ci extra seconds if he's small. di extra seconds otherwise (he's large). Also, landing on i-th chair takes: bi extra seconds if he's small. ai extra seconds otherwise (he's large). In simpler words, jumping from i-th chair to j-th chair takes exactly: |xiβ-βxj|β+βciβ+βbj seconds if jβ<βi. |xiβ-βxj|β+βdiβ+βaj seconds otherwise (jβ>βi). Given values of x, a, b, c, d find the minimum time Scott can get to Cross, assuming he wants to visit each chair exactly once. | Input: ['7 4 38 11 12 16 17 18 2017 16 20 2 20 5 1317 8 8 16 12 15 1312 4 16 4 15 7 68 14 2 11 17 12 8'] Output:['139'] | [
2
] |
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. | Input: ['3 41 31 11 22 3'] Output:['1232'] | [
0
] |
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX β beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1βββ2βββ...βββnβββ1. Formally, for every 1ββ€βiβ<βn there is a road between i-th and iβ+β1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1ββ€βiββ€βn,ββiββ βx, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ciΒ·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (aβ<βb), such that there is a road between a and b you are to find sum of products caΒ·cb. Will you help her? | Input: ['4 12 3 1 23'] Output:['17'] | [
3
] |
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers.Vasiliy's car is not new β it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station.To drive one kilometer on car Vasiliy spends a seconds, to walk one kilometer on foot he needs b seconds (aβ<βb).Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot. | Input: ['5 2 1 4 10'] Output:['14'] | [
3
] |
You are given n points on the straight line β the positions (x-coordinates) of the cities and m points on the same line β the positions (x-coordinates) of the cellular towers. All towers work in the same way β they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If rβ=β0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower. | Input: ['3 2-2 2 4-3 0'] Output:['4'] | [
4
] |
You are given n integers a1,βa2,β...,βan. Find the number of pairs of indexes i,βj (iβ<βj) that aiβ+βaj is a power of 2 (i. e. some integer x exists so that aiβ+βajβ=β2x). | Input: ['47 3 2 1'] Output:['2'] | [
0,
3
] |
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. | Input: ['51 7 2 11 15'] Output:['3'] | [
2
] |
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number nβ-β1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit. | Input: ['3AaA'] Output:['2'] | [
4
] |
Vasya has the square chessboard of size nβΓβn and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board. | Input: ['3 31 13 12 2'] Output:['4 2 0 '] | [
3
] |
There are n cards (n is even) in the deck. Each card has a positive integer written on it. nβ/β2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible. | Input: ['61 5 7 4 4 3'] Output:['1 36 24 5'] | [
2
] |
Alice wants to send an important message to Bob. Message aβ=β(a1,β...,βan) is a sequence of positive integers (characters).To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function f, that maps each letter that appears in the string to some binary string (that is, string consisting of characters '0' and '1' only) such that for each pair of different characters ai and aj string f(ai) is not a prefix of f(aj) (and vice versa). The result of the encoding of the message a1,βa2,β...,βan is the concatenation of the encoding of each character, that is the string f(a1)f(a2)... f(an). Huffman codes are very useful, as the compressed message can be easily and uniquely decompressed, if the function f is given. Code is usually chosen in order to minimize the total length of the compressed message, i.e. the length of the string f(a1)f(a2)... f(an).Because of security issues Alice doesn't want to send the whole message. Instead, she picks some substrings of the message and wants to send them separately. For each of the given substrings ali... ari she wants to know the minimum possible length of the Huffman coding. Help her solve this problem. | Input: ['71 2 1 3 1 2 151 71 33 52 44 4'] Output:['103350'] | [
2
] |
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. | Input: ['5 10 1 2 5'] Output:['5.0000000000'] | [
3,
4
] |
Bearland is a dangerous place. Limak canβt travel on foot. Instead, he has k magic teleportation stones. Each stone can be used at most once. The i-th stone allows to teleport to a point (axi,βayi). Limak can use stones in any order.There are n monsters in Bearland. The i-th of them stands at (mxi,βmyi).The given kβ+βn points are pairwise distinct.After each teleportation, Limak can shoot an arrow in some direction. An arrow will hit the first monster in the chosen direction. Then, both an arrow and a monster disappear. Itβs dangerous to stay in one place for long, so Limak can shoot only one arrow from one place.A monster should be afraid if itβs possible that Limak will hit it. How many monsters should be afraid of Limak? | Input: ['2 4-2 -14 54 22 14 -11 -1'] Output:['3'] | [
0,
3
] |
While creating high loaded systems one should pay a special attention to caching. This problem will be about one of the most popular caching algorithms called LRU (Least Recently Used).Suppose the cache may store no more than k objects. At the beginning of the workflow the cache is empty. When some object is queried we check if it is present in the cache and move it here if it's not. If there are more than k objects in the cache after this, the least recently used one should be removed. In other words, we remove the object that has the smallest time of the last query.Consider there are n videos being stored on the server, all of the same size. Cache can store no more than k videos and caching algorithm described above is applied. We know that any time a user enters the server he pick the video i with probability pi. The choice of the video is independent to any events before.The goal of this problem is to count for each of the videos the probability it will be present in the cache after 10100 queries. | Input: ['3 10.3 0.2 0.5'] Output:['0.3 0.2 0.5 '] | [
3
] |
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and xβ=βAβΓβ10B is true. In our case A is between 0 and 9 and B is non-negative.Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding. | Input: ['8.549e2'] Output:['854.9'] | [
0,
3
] |
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, tβ+βs, tβ+βsβ+β1, tβ+β2s, tβ+β2sβ+β1, etc. Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time. | Input: ['3 10 4'] Output:['NO'] | [
3
] |
Barney has finally found the one, a beautiful young lady named Lyanna. The problem is, Lyanna and Barney are trapped in Lord Loss' castle. This castle has shape of a convex polygon of n points. Like most of castles in Demonata worlds, this castle has no ceiling. Barney and Lyanna have an escape plan, but it requires some geometry knowledge, so they asked for your help.Barney knows that demons are organized and move in lines. He and Lyanna want to wait for the appropriate time so they need to watch for the demons. Each of them wants to stay in a point inside the castle (possibly on edges or corners), also they may stay in the same position. They both want to pick a real number r and watch all points in the circles with radius r around each of them (these two circles may overlap). We say that Barney and Lyanna are watching carefully if and only if for every edge of the polygon, at least one of them can see at least one point on the line this edge lies on, thus such point may not be on the edge but it should be on edge's line. Formally, each edge line should have at least one common point with at least one of two circles.The greater r is, the more energy and focus they need. So they asked you to tell them the minimum value of r such that they can watch carefully. | Input: ['4-41 67-16 2025 25-36 85'] Output:['0-16 20-36 85'] | [
4
] |
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1,βa2,β...,βak such that in other words, n is multiplication of all elements of the given array.Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction pβ/βq such that , where is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109β+β7.Please note that we want of p and q to be 1, not of their remainders after dividing by 109β+β7. | Input: ['12'] Output:['1/2'] | [
3
] |
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and nβ-β1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:let starting_time be an array of length ncurrent_time = 0dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u)As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help. | Input: ['71 2 1 1 4 4'] Output:['1.0 4.0 5.0 3.5 4.5 5.0 5.0 '] | [
3
] |
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | Input: ['71 3 4 301 4 1 21 3 6 82 4 31 6 1 402 3 72 2 4'] Output:['94032'] | [
0
] |
Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with n balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) β the number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball β the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold p square meters, the players win. Otherwise, they lose.The organizers of the game are trying to select an appropriate value for p so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of p. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different. | Input: ['54 2 6 1 341 3 5 8'] Output:['20181410'] | [
0
] |
You are given a permutation of the numbers 1,β2,β...,βn and m pairs of positions (aj,βbj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1,β2,β...,βn. p is lexicographically smaller than the q if a number 1ββ€βiββ€βn exists, so pkβ=βqk for 1ββ€βkβ<βi and piβ<βqi. | Input: ['9 61 2 3 4 5 6 7 8 91 44 72 55 83 66 9'] Output:['7 8 9 4 5 6 1 2 3'] | [
3
] |
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) β who knows? Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l,βr), Mike can instantly tell the value of while !Mike can instantly tell the value of .Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l,βr) (1ββ€βlββ€βrββ€βn) (so he will make exactly n(nβ+β1)β/β2 queries) and counts how many times their answers coincide, thus for how many pairs is satisfied.How many occasions will the robot count? | Input: ['61 2 3 2 1 46 7 1 2 3 2'] Output:['2'] | [
4
] |
Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible! Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly k times more than the previous one. The value of k (kβ>β1) is a secret integer known only to them. It is also known that each thief's bag can carry at most n chocolates (if they intend to take more, the deal is cancelled) and that there were exactly four thieves involved. Sadly, only the thieves know the value of n, but rumours say that the numbers of ways they could have taken the chocolates (for a fixed n, but not fixed k) is m. Two ways are considered different if one of the thieves (they should be numbered in the order they take chocolates) took different number of chocolates in them.Mike want to track the thieves down, so he wants to know what their bags are and value of n will help him in that. Please find the smallest possible value of n or tell him that the rumors are false and there is no such n. | Input: ['1'] Output:['8'] | [
3,
4
] |
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |iβ-βj| units of energy. The total energy spent by Mike to visit a sequence of intersections p1β=β1,βp2,β...,βpk is equal to units of energy.Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (iββ€βaiββ€βaiβ+β1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1β=β1,βp2,β...,βpk then for each 1ββ€βiβ<βk satisfying piβ+β1β=βapi and apiββ βpi Mike will spend only 1 unit of energy instead of |piβ-βpiβ+β1| walking from the intersection pi to intersection piβ+β1. For example, if Mike chooses a sequence p1β=β1,βp2β=βap1,βp3β=βap2,β...,βpkβ=βapkβ-β1, he spends exactly kβ-β1 units of total energy walking around them.Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1ββ€βiββ€βn Mike is interested in finding minimum possible total energy of some sequence p1β=β1,βp2,β...,βpkβ=βi. | Input: ['32 2 3'] Output:['0 1 2 '] | [
2
] |
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253": Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements? | Input: ['3586'] Output:['NO'] | [
0
] |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number? | Input: ['1'] Output:['11'] | [
3
] |
Long time ago, there was a great kingdom and it was being ruled by The Great Arya and Pari The Great. These two had some problems about the numbers they like, so they decided to divide the great kingdom between themselves.The great kingdom consisted of n cities numbered from 1 to n and m bidirectional roads between these cities, numbered from 1 to m. The i-th road had length equal to wi. The Great Arya and Pari The Great were discussing about destructing some prefix (all road with numbers less than some x) and suffix (all roads with numbers greater than some x) of the roads so there will remain only the roads with numbers l,βlβ+β1,β...,βrβ-β1 and r.After that they will divide the great kingdom into two pieces (with each city belonging to exactly one piece) such that the hardness of the division is minimized. The hardness of a division is the maximum length of a road such that its both endpoints are in the same piece of the kingdom. In case there is no such road, the hardness of the division is considered to be equal to β-β1.Historians found the map of the great kingdom, and they have q guesses about the l and r chosen by those great rulers. Given these data, for each guess li and ri print the minimum possible hardness of the division of the kingdom. | Input: ['5 6 55 4 865 1 01 3 382 1 332 4 282 3 403 52 61 32 31 6'] Output:['-133-1-133'] | [
0
] |
Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1,βc2,β...,βcn and Pari has to tell Arya if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value for any positive integer x?Note, that means the remainder of x after dividing it by y. | Input: ['4 52 3 5 12'] Output:['Yes'] | [
3
] |
Gerda is travelling to the palace of the Snow Queen.The road network consists of n intersections and m bidirectional roads. Roads are numbered from 1 to m. Snow Queen put a powerful spell on the roads to change the weather conditions there. Now, if Gerda steps on the road i at the moment of time less or equal to i, she will leave the road exactly at the moment i. In case she steps on the road i at the moment of time greater than i, she stays there forever.Gerda starts at the moment of time l at the intersection number s and goes to the palace of the Snow Queen, located at the intersection number t. Moreover, she has to be there at the moment r (or earlier), before the arrival of the Queen.Given the description of the road network, determine for q queries li, ri, si and ti if it's possible for Gerda to get to the palace on time. | Input: ['5 4 61 22 33 43 51 3 1 41 3 2 41 4 4 51 4 4 12 3 1 42 2 2 3'] Output:['YesYesYesNoNoYes'] | [
0
] |
Snow Queen told Kay to form a word "eternity" using pieces of ice. Kay is eager to deal with the task, because he will then become free, and Snow Queen will give him all the world and a pair of skates.Behind the palace of the Snow Queen there is an infinite field consisting of cells. There are n pieces of ice spread over the field, each piece occupying exactly one cell and no two pieces occupying the same cell. To estimate the difficulty of the task Kay looks at some squares of size kβΓβk cells, with corners located at the corners of the cells and sides parallel to coordinate axis and counts the number of pieces of the ice inside them.This method gives an estimation of the difficulty of some part of the field. However, Kay also wants to estimate the total difficulty, so he came up with the following criteria: for each x (1ββ€βxββ€βn) he wants to count the number of squares of size kβΓβk, such that there are exactly x pieces of the ice inside.Please, help Kay estimate the difficulty of the task given by the Snow Queen. | Input: ['5 34 54 65 55 67 7'] Output:['10 8 1 4 0 '] | [
0
] |
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.Mole wants to find an optimal point to watch roses, that is such point with integer coordinates that the maximum Manhattan distance to the rose is minimum possible.As usual, he asks you to help.Manhattan distance between points (x1,β y1,β z1) and (x2,β y2,β z2) is defined as |x1β-βx2|β+β|y1β-βy2|β+β|z1β-βz2|. | Input: ['150 0 40 0 -40 4 04 0 01 1 1'] Output:['0 0 0'] | [
3,
4
] |
Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches.First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hours, and each hour in m minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from 0 to nβ-β1, while the second has the smallest possible number of places that is necessary to display any integer from 0 to mβ-β1. Finally, if some value of hours or minutes can be displayed using less number of places in base 7 than this watches have, the required number of zeroes is added at the beginning of notation.Note that to display number 0 section of the watches is required to have at least one place.Little robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are distinct. Help her calculate this number. | Input: ['2 3'] Output:['4'] | [
0,
3
] |
A chocolate bar has a rectangular shape and consists of nβΓβm slices. In other words, a bar consists of n rows with m slices of chocolate in each row.Each slice of chocolate is known to weigh 1 gram. Your task is to determine for each of the q chocolate bars whether it is possible to obtain a piece weighing p grams by breaking the bar several (possibly zero) times. The final piece of the chocolate bar should be whole, and breaks are made along the line of slices' section for the whole length of the current piece. | Input: ['23 3 44 4 7'] Output:['YesNo'] | [
3
] |
After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers β the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5.Formally, Alyona wants to count the number of pairs of integers (x,βy) such that 1ββ€βxββ€βn, 1ββ€βyββ€βm and equals 0.As usual, Alyona has some troubles and asks you to help. | Input: ['6 12'] Output:['14'] | [
3
] |
Petya has recently learned data structure named "Binary heap".The heap he is now operating with allows the following operations: put the given number into the heap; get the value of the minimum element in the heap; extract the minimum element from the heap; Thus, at any moment of time the heap contains several integers (possibly none), some of them might be equal.In order to better learn this data structure Petya took an empty heap and applied some operations above to it. Also, he carefully wrote down all the operations and their results to his event log, following the format: insert x β put the element with value x in the heap; getMin x β the value of the minimum element contained in the heap was equal to x; removeMin β the minimum element was extracted from the heap (only one instance, if there were many). All the operations were correct, i.e. there was at least one element in the heap each time getMin or removeMin operations were applied.While Petya was away for a lunch, his little brother Vova came to the room, took away some of the pages from Petya's log and used them to make paper boats.Now Vova is worried, if he made Petya's sequence of operations inconsistent. For example, if one apply operations one-by-one in the order they are written in the event log, results of getMin operations might differ from the results recorded by Petya, and some of getMin or removeMin operations may be incorrect, as the heap is empty at the moment they are applied.Now Vova wants to add some new operation records to the event log in order to make the resulting sequence of operations correct. That is, the result of each getMin operation is equal to the result in the record, and the heap is non-empty when getMin ad removeMin are applied. Vova wants to complete this as fast as possible, as the Petya may get back at any moment. He asks you to add the least possible number of operation records to the current log. Note that arbitrary number of operations may be added at the beginning, between any two other operations, or at the end of the log. | Input: ['2insert 3getMin 4'] Output:['4insert 3removeMininsert 4getMin 4'] | [
2
] |
Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to 0.Kolya remembers that at the beginning of the game his game-coin score was equal to n and that he have bought only some houses (for 1β234β567 game-coins each), cars (for 123β456 game-coins each) and computers (for 1β234 game-coins each).Kolya is now interested, whether he could have spent all of his initial n game-coins buying only houses, cars and computers or there is a bug in the game. Formally, is there a triple of non-negative integers a, b and c such that aβΓβ1β234β567β+βbβΓβ123β456β+βcβΓβ1β234β=βn?Please help Kolya answer this question. | Input: ['1359257'] Output:['YES'] | [
0
] |
Bearland has n cities, numbered 1 through n. There are m bidirectional roads. The i-th road connects two distinct cities ai and bi. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).The distance between cities a and b is defined as the minimum number of roads used to travel between a and b.Limak is a grizzly bear. He is a criminal and your task is to catch him, or at least to try to catch him. You have only two days (today and tomorrow) and after that Limak is going to hide forever.Your main weapon is BCD (Bear Criminal Detector). Where you are in some city, you can use BCD and it tells you the distance between you and a city where Limak currently is. Unfortunately, BCD can be used only once a day.You don't know much about Limak's current location. You assume that he is in one of n cities, chosen uniformly at random (each city with probability ). You decided for the following plan: Choose one city and use BCD there. After using BCD you can try to catch Limak (but maybe it isn't a good idea). In this case you choose one city and check it. You win if Limak is there. Otherwise, Limak becomes more careful and you will never catch him (you loose). Wait 24 hours to use BCD again. You know that Limak will change his location during that time. In detail, he will choose uniformly at random one of roads from his initial city, and he will use the chosen road, going to some other city. Tomorrow, you will again choose one city and use BCD there. Finally, you will try to catch Limak. You will choose one city and check it. You will win if Limak is there, and loose otherwise. Each time when you choose one of cities, you can choose any of n cities. Let's say it isn't a problem for you to quickly get somewhere.What is the probability of finding Limak, if you behave optimally? | Input: ['3 31 21 32 3'] Output:['0.833333333333'] | [
0,
3
] |
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.A block with side a has volume a3. A tower consisting of blocks with sides a1,βa2,β...,βak has the total volume a13β+βa23β+β...β+βak3.Limak is going to build a tower. First, he asks you to tell him a positive integer X β the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.Can you help Limak? Find the maximum number of blocks his tower can have and the maximum Xββ€βm that results this number of blocks. | Input: ['48'] Output:['9 42'] | [
2,
4
] |
This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number β an integer from interval [2,β100]. Your task is to say if the hidden number is prime or composite.Integer xβ>β1 is called prime if it has exactly two distinct divisors, 1 and x. If integer xβ>β1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2,β100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2,β100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below). | Input: ['yesnoyes'] Output:['2805composite'] | [
3
] |
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory. | Input: ['30.0 0.5 0.80.5 0.0 0.40.2 0.6 0.0'] Output:['0.680000000000000'] | [
3
] |
Consider a linear function f(x)β=βAxβ+βB. Let's define g(0)(x)β=βx and g(n)(x)β=βf(g(nβ-β1)(x)) for nβ>β0. For the given integer values A, B, n and x find the value of g(n)(x) modulo 109β+β7. | Input: ['3 4 1 1'] Output:['7'] | [
3
] |
Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a and b can be either painted Red or Blue.After her painting is done, she will get p chocolates for each tile that is painted Red and q chocolates for each tile that is painted Blue.Note that she can paint tiles in any order she wants.Given the required information, find the maximum number of chocolates Joty can get. | Input: ['5 2 3 12 15'] Output:['39'] | [
3
] |
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k. | Input: ['5 3'] Output:['6'] | [
3
] |
Vanya plays a game of balloons on the field of size nβΓβn, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:**o****o**ooooo**o****o**oro***o*o*o***o***o*o*o***oFormally, the cross is given by three integers r, c and d, such that dββ€βr,βcββ€βnβ-βdβ+β1. The normal cross consists of balloons located in cells (x,βy) (where x stay for the number of the row and y for the number of the column), such that |xβ-βr|Β·|yβ-βc|β=β0 and |xβ-βr|β+β|yβ-βc|β<βd. Rotated cross consists of balloons located in cells (x,βy), such that |xβ-βr|β=β|yβ-βc| and |xβ-βr|β<βd.Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109β+β7. | Input: ['41233021320200303'] Output:['108'] | [
0,
4
] |
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens: If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece. Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed. | Input: ['5 6 35 4 3 2 1'] Output:['5'] | [
3
] |
100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.The following game was chosen for the fights: initially there is a polynomial P(x)β=βanxnβ+βanβ-β1xnβ-β1β+β...β+βa1xβ+βa0,β with yet undefined coefficients and the integer k. Players alternate their turns. At each turn, a player pick some index j, such that coefficient aj that stay near xj is not determined yet and sets it to any value (integer or real, positive or negative, 0 is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by Q(x)β=βxβ-βk.Polynomial P(x) is said to be divisible by polynomial Q(x) if there exists a representation P(x)β=βB(x)Q(x), where B(x) is also some polynomial.Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally? | Input: ['1 2-1?'] Output:['Yes'] | [
3
] |
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? | Input: ['4 2abba'] Output:['4'] | [
4
] |
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (counting from the top), then 3 glasses on the third level and so on.The bottom level consists of n glasses.Vlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid.Each second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in t seconds.Pictures below illustrate the pyramid consisting of three levels. | Input: ['3 5'] Output:['4'] | [
3,
3
] |
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from iβ+β1 to ai inclusive. No tickets are sold at the last station.Let Οi,βj be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values Οi,βj among all pairs 1ββ€βiβ<βjββ€βn. | Input: ['44 4 4'] Output:['6'] | [
2
] |
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if nβ>β1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero. | Input: ['35 0 -5'] Output:['1'] | [
2
] |
Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. The painting is a square 3βΓβ3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. The sum of integers in each of four squares 2βΓβ2 is equal to the sum of integers in the top left square 2βΓβ2. Four elements a, b, c and d are known and are located as shown on the picture below. Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong.Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. | Input: ['2 1 1 1 2'] Output:['2'] | [
0,
3
] |
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1β=βa), and the difference between any two neighbouring elements is equal to c (siβ-βsiβ-β1β=βc). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that siβ=βb. Of course, you are the person he asks for a help. | Input: ['1 7 3'] Output:['YES'] | [
3
] |
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions. Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k. | Input: ['5 21 45 2'] Output:['2'] | [
2
] |
Kekoland is a country with n beautiful cities numbered from left to right and connected by nβ-β1 roads. The i-th road connects cities i and iβ+β1 and length of this road is wi kilometers. When you drive in Kekoland, each time you arrive in city i by car you immediately receive gi liters of gas. There is no other way to get gas in Kekoland.You were hired by the Kekoland president Keko to organize the most beautiful race Kekoland has ever seen. Let race be between cities l and r (lββ€βr). Race will consist of two stages. On the first stage cars will go from city l to city r. After completing first stage, next day second stage will be held, now racers will go from r to l with their cars. Of course, as it is a race, racers drive directly from start city to finish city. It means that at the first stage they will go only right, and at the second stage they go only left. Beauty of the race between l and r is equal to rβ-βlβ+β1 since racers will see rβ-βlβ+β1 beautiful cities of Kekoland. Cars have infinite tank so racers will take all the gas given to them.At the beginning of each stage racers start the race with empty tank (0 liters of gasoline). They will immediately take their gasoline in start cities (l for the first stage and r for the second stage) right after the race starts. It may not be possible to organize a race between l and r if cars will run out of gas before they reach finish.You have k presents. Each time you give a present to city i its value gi increases by 1. You may distribute presents among cities in any way (also give many presents to one city, each time increasing gi by 1). What is the most beautiful race you can organize?Each car consumes 1 liter of gas per one kilometer. | Input: ['4 42 2 21 1 1 1'] Output:['4'] | [
2
] |
Mayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.Yusland consists of n intersections connected by nβ-β1 bidirectional roads. One can travel from any intersection to any other intersection using only these roads.There is only one road repairing company in town, named "RC company". Company's center is located at the intersection 1. RC company doesn't repair roads you tell them. Instead, they have workers at some intersections, who can repair only some specific paths. The i-th worker can be paid ci coins and then he repairs all roads on a path from ui to some vi that lies on the path from ui to intersection 1. Mayor asks you to choose the cheapest way to hire some subset of workers in order to repair all the roads in Yusland. It's allowed that some roads will be repaired more than once.If it's impossible to repair all roads print β-β1. | Input: ['6 51 21 33 44 54 62 1 23 1 44 1 35 3 16 3 2'] Output:['8'] | [
2
] |
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer. | Input: ['4 11 1 4 2'] Output:['2'] | [
2,
4
] |
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi,βyi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: Choose to stop or to continue to collect bottles. If the choice was to continue then choose some bottle and walk towards it. Pick this bottle and walk to the recycling bin. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. | Input: ['3 1 1 2 0 031 12 12 3'] Output:['11.084259940083'] | [
2
] |
Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k β the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used). | Input: ['003512021'] Output:['30021'] | [
0
] |
The term of this problem is the same as the previous one, the only exception β increased restrictions. | Input: ['1 100000000011000000000'] Output:['2000000000'] | [
4
] |
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai β how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder. | Input: ['3 12 1 411 3 16'] Output:['4'] | [
0,
4
] |
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings β 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. | Input: ['14'] Output:['4 4'] | [
0,
2,
3
] |
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.How many times can Artem give presents to Masha? | Input: ['1'] Output:['1'] | [
3
] |
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom. You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter. | Input: ['1 2 3 100'] Output:['NO'] | [
3
] |
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions. To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible. | Input: ['21 11 -1-1 1-1 -11 12 24 46 6'] Output:['01 11 -1-1 1-1 -1-1'] | [
0
] |
If an integer a is divisible by another integer b, then b is called the divisor of a.For example: 12 has positive 6 divisors. They are 1, 2, 3, 4, 6 and 12.Letβs define a function D(n) β number of integers between 1 and n (inclusive) which has exactly four positive divisors.Between 1 and 10 only the integers 6, 8 and 10 has exactly four positive divisors. So, D(10)β=β3.You are given an integer n. You have to calculate D(n). | Input: ['10'] Output:['3'] | [
3
] |
A tuple of positive integers {x1,βx2,β...,βxk} is called simple if for all pairs of positive integers (i,ββj) (1βββ€βiββ<ββjββ€βk), xiββ+ββxj is a prime.You are given an array a with n positive integers a1,ββa2,ββ...,ββan (not necessary distinct). You want to find a simple subset of the array a with the maximum size.A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it. | Input: ['22 3'] Output:['23 2'] | [
2
] |
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task! | Input: ['aab'] Output:['bab'] | [
2
] |
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1ββ€βjββ€βm) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1)β+βpos(ai2)β+β...β+βpos(aim) for the i-th customer.When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.Your task is to calculate the total time it takes for Ayush to process all the orders.You can assume that the market has endless stock. | Input: ['2 2 53 4 1 2 51 53 1'] Output:['14'] | [
0
] |
Greatest common divisor GCD(a,βb) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a,βb), for example, Euclid algorithm. Formally, find the biggest integer d, such that all integers a,βaβ+β1,βaβ+β2,β...,βb are divisible by d. To make the problem even more complicated we allow a and b to be up to googol, 10100 β such number do not fit even in 64-bit integer type! | Input: ['1 2'] Output:['1'] | [
3
] |
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds. | Input: ['? + ? - ? + ? + ? = 42'] Output:['Possible9 + 13 - 39 + 28 + 31 = 42'] | [
2,
3
] |
Consider a regular Codeforces round consisting of three problems that uses dynamic scoring.You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack it or not. The only changes in the scoreboard that will happen before the end of the round are your challenges.What is the best place you may take at the end?More formally, n people are participating (including yourself). For any problem, if it was solved by exactly k people at the end of the round, the maximum score for this problem is defined as: If nβ<β2kββ€β2n, then the maximum possible score is 500; If nβ<β4kββ€β2n, then the maximum possible score is 1000; If nβ<β8kββ€β2n, then the maximum possible score is 1500; If nβ<β16kββ€β2n, then the maximum possible score is 2000; If nβ<β32kββ€β2n, then the maximum possible score is 2500; If 32kββ€βn, then the maximum possible score is 3000. Let the maximum possible score for some problem be equal to s. Then a contestant who didn't manage to get it accepted (or his solution was hacked) earns 0 points for this problem. If he got the the solution accepted t minutes after the beginning of the round (and his solution wasn't hacked), he earns points for this problem.The overall score of a participant is equal to the sum of points he earns for each problem plus 100 points for each successful hack (only you make hacks).The resulting place you get is equal to one plus the number of participants who's overall score is strictly greater than yours. | Input: ['4120 120 161 61 120-61 61 1200 0 0'] Output:['1'] | [
0,
2
] |
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for. | Input: ["5IAO'15IAO'2015IAO'1IAO'9IAO'0"] Output:['201512015199119891990'] | [
2,
3
] |
You are given a table consisting of n rows and m columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa.What is the minimum number of cells with value 1 you can get after applying some number of operations? | Input: ['3 4011010100111'] Output:['2'] | [
0,
3
] |
As you know, the game of "Nim" is played with n piles of stones, where the i-th pile initially contains ai stones. Two players alternate the turns. During a turn a player picks any non-empty pile and removes any positive number of stones from it. The one who is not able to make a move loses the game.Petya and Vasya are tired of playing Nim, so they invented their own version of the game and named it the "Gambling Nim". They have n two-sided cards, one side of the i-th card has number ai written on it, while the other side has number bi. At the beginning of the game the players put all the cards on the table, each card only one of its sides up, and this side is chosen independently and uniformly. Thus they obtain a sequence c1,βc2,β...,βcn, where ci is equal to ai or bi. Then they take n piles of stones, with i-th pile containing exactly ci stones and play Nim. Petya takes the first turn.Given that both players play optimally, find the probability of Petya's victory. Output the answer as an irreducible fraction. | Input: ['21 11 1'] Output:['0/1'] | [
3
] |
Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record!For rolling a ball one gets a score β an integer (maybe negative) number of points. Score for the i-th roll is multiplied by i and scores are summed up. So, for k rolls with scores s1,βs2,β...,βsk, the total score is . The total score is 0 if there were no rolls.Limak made n rolls and got score ai for the i-th of them. He wants to maximize his total score and he came up with an interesting idea. He can say that some first rolls were only a warm-up, and that he wasn't focused during the last rolls. More formally, he can cancel any prefix and any suffix of the sequence a1,βa2,β...,βan. It is allowed to cancel all rolls, or to cancel none of them.The total score is calculated as if there were only non-canceled rolls. So, the first non-canceled roll has score multiplied by 1, the second one has score multiplied by 2, and so on, till the last non-canceled roll.What maximum total score can Limak get? | Input: ['65 -1000 1 -3 7 -8'] Output:['16'] | [
4,
4
] |
For a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence).You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo 109β+β7. | Input: ['1 3'] Output:['6'] | [
3
] |
You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a). | Input: ['7 11 0 0 1 1 0 1'] Output:['41 0 0 1 1 1 1'] | [
4
] |
You are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1. | Input: ['32 7 28'] Output:['12 7 9 28'] | [
2,
3
] |
The farmer Polycarp has a warehouse with hay, which can be represented as an nβΓβm rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai,βj and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1βΓβ1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.Polycarp wants the following requirements to hold after the reorganization: the total amount of hay remaining in the warehouse must be equal to k, the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same, the height of at least one stack must remain the same as it was, for the stability of the remaining structure all the stacks should form one connected region. The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.Help Polycarp complete this challenging task or inform that it is impossible. | Input: ['2 3 3510 4 99 9 7'] Output:['YES7 0 7 7 7 7 '] | [
2
] |
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform. | Input: ['4 32 11 34 3'] Output:['1'] | [
2
] |
Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition β determine the number of dangerous turns on the track. | Input: ['60 00 11 11 22 22 00 0'] Output:['1'] | [
3
] |
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1,βa2,β...,βan from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this. | Input: ['3 71 3 4'] Output:['22 5 '] | [
2
] |
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direction of increasing numbers (in this order entrance n should be followed by entrance 1). The negative value of b corresponds to moving |b| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance n). If bβ=β0, then Vasya prefers to walk beside his entrance. Illustration for nβ=β6, aβ=β2, bβ=ββ-β5. Help Vasya to determine the number of the entrance, near which he will be at the end of his walk. | Input: ['6 2 -5'] Output:['3'] | [
3
] |
Pussycat Sonya has an array consisting of n positive integers. There are 2n possible subsequences of the array. For each subsequence she counts the minimum number of operations to make all its elements equal. Each operation must be one of two: Choose some element of the subsequence and multiply it by some prime number. Choose some element of the subsequence and divide it by some prime number. The chosen element must be divisible by the chosen prime number. What is the sum of minimum number of operations for all 2n possible subsequences? Find and print this sum modulo 109β+β7. | Input: ['360 60 40'] Output:['6'] | [
3
] |
Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight. | Input: ['4 4 31 2 22 4 11 3 13 4 2'] Output:['1.5000000000'] | [
4
] |
The life goes up and down, just like nice sequences. Sequence t1,βt2,β...,βtn is called nice if the following two conditions are satisfied: tiβ<βtiβ+β1 for each odd iβ<βn; tiβ>βtiβ+β1 for each even iβ<βn. For example, sequences (2,β8), (1,β5,β1) and (2,β5,β1,β100,β99,β120) are nice, while (1,β1), (1,β2,β3) and (2,β5,β3,β2) are not.Bear Limak has a sequence of positive integers t1,βt2,β...,βtn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices iβ<βj and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. | Input: ['52 8 4 7 7'] Output:['2'] | [
0
] |
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.Limak wants to start with a string of length n and perform nβ-β1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows. | Input: ['3 5ab acc cca aee cff d'] Output:['4'] | [
0
] |
Limak is a little polar bear. He has n balls, the i-th ball has size ti.Limak wants to give one ball to each of his three friends. Giving gifts isn't easy β there are two rules Limak must obey to make friends happy: No two friends can get balls of the same size. No two friends can get balls of sizes that differ by more than 2. For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).Your task is to check whether Limak can choose three balls that satisfy conditions above. | Input: ['418 55 16 17'] Output:['YES'] | [
0
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.