question_text
stringlengths 2
3.82k
| input_outputs
stringlengths 23
941
| algo_tags
sequence |
---|---|---|
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell (0, 0). Robot can perform the following four kinds of operations: U β move from (x, y) to (x, y + 1); D β move from (x, y) to (x, y - 1); L β move from (x, y) to (x - 1, y); R β move from (x, y) to (x + 1, y). Vasya also has got a sequence of n operations. Vasya wants to modify this sequence so after performing it the robot will end up in (x, y).Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: maxID - minID + 1, where maxID is the maximum index of a changed operation, and minID is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices 2, 5 and 7 are changed, so the length of changed subsegment is 7 - 2 + 1 = 6. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is 1. If there are no changes, then the length of changed subsegment is 0. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from (0, 0) to (x, y), or tell him that it's impossible. | Input: ['5RURUU-2 3'] Output:['3'] | [
4
] |
Vasya has got n books, numbered from 1 to n, arranged in a stack. The topmost book has number a_1, the next one β a_2, and so on. The book at the bottom of the stack has number a_n. All numbers are distinct.Vasya wants to move all the books to his backpack in n steps. During i-th step he wants to move the book number b_i into his backpack. If the book with number b_i is in the stack, he takes this book and all the books above the book b_i, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order [1, 2, 3] (book 1 is the topmost), and Vasya moves the books in the order [2, 1, 3], then during the first step he will move two books (1 and 2), during the second step he will do nothing (since book 1 is already in the backpack), and during the third step β one book (the book number 3). Note that b_1, b_2, ..., b_n are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step. | Input: ['31 2 32 1 3'] Output:['2 0 1 '] | [
3
] |
A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles.The workplace of the mechanism is a part of plane just above the driver. Its functional part consists of two rails with sliding endpoints of a piece of stretching rope. For the sake of simplicity we can consider this as a pair of parallel segments in a plane with the rope segment, whose endpoints we are free to choose as any points on these rails segments. The algorithmic part of the mechanism detects each particular raindrop and predicts when and where it reaches the plane. At this exact moment the rope segment must contain the raindrop point (so the rope adsorbs the raindrop).You are given the initial position of the rope endpoints and all information about raindrops. You are to choose the minimal possible speed v of the endpoints sliding (both endpoints can slide in any direction along their segments independently of each other) in such a way that it is possible to catch all raindrops moving both endpoints with speed not greater than v, or find out that it's impossible no matter how high the speed is. | Input: ['3 5 50 01 1 42 2 43 3 4'] Output:['1.0000000019'] | [
4
] |
Polycarp is working on a new operating system called BerOS. He asks you to help with implementation of a file suggestion feature.There are n files on hard drive and their names are f_1, f_2, ..., f_n. Any file name contains between 1 and 8 characters, inclusive. All file names are unique.The file suggestion feature handles queries, each represented by a string s. For each query s it should count number of files containing s as a substring (i.e. some continuous segment of characters in a file name equals s) and suggest any such file name.For example, if file names are "read.me", "hosts", "ops", and "beros.18", and the query is "os", the number of matched files is 2 (two file names contain "os" as a substring) and suggested file name can be either "hosts" or "beros.18". | Input: ['4testconteststest..test6ts.st..testcontes.st'] Output:['1 contests2 .test1 test.1 .test0 -4 test.'] | [
0
] |
Polycarp is an introvert person. In fact he is so much of an introvert that he plays "Monsters and Potions" board game alone. The board of the game is a row of n cells. The cells are numbered from 1 to n from left to right. There are three types of cells: a cell containing a single monster, a cell containing a single potion or a blank cell (it contains neither a monster nor a potion).Polycarp has m tokens representing heroes fighting monsters, which are initially located in the blank cells s_1, s_2, ..., s_m. Polycarp's task is to choose a single cell (rally point) and one by one move all the heroes into this cell. A rally point can be a cell of any of three types.After Policarp selects a rally point, he picks a hero and orders him to move directly to the point. Once that hero reaches the point, Polycarp picks another hero and orders him also to go to the point. And so forth, until all the heroes reach the rally point cell. While going to the point, a hero can not deviate from the direct route or take a step back. A hero just moves cell by cell in the direction of the point until he reaches it. It is possible that multiple heroes are simultaneously in the same cell.Initially the i-th hero has h_i hit points (HP). Monsters also have HP, different monsters might have different HP. And potions also have HP, different potions might have different HP.If a hero steps into a cell which is blank (i.e. doesn't contain a monster/potion), hero's HP does not change.If a hero steps into a cell containing a monster, then the hero and the monster fight. If monster's HP is strictly higher than hero's HP, then the monster wins and Polycarp loses the whole game. If hero's HP is greater or equal to monster's HP, then the hero wins and monster's HP is subtracted from hero's HP. I.e. the hero survives if his HP drops to zero, but dies (and Polycarp looses) if his HP becomes negative due to a fight. If a hero wins a fight with a monster, then the monster disappears, and the cell becomes blank.If a hero steps into a cell containing a potion, then the hero drinks the potion immediately. As a result, potion's HP is added to hero's HP, the potion disappears, and the cell becomes blank.Obviously, Polycarp wants to win the game. It means that he must choose such rally point and the order in which heroes move, that every hero reaches the rally point and survives. I.e. Polycarp loses if a hero reaches rally point but is killed by a monster at the same time. Polycarp can use any of n cells as a rally point β initially it can contain a monster, a potion, or be a blank cell with or without a hero in it.Help Polycarp write a program to choose a rally point and the order in which heroes move. | Input: ['8 38 21 34 90 3 -5 0 -5 -4 -1 0'] Output:['63 1 2 '] | [
0,
2
] |
Elections in Berland are coming. There are only two candidates β Alice and Bob.The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views: supporting none of candidates (this kind is denoted as "00"), supporting Alice but not Bob (this kind is denoted as "10"), supporting Bob but not Alice (this kind is denoted as "01"), supporting both candidates (this kind is denoted as "11"). The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions: at least half of spectators support Alice (i.e. 2 \cdot a >= m, where a is number of spectators supporting Alice and m is the total number of spectators), at least half of spectators support Bob (i.e. 2 \cdot b >= m, where b is number of spectators supporting Bob and m is the total number of spectators), the total influence of spectators is maximal possible. Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible. | Input: ['611 610 401 300 300 700 9'] Output:['22'] | [
2
] |
Polycarp has a lot of work to do. Recently he has learned a new time management rule: "if a task takes five minutes or less, do it immediately". Polycarp likes the new rule, however he is not sure that five minutes is the optimal value. He supposes that this value d should be chosen based on existing task list.Polycarp has a list of n tasks to complete. The i-th task has difficulty p_i, i.e. it requires exactly p_i minutes to be done. Polycarp reads the tasks one by one from the first to the n-th. If a task difficulty is d or less, Polycarp starts the work on the task immediately. If a task difficulty is strictly greater than d, he will not do the task at all. It is not allowed to rearrange tasks in the list. Polycarp doesn't spend any time for reading a task or skipping it.Polycarp has t minutes in total to complete maximum number of tasks. But he does not want to work all the time. He decides to make a break after each group of m consecutive tasks he was working on. The break should take the same amount of time as it was spent in total on completion of these m tasks.For example, if n=7, p=[3, 1, 4, 1, 5, 9, 2], d=3 and m=2 Polycarp works by the following schedule: Polycarp reads the first task, its difficulty is not greater than d (p_1=3 <= d=3) and works for 3 minutes (i.e. the minutes 1, 2, 3); Polycarp reads the second task, its difficulty is not greater than d (p_2=1 <= d=3) and works for 1 minute (i.e. the minute 4); Polycarp notices that he has finished m=2 tasks and takes a break for 3+1=4 minutes (i.e. on the minutes 5, 6, 7, 8); Polycarp reads the third task, its difficulty is greater than d (p_3=4 > d=3) and skips it without spending any time; Polycarp reads the fourth task, its difficulty is not greater than d (p_4=1 <= d=3) and works for 1 minute (i.e. the minute 9); Polycarp reads the tasks 5 and 6, skips both of them (p_5>d and p_6>d); Polycarp reads the 7-th task, its difficulty is not greater than d (p_7=2 <= d=3) and works for 2 minutes (i.e. the minutes 10, 11); Polycarp notices that he has finished m=2 tasks and takes a break for 1+2=3 minutes (i.e. on the minutes 12, 13, 14). Polycarp stops exactly after t minutes. If Polycarp started a task but has not finished it by that time, the task is not considered as completed. It is allowed to complete less than m tasks in the last group. Also Polycarp considers acceptable to have shorter break than needed after the last group of tasks or even not to have this break at all β his working day is over and he will have enough time to rest anyway.Please help Polycarp to find such value d, which would allow him to complete maximum possible number of tasks in t minutes. | Input: ['45 2 165 6 1 4 75 3 305 6 1 4 76 4 1512 5 15 7 20 171 1 50100'] Output:['3 54 72 100 25'] | [
4
] |
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.For each of next n days Vasya knows a_i β number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day. | Input: ['3 23 2 1'] Output:['3'] | [
2
] |
Buber is a Berland technology company that specializes in waste of investor's money. Recently Buber decided to transfer its infrastructure to a cloud. The company decided to rent CPU cores in the cloud for n consecutive days, which are numbered from 1 to n. Buber requires k CPU cores each day.The cloud provider offers m tariff plans, the i-th tariff plan is characterized by the following parameters: l_i and r_i β the i-th tariff plan is available only on days from l_i to r_i, inclusive, c_i β the number of cores per day available for rent on the i-th tariff plan, p_i β the price of renting one core per day on the i-th tariff plan. Buber can arbitrarily share its computing core needs between the tariff plans. Every day Buber can rent an arbitrary number of cores (from 0 to c_i) on each of the available plans. The number of rented cores on a tariff plan can vary arbitrarily from day to day.Find the minimum amount of money that Buber will pay for its work for n days from 1 to n. If on a day the total number of cores for all available tariff plans is strictly less than k, then this day Buber will have to work on fewer cores (and it rents all the available cores), otherwise Buber rents exactly k cores this day. | Input: ['5 7 31 4 5 31 3 5 22 5 10 1'] Output:['44'] | [
2
] |
Berkomnadzor β Federal Service for Supervision of Communications, Information Technology and Mass Media β is a Berland federal executive body that protects ordinary residents of Berland from the threats of modern internet.Berkomnadzor maintains a list of prohibited IPv4 subnets (blacklist) and a list of allowed IPv4 subnets (whitelist). All Internet Service Providers (ISPs) in Berland must configure the network equipment to block access to all IPv4 addresses matching the blacklist. Also ISPs must provide access (that is, do not block) to all IPv4 addresses matching the whitelist. If an IPv4 address does not match either of those lists, it's up to the ISP to decide whether to block it or not. An IPv4 address matches the blacklist (whitelist) if and only if it matches some subnet from the blacklist (whitelist). An IPv4 address can belong to a whitelist and to a blacklist at the same time, this situation leads to a contradiction (see no solution case in the output description).An IPv4 address is a 32-bit unsigned integer written in the form a.b.c.d, where each of the values a,b,c,d is called an octet and is an integer from 0 to 255 written in decimal notation. For example, IPv4 address 192.168.0.1 can be converted to a 32-bit number using the following expression 192 \cdot 2^{24} + 168 \cdot 2^{16} + 0 \cdot 2^8 + 1 \cdot 2^0. First octet a encodes the most significant (leftmost) 8 bits, the octets b and c β the following blocks of 8 bits (in this order), and the octet d encodes the least significant (rightmost) 8 bits.The IPv4 network in Berland is slightly different from the rest of the world. There are no reserved or internal addresses in Berland and use all 2^{32} possible values.An IPv4 subnet is represented either as a.b.c.d or as a.b.c.d/x (where 0 <= x <= 32). A subnet a.b.c.d contains a single address a.b.c.d. A subnet a.b.c.d/x contains all IPv4 addresses with x leftmost (most significant) bits equal to x leftmost bits of the address a.b.c.d. It is required that 32 - x rightmost (least significant) bits of subnet a.b.c.d/x are zeroes.Naturally it happens that all addresses matching subnet a.b.c.d/x form a continuous range. The range starts with address a.b.c.d (its rightmost 32 - x bits are zeroes). The range ends with address which x leftmost bits equal to x leftmost bits of address a.b.c.d, and its 32 - x rightmost bits are all ones. Subnet contains exactly 2^{32-x} addresses. Subnet a.b.c.d/32 contains exactly one address and can also be represented by just a.b.c.d.For example subnet 192.168.0.0/24 contains range of 256 addresses. 192.168.0.0 is the first address of the range, and 192.168.0.255 is the last one.Berkomnadzor's engineers have devised a plan to improve performance of Berland's global network. Instead of maintaining both whitelist and blacklist they want to build only a single optimised blacklist containing minimal number of subnets. The idea is to block all IPv4 addresses matching the optimised blacklist and allow all the rest addresses. Of course, IPv4 addresses from the old blacklist must remain blocked and all IPv4 addresses from the old whitelist must still be allowed. Those IPv4 addresses which matched neither the old blacklist nor the old whitelist may be either blocked or allowed regardless of their accessibility before. Please write a program which takes blacklist and whitelist as input and produces optimised blacklist. The optimised blacklist must contain the minimal possible number of subnets and satisfy all IPv4 addresses accessibility requirements mentioned above. IPv4 subnets in the source lists may intersect arbitrarily. Please output a single number -1 if some IPv4 address matches both source whitelist and blacklist. | Input: ['1-149.154.167.99'] Output:['10.0.0.0/0'] | [
2
] |
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes \frac{[a, \,\, b]}{a} on blackboard. Here [a, \,\, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board. | Input: ['1'] Output:['1'] | [
3
] |
Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than L coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms. | Input: ['20 15 2 3'] Output:['1'] | [
3
] |
Let's define rank of undirected graph as rank of its adjacency matrix in \mathbb{R}^{n * n}.Given a tree. Each edge of this tree will be deleted with probability 1/2, all these deletions are independent. Let E be the expected rank of resulting forest. Find E \cdot 2^{n-1} modulo 998244353 (it is easy to show that E \cdot 2^{n-1} is an integer). | Input: ['31 22 3'] Output:['6'] | [
3
] |
Ivan plays some computer game. There are n quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has 3 parameters a_{i}, b_{i}, p_{i}: reward for completing quest before upgrade, reward for completing quest after upgrade (a_{i} < b_{i}) and probability of successful completing the quest.Each second Ivan can try to complete one quest and he will succeed with probability p_{i}. In case of success Ivan will get the reward and opportunity to upgrade any one quest (not necessary the one he just completed). In case of failure he gets nothing. Quests do not vanish after completing.Ivan has t seconds. He wants to maximize expected value of his total gain after t seconds. Help him to calculate this value. | Input: ['3 23 1000 0.51 2 0.483 20 0.3'] Output:['252.2500000000000'] | [
2,
3
] |
You are given two huge binary integer numbers a and b of lengths n and m respectively. You will repeat the following process: if b > 0, then add to the answer the value a~ \&~ b and divide b by 2 rounding down (i.e. remove the last digit of b), and repeat the process again, otherwise stop the process.The value a~ \&~ b means bitwise AND of a and b. Your task is to calculate the answer modulo 998244353.Note that you should add the value a~ \&~ b to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if a = 1010_2~ (10_{10}) and b = 1000_2~ (8_{10}), then the value a~ \&~ b will be equal to 8, not to 1000. | Input: ['4 410101101'] Output:['12'] | [
3
] |
Maksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change). | Input: ['5 2 65 2 1 4 2'] Output:['4'] | [
4
] |
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0.Each heater has a value r (r is the same for all heaters). This value means that the heater at the position pos can warm up all the elements in range [pos - r + 1; pos + r - 1].Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if n = 6, r = 2 and heaters are at positions 2 and 5, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first 3 elements will be warmed up by the first heater and the last 3 elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house. | Input: ['6 20 1 1 0 0 1'] Output:['3'] | [
2
] |
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute β at the point 2 and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by v (i.e. the first lantern is at the point v, the second is at the point 2v and so on).There is also exactly one standing train which occupies all the points from l to r inclusive.Vova can see the lantern at the point p if p is divisible by v and there is no standing train at this position (p \not\in [l; r]). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to t different conferences, so you should answer t independent queries. | Input: ['410 2 3 7100 51 51 511234 1 100 1991000000000 1 1 1000000000'] Output:['3011340'] | [
3
] |
There is a toy building consisting of n towers. Each tower consists of several cubes standing on each other. The i-th tower consists of h_i cubes, so it has height h_i.Let's define operation slice on some height H as following: for each tower i, if its height is greater than H, then remove some top cubes to make tower's height equal to H. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to k (k >= n). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so. | Input: ['5 53 1 2 2 4'] Output:['2'] | [
2
] |
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times.Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get! | Input: ['210 3 1 11000000000 1 1000000000 1'] Output:['131000000001000000000'] | [
3
] |
Colossal! β exclaimed Hawk-nose. β A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: a - (a \oplus x) - x = 0 for some given a, where \oplus stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some x, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help. | Input: ['3021073741823'] Output:['121073741824'] | [
3
] |
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a triangle of positive area. Sticks should be used as triangle's sides (one stick for one side) and their endpoints should be located at triangle's vertices. | Input: ['3 4 5'] Output:['0'] | [
0,
3
] |
Oleg came to see the maze of mirrors. The maze is a n by n room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze.Oleg is a person of curious nature, so he decided to install n lasers facing internal of the maze on the south wall of the maze. On the north wall of the maze, Oleg installed n receivers, also facing internal of the maze. Let's number lasers and receivers from west to east with distinct integers from 1 to n. Each laser sends a beam of some specific kind and receiver with number a_i should receive the beam sent from laser number i. Since two lasers' beams can't come to the same receiver, these numbers form a permutation β each of the receiver numbers occurs exactly once.You came to the maze together with Oleg. Help him to place the mirrors in the initially empty maze so that the maximum number of lasers' beams will come to the receivers they should. There are no mirrors outside the maze, so if the laser beam leaves the maze, it will not be able to go back. | Input: ['44 1 3 2'] Output:['3.\\..\\\\../../...\\'] | [
3
] |
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly k candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.Before starting to give candies, Lena step out of the circle, after that there were exactly n people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with 1 in such a way that index 1 was assigned to her best friend Roma.Initially, Lena gave the box to the friend with number l, after that each friend (starting from friend number l) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number r taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.Lena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this. | Input: ['4 1 4 12'] Output:['2'] | [
0,
3
] |
This is an interactive problem.In good old times dwarves tried to develop extrasensory abilities: Exactly n dwarves entered completely dark cave. Each dwarf received a hat β white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves. Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information. The task for dwarves was to got diverged into two parts β one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color β black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive β the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output. | Input: ['5blackblackwhitewhiteblack'] Output:['0 03 12 34 40 21 3 4 1'] | [
4
] |
The company X has n employees numbered from 1 through n. Each employee u has a direct boss p_u (1 <= p_u <= n), except for the employee 1 who has no boss. It is guaranteed, that values p_i form a tree. Employee u is said to be in charge of employee v if u is the direct boss of v or there is an employee w such that w is in charge of v and u is the direct boss of w. Also, any employee is considered to be in charge of himself.In addition, for each employee u we define it's level lv(u) as follow: lv(1)=0 lv(u)=lv(p_u)+1 for u \neq 1 In the near future, there are q possible plans for the company to operate. The i-th plan consists of two integers l_i and r_i, meaning that all the employees in the range [l_i, r_i], and only they, are involved in this plan. To operate the plan smoothly, there must be a project manager who is an employee in charge of all the involved employees. To be precise, if an employee u is chosen as the project manager for the i-th plan then for every employee v \in [l_i, r_i], u must be in charge of v. Note, that u is not necessary in the range [l_i, r_i]. Also, u is always chosen in such a way that lv(u) is as large as possible (the higher the level is, the lower the salary that the company has to pay the employee).Before any plan is operated, the company has JATC take a look at their plans. After a glance, he tells the company that for every plan, it's possible to reduce the number of the involved employees exactly by one without affecting the plan. Being greedy, the company asks JATC which employee they should kick out of the plan so that the level of the project manager required is as large as possible. JATC has already figured out the answer and challenges you to do the same. | Input: ['11 51 1 3 3 3 4 2 7 7 64 64 81 119 118 11'] Output:['4 18 11 011 38 1'] | [
2,
4
] |
You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 <= |a|, |b| <= n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a \cdot x = b or b \cdot x = a), where |x| denotes the absolute value of x.After such a transformation, your score increases by |x| points and you are not allowed to transform a into b nor b into a anymore.Initially, you have a score of 0. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve? | Input: ['4'] Output:['8'] | [
3
] |
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i \in \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\_, \_, 2]. After eating the last part, JATC's enjoyment will become 4.However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7. | Input: ['4 210111 43 4'] Output:['143'] | [
2,
3
] |
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times: mul x: multiplies n by x (where x is an arbitrary positive integer). sqrt: replaces n with \sqrt{n} (to apply this operation, \sqrt{n} must be an integer). You can perform these operations as many times as you like. What is the minimum value of n, that can be achieved and what is the minimum number of operations, to achieve that minimum value?Apparently, no one in the class knows the answer to this problem, maybe you can help them? | Input: ['20'] Output:['10 2'] | [
2,
3
] |
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 <= a_1 < a_2 < ... < a_n <= 10^3, and then went to the bathroom.JATC decided to prank his friend by erasing some consecutive elements in the array. Since he doesn't want for the prank to go too far, he will only erase in a way, such that Giraffe can still restore the array using the information from the remaining elements. Because Giraffe has created the array, he's also aware that it's an increasing array and all the elements are integers in the range [1, 10^3].JATC wonders what is the greatest number of elements he can erase? | Input: ['61 3 4 5 6 9'] Output:['2'] | [
2
] |
There are n TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The i-th of the shows is going from l_i-th to r_i-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments [l_i, r_i] and [l_j, r_j] intersect, then shows i and j can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for x rupees, and charges y (y < x) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes [a; b] you will need to pay x + y \cdot (b - a). You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo 10^9 + 7. | Input: ['5 4 31 24 102 410 115 9'] Output:['60'] | [
2
] |
You are given an integer array a_1, a_2, ..., a_n.The array b is called to be a subsequence of a if it is possible to remove some elements from a to get b.Array b_1, b_2, ..., b_k is called to be good if it is not empty and for every i (1 <= i <= k) b_i is divisible by i.Find the number of good subsequences in a modulo 10^9 + 7. Two subsequences are considered different if index sets of numbers included in them are different. That is, the values βof the elements βdo not matter in the comparison of subsequences. In particular, the array a has exactly 2^n - 1 different subsequences (excluding an empty subsequence). | Input: ['21 2'] Output:['3'] | [
3
] |
You came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface.The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either. | Input: ['5 63 3 3 3 3'] Output:['10'] | [
2
] |
You have unlimited number of coins with values 1, 2, ..., n. You want to select some set of coins having the total value of S. It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S? | Input: ['5 11'] Output:['3'] | [
2,
3
] |
You invited n guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the i-th guest wants to have a least l_i free chairs to the left of his chair, and at least r_i free chairs to the right. The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the l_i chairs to his left and r_i chairs to his right may overlap.What is smallest total number of chairs you have to use? | Input: ['31 11 11 1'] Output:['6'] | [
2,
3
] |
You are given two arrays a and b of positive integers, with length n and m respectively. Let c be an n * m matrix, where c_{i,j} = a_i \cdot b_j. You need to find a subrectangle of the matrix c such that the sum of its elements is at most x, and its area (the total number of elements) is the largest possible.Formally, you need to find the largest number s such that it is possible to choose integers x_1, x_2, y_1, y_2 subject to 1 <=q x_1 <=q x_2 <=q n, 1 <=q y_1 <=q y_2 <=q m, (x_2 - x_1 + 1) * (y_2 - y_1 + 1) = s, and \sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} <=q x. | Input: ['3 31 2 31 2 39'] Output:['4'] | [
4
] |
You are given a positive integer n.Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0.Your task is to find two integers a, b, such that 0 <=q a, b <=q n, a + b = n and S(a) + S(b) is the largest possible among all such pairs. | Input: ['35'] Output:['17'] | [
2
] |
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.You have n cards with digits, and you want to use them to make as many phone numbers as possible. Each card must be used in at most one phone number, and you don't have to use all cards. The phone numbers do not necessarily have to be distinct. | Input: ['1100000000008'] Output:['1'] | [
0
] |
You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path.A vertical path is a sequence of vertices v_1, v_2, ..., v_k where v_i (i >= 2) is the parent of v_{i - 1}. | Input: ['3 1 31 2 31 1'] Output:['3'] | [
2,
4
] |
There is a forest that we model as a plane and live n rare animals. Animal number i has its lair in the point (x_{i}, y_{i}). In order to protect them, a decision to build a nature reserve has been made.The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.For convenience, scientists have made a transformation of coordinates so that the river is defined by y = 0. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve. | Input: ['10 1'] Output:['0.5'] | [
4,
4
] |
Let's call the following process a transformation of a sequence of length n.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.A sequence a_1, a_2, ..., a_n is lexicographically larger than a sequence b_1, b_2, ..., b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i. | Input: ['3'] Output:['1 1 3 '] | [
3
] |
We get more and more news about DDoS-attacks of popular websites.Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 \cdot t, where t β the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i β the number of requests in the i-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n]. | Input: ['5100 200 1 1 1'] Output:['3'] | [
0
] |
Having problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city.Unfortunately for Arkady, the line is circular. It means that the stations are enumerated from 1 to n and there is a tunnel between any pair of consecutive stations as well as between the station 1 and the station n. Trains that go in clockwise direction visit the stations in order 1 \to 2 \to 3 \to ... \to n \to 1 while the trains that go in the counter-clockwise direction visit the stations in the reverse order.The stations that have numbers from 1 to m have interior mostly in red colors while the stations that have numbers from m + 1 to n have blue interior. Arkady entered the metro at station s and decided to use the following algorithm to choose his way home. Initially he has a positive integer t in his mind. If the current station has red interior, he takes a clockwise-directed train, otherwise he takes a counter-clockwise-directed train. He rides exactly t stations on the train and leaves the train. He decreases t by one. If t is still positive, he returns to step 2. Otherwise he exits the metro. You have already realized that this algorithm most probably won't bring Arkady home. Find the station he will exit the metro at so that you can continue helping him. | Input: ['10 4', '3 1', ''] Output:['4', ''] | [
0
] |
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of n problems and lasts for T minutes. Each of the problems is defined by two positive integers a_i and p_i β its difficulty and the score awarded by its solution.Polycarp's experience suggests that his skill level is defined with positive real value s, and initially s=1.0. To solve the i-th problem Polycarp needs a_i/s minutes.Polycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by 10\%, that is skill level s decreases to 0.9s. Each episode takes exactly 10 minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for a_i/s minutes, where s is his current skill level. In calculation of a_i/s no rounding is performed, only division of integer value a_i by real value s happens.Also, Polycarp can train for some time. If he trains for t minutes, he increases his skill by C \cdot t, where C is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.Polycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed before solving the first problem. | Input: ['241.000 31.00012 320 630 15 131.000 30.0001 1010 1020 8'] Output:['720'] | [
3,
4
] |
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal s towards a faraway galaxy. Recently they've received a response t which they believe to be a response from aliens! The scientists now want to check if the signal t is similar to s.The original signal s was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal t, however, does not look as easy as s, but the scientists don't give up! They represented t as a sequence of English letters and say that t is similar to s if you can replace all zeros in s with some string r_0 and all ones in s with some other string r_1 and obtain t. The strings r_0 and r_1 must be different and non-empty.Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings r_0 and r_1) that transform s to t. | Input: ['01', 'aaaaaa', ''] Output:['4', ''] | [
0
] |
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from 1 to n, the junction 1 is called the root.A subtree of a junction v is a set of junctions u such that the path from u to the root must pass through v. Note that v itself is included in a subtree of v.A leaf is such a junction that its subtree contains exactly one junction.The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction t that all light bulbs in the subtree of t have different colors.Arkady is interested in the following question: for each k from 1 to n, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to k? | Input: ['3', '1 1', ''] Output:['1 1 2 ', ''] | [
2
] |
Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are 2 teams each having n players and 2n heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the i-th of the heroes as p_i. Each team wants to maximize the total power of its heroes. However, there is one exception: there are m pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of q or greater regardless of jury's program choices, you must get q or greater to pass a test. | Input: ['3 1', '1 2 3 4 5 6', '2 6', '1', '', '2', '', '4', '', '1', ''] Output:['', '', '', '', '6', '', '5', '', '3', ''] | [
2
] |
Arkady and his friends love playing checkers on an n * n field. The rows and the columns of the field are enumerated from 1 to n.The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set of candies per each cell of the field: the set of candies for cell (i, j) will have exactly (i^2 + j^2) candies of unique type.There are m friends who deserve the present. How many of these n * n sets of candies can be split equally into m parts without cutting a candy into pieces? Note that each set has to be split independently since the types of candies in different sets are different. | Input: ['3 3', ''] Output:['1', ''] | [
3
] |
You are a given a list of integers a_1, a_2, ..., a_n and s of its segments [l_j; r_j] (where 1 <= l_j <= r_j <= n).You need to select exactly m segments in such a way that the k-th order statistic of the multiset of a_i, where i is contained in at least one segment, is the smallest possible. If it's impossible to select a set of m segments in such a way that the multiset contains at least k elements, print -1.The k-th order statistic of a multiset is the value of the k-th element after sorting the multiset in non-descending order. | Input: ['4 3 2 23 1 3 21 22 34 4'] Output:['2'] | [
4
] |
Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called "massive refactoring", which can replace names of many variable in just one run. To use it, Alice needs to select two strings s and t and after that for each variable the following algorithm is performed: if the variable's name contains s as a substring, then the first (and only first) occurrence of s is replaced with t. If the name doesn't contain s, then this variable's name stays the same.The list of variables is known and for each variable both the initial name and the name Alice wants this variable change to are known. Moreover, for each variable the lengths of the initial name and the target name are equal (otherwise the alignment of the code could become broken). You need to perform renaming of all variables in exactly one run of the massive refactoring command or determine that it is impossible. | Input: ['1topforcescodecoder'] Output:['YEStopforcescodecoder'] | [
2
] |
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days [l_a; r_a] are lucky, then there are some unlucky days: [r_a + 1; l_a + t_a - 1], and then there are lucky days again: [l_a + t_a; r_a + t_a] and so on. In other words, the day is lucky for Alice if it lies in the segment [l_a + k t_a; r_a + k t_a] for some non-negative integer k.The Bob's lucky day have similar structure, however the parameters of his sequence are different: l_b, r_b, t_b. So a day is a lucky for Bob if it lies in a segment [l_b + k t_b; r_b + k t_b], for some non-negative integer k.Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob. | Input: ['0 2 51 3 5'] Output:['2'] | [
3
] |
You are given two arrays a_0, a_1, ..., a_{n - 1} and b_0, b_1, ..., b_{m-1}, and an integer c.Compute the following sum:\sum_{i=0}^{n-1} \sum_{j=0}^{m-1} a_i b_j c^{i^2\,j^3}Since it's value can be really large, print it modulo 490019. | Input: ['2 2 30 10 1'] Output:['3'] | [
3
] |
The king of some country N decided to completely rebuild the road network. There are n people living in the country, they are enumerated from 1 to n. It is possible to construct a road between the house of any citizen a to the house of any other citizen b. There should not be more than one road between any pair of citizens. The road network must be connected, i.e. it should be possible to reach every citizen starting from anyone using roads. To save funds, it was decided to build exactly n-1 road, so the road network should be a tree.However, it is not that easy as it sounds, that's why the king addressed you for help. There are m secret communities in the country, each of them unites a non-empty subset of citizens. The king does not want to conflict with any of the communities, so he wants to build the network such that the houses of members of each society form a connected subtree in network. A set of vertices forms a connected subtree if and only if the graph remains connected when we delete all the other vertices and all edges but ones that connect the vertices from the set.Help the king to determine if it is possible to build the desired road network, and if it is, build it. | Input: ['24 30011111001113 3011101110'] Output:['YES1 32 33 4NO'] | [
2,
3
] |
Egor came up with a new chips puzzle and suggests you to play.The puzzle has the form of a table with n rows and m columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), possibly empty, and the whole puzzle can be described as a table, where each cell is a string of zeros and ones. The task is to get from one state of the puzzle some other state.To do this, you can use the following operation. select 2 different cells (x_1, y_1) and (x_2, y_2): the cells must be in the same row or in the same column of the table, and the string in the cell (x_1, y_1) must be non-empty; in one operation you can move the last character of the string at the cell (x_1, y_1) to the beginning of the string at the cell (x_2, y_2). Egor came up with two states of the table for you: the initial state and the final one. It is guaranteed that the number of zeros and ones in the tables are the same. Your goal is with several operations get the final state from the initial state. Of course, Egor does not want the number of operations to be very large. Let's denote as s the number of characters in each of the tables (which are the same). Then you should use no more than 4 \cdot s operations. | Input: ['2 200 1001 1110 0110 01'] Output:['42 1 1 11 1 1 21 2 2 22 2 2 1'] | [
3
] |
At a break Vanya came to the class and saw an array of n k-bit integers a_1, a_2, ..., a_n on the board. An integer x is called a k-bit integer if 0 <=q x <=q 2^k - 1. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array i (1 <=q i <=q n) and replace the number a_i with the number \overline{a_i}. We define \overline{x} for a k-bit integer x as the k-bit integer such that all its k bits differ from the corresponding bits of x. Vanya does not like the number 0. Therefore, he likes such segments [l, r] (1 <=q l <=q r <=q n) such that a_l \oplus a_{l+1} \oplus ... \oplus a_r \neq 0, where \oplus denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above. | Input: ['3 21 3 0'] Output:['5'] | [
2
] |
Suppose you are given a sequence S of k pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_k, b_k).You can perform the following operations on it: Choose some position i and increase a_i by 1. That can be performed only if there exists at least one such position j that i!=j and a_i = a_j. The cost of this operation is b_i; Choose some position i and decrease a_i by 1. That can be performed only if there exists at least one such position j that a_i = a_j + 1. The cost of this operation is -b_i. Each operation can be performed arbitrary number of times (possibly zero).Let f(S) be minimum possible x such that there exists a sequence of operations with total cost x, after which all a_i from S are pairwise distinct. Now for the task itself ...You are given a sequence P consisting of n pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n). All b_i are pairwise distinct. Let P_i be the sequence consisting of the first i pairs of P. Your task is to calculate the values of f(P_1), f(P_2), ..., f(P_n). | Input: ['51 13 35 54 22 4'] Output:['000-5-16'] | [
2
] |
Vasya owns three big integers β a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, ..., s_k that s_1 + s_2 + ... + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of a beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number a, which has each of s_i satisfy the condition l <= s_i <= r. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number a such that they match all the given requirements. The result can be rather big, so print it modulo 998244353. | Input: ['135115'] Output:['2'] | [
4
] |
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the quantity of nice numbers in multiset a would be the same as the quantity of nice numbers in multiset b (the quantity of numbers to appear exactly once in multiset a and the quantity of numbers to appear exactly once in multiset b). | Input: ['43 5 7 1'] Output:['YESBABA'] | [
0,
2,
3
] |
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) <= 3 \cdot 10^5 and (r - l) is always odd.You want to split these numbers into exactly \frac{r - l + 1}{2} pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them. | Input: ['1 8'] Output:['YES2 74 13 86 5'] | [
2,
3
] |
Vasya came up with a password to register for EatForces β a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords "abaCABA12", "Z7q" and "3R24m" are valid, and the passwords "qwerty", "qwerty12345" and "Password" are not. A substring of string s is a string x = s_l s_{l + 1} ... s_{l + len - 1} (1 <= l <= |s|, 0 <= len <= |s| - l + 1). len is the length of the substring. Note that the empty string is also considered a substring of s, it has the length 0.Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of s should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits. | Input: ['2abcDCEhtQw27'] Output:['abcD4EhtQw27'] | [
2
] |
There are n points on the plane, (x_1,y_1), (x_2,y_2), ..., (x_n,y_n).You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle. | Input: ['31 11 22 1'] Output:['3'] | [
3
] |
Little C loves number Β«3Β» very much. He loves all things about it.Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution. | Input: ['3'] Output:['1 1 1'] | [
3
] |
Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race. | Input: ['4 350 30 20 1015 10 7 3'] Output:['2'] | [
2
] |
Being bored of exploring the Moon over and over again Wall-B decided to explore something he is made of β binary numbers. He took a binary number and decided to count how many times different substrings of length two appeared. He stored those values in c_{00}, c_{01}, c_{10} and c_{11}, representing how many times substrings 00, 01, 10 and 11 appear in the number respectively. For example: 10111100 \rightarrow c_{00} = 1, \ c_{01} = 1,\ c_{10} = 2,\ c_{11} = 3 10000 \rightarrow c_{00} = 3,\ c_{01} = 0,\ c_{10} = 1,\ c_{11} = 0 10101001 \rightarrow c_{00} = 1,\ c_{01} = 3,\ c_{10} = 3,\ c_{11} = 0 1 \rightarrow c_{00} = 0,\ c_{01} = 0,\ c_{10} = 0,\ c_{11} = 0Wall-B noticed that there can be multiple binary numbers satisfying the same c_{00}, c_{01}, c_{10} and c_{11} constraints. Because of that he wanted to count how many binary numbers satisfy the constraints c_{xy} given the interval [A, B]. Unfortunately, his processing power wasn't strong enough to handle large intervals he was curious about. Can you help him? Since this number can be large print it modulo 10^9 + 7. | Input: ['1010010011'] Output:['1'] | [
3
] |
Ani and Borna are playing a short game on a two-variable polynomial. It's a special kind of a polynomial: the monomials are fixed, but all of its coefficients are fill-in-the-blanks dashes, e.g. \_ xy + \_ x^4 y^7 + \_ x^8 y^3 + ... Borna will fill in the blanks with positive integers. He wants the polynomial to be bounded from below, i.e. his goal is to make sure there exists a real number M such that the value of the polynomial at any point is greater than M. Ani is mischievous, and wants the polynomial to be unbounded. Along with stealing Borna's heart, she can also steal parts of polynomials. Ani is only a petty kind of thief, though: she can only steal at most one monomial from the polynomial before Borna fills in the blanks. If Ani and Borna play their only moves optimally, who wins? | Input: ['31 12 00 2'] Output:['Ani'] | [
3
] |
In the intergalactic empire Bubbledom there are N planets, of which some pairs are directly connected by two-way wormholes. There are N-1 wormholes. The wormholes are of extreme religious importance in Bubbledom, a set of planets in Bubbledom consider themselves one intergalactic kingdom if and only if any two planets in the set can reach each other by traversing the wormholes. You are given that Bubbledom is one kingdom. In other words, the network of planets and wormholes is a tree.However, Bubbledom is facing a powerful enemy also possessing teleportation technology. The enemy attacks every night, and the government of Bubbledom retakes all the planets during the day. In a single attack, the enemy attacks every planet of Bubbledom at once, but some planets are more resilient than others. Planets are number 0,1,β¦,N-1 and the planet i will fall with probability p_i. Before every night (including the very first one), the government reinforces or weakens the defenses of a single planet.The government of Bubbledom is interested in the following question: what is the expected number of intergalactic kingdoms Bubbledom will be split into, after a single enemy attack (before they get a chance to rebuild)? In other words, you need to print the expected number of connected components after every attack. | Input: ['50.50 0.29 0.49 0.95 0.832 30 33 42 134 0.661 0.690 0.36'] Output:['1.680401.484401.61740'] | [
3
] |
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1. Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number! | Input: ['2 3681 5 61 9 42 4 2'] Output:['1'] | [
4
] |
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of n integers a_i.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score 1. Now Janusz wonders, for given sequence, how much elements should the player choose? | Input: ['310 6 15'] Output:['3'] | [
3
] |
Zibi is a competitive programming coach. There are n competitors who want to be prepared well. The training contests are quite unusual β there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the i-th competitor will always have score x_i when he codes the first task and y_i when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are m pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in? | Input: ['3 21 22 31 31 22 3'] Output:['3 0 3 '] | [
2,
3
] |
Acingel is a small town. There was only one doctor here β Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked m neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from 1 to n. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.However, some facts are very suspicious β how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" β thinks Gawry β "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that β some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.In how many ways he can do it? Two ways are called different if the remaining common part is different. | Input: ['3 21 2 32 3 1'] Output:['4'] | [
0,
3
] |
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" β thought the girl β "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from 1 to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a!=b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. | Input: ['bbab'] Output:['0 1 1 0'] | [
2
] |
Awruk is taking part in elections in his school. It is the final round. He has only one opponent β Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from this person. Of course 0 <= k - a_i holds.Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows a_1, a_2, ..., a_n β how many votes for Elodreip each student wants to give. Now he wants to change the number k to win the elections. Of course he knows that bigger k means bigger chance that somebody may notice that he has changed something and then he will be disqualified.So, Awruk knows a_1, a_2, ..., a_n β how many votes each student will give to his opponent. Help him select the smallest winning number k. In order to win, Awruk needs to get strictly more votes than Elodreip. | Input: ['51 1 1 5 1'] Output:['5'] | [
3
] |
You are given an undirected tree, consisting of n vertices.The vertex is called a leaf if it has exactly one vertex adjacent to it.The distance between some pair of vertices is the number of edges in the shortest path between them.Let's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to k.You want to split all leaves into non-intersecting beautiful sets. What is the minimal number of sets in such a split? | Input: ['9 31 21 32 42 53 66 76 83 9'] Output:['2'] | [
2
] |
Vasya has got a magic matrix a of size n * m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to \sqrt{(i_1-i_2)^2 + (j_1-j_2)^2}.Calculate the expected value of the Vasya's final score.It can be shown that the answer can be represented as \frac{P}{Q}, where P and Q are coprime integer numbers, and Q \not\equiv 0~(mod ~ 998244353). Print the value P \cdot Q^{-1} modulo 998244353. | Input: ['1 41 1 2 11 3'] Output:['2'] | [
3
] |
You are given an array a consisting of n integers. You can perform the following operations with it: Choose some positions i and j (1 <= i, j <= n, i!=j), write the value of a_i \cdot a_j into the j-th cell and remove the number from the i-th cell; Choose some position i and remove the number from the i-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly n - 1 operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print. | Input: ['55 -2 0 1 -3'] Output:['2 31 1 21 2 41 4 5'] | [
2,
3
] |
Berland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it. | Input: ['45 C6 B16 BAC4 A'] Output:['15'] | [
0
] |
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k.Nobody leaves the taken seat during the whole process. | Input: ['461111'] Output:['3 7'] | [
4
] |
You are given a tube which is reflective inside represented as two non-coinciding, but parallel to Ox lines. Each line has some special integer points β positions of sensors on sides of the tube.You are going to emit a laser ray in the tube. To do so, you have to choose two integer points A and B on the first and the second line respectively (coordinates can be negative): the point A is responsible for the position of the laser, and the point B β for the direction of the laser ray. The laser ray is a ray starting at A and directed at B which will reflect from the sides of the tube (it doesn't matter if there are any sensors at a reflection point or not). A sensor will only register the ray if the ray hits exactly at the position of the sensor. Examples of laser rays. Note that image contains two examples. The 3 sensors (denoted by black bold points on the tube sides) will register the blue ray but only 2 will register the red. Calculate the maximum number of sensors which can register your ray if you choose points A and B on the first and the second lines respectively. | Input: ['3 11 5 61 33'] Output:['3'] | [
3
] |
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so. | Input: ['43 41 43 4'] Output:['YES1 33 22 4'] | [
2
] |
A plane is flying at a constant height of h meters above the ground surface. Let's consider that it is flying from the point (-10^9, h) to the point (10^9, h) parallel with Ox axis.A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to Ox axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.There are ascending air flows on certain segments, each such segment is characterized by two numbers x_1 and x_2 (x_1 < x_2) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along Ox axis, covering one unit of distance every second. If the glider jumps out at 1, he will stop at 10. Otherwise, if he jumps out at 2, he will stop at 12. Determine the maximum distance along Ox axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is 0. | Input: ['3 42 57 910 11'] Output:['10'] | [
4
] |
Recently Monocarp got a job. His working day lasts exactly m minutes. During work, Monocarp wants to drink coffee at certain moments: there are n minutes a_1, a_2, ..., a_n, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute a_i, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least d minutes pass between any two coffee breaks. Monocarp also wants to take these n coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than d minutes pass between the end of any working day and the start of the following working day.For each of the n given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent. | Input: ['4 5 33 5 1 2'] Output:['33 1 1 2 '] | [
2,
4
] |
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, and the height of the screen is h, then the following condition should be met: \frac{w}{h} = \frac{x}{y}.There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers w and h there is a TV set with screen width w and height h in the shop.Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers w and h, beforehand, such that (w <= a), (h <= b) and (\frac{w}{h} = \frac{x}{y}).In other words, Monocarp wants to determine the number of TV sets having aspect ratio \frac{x}{y}, screen width not exceeding a, and screen height not exceeding b. Two TV sets are considered different if they have different screen width or different screen height. | Input: ['17 15 5 3'] Output:['3'] | [
3
] |
There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards had indices 10, 11, 12, 13, 14, 15 and 16.After the heist, only n keyboards remain, and they have indices a_1, a_2, ..., a_n. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither x nor the number of keyboards in the store before the heist. | Input: ['410 13 12 8'] Output:['2'] | [
2
] |
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out n skewers parallel to each other, and enumerated them with consecutive integers from 1 to n in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number i, it leads to turning k closest skewers from each side of the skewer i, that is, skewers number i - k, i - k + 1, ..., i - 1, i + 1, ..., i + k - 1, i + k (if they exist). For example, let n = 6 and k = 1. When Miroslav turns skewer number 3, then skewers with numbers 2, 3, and 4 will come up turned over. If after that he turns skewer number 1, then skewers number 1, 3, and 4 will be turned over, while skewer number 2 will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all n skewers with the minimal possible number of actions. For example, for the above example n = 6 and k = 1, two turnings are sufficient: he can turn over skewers number 2 and 5.Help Miroslav turn over all n skewers. | Input: ['7 2'] Output:['21 6 '] | [
2,
3
] |
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them β a black one, and for the rest the suit will be bought in the future.On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending. | Input: ['5 100 10 1 2 1 2'] Output:['101'] | [
2
] |
The Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have distinct encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe.You have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number x in the same aforementioned range, and when server i is infected, its encryption key changes from c_i to c_i \oplus x, where \oplus denotes the bitwise XOR operation.Sadly, you know neither the number x nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs (A, x), where A is some (possibly empty) subset of the set of servers and x is some number in the range from 0 to 2^k - 1, such that when all servers from the chosen subset A and none of the others are infected by a virus containing the number x, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo 10^9 + 7. | Input: ['4 4 20 1 0 11 22 33 44 1'] Output:['50'] | [
3
] |
This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with n stations, indexed consecutively from 1 to n. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers l and r (l <= r), and then check, whether the train is located on a station with index between l and r, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most k stations away. Formally, if the train was at the station x when the gadget was applied, then at the next application of the gadget the train can appear at any station y such that \max(1, x - k) <=q y <=q \min(n, x + k).Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than 4500 applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than 4500 applications of the gadgets? | Input: ['10 2YesNoYesYes'] Output:['3 53 33 45 5'] | [
4
] |
There are two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route.At each station one can find a sorted list of moments of time when a bus is at this station. We denote this list as a_1 < a_2 < ... < a_n for stop A and as b_1 < b_2 < ... < b_n for stop B. The buses always depart from A and arrive to B according to the timetable, but the order in which the buses arrive may differ. Let's call an order of arrivals valid if each bus arrives at least t units of time later than departs.It is known that for an order to be valid the latest possible arrival for the bus that departs at a_i is b_{x_i}, i.e. x_i-th in the timetable. In other words, for each i there exists such a valid order of arrivals that the bus departed i-th arrives x_i-th (and all other buses can arrive arbitrary), but there is no valid order of arrivals in which the i-th departed bus arrives (x_i + 1)-th.Formally, let's call a permutation p_1, p_2, ..., p_n valid, if b_{p_i} >= a_i + t for all i. Then x_i is the maximum value of p_i among all valid permutations.You are given the sequences a_1, a_2, ..., a_n and x_1, x_2, ..., x_n, but not the arrival timetable. Find out any suitable timetable for stop B b_1, b_2, ..., b_n or determine that there is no such timetable. | Input: ['3 104 6 82 2 3'] Output:['Yes16 17 21 '] | [
2,
3
] |
You are given n blocks, each of them is of the form [color_1|value|color_2], where the block can also be flipped to get [color_2|value|color_1]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.The value of the sequence is defined as the sum of the values of the blocks in this sequence.Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence. | Input: ['62 1 41 2 43 4 42 8 33 16 31 32 2'] Output:['63'] | [
0
] |
There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value x eats a slime with a value y, the eaten slime disappears, and the value of the remaining slime changes to x - y.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime. | Input: ['42 1 2 1'] Output:['4'] | [
2
] |
Two players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements \{1, 2, 2, 3\} in a list and you decided to choose 2 for the next turn, only a single instance of 2 will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same. | Input: ['21 45 1'] Output:['0'] | [
2
] |
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that:\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1 Here \mathrm{sum}(S) denotes the sum of all elements present in set S and \mathrm{gcd} means thegreatest common divisor.Every integer number from 1 to n should be present in exactly one of S_1 or S_2. | Input: ['1'] Output:['No'] | [
3
] |
Given an array a of n integers and an integer k (2 <= k <= n), where each element of the array is denoted by a_i (0 <= i < n). Perform the operation z given below on a and print the value of z(a,k) modulo 10^{9}+7.function z(array a, integer k): if length(a) < k: return 0 else: b = empty array ans = 0 for i = 0 .. (length(a) - k): temp = a[i] for j = i .. (i + k - 1): temp = max(temp, a[j]) append temp to the end of b ans = ans + temp return ans + z(b, k) | Input: ['3 29 1 10'] Output:['29'] | [
3
] |
You are given two binary strings a and b of the same length. You can perform the following two operations on the string a: Swap any two bits at indices i and j respectively (1 <= i, j <= n), the cost of this operation is |i - j|, that is, the absolute difference between i and j. Select any arbitrary index i (1 <= i <= n) and flip (change 0 to 1 or 1 to 0) the bit at this index. The cost of this operation is 1. Find the minimum cost to make the string a equal to b. It is not allowed to modify string b. | Input: ['3100001'] Output:['2'] | [
2
] |
You are given an array a of n integers and an integer s. It is guaranteed that n is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array 6, 5, 8 is equal to 6, since if we sort this array we will get 5, 6, 8, and 6 is located on the middle position. | Input: ['3 86 5 8'] Output:['2'] | [
2
] |
You have n coins, each of the same value of 1.Distribute them into packets such that any amount x (1 <=q x <=q n) can be formed using some (possibly one or all) number of these packets.Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, however it may be reused for the formation of other x's.Find the minimum number of packets in such a distribution. | Input: ['6'] Output:['3'] | [
2,
3
] |
You are given an acyclic directed graph, consisting of n vertices and m edges. The graph contains no multiple edges and no self-loops.The vertex is called a source if it has no incoming edges. The vertex is called a sink if it has no outgoing edges. These definitions imply that some vertices can be both source and sink.The number of sources in the given graph is equal to the number of sinks in it, and each of these numbers doesn't exceed 20.The following algorithm is applied to the graph: if the graph has no sources and sinks then quit; choose arbitrary source s, arbitrary sink t, add an edge from t to s to the graph and go to step 1 (that operation pops s out of sources and t out of sinks). Note that s and t may be the same vertex, then a self-loop is added. At the end you check if the graph becomes strongly connected (that is, any vertex is reachable from any other vertex).Your task is to check that the graph becomes strongly connected no matter the choice of sources and sinks on the second step of the algorithm. | Input: ['3 11 2'] Output:['NO'] | [
0
] |
Consider some positive integer x. Its prime factorization will be of form x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot ...Let's call x elegant if the greatest common divisor of the sequence k_1, k_2, ... is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 \cdot 3, 72 = 2^3 \cdot 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2^2 \cdot 5^4 (GCD = 2) are not.Count the number of elegant integers from 2 to n.Each testcase contains several values of n, for each of them you are required to solve the problem separately. | Input: ['4427210'] Output:['21616'] | [
3
] |
Vasya has two arrays A and B of lengths n and m, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal. | Input: ['511 2 3 5 7411 7 3 7'] Output:['3'] | [
2
] |
Mikhail walks on a Cartesian plane. He starts at the point (0, 0), and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point (0, 0), he can go to any of the following points in one move: (1, 0); (1, 1); (0, 1); (-1, 1); (-1, 0); (-1, -1); (0, -1); (1, -1). If Mikhail goes from the point (x1, y1) to the point (x2, y2) in one move, and x1!=x2 and y1!=y2, then such a move is called a diagonal move.Mikhail has q queries. For the i-th query Mikhail's target is to go to the point (n_i, m_i) from the point (0, 0) in exactly k_i moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point (0, 0) to the point (n_i, m_i) in k_i moves.Note that Mikhail can visit any point any number of times (even the destination point!). | Input: ['32 2 34 3 710 1 9'] Output:['16-1'] | [
3
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.