task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Mafia Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? Input Specification: The first line contains integer *n* (3<=≀<=*n*<=≀<=105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109) β€” the *i*-th number in the list is the number of rounds the *i*-th person wants to play. Output Specification: In a single line print a single integer β€” the minimum number of game rounds the friends need to let the *i*-th person play at least *a**i* rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['3\n3 2 2\n', '4\n2 2 2 2\n'] Demo Output: ['4\n', '3\n'] Note: You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
800
Title: Banners Time Limit: None seconds Memory Limit: None megabytes Problem Description: All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads. Suppose that a paid version of the app costs *p* (*p* is an integer) rubles, and the free version of the application contains *c* ad banners. Each user can be described by two integers: *a**i* β€” the number of rubles this user is willing to pay for the paid version of the application, and *b**i* β€” the number of banners he is willing to tolerate in the free version. The behavior of each member shall be considered strictly deterministic: - if for user *i*, value *b**i* is at least *c*, then he uses the free version, - otherwise, if value *a**i* is at least *p*, then he buys the paid version without advertising, - otherwise the user simply does not use the application. Each user of the free version brings the profit of *c*<=Γ—<=*w* rubles. Each user of the paid version brings the profit of *p* rubles. Your task is to help the application developers to select the optimal parameters *p* and *c*. Namely, knowing all the characteristics of users, for each value of *c* from 0 to (*max*Β *b**i*)<=+<=1 you need to determine the maximum profit from the application and the corresponding parameter *p*. Input Specification: The first line contains two integers *n* and *w* (1<=≀<=*n*<=≀<=105;Β 1<=≀<=*w*<=≀<=105) β€” the number of users and the profit from a single banner. Each of the next *n* lines contains two integers *a**i* and *b**i* (0<=≀<=*a**i*,<=*b**i*<=≀<=105) β€” the characteristics of the *i*-th user. Output Specification: Print (*max*Β *b**i*)<=+<=2 lines, in the *i*-th line print two integers: *pay* β€” the maximum gained profit at *c*<==<=*i*<=-<=1, *p* (0<=≀<=*p*<=≀<=109) β€” the corresponding optimal app cost. If there are multiple optimal solutions, print any of them. Demo Input: ['2 1\n2 0\n0 2\n', '3 1\n3 1\n2 2\n1 3\n'] Demo Output: ['0 3\n3 2\n4 2\n2 2\n', '0 4\n3 4\n7 3\n7 2\n4 2\n'] Note: none
801
Title: Lara Croft and the New Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of *n* rows and *m* columns. Cell (*x*,<=*y*) is the cell in the *x*-th row in the *y*-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1,<=1), that is top left corner of the matrix. Then she goes down all the way to cell (*n*,<=1) β€” the bottom left corner. Then she starts moving in the snake fashion β€” all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. *n* and *m* given are such that she always end up in cell (1,<=2). Lara has already moved to a neighbouring cell *k* times. Can you determine her current position? Input Specification: The only line contains three integers *n*, *m* and *k* (2<=≀<=*n*,<=*m*<=≀<=109, *n* is always even, 0<=≀<=*k*<=&lt;<=*n*Β·*m*). Note that *k* doesn't fit into 32-bit integer type! Output Specification: Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves *k* times. Demo Input: ['4 3 0\n', '4 3 11\n', '4 3 7\n'] Demo Output: ['1 1\n', '1 2\n', '3 2\n'] Note: Here is her path on matrix 4 by 3:
802
Title: Dreamoon and Sets Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dreamoon likes to play with sets, integers and . is defined as the largest positive integer that divides both *a* and *b*. Let *S* be a set of exactly four distinct integers greater than 0. Define *S* to be of rank *k* if and only if for all pairs of distinct elements *s**i*, *s**j* from *S*, . Given *k* and *n*, Dreamoon wants to make up *n* sets of rank *k* using integers from 1 to *m* such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum *m* that makes it possible and print one possible solution. Input Specification: The single line of the input contains two space separated integers *n*, *k* (1<=≀<=*n*<=≀<=10<=000,<=1<=≀<=*k*<=≀<=100). Output Specification: On the first line print a single integer β€” the minimal possible *m*. On each of the next *n* lines print four space separated integers representing the *i*-th set. Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal *m*, print any one of them. Demo Input: ['1 1\n', '2 2\n'] Demo Output: ['5\n1 2 3 5\n', '22\n2 4 6 22\n14 18 10 16\n'] Note: For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e2af04e5e60e1fe79a4d74bf22dfa575f0b0f7bb.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
803
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Karafs is some kind of vegetable in shape of an 1<=Γ—<=*h* rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the *i*-th Karafs is *s**i*<==<=*A*<=+<=(*i*<=-<=1)<=Γ—<=*B*. For a given *m*, let's define an *m*-bite operation as decreasing the height of at most *m* distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero. Now SaDDas asks you *n* queries. In each query he gives you numbers *l*, *t* and *m* and you should find the largest number *r* such that *l*<=≀<=*r* and sequence *s**l*,<=*s**l*<=+<=1,<=...,<=*s**r* can be eaten by performing *m*-bite no more than *t* times or print -1 if there is no such number *r*. Input Specification: The first line of input contains three integers *A*, *B* and *n* (1<=≀<=*A*,<=*B*<=≀<=106, 1<=≀<=*n*<=≀<=105). Next *n* lines contain information about queries. *i*-th line contains integers *l*,<=*t*,<=*m* (1<=≀<=*l*,<=*t*,<=*m*<=≀<=106) for *i*-th query. Output Specification: For each query, print its answer in a single line. Demo Input: ['2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8\n', '1 5 2\n1 5 10\n2 7 4\n'] Demo Output: ['4\n-1\n8\n-1\n', '1\n2\n'] Note: none
804
Title: Little Pony and Summer Sun Celebration Time Limit: None seconds Memory Limit: None megabytes Problem Description: Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information? Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4*n* places. Input Specification: The first line contains two integers *n* and *m* (2<=≀<=*n*<=≀<=105;Β 0<=≀<=*m*<=≀<=105) β€” the number of places and the number of roads in Ponyville. Each of the following *m* lines contains two integers *u**i*,<=*v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*;Β *u**i*<=β‰ <=*v**i*), these integers describe a road between places *u**i* and *v**i*. The next line contains *n* integers: *x*1,<=*x*2,<=...,<=*x**n* (0<=≀<=*x**i*<=≀<=1) β€” the parity of the number of times that each place must be visited. If *x**i*<==<=0, then the *i*-th place must be visited even number of times, else it must be visited odd number of times. Output Specification: Output the number of visited places *k* in the first line (0<=≀<=*k*<=≀<=4*n*). Then output *k* integers β€” the numbers of places in the order of path. If *x**i*<==<=0, then the *i*-th place must appear in the path even number of times, else *i*-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct. If there is no required path, output -1. If there multiple possible paths, you can output any of them. Demo Input: ['3 2\n1 2\n2 3\n1 1 1\n', '5 7\n1 2\n1 3\n1 4\n1 5\n3 4\n3 5\n4 5\n0 1 0 1 0\n', '2 0\n0 0\n'] Demo Output: ['3\n1 2 3\n', '10\n2 1 3 4 5 4 5 4 3 1 ', '0\n'] Note: none
805
Title: Number With The Given Amount Of Divisors Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Given the number *n*, find the smallest positive integer which has exactly *n* divisors. It is guaranteed that for the given *n* the answer will not exceed 1018. Input Specification: The first line of the input contains integer *n* (1<=≀<=*n*<=≀<=1000). Output Specification: Output the smallest positive integer with exactly *n* divisors. Demo Input: ['4\n', '6\n'] Demo Output: ['6\n', '12\n'] Note: none
806
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF. You are given two strings *s*1, *s*2 and another string called *virus*. Your task is to find the longest common subsequence of *s*1 and *s*2, such that it doesn't contain *virus* as a substring. Input Specification: The input contains three strings in three separate lines: *s*1, *s*2 and *virus* (1<=≀<=|*s*1|,<=|*s*2|,<=|*virus*|<=≀<=100). Each string consists only of uppercase English letters. Output Specification: Output the longest common subsequence of *s*1 and *s*2 without *virus* as a substring. If there are multiple answers, any of them will be accepted. If there is no valid common subsequence, output 0. Demo Input: ['AJKEQSLOBSROFGZ\nOVGURWZLWVLUXTH\nOZ\n', 'AA\nA\nA\n'] Demo Output: ['ORZ\n', '0\n'] Note: none
807
Title: Choosing Subtree is Fun Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is a tree consisting of *n* vertices. The vertices are numbered from 1 to *n*. Let's define the length of an interval [*l*,<=*r*] as the value *r*<=-<=*l*<=+<=1. The score of a subtree of this tree is the maximum length of such an interval [*l*,<=*r*] that, the vertices with numbers *l*,<=*l*<=+<=1,<=...,<=*r* belong to the subtree. Considering all subtrees of the tree whose size is at most *k*, return the maximum score of the subtree. Note, that in this problem tree is not rooted, so a subtree β€” is an arbitrary connected subgraph of the tree. Input Specification: There are two integers in the first line, *n* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=105). Each of the next *n*<=-<=1 lines contains integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*). That means *a**i* and *b**i* are connected by a tree edge. It is guaranteed that the input represents a tree. Output Specification: Output should contain a single integer β€” the maximum possible score. Demo Input: ['10 6\n4 10\n10 6\n2 9\n9 6\n8 5\n7 1\n4 7\n7 3\n1 8\n', '16 7\n13 11\n12 11\n2 14\n8 6\n9 15\n16 11\n5 14\n6 15\n4 3\n11 15\n15 14\n10 1\n3 14\n14 7\n1 7\n'] Demo Output: ['3\n', '6\n'] Note: For the first case, there is some subtree whose size is at most 6, including 3 consecutive numbers of vertices. For example, the subtree that consists of {1, 3, 4, 5, 7, 8} or of {1, 4, 6, 7, 8, 10} includes 3 consecutive numbers of vertices. But there is no subtree whose size is at most 6, which includes 4 or more consecutive numbers of vertices.
808
Title: Test Data Generation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Test data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness. For example, consider a problem from an old Codeforces round. Its input format looks roughly as follows: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=*max**n*)Β β€” the size of the set. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=*max**a*)Β β€” the elements of the set in increasing order. If you don't pay attention to the problem solution, it looks fairly easy to generate a good test case for this problem. Let *n*<==<=*max**n*, take random distinct *a**i* from 1 to *max**a*, sort them... Soon you understand that it's not that easy. Here is the actual problem solution. Let *g* be the greatest common divisor of *a*1,<=*a*2,<=...,<=*a**n*. Let *x*<==<=*a**n*<=/<=*g*<=-<=*n*. Then the correct solution outputs "Alice" if *x* is odd, and "Bob" if *x* is even. Consider two wrong solutions to this problem which differ from the correct one only in the formula for calculating *x*. The first wrong solution calculates *x* as *x*<==<=*a**n*<=/<=*g* (without subtracting *n*). The second wrong solution calculates *x* as *x*<==<=*a**n*<=-<=*n* (without dividing by *g*). A test case is interesting if it makes both wrong solutions output an incorrect answer. Given *max**n*, *max**a* and *q*, find the number of interesting test cases satisfying the constraints, and output it modulo *q*. Input Specification: The only line contains three integers *max**n*, *max**a* and *q* (1<=≀<=*max**n*<=≀<=30<=000; *max**n*<=≀<=*max**a*<=≀<=109; 104<=≀<=*q*<=≀<=105<=+<=129). Output Specification: Output a single integerΒ β€” the number of test cases which satisfy the constraints and make both wrong solutions output an incorrect answer, modulo *q*. Demo Input: ['3 6 100000\n', '6 21 100129\n', '58 787788 50216\n'] Demo Output: ['4\n', '154\n', '46009\n'] Note: In the first example, interesting test cases look as follows:
809
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to *n* (*n*<=β‰₯<=2) burles and the amount of tax he has to pay is calculated as the maximum divisor of *n* (not equal to *n*, of course). For example, if *n*<==<=6 then Funt has to pay 3 burles, while for *n*<==<=25 he needs to pay 5 and if *n*<==<=2 he pays only 1 burle. As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial *n* in several parts *n*1<=+<=*n*2<=+<=...<=+<=*n**k*<==<=*n* (here *k* is arbitrary, even *k*<==<=1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition *n**i*<=β‰₯<=2 should hold for all *i* from 1 to *k*. Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split *n* in parts. Input Specification: The first line of the input contains a single integer *n* (2<=≀<=*n*<=≀<=2Β·109)Β β€” the total year income of mr. Funt. Output Specification: Print one integerΒ β€” minimum possible number of burles that mr. Funt has to pay as a tax. Demo Input: ['4\n', '27\n'] Demo Output: ['2\n', '3\n'] Note: none
810
Title: Palindrome pairs Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a non-empty string *s* consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string. In a more formal way, you have to find the quantity of tuples (*a*,<=*b*,<=*x*,<=*y*) such that 1<=≀<=*a*<=≀<=*b*<=&lt;<=*x*<=≀<=*y*<=≀<=|*s*| and substrings *s*[*a*... *b*], *s*[*x*... *y*] are palindromes. A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes. A substring *s*[*i*... *j*] (1<=≀<=*i*<=≀<=*j*<=≀<=|*s*|) of string *s* = *s*1*s*2... *s*|*s*| is a string *s**i**s**i*<=+<=1... *s**j*. For example, substring *s*[2...4] of string *s* = "abacaba" equals "bac". Input Specification: The first line of input contains a non-empty string *s* which consists of lowercase letters ('a'...'z'), *s* contains at most 2000 characters. Output Specification: Output a single number β€” the quantity of pairs of non-overlapping palindromic substrings of *s*. Please do not use the %lld format specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d format specifier. Demo Input: ['aa\n', 'aaa\n', 'abacaba\n'] Demo Output: ['1\n', '5\n', '36\n'] Note: none
811
Title: Wallpaper Time Limit: None seconds Memory Limit: None megabytes Problem Description: Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has *n* rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris chose *m* types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type. The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely. After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him. Input Specification: The first line contains a positive integer *n* (1<=≀<=*n*<=≀<=500) β€” the number of rooms in Boris's apartment. Each of the next *n* lines contains three space-separated positive integers β€” the length, width and height of the walls in a given room in meters, respectively. The next line contains a positive integer *m* (1<=≀<=*m*<=≀<=500) β€” the number of available wallpaper types. Each of the following *m* lines contains three space-separated positive integers β€” the length and width in meters of a given wallpaper and the price of one roll, respectively. All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper. Output Specification: Print a single number β€” the minimum total cost of the rolls. Demo Input: ['1\n5 5 3\n3\n10 1 100\n15 2 320\n3 19 500\n'] Demo Output: ['640\n'] Note: Note to the sample: The total length of the walls (the perimeter) of the room is 20 m. One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700. A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640. One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.
812
Title: Help Shrek and Donkey 2 Time Limit: None seconds Memory Limit: None megabytes Problem Description: Having learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers. The rules of the game are as follows: there is a battlefield, its size equals *n*<=Γ—<=*m* squares, some squares contain the toy soldiers (the green ones belong to Shrek and the red ones belong to Donkey). Besides, each of the *n* lines of the area contains not more than two soldiers. During a move a players should select not less than 1 and not more than *k* soldiers belonging to him and make them either attack or retreat. An attack is moving all of the selected soldiers along the lines on which they stand in the direction of an enemy soldier, if he is in this line. If this line doesn't have an enemy soldier, then the selected soldier on this line can move in any direction during the player's move. Each selected soldier has to move at least by one cell. Different soldiers can move by a different number of cells. During the attack the soldiers are not allowed to cross the cells where other soldiers stand (or stood immediately before the attack). It is also not allowed to go beyond the battlefield or finish the attack in the cells, where other soldiers stand (or stood immediately before attack). A retreat is moving all of the selected soldiers along the lines on which they stand in the direction from an enemy soldier, if he is in this line. The other rules repeat the rules of the attack. For example, let's suppose that the original battlefield had the form (here symbols "G" mark Shrek's green soldiers and symbols "R" mark Donkey's red ones): Let's suppose that *k*<==<=2 and Shrek moves first. If he decides to attack, then after his move the battlefield can look like that: If in the previous example Shrek decides to retreat, then after his move the battlefield can look like that: On the other hand, the followings fields cannot result from Shrek's correct move: Shrek starts the game. To make a move means to attack or to retreat by the rules. A player who cannot make a move loses and his opponent is the winner. Determine the winner of the given toy soldier game if Shrek and Donkey continue to be under the yellow pills from the last rounds' problem. Thus, they always play optimally (that is, they try to win if it is possible, or finish the game in a draw, by ensuring that it lasts forever, if they cannot win). Input Specification: The first line contains space-separated integers *n*, *m* and *k* (1<=≀<=*n*,<=*m*,<=*k*<=≀<=100). Then *n* lines contain *m* characters each. These characters belong to the set {"-", "G", "R"}, denoting, respectively, a battlefield's free cell, a cell occupied by Shrek's soldiers and a cell occupied by Donkey's soldiers. It is guaranteed that each line contains no more than two soldiers. Output Specification: Print "First" (without the quotes) if Shrek wins in the given Toy Soldier game. If Donkey wins, print "Second" (without the quotes). If the game continues forever, print "Draw" (also without the quotes). Demo Input: ['2 3 1\nR-G\nRG-\n', '3 3 2\nG-R\nR-G\nG-R\n', '2 3 1\n-R-\n-G-\n', '2 5 2\n-G-R-\n-R-G-\n'] Demo Output: ['First\n', 'Second\n', 'Draw\n', 'First\n'] Note: none
813
Title: Send the Fool Further! (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Heidi is terrified by your estimate and she found it unrealistic that her friends would collaborate to drive her into debt. She expects that, actually, each person will just pick a random friend to send Heidi to. (This randomness assumption implies, however, that she can now visit the same friend an arbitrary number of times...) Moreover, if a person only has one friend in common with Heidi (i.e., if that person is in a leaf of the tree), then that person will not send Heidi back (so that Heidi's travel will end at some point). Heidi also found unrealistic the assumption that she can make all the travels in one day. Therefore now she assumes that every time she travels a route between two friends, she needs to buy a new ticket. She wants to know: how much should she expect to spend on the trips? For what it's worth, Heidi knows that Jenny has at least two friends. Input Specification: The first line contains the number of friends *n* (3<=≀<=*n*<=≀<=105). The next *n*<=-<=1 lines each contain three space-separated integers *u*, *v* and *c* (0<=≀<=*u*,<=*v*<=≀<=*n*<=-<=1, 1<=≀<=*c*<=≀<=104) meaning that *u* and *v* are friends and the cost for traveling between *u* and *v* is *c* (paid every time!). It is again guaranteed that the social network of the input forms a tree. Output Specification: Assume that the expected cost of the trips is written as an irreducible fraction *a*<=/<=*b* (that is, *a* and *b* are coprime). Then Heidi, the weird cow that she is, asks you to output . (Output a single integer between 0 and 109<=+<=6.) Demo Input: ['3\n0 1 10\n0 2 20\n', '4\n0 1 3\n0 2 9\n0 3 27\n', '7\n0 1 3\n0 5 7\n1 2 2\n1 3 1\n1 4 5\n5 6 8\n', '11\n1 0 6646\n2 0 8816\n3 2 9375\n4 2 5950\n5 1 8702\n6 2 2657\n7 2 885\n8 7 2660\n9 2 5369\n10 6 3798\n', '6\n0 1 8\n0 2 24\n1 3 40\n1 4 16\n4 5 8\n'] Demo Output: ['15\n', '13\n', '400000019\n', '153869806\n', '39\n'] Note: In the first example, with probability 1 / 2 Heidi will go to 1 from 0, and with probability 1 / 2 she will go to 2. In the first case the cost would be 10, and in the second it would be 20. After reaching 1 or 2 she will stop, as 1 and 2 are leaves of the social tree. Hence, the expected cost she has to pay is 10Β·1 / 2 + 20Β·1 / 2 = 15. In the third example, the expected cost is 81 / 5. You should output 400000019. In her travels, Heidi has learned an intriguing fact about the structure of her social network. She tells you the following: The mysterious determinant that you might be wondering about is such that it does not cause strange errors in your reasonable solution... Did we mention that Heidi is a weird cow?
814
Title: Little Brother Time Limit: None seconds Memory Limit: None megabytes Problem Description: Masha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister. Masha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing. At first, the line going through two points, that brother drew, doesn't intersect or touch any circle. Also, no two circles intersect or touch, and there is no pair of circles such that one circle is located inside another. Moreover, for each circle, Masha drew a square of the minimal area with sides parallel axis such that this circle is located inside the square and noticed that there is no two squares intersect or touch and there is no pair of squares such that one square is located inside other. Now Masha wants to draw circle of minimal possible radius such that it goes through two points that brother drew and doesn't intersect any other circle, but other circles can touch Masha's circle and can be located inside it. It's guaranteed, that answer won't exceed 1012. It should be held for hacks as well. Input Specification: First line contains four integers *x*1, *y*1, *x*2, *y*2 (<=-<=105<=≀<=*x*1,<=*y*1,<=*x*2,<=*y*2<=≀<=105)Β β€” coordinates of points that brother drew. First point has coordinates (*x*1, *y*1) and second point has coordinates (*x*2, *y*2). These two points are different. The second line contains single integer *n* (1<=≀<=*n*<=≀<=105)Β β€” the number of circles that brother drew. Next *n* lines contains descriptions of circles. Each line contains three integers *x**i*, *y**i*, *r**i* (<=-<=105<=≀<=*x**i*,<=*y**i*<=≀<=105, 1<=≀<=*r**i*<=≀<=105) describing circle with center (*x**i*, *y**i*) and radius *r**i*. Output Specification: Output smallest real number, that it's possible to draw a circle with such radius through given points in such a way that it doesn't intersect other circles. The output is considered correct if it has a relative or absolute error of at most 10<=-<=4. Demo Input: ['2 4 7 13\n3\n3 0 1\n12 4 2\n-4 14 2\n', '-2 3 10 -10\n2\n7 0 3\n-5 -5 2\n'] Demo Output: ['5.1478150705', '9.1481831923'] Note: <img class="tex-graphics" src="https://espresso.codeforces.com/5a8f62f2439db62d006a0959f077351937f109a0.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img class="tex-graphics" src="https://espresso.codeforces.com/0500120c641e4aab8bb5490323ce5a68957a6621.png" style="max-width: 100.0%;max-height: 100.0%;"/>
815
Title: Counting Kangaroos is Fun Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. Input Specification: The first line contains a single integer β€” *n* (1<=≀<=*n*<=≀<=5Β·105). Each of the next *n* lines contains an integer *s**i* β€” the size of the *i*-th kangaroo (1<=≀<=*s**i*<=≀<=105). Output Specification: Output a single integer β€” the optimal number of visible kangaroos. Demo Input: ['8\n2\n5\n7\n6\n9\n8\n4\n2\n', '8\n9\n1\n6\n2\n6\n5\n8\n3\n'] Demo Output: ['5\n', '5\n'] Note: none
816
Title: Polo the Penguin and Lucky Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Polo the Penguin have two positive integers *l* and *r* (*l*<=&lt;<=*r*), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other. Let's assume that *n* is the number of distinct lucky numbers, each of them cannot be greater than *r* or less than *l*, and *a**i* is the *i*-th (in increasing order) number of them. Find *a*1Β·*a*2<=+<=*a*2Β·*a*3<=+<=...<=+<=*a**n*<=-<=1Β·*a**n*. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109<=+<=7). Input Specification: The first line contains a positive integer *l*, and the second line contains a positive integer *r* (1<=≀<=*l*<=&lt;<=*r*<=≀<=10100000). The numbers are given without any leading zeroes. It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers. Output Specification: In the single line print a single integer β€” the answer to the problem modulo 1000000007 (109<=+<=7). Demo Input: ['4\n7\n', '474\n777\n'] Demo Output: ['28\n', '2316330\n'] Note: none
817
Title: Swaps Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* players sitting at a round table. All of them have *s* cards of *n* colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules: - as the players swap, a player can give a card of his color only; - a player can't accept a card of a color he already has (particularly, he can't take cards of his color, no matter whether he has given out all of them or not); - during one swap a pair of people swaps cards (each person gives one card and takes one card). The aim of all *n* people is as follows: each of them should give out all the cards he had initially (that is, all cards of his color). Your task is to denote whether such sequence of swaps is possible. If the answer is positive, you should list all the swaps. Input Specification: The first line contains integers *n* (1<=≀<=*n*<=≀<=200000) and *s* (1<=≀<=*s*<=≀<=200000). The second line contains *n* numbers, the *i*-th number stands for how many cards the *i*-th player has by the moment the game starts. It is possible that a player has no cards initially. Output Specification: On the first line print "No" if such sequence of swaps is impossible. Otherwise, print "Yes". If the answer is positive, next print number *k* β€” the number of the swaps. Then on *k* lines describe the swaps by pairs of indices of the swapping players. Print the swaps and the numbers of the swaps in any order. Demo Input: ['4 8\n2 2 2 2\n', '6 12\n1 1 2 2 3 3\n', '5 5\n0 0 0 0 5\n'] Demo Output: ['Yes\n4\n4 3\n4 2\n1 3\n1 2\n', 'Yes\n6\n6 5\n6 4\n6 3\n5 4\n5 3\n2 1\n', 'No\n'] Note: none
818
Title: Facetook Priority Wall Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described). This priority factor will be affected by three types of actions: - 1. "*X* posted on *Y*'s wall" (15 points), - 2. "*X* commented on *Y*'s post" (10 points), - 3. "*X* likes *Y*'s post" (5 points). *X* and *Y* will be two distinct names. And each action will increase the priority factor between *X* and *Y* (and vice versa) by the above value of points (the priority factor between *X* and *Y* is the same as the priority factor between *Y* and *X*). You will be given *n* actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you. Input Specification: The first line contains your name. The second line contains an integer *n*, which is the number of actions (1<=≀<=*n*<=≀<=100). Then *n* lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters. Output Specification: Print *m* lines, where *m* is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order. Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor. The lexicographical comparison is performed by the standard "&lt;" operator in modern programming languages. The line *a* is lexicographically smaller than the line *b*, if either *a* is the prefix of *b*, or if exists such an *i* (1<=≀<=*i*<=≀<=*min*(|*a*|,<=|*b*|)), that *a**i*<=&lt;<=*b**i*, and for any *j* (1<=≀<=*j*<=&lt;<=*i*) *a**j*<==<=*b**j*, where |*a*| and |*b*| stand for the lengths of strings *a* and *b* correspondently. Demo Input: ["ahmed\n3\nahmed posted on fatma's wall\nfatma commented on ahmed's post\nmona likes ahmed's post\n", "aba\n1\nlikes likes posted's post\n"] Demo Output: ['fatma\nmona\n', 'likes\nposted\n'] Note: none
819
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Nephren is playing a game with little leprechauns. She gives them an infinite array of strings, *f*0... ∞. *f*0 is "What are you doing at the end of the world? Are you busy? Will you save us?". She wants to let more people know about it, so she defines *f**i*<==<= "What are you doing while sending "*f**i*<=-<=1"? Are you busy? Will you send "*f**i*<=-<=1"?" for all *i*<=β‰₯<=1. For example, *f*1 is "What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of *f*1. It can be seen that the characters in *f**i* are letters, question marks, (possibly) quotation marks and spaces. Nephren will ask the little leprechauns *q* times. Each time she will let them find the *k*-th character of *f**n*. The characters are indexed starting from 1. If *f**n* consists of less than *k* characters, output '.' (without quotes). Can you answer her queries? Input Specification: The first line contains one integer *q* (1<=≀<=*q*<=≀<=10)Β β€” the number of Nephren's questions. Each of the next *q* lines describes Nephren's question and contains two integers *n* and *k* (0<=≀<=*n*<=≀<=105,<=1<=≀<=*k*<=≀<=1018). Output Specification: One line containing *q* characters. The *i*-th character in it should be the answer for the *i*-th query. Demo Input: ['3\n1 1\n1 2\n1 111111111111\n', '5\n0 69\n1 194\n1 139\n0 47\n1 66\n', '10\n4 1825\n3 75\n3 530\n4 1829\n4 1651\n3 187\n4 584\n4 255\n4 774\n2 474\n'] Demo Output: ['Wh.', 'abdef', 'Areyoubusy'] Note: For the first two examples, refer to *f*<sub class="lower-index">0</sub> and *f*<sub class="lower-index">1</sub> given in the legend.
820
Title: Roads in Berland Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* cities numbered from 1 to *n* in Berland. Some of them are connected by two-way roads. Each road has its own length β€” an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build *k* new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β€” for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. Input Specification: The first line contains integer *n* (2<=≀<=*n*<=≀<=300) β€” amount of cities in Berland. Then there follow *n* lines with *n* integer numbers each β€” the matrix of shortest distances. *j*-th integer in the *i*-th row β€” *d**i*,<=*j*, the shortest distance between cities *i* and *j*. It is guaranteed that *d**i*,<=*i*<==<=0,<=*d**i*,<=*j*<==<=*d**j*,<=*i*, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer *k* (1<=≀<=*k*<=≀<=300) β€” amount of planned roads. Following *k* lines contain the description of the planned roads. Each road is described by three space-separated integers *a**i*, *b**i*, *c**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*,<=1<=≀<=*c**i*<=≀<=1000) β€” *a**i* and *b**i* β€” pair of cities, which the road connects, *c**i* β€” the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. Output Specification: Output *k* space-separated integers *q**i* (1<=≀<=*i*<=≀<=*k*). *q**i* should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to *i*. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. Demo Input: ['2\n0 5\n5 0\n1\n1 2 3\n', '3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1\n'] Demo Output: ['3 ', '17 12 '] Note: none
821
Title: Regular Bracket Sequence Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters Β«+Β» and Β«1Β» into this sequence. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not. One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? Input Specification: Input consists of a single line with non-empty string of Β«(Β» and Β«)Β» characters. Its length does not exceed 106. Output Specification: Output the maximum possible length of a regular bracket sequence. Demo Input: ['(()))(\n', '((()())\n'] Demo Output: ['4\n', '6\n'] Note: none
822
Title: You're Given a String... Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2). Input Specification: The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100. Output Specification: Output one number β€” length of the longest substring that can be met in the string at least twice. Demo Input: ['abcd\n', 'ababa\n', 'zzz\n'] Demo Output: ['0', '3', '2'] Note: none
823
Title: Santa Claus and a Place in a Class Time Limit: None seconds Memory Limit: None megabytes Problem Description: Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture). The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i.Β e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i.Β e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right! Input Specification: The only line contains three integers *n*, *m* and *k* (1<=≀<=*n*,<=*m*<=≀<=10<=000, 1<=≀<=*k*<=≀<=2*nm*)Β β€” the number of lanes, the number of desks in each lane and the number of Santa Claus' place. Output Specification: Print two integers: the number of lane *r*, the number of desk *d*, and a character *s*, which stands for the side of the desk Santa Claus. The character *s* should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right. Demo Input: ['4 3 9\n', '4 3 24\n', '2 4 4\n'] Demo Output: ['2 2 L\n', '4 3 R\n', '1 2 R\n'] Note: The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example. In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right.
824
Title: Contest Balloons Time Limit: None seconds Memory Limit: None megabytes Problem Description: One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed. You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings. A contest has just finished. There are *n* teams, numbered 1 through *n*. The *i*-th team has *t**i* balloons and weight *w**i*. It's guaranteed that *t**i* doesn't exceed *w**i* so nobody floats initially. Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has. What is the best place Limak can get? Input Specification: The first line of the standard input contains one integer *n* (2<=≀<=*n*<=≀<=300<=000)Β β€” the number of teams. The *i*-th of *n* following lines contains two integers *t**i* and *w**i* (0<=≀<=*t**i*<=≀<=*w**i*<=≀<=1018)Β β€” respectively the number of balloons and the weight of the *i*-th team. Limak is a member of the first team. Output Specification: Print one integer denoting the best place Limak can get. Demo Input: ['8\n20 1000\n32 37\n40 1000\n45 50\n16 16\n16 16\n14 1000\n2 1000\n', '7\n4 4\n4 4\n4 4\n4 4\n4 4\n4 4\n5 5\n', '7\n14000000003 1000000000000000000\n81000000000 88000000000\n5000000000 7000000000\n15000000000 39000000000\n46000000000 51000000000\n0 1000000000\n0 0\n'] Demo Output: ['3\n', '2\n', '2\n'] Note: In the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is: 1. Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place.1. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified.1. Limak gives 1 balloon to each of two teams with 16 balloons initially.1. Limak has 20 - 6 - 6 - 1 - 1 = 6 balloons.1. There are three other teams left and their numbers of balloons are 40, 14 and 2.1. Limak gets the third place because there are two teams with more balloons. In the second sample, Limak has the second place and he can't improve it. In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81 000 000 000, 5 000 000 000 and 46 000 000 000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7).
825
Title: Binary Key Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's assume that *p* and *q* are strings of positive length, called the container and the key correspondingly, string *q* only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message *s* from the given container *p*: In the given pseudocode *i*, *j* are integer variables, *s* is a string, '=' is an assignment operator, '==' is a comparison operation, '[]' is the operation of obtaining the string character with the preset index, '&lt;&gt;' is an empty string. We suppose that in all strings the characters are numbered starting from zero. We understand that implementing such algorithm is quite easy, so your task is going to be slightly different. You need to construct the lexicographically minimum key of length *k*, such that when it is used, the algorithm given above extracts message *s* from container *p* (otherwise find out that such key doesn't exist). Input Specification: The first two lines of the input are non-empty strings *p* and *s* (1<=≀<=|*p*|<=≀<=106, 1<=≀<=|*s*|<=≀<=200), describing the container and the message, correspondingly. The strings can contain any characters with the ASCII codes from 32 to 126, inclusive. The third line contains a single integer *k* (1<=≀<=*k*<=≀<=2000) β€” the key's length. Output Specification: Print the required key (string of length *k*, consisting only of characters 0 and 1). If the key doesn't exist, print the single character 0. Demo Input: ['abacaba\naba\n6\n', 'abacaba\naba\n3\n'] Demo Output: ['100001\n', '0\n'] Note: String *x* = *x*<sub class="lower-index">1</sub>*x*<sub class="lower-index">2</sub>... *x*<sub class="lower-index">*p*</sub> is lexicographically smaller than string *y* = *y*<sub class="lower-index">1</sub>*y*<sub class="lower-index">2</sub>... *y*<sub class="lower-index">*q*</sub>, if either *p* &lt; *q* and *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*p*</sub> = *y*<sub class="lower-index">*p*</sub>, or there exists such integer *r* (0 ≀ *r* &lt; *min*(*p*, *q*)) that *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*r*</sub> = *y*<sub class="lower-index">*r*</sub> and *x*<sub class="lower-index">*r* + 1</sub> &lt; *y*<sub class="lower-index">*r* + 1</sub>. Symbols are compared according to their ASCII codes.
826
Title: TorCoder Time Limit: None seconds Memory Limit: None megabytes Problem Description: A boy named Leo doesn't miss a single TorCoder contest round. On the last TorCoder round number 100666 Leo stumbled over the following problem. He was given a string *s*, consisting of *n* lowercase English letters, and *m* queries. Each query is characterised by a pair of integers *l**i*,<=*r**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*). We'll consider the letters in the string numbered from 1 to *n* from left to right, that is, *s*<==<=*s*1*s*2... *s**n*. After each query he must swap letters with indexes from *l**i* to *r**i* inclusive in string *s* so as to make substring (*l**i*,<=*r**i*) a palindrome. If there are multiple such letter permutations, you should choose the one where string (*l**i*,<=*r**i*) will be lexicographically minimum. If no such permutation exists, you should ignore the query (that is, not change string *s*). Everybody knows that on TorCoder rounds input line and array size limits never exceed 60, so Leo solved this problem easily. Your task is to solve the problem on a little bit larger limits. Given string *s* and *m* queries, print the string that results after applying all *m* queries to string *s*. Input Specification: The first input line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the string length and the number of the queries. The second line contains string *s*, consisting of *n* lowercase Latin letters. Each of the next *m* lines contains a pair of integers *l**i*,<=*r**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*) β€” a query to apply to the string. Output Specification: In a single line print the result of applying *m* queries to string *s*. Print the queries in the order in which they are given in the input. Demo Input: ['7 2\naabcbaa\n1 3\n5 7\n', '3 2\nabc\n1 2\n2 3\n'] Demo Output: ['abacaba\n', 'abc\n'] Note: A substring (*l*<sub class="lower-index">*i*</sub>, *r*<sub class="lower-index">*i*</sub>) 1 ≀ *l*<sub class="lower-index">*i*</sub> ≀ *r*<sub class="lower-index">*i*</sub> ≀ *n*) of string *s* = *s*<sub class="lower-index">1</sub>*s*<sub class="lower-index">2</sub>... *s*<sub class="lower-index">*n*</sub> of length *n* is a sequence of characters *s*<sub class="lower-index">*l*<sub class="lower-index">*i*</sub></sub>*s*<sub class="lower-index">*l*<sub class="lower-index">*i* + 1</sub></sub>...*s*<sub class="lower-index">*r*<sub class="lower-index">*i*</sub></sub>. A string is a palindrome, if it reads the same from left to right and from right to left. String *x*<sub class="lower-index">1</sub>*x*<sub class="lower-index">2</sub>... *x*<sub class="lower-index">*p*</sub> is lexicographically smaller than string *y*<sub class="lower-index">1</sub>*y*<sub class="lower-index">2</sub>... *y*<sub class="lower-index">*q*</sub>, if either *p* &lt; *q* and *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*p*</sub> = *y*<sub class="lower-index">*p*</sub>, or exists such number *r* (*r* &lt; *p*, *r* &lt; *q*), that *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*r*</sub> = *y*<sub class="lower-index">*r*</sub> and *x*<sub class="lower-index">*r* + 1</sub> &lt; *y*<sub class="lower-index">*r* + 1</sub>.
827
Title: Bulbo Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights. In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |*pos**new*<=-<=*pos**old*|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs. Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families. Input Specification: The first line contains number of turns *n* and initial position *x*. Next *n* lines contain two numbers *l**start* and *l**end*, which represent that all bulbs from interval [*l**start*,<=*l**end*] are shining this turn. - 1<=≀<=*n*<=≀<=5000 - 1<=≀<=*x*<=≀<=109 - 1<=≀<=*l**start*<=≀<=*l**end*<=≀<=109 Output Specification: Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game. Demo Input: ['5 4\n2 7\n9 16\n8 10\n9 17\n1 6\n'] Demo Output: ['8\n'] Note: Before 1. turn move to position 5 Before 2. turn move to position 9 Before 5. turn move to position 8
828
Title: Binary Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a matrix of size *n*<=Γ—<=*m*. Each element of the matrix is either 1 or 0. You have to determine the number of connected components consisting of 1's. Two cells belong to the same component if they have a common border, and both elements in these cells are 1's. Note that the memory limit is unusual! Input Specification: The first line contains two numbers *n* and *m* (1<=≀<=*n*<=≀<=212, 4<=≀<=*m*<=≀<=214) β€” the number of rows and columns, respectively. It is guaranteed that *m* is divisible by 4. Then the representation of matrix follows. Each of *n* next lines contains one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from *A* to *F*). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number *B* is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101. Elements are not separated by whitespaces. Output Specification: Print the number of connected components consisting of 1's. Demo Input: ['3 4\n1\nA\n8\n', '2 8\n5F\nE3\n', '1 4\n0\n'] Demo Output: ['3\n', '2\n', '0\n'] Note: In the first example the matrix is: It is clear that it has three components. The second example: It is clear that the number of components is 2. There are no 1's in the third example, so the answer is 0.
829
Title: Rock-paper-scissors Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up β€” who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown. Input Specification: The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture. Output Specification: Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?". Demo Input: ['rock\nrock\nrock\n', 'paper\nrock\nrock\n', 'scissors\nrock\nrock\n', 'scissors\npaper\nrock\n'] Demo Output: ['?\n', 'F\n', '?\n', '?\n'] Note: none
830
Title: Sonya and Ice Cream Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops. Sonya lives in a city with $n$ junctions and $n-1$ streets between them. All streets are two-way and connect two junctions. It is possible to travel from any junction to any other using one or more streets. City Hall allows opening shops only on junctions. The girl cannot open shops in the middle of streets. Sonya has exactly $k$ friends whom she can trust. If she opens a shop, one of her friends has to work there and not to allow anybody to eat an ice cream not paying for it. Since Sonya does not want to skip an important competition, she will not work in shops personally. Sonya wants all her ice cream shops to form a simple path of the length $r$ ($1 \le r \le k$), i.e. to be located in different junctions $f_1, f_2, \dots, f_r$ and there is street between $f_i$ and $f_{i+1}$ for each $i$ from $1$ to $r-1$. The girl takes care of potential buyers, so she also wants to minimize the maximum distance between the junctions to the nearest ice cream shop. The distance between two junctions $a$ and $b$ is equal to the sum of all the street lengths that you need to pass to get from the junction $a$ to the junction $b$. So Sonya wants to minimize $$\max_{a} \min_{1 \le i \le r} d_{a,f_i}$$ where $a$ takes a value of all possible $n$ junctions, $f_i$Β β€” the junction where the $i$-th Sonya's shop is located, and $d_{x,y}$Β β€” the distance between the junctions $x$ and $y$. Sonya is not sure that she can find the optimal shops locations, that is why she is asking you to help her to open not more than $k$ shops that will form a simple path and the maximum distance between any junction and the nearest shop would be minimal. Input Specification: The first line contains two integers $n$ and $k$ ($1\leq k\leq n\leq 10^5$)Β β€” the number of junctions and friends respectively. Each of the next $n-1$ lines contains three integers $u_i$, $v_i$, and $d_i$ ($1\leq u_i, v_i\leq n$, $v_i\neq u_i$, $1\leq d\leq 10^4$)Β β€” junctions that are connected by a street and the length of this street. It is guaranteed that each pair of junctions is connected by at most one street. It is guaranteed that you can get from any junctions to any other. Output Specification: Print one numberΒ β€” the minimal possible maximum distance that you need to pass to get from any junction to the nearest ice cream shop. Sonya's shops must form a simple path and the number of shops must be at most $k$. Demo Input: ['6 2\n1 2 3\n2 3 4\n4 5 2\n4 6 3\n2 4 6\n', '10 3\n1 2 5\n5 7 2\n3 2 6\n10 6 3\n3 8 1\n6 4 2\n4 1 6\n6 9 4\n5 2 5\n'] Demo Output: ['4\n', '7\n'] Note: In the first example, you can choose the path 2-4, so the answer will be 4. In the second example, you can choose the path 4-1-2, so the answer will be 7.
831
Title: Complete the Word Time Limit: None seconds Memory Limit: None megabytes Problem Description: ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not nice. Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him? Input Specification: The first and only line of the input contains a single string *s* (1<=≀<=|*s*|<=≀<=50<=000), the word that ZS the Coder remembers. Each character of the string is the uppercase letter of English alphabet ('A'-'Z') or is a question mark ('?'), where the question marks denotes the letters that ZS the Coder can't remember. Output Specification: If there is no way to replace all the question marks with uppercase letters such that the resulting word is nice, then print <=-<=1 in the only line. Otherwise, print a string which denotes a possible nice word that ZS the Coder learned. This string should match the string from the input, except for the question marks replaced with uppercase English letters. If there are multiple solutions, you may print any of them. Demo Input: ['ABC??FGHIJK???OPQR?TUVWXY?\n', 'WELCOMETOCODEFORCESROUNDTHREEHUNDREDANDSEVENTYTWO\n', '??????????????????????????\n', 'AABCDEFGHIJKLMNOPQRSTUVW??M\n'] Demo Output: ['ABCDEFGHIJKLMNOPQRZTUVWXYS', '-1', 'MNBVCXZLKJHGFDSAQPWOEIRUYT', '-1'] Note: In the first sample case, ABCDEFGHIJKLMNOPQRZTUVWXYS is a valid answer beacuse it contains a substring of length 26 (the whole string in this case) which contains all the letters of the English alphabet exactly once. Note that there are many possible solutions, such as ABCDEFGHIJKLMNOPQRSTUVWXYZ or ABCEDFGHIJKLMNOPQRZTUVWXYS. In the second sample case, there are no missing letters. In addition, the given string does not have a substring of length 26 that contains all the letters of the alphabet, so the answer is  - 1. In the third sample case, any string of length 26 that contains all letters of the English alphabet fits as an answer.
832
Title: Tiling with Hexagons Time Limit: None seconds Memory Limit: None megabytes Problem Description: Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles. The hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has *a*, *b*, *c*, *a*, *b* and *c* adjacent tiles, correspondingly. To better visualize the situation, look at the picture showing a similar hexagon for *a*<==<=2, *b*<==<=3 and *c*<==<=4. According to the legend, as the King of Berland obtained the values *a*, *b* and *c*, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same? Input Specification: The first line contains three integers: *a*, *b* and *c* (2<=≀<=*a*,<=*b*,<=*c*<=≀<=1000). Output Specification: Print a single number β€” the total number of tiles on the hall floor. Demo Input: ['2 3 4\n'] Demo Output: ['18'] Note: none
833
Title: Bear and Strings Time Limit: None seconds Memory Limit: None megabytes Problem Description: The bear has a string *s*<==<=*s*1*s*2... *s*|*s*| (record |*s*| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices *i*,<=*j* (1<=≀<=*i*<=≀<=*j*<=≀<=|*s*|), that string *x*(*i*,<=*j*)<==<=*s**i**s**i*<=+<=1... *s**j* contains at least one string "bear" as a substring. String *x*(*i*,<=*j*) contains string "bear", if there is such index *k* (*i*<=≀<=*k*<=≀<=*j*<=-<=3), that *s**k*<==<=*b*, *s**k*<=+<=1<==<=*e*, *s**k*<=+<=2<==<=*a*, *s**k*<=+<=3<==<=*r*. Help the bear cope with the given problem. Input Specification: The first line contains a non-empty string *s* (1<=≀<=|*s*|<=≀<=5000). It is guaranteed that the string only consists of lowercase English letters. Output Specification: Print a single number β€” the answer to the problem. Demo Input: ['bearbtear\n', 'bearaabearc\n'] Demo Output: ['6\n', '20\n'] Note: In the first sample, the following pairs (*i*, *j*) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (*i*, *j*) match: (1,  4), (1,  5), (1,  6), (1,  7), (1,  8), (1,  9), (1,  10), (1,  11), (2,  10), (2,  11), (3,  10), (3,  11), (4,  10), (4,  11), (5,  10), (5,  11), (6,  10), (6,  11), (7,  10), (7,  11).
834
Title: XOR-pyramid Time Limit: None seconds Memory Limit: None megabytes Problem Description: For an array $b$ of length $m$ we define the function $f$ as where $\oplus$ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$. Input Specification: The first line contains a single integer $n$ ($1 \le n \le 5000$)Β β€” the length of $a$. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$)Β β€” the elements of the array. The third line contains a single integer $q$ ($1 \le q \le 100\,000$)Β β€” the number of queries. Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$). Output Specification: Print $q$ linesΒ β€” the answers for the queries. Demo Input: ['3\n8 4 1\n2\n2 3\n1 2\n', '6\n1 2 4 8 16 32\n4\n1 6\n2 5\n3 4\n1 2\n'] Demo Output: ['5\n12\n', '60\n30\n12\n3\n'] Note: In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment. In second sample, optimal segment for first query are $[3,6]$, for second query β€” $[2,5]$, for third β€” $[3,4]$, for fourth β€” $[1,2]$.
835
Title: Sonya and Exhibition Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily. She knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies. Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible. Input Specification: The first line contains two integers $n$ and $m$ ($1\leq n, m\leq 10^3$)Β β€” the number of flowers and visitors respectively. Each of the next $m$ lines contains two integers $l_i$ and $r_i$ ($1\leq l_i\leq r_i\leq n$), meaning that $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. Output Specification: Print the string of $n$ characters. The $i$-th symbol should be Β«0Β» if you want to put a rose in the $i$-th position, otherwise Β«1Β» if you want to put a lily. If there are multiple answers, print any. Demo Input: ['5 3\n1 3\n2 4\n2 5\n', '6 3\n5 6\n1 4\n4 6\n'] Demo Output: ['01100', '110010'] Note: In the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; - in the segment $[1\ldots3]$, there are one rose and two lilies, so the beauty is equal to $1\cdot 2=2$; - in the segment $[2\ldots4]$, there are one rose and two lilies, so the beauty is equal to $1\cdot 2=2$; - in the segment $[2\ldots5]$, there are two roses and two lilies, so the beauty is equal to $2\cdot 2=4$. The total beauty is equal to $2+2+4=8$. In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; - in the segment $[5\ldots6]$, there are one rose and one lily, so the beauty is equal to $1\cdot 1=1$; - in the segment $[1\ldots4]$, there are two roses and two lilies, so the beauty is equal to $2\cdot 2=4$; - in the segment $[4\ldots6]$, there are two roses and one lily, so the beauty is equal to $2\cdot 1=2$. The total beauty is equal to $1+4+2=7$.
836
Title: Gerald and Giant Chess Time Limit: None seconds Memory Limit: None megabytes Problem Description: Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an *h*<=Γ—<=*w* field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process. Input Specification: The first line of the input contains three integers: *h*,<=*w*,<=*n* β€” the sides of the board and the number of black cells (1<=≀<=*h*,<=*w*<=≀<=105,<=1<=≀<=*n*<=≀<=2000). Next *n* lines contain the description of black cells. The *i*-th of these lines contains numbers *r**i*,<=*c**i* (1<=≀<=*r**i*<=≀<=*h*,<=1<=≀<=*c**i*<=≀<=*w*) β€” the number of the row and column of the *i*-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct. Output Specification: Print a single line β€” the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109<=+<=7. Demo Input: ['3 4 2\n2 2\n2 3\n', '100 100 3\n15 16\n16 15\n99 88\n'] Demo Output: ['2\n', '545732279\n'] Note: none
837
Title: Double Knapsack Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given two multisets *A* and *B*. Each multiset has exactly *n* integers each between 1 and *n* inclusive. Multisets may contain multiple copies of the same number. You would like to find a nonempty subset of *A* and a nonempty subset of *B* such that the sum of elements in these subsets are equal. Subsets are also multisets, i.e. they can contain elements with equal values. If no solution exists, print <=-<=1. Otherwise, print the indices of elements in any such subsets of *A* and *B* that have the same sum. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1<=000<=000)Β β€” the size of both multisets. The second line contains *n* integers, denoting the elements of *A*. Each element will be between 1 and *n* inclusive. The third line contains *n* integers, denoting the elements of *B*. Each element will be between 1 and *n* inclusive. Output Specification: If there is no solution, print a single integer <=-<=1. Otherwise, your solution should be printed on four lines. The first line should contain a single integer *k**a*, the size of the corresponding subset of *A*. The second line should contain *k**a* distinct integers, the indices of the subset of *A*. The third line should contain a single integer *k**b*, the size of the corresponding subset of *B*. The fourth line should contain *k**b* distinct integers, the indices of the subset of *B*. Elements in both sets are numbered from 1 to *n*. If there are multiple possible solutions, print any of them. Demo Input: ['10\n10 10 10 10 10 10 10 10 10 10\n10 9 8 7 6 5 4 3 2 1\n', '5\n4 4 3 3 3\n2 2 2 2 5\n'] Demo Output: ['1\n2\n3\n5 8 10\n', '2\n2 3\n2\n3 5\n'] Note: none
838
Title: Randomizer Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows. A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a basic polygon. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the basic polygon. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer? During the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the basic polygon. Let's assume that there are *k* versions of the polygons. Then the Randomizer chooses each of them with probability . Input Specification: The first line of the input contains a single integer *n* (3<=≀<=*n*<=≀<=100<=000) β€” the number of vertices of the basic polygon. Next *n* lines contain the coordinates of the vertices of the basic polygon. The *i*-th of these lines contain two integers *x**i* and *y**i* (<=-<=109<=≀<=*x**i*,<=*y**i*<=≀<=109) β€” the coordinates of the *i*-th vertex of the polygon. The vertices are given in the counter-clockwise order. Output Specification: Print the sought expected value with absolute or relative error at most 10<=-<=9. Demo Input: ['4\n0 0\n2 0\n2 2\n0 2\n', '5\n0 0\n2 0\n2 2\n1 3\n0 2\n'] Demo Output: ['0.2\n', '0.8125\n'] Note: A polygon is called strictly convex if it is convex and no its vertices lie on the same line. Let's assume that a random variable takes values *x*<sub class="lower-index">1</sub>, ..., *x*<sub class="lower-index">*n*</sub> with probabilities *p*<sub class="lower-index">1</sub>, ..., *p*<sub class="lower-index">*n*</sub>, correspondingly. Then the expected value of this variable equals to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e592ba0986f3722e82626df9d579add61ddc5d36.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
839
Title: Pashmak and Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with *n* vertices and *m* edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input Specification: The first line contains two integers *n*, *m* (2<=≀<=*n*<=≀<=3Β·105;Β 1<=≀<=*m*<=≀<=*min*(*n*Β·(*n*<=-<=1),<=3Β·105)). Then, *m* lines follows. The *i*-th line contains three space separated integers: *u**i*, *v**i*, *w**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*;Β 1<=≀<=*w**i*<=≀<=105) which indicates that there's a directed edge with weight *w**i* from vertex *u**i* to vertex *v**i*. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Specification: Print a single integer β€” the answer to the problem. Demo Input: ['3 3\n1 2 1\n2 3 1\n3 1 1\n', '3 3\n1 2 1\n2 3 2\n3 1 3\n', '6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4\n'] Demo Output: ['1\n', '3\n', '6\n'] Note: In the first sample the maximum trail can be any of this trails: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1534088dd4d998a9bcc7e17dba96f7c213c54fc6.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample the maximum trail is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9b1d1f66686c43090329870c208942499764a73b.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the third sample the maximum trail is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1db1cef44580d43663d6896f0190e5ccee9502c9.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
840
Title: Island Puzzle Time Limit: None seconds Memory Limit: None megabytes Problem Description: A remote island chain contains *n* islands, labeled 1 through *n*. Bidirectional bridges connect the islands to form a simple cycleΒ β€” a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands *n* and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. Determine if it is possible for the islanders to arrange the statues in the desired order. Input Specification: The first line contains a single integer *n* (2<=≀<=*n*<=≀<=200<=000)Β β€” the total number of islands. The second line contains *n* space-separated integers *a**i* (0<=≀<=*a**i*<=≀<=*n*<=-<=1)Β β€” the statue currently placed on the *i*-th island. If *a**i*<==<=0, then the island has no statue. It is guaranteed that the *a**i* are distinct. The third line contains *n* space-separated integers *b**i* (0<=≀<=*b**i*<=≀<=*n*<=-<=1) β€” the desired statues of the *i*th island. Once again, *b**i*<==<=0 indicates the island desires no statue. It is guaranteed that the *b**i* are distinct. Output Specification: Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise. Demo Input: ['3\n1 0 2\n2 0 1\n', '2\n1 0\n0 1\n', '4\n1 2 3 0\n0 3 2 1\n'] Demo Output: ['YES\n', 'YES\n', 'NO\n'] Note: In the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. In the third sample, no sequence of movements results in the desired position.
841
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most *k* bills from it, and the bills may be of at most two distinct denominations. For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at *k*<==<=20 such ATM can give sums 100<=000 burles and 96<=000 burles, but it cannot give sums 99<=000 and 101<=000 burles. Let's suppose that the country uses bills of *n* distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash *q* times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the *q* of requests for cash withdrawal. Input Specification: The first line contains two integers *n*, *k* (1<=≀<=*n*<=≀<=5000, 1<=≀<=*k*<=≀<=20). The next line contains *n* space-separated integers *a**i* (1<=≀<=*a**i*<=≀<=107) β€” the denominations of the bills that are used in the country. Numbers *a**i* follow in the strictly increasing order. The next line contains integer *q* (1<=≀<=*q*<=≀<=20) β€” the number of requests for cash withdrawal that you will make. The next *q* lines contain numbers *x**i* (1<=≀<=*x**i*<=≀<=2Β·108) β€” the sums of money in burles that you are going to withdraw from the ATM. Output Specification: For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print <=-<=1, if it is impossible to get the corresponding sum. Demo Input: ['6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950\n', '5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15\n'] Demo Output: ['6\n20\n19\n20\n-1\n3\n-1\n-1\n', '1\n1\n1\n2\n2\n2\n2\n-1\n'] Note: none
842
Title: Snacktower Time Limit: None seconds Memory Limit: None megabytes Problem Description: According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top. Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it. Write a program that models the behavior of Ankh-Morpork residents. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the total number of snacks. The second line contains *n* integers, the *i*-th of them equals the size of the snack which fell on the *i*-th day. Sizes are distinct integers from 1 to *n*. Output Specification: Print *n* lines. On the *i*-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the *i*-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty. Demo Input: ['3\n3 1 2\n', '5\n4 5 1 2 3\n'] Demo Output: ['3\n\xa0\n2 1', '5 4\n\xa0\n\xa0\n3 2 1\n'] Note: In the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.
843
Title: Stones on the Table Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=50) β€” the number of stones on the table. The next line contains string *s*, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to *n* from left to right. Then the *i*-th character *s* equals "R", if the *i*-th stone is red, "G", if it's green and "B", if it's blue. Output Specification: Print a single integer β€” the answer to the problem. Demo Input: ['3\nRRG\n', '5\nRRRRR\n', '4\nBRBG\n'] Demo Output: ['1\n', '4\n', '0\n'] Note: none
844
Title: Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vitaly has an array of *n* distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero (<=&lt;<=0). 1. The product of all numbers in the second set is greater than zero (<=&gt;<=0). 1. The product of all numbers in the third set is equal to zero. 1. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. Input Specification: The first line of the input contains integer *n* (3<=≀<=*n*<=≀<=100). The second line contains *n* space-separated distinct integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=≀<=103) β€” the array elements. Output Specification: In the first line print integer *n*1 (*n*1<=&gt;<=0) β€” the number of elements in the first set. Then print *n*1 numbers β€” the elements that got to the first set. In the next line print integer *n*2 (*n*2<=&gt;<=0) β€” the number of elements in the second set. Then print *n*2 numbers β€” the elements that got to the second set. In the next line print integer *n*3 (*n*3<=&gt;<=0) β€” the number of elements in the third set. Then print *n*3 numbers β€” the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. Demo Input: ['3\n-1 2 0\n', '4\n-1 -2 -3 0\n'] Demo Output: ['1 -1\n1 2\n1 0\n', '1 -1\n2 -3 -2\n1 0\n'] Note: none
845
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* points on a straight line, and the *i*-th point among them is located at *x**i*. All these coordinates are distinct. Determine the number *m* β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal. Input Specification: The first line contains a single integer *n* (3<=≀<=*n*<=≀<=100<=000) β€” the number of points. The second line contains a sequence of integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=109<=≀<=*x**i*<=≀<=109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order. Output Specification: Print a single integer *m* β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal. Demo Input: ['3\n-5 10 5\n', '6\n100 200 400 300 600 500\n', '4\n10 9 0 -1\n'] Demo Output: ['1\n', '0\n', '8\n'] Note: In the first example you can add one point with coordinate 0. In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
846
Title: Beautiful Paintings Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of *a* in any order. What is the maximum possible number of indices *i* (1<=≀<=*i*<=≀<=*n*<=-<=1), such that *a**i*<=+<=1<=&gt;<=*a**i*. Input Specification: The first line of the input contains integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the number of painting. The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=1000), where *a**i* means the beauty of the *i*-th painting. Output Specification: Print one integerΒ β€” the maximum possible number of neighbouring pairs, such that *a**i*<=+<=1<=&gt;<=*a**i*, after the optimal rearrangement. Demo Input: ['5\n20 30 10 50 40\n', '4\n200 100 100 200\n'] Demo Output: ['4\n', '2\n'] Note: In the first sample, the optimal order is: 10, 20, 30, 40, 50. In the second sample, the optimal order is: 100, 200, 100, 200.
847
Title: Tree Requests Time Limit: None seconds Memory Limit: None megabytes Problem Description: Roman planted a tree consisting of *n* vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the *n*<=-<=1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex *i* is vertex *p**i*, the parent index is always less than the index of the vertex (i.e., *p**i*<=&lt;<=*i*). The depth of the vertex is the number of nodes on the path from the root to *v* along the edges. In particular, the depth of the root is equal to 1. We say that vertex *u* is in the subtree of vertex *v*, if we can get from *u* to *v*, moving from the vertex to the parent. In particular, vertex *v* is in its subtree. Roma gives you *m* queries, the *i*-th of which consists of two numbers *v**i*, *h**i*. Let's consider the vertices in the subtree *v**i* located at depth *h**i*. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used. Input Specification: The first line contains two integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=500<=000) β€” the number of nodes in the tree and queries, respectively. The following line contains *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* β€” the parents of vertices from the second to the *n*-th (1<=≀<=*p**i*<=&lt;<=*i*). The next line contains *n* lowercase English letters, the *i*-th of these letters is written on vertex *i*. Next *m* lines describe the queries, the *i*-th line contains two numbers *v**i*, *h**i* (1<=≀<=*v**i*,<=*h**i*<=≀<=*n*) β€” the vertex and the depth that appear in the *i*-th query. Output Specification: Print *m* lines. In the *i*-th line print "Yes" (without the quotes), if in the *i*-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes). Demo Input: ['6 5\n1 1 1 3 3\nzacccd\n1 1\n3 3\n4 1\n6 1\n1 2\n'] Demo Output: ['Yes\nNo\nYes\nYes\nYes\n'] Note: String *s* is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".
848
Title: Sets Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose *n* non-empty sets in such a way, that no two of them have common elements. One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on *n*Β·(*n*<=-<=1)<=/<=2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order. For example, if *n*<==<=4, and the actual sets have the following form {1,<=3}, {5}, {2,<=4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: - 2,<=7,<=4. - 1,<=7,<=3; - 5,<=4,<=2; - 1,<=3,<=5; - 3,<=1,<=2,<=4; - 5,<=7. Then Vasya showed the pieces of paper to his friends, but kept the *n* sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper? Input Specification: The first input file line contains a number *n* (2<=≀<=*n*<=≀<=200), *n* is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on *n*Β·(*n*<=-<=1)<=/<=2 lines. Each set starts with the number *k**i* (2<=≀<=*k**i*<=≀<=200), which is the number of numbers written of the *i*-th piece of paper, and then follow *k**i* numbers *a**ij* (1<=≀<=*a**ij*<=≀<=200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from *n* non-intersecting sets. Output Specification: Print on *n* lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution. Demo Input: ['4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7\n', '4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2\n', '3\n2 1 2\n2 1 3\n2 2 3\n'] Demo Output: ['1 7 \n2 2 4 \n2 1 3 \n1 5 \n', '3 7 8 9 \n2 6 100 \n1 1 \n1 2 \n', '1 1 \n1 2 \n1 3 \n'] Note: none
849
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is *t*1, and the hot water's temperature is *t*2. The cold water tap can transmit any integer number of water units per second from 0 to *x*1, inclusive. Similarly, the hot water tap can transmit from 0 to *x*2 water units per second. If *y*1 water units per second flow through the first tap and *y*2 water units per second flow through the second tap, then the resulting bath water temperature will be: Bob wants to open both taps so that the bath water temperature was not less than *t*0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible. Determine how much each tap should be opened so that Bob was pleased with the result in the end. Input Specification: You are given five integers *t*1, *t*2, *x*1, *x*2 and *t*0 (1<=≀<=*t*1<=≀<=*t*0<=≀<=*t*2<=≀<=106, 1<=≀<=*x*1,<=*x*2<=≀<=106). Output Specification: Print two space-separated integers *y*1 and *y*2 (0<=≀<=*y*1<=≀<=*x*1, 0<=≀<=*y*2<=≀<=*x*2). Demo Input: ['10 70 100 100 25\n', '300 500 1000 1000 300\n', '143 456 110 117 273\n'] Demo Output: ['99 33', '1000 0', '76 54'] Note: In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
850
Title: Champions' League Time Limit: None seconds Memory Limit: None megabytes Problem Description: In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world β€” the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the draw stage, the process of sorting teams into groups. The process of the draw goes as follows (the rules that are described in this problem, are somehow simplified compared to the real life). Suppose *n* teams will take part in the group stage (*n* is divisible by four). The teams should be divided into groups of four. Let's denote the number of groups as *m* (). Each team has a rating β€” an integer characterizing the team's previous achievements. The teams are sorted by the rating's decreasing (no two teams have the same rating). After that four "baskets" are formed, each of which will contain *m* teams: the first *m* teams with the highest rating go to the first basket, the following *m* teams go to the second one, and so on. Then the following procedure repeats *m*<=-<=1 times. A team is randomly taken from each basket, first from the first basket, then from the second, then from the third, and at last, from the fourth. The taken teams form another group. After that, they are removed from their baskets. The four teams remaining in the baskets after (*m*<=-<=1) such procedures are performed, form the last group. In the real draw the random selection of teams from the basket is performed by people β€” as a rule, the well-known players of the past. As we have none, we will use a random number generator, which is constructed as follows. Its parameters are four positive integers *x*,<=*a*,<=*b*,<=*c*. Every time there is a call to the random number generator, it produces the following actions: - calculates ; - replaces parameter *x* by value *y* (assigns ); - returns *x* as another random number. Operation means taking the remainder after division: , . A random number generator will be used in the draw as follows: each time we need to randomly choose a team from the basket, it will generate a random number *k*. The teams that yet remain in the basket are considered numbered with consecutive integers from 0 to *s*<=-<=1, in the order of decreasing rating, where *s* is the current size of the basket. Then a team number is taken from the basket. Given a list of teams and the parameters of the random number generator, determine the result of the draw. Input Specification: The first input line contains integer *n* (4<=≀<=*n*<=≀<=64, *n* is divisible by four) β€” the number of teams that take part in the sorting. The second line contains four space-separated integers *x*,<=*a*,<=*b*,<=*c* (1<=≀<=*x*,<=*a*,<=*b*,<=*c*<=≀<=1000) β€” the parameters of the random number generator. Each of the following *n* lines describes one team. The description consists of the name of the team and its rating, separated by a single space. The name of a team consists of uppercase and lowercase English letters and has length from 1 to 20 characters. A team's rating is an integer from 0 to 1000. All teams' names are distinct. All team's ratings are also distinct. Output Specification: Print the way the teams must be sorted into groups. Print the groups in the order, in which they are formed in the sorting. Number the groups by consecutive uppercase English letters, starting from letter 'A'. Inside each group print the teams' names one per line, in the order of decreasing of the teams' rating. See samples for a better understanding of the output format. Demo Input: ['8\n1 3 1 7\nBarcelona 158\nMilan 90\nSpartak 46\nAnderlecht 48\nCeltic 32\nBenfica 87\nZenit 79\nMalaga 16\n'] Demo Output: ['Group A:\nBarcelona\nBenfica\nSpartak\nCeltic\nGroup B:\nMilan\nZenit\nAnderlecht\nMalaga\n'] Note: In the given sample the random number generator will be executed four times: - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2d76d911e7446d6db4b0be2679ce6e5ab930ab92.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/cc339c0d810046d7adb9ef4339e48f5554842ae2.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/74fb01e5b91f6c73ead806139c45f3e73fa1232d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f8a9ac4805dfae22b7d7a65c5daa8f4cc5a21a5a.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
851
Title: Andryusha and Colored Balloons Time Limit: None seconds Memory Limit: None megabytes Problem Description: Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them. The park consists of *n* squares connected with (*n*<=-<=1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if *a*, *b* and *c* are distinct squares that *a* and *b* have a direct path between them, and *b* and *c* have a direct path between them, then balloon colors on these three squares are distinct. Andryusha wants to use as little different colors as possible. Help him to choose the colors! Input Specification: The first line contains single integer *n* (3<=≀<=*n*<=≀<=2Β·105)Β β€” the number of squares in the park. Each of the next (*n*<=-<=1) lines contains two integers *x* and *y* (1<=≀<=*x*,<=*y*<=≀<=*n*)Β β€” the indices of two squares directly connected by a path. It is guaranteed that any square is reachable from any other using the paths. Output Specification: In the first line print single integer *k*Β β€” the minimum number of colors Andryusha has to use. In the second line print *n* integers, the *i*-th of them should be equal to the balloon color on the *i*-th square. Each of these numbers should be within range from 1 to *k*. Demo Input: ['3\n2 3\n1 3\n', '5\n2 3\n5 3\n4 3\n1 3\n', '5\n2 1\n3 2\n4 3\n5 4\n'] Demo Output: ['3\n1 3 2 ', '5\n1 3 2 5 4 ', '3\n1 2 3 1 2 '] Note: In the first sample the park consists of three squares: 1 → 3 → 2. Thus, the balloon colors have to be distinct. In the second example there are following triples of consequently connected squares: - 1 → 3 → 2 - 1 → 3 → 4 - 1 → 3 → 5 - 2 → 3 → 4 - 2 → 3 → 5 - 4 → 3 → 5 In the third example there are following triples: - 1 → 2 → 3 - 2 → 3 → 4 - 3 → 4 → 5
852
Title: Expression Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: One day Vasya was solving arithmetical problems. He wrote down an expression *a*<=+<=*b*<==<=*c* in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers *a*, *b* and *c*, but he can't remember what numbers they actually were. Help Vasya, find such numbers *x*, *y* and *z*, with which the following conditions are met: - *x*<=+<=*y*<==<=*z*, - from the expression *x*<=+<=*y*<==<=*z* several digits can be erased in such a way that the result will be *a*<=+<=*b*<==<=*c*, - the expression *x*<=+<=*y*<==<=*z* should have the minimal length. Input Specification: The first and only input line contains the expression *a*<=+<=*b*<==<=*c* (1<=≀<=*a*,<=*b*,<=*c*<=≀<=106, *a*, *b* and *c* don't contain leading zeroes) which is the expression Vasya wrote down. Output Specification: Print the correct expression *x*<=+<=*y*<==<=*z* (*x*, *y* and *z* are non-negative numbers without leading zeroes). The expression *a*<=+<=*b*<==<=*c* must be met in *x*<=+<=*y*<==<=*z* as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them. Demo Input: ['2+4=5\n', '1+1=3\n', '1+1=2\n'] Demo Output: ['21+4=25\n', '1+31=32\n', '1+1=2\n'] Note: none
853
Title: Adam and Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: - There is no vertex that has more than two incident edges painted the same color. - For any two vertexes that have incident edges painted the same color (say, *c*), the path between them consists of the edges of the color *c*. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=106) β€” the number of times a new vertex is added. The second line contains *n* numbers *p**i* (1<=≀<=*p**i*<=≀<=*i*) β€” the numbers of the vertexes to which we add another vertex. Output Specification: Print *n* integers β€” the minimum costs of the tree painting after each addition. Demo Input: ['11\n1 1 1 3 4 4 7 3 7 6 6\n'] Demo Output: ['1 1 1 1 1 2 2 2 2 2 3 '] Note: The figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3. <img class="tex-graphics" src="https://espresso.codeforces.com/3e0ae59416472763f3e14b7c4a5094de154d3b50.png" style="max-width: 100.0%;max-height: 100.0%;"/>
854
Title: Fancy Fence Time Limit: None seconds Memory Limit: None megabytes Problem Description: Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*. Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*? Input Specification: The first line of input contains an integer *t* (0<=&lt;<=*t*<=&lt;<=180) β€” the number of tests. Each of the following *t* lines contains a single integer *a* (0<=&lt;<=*a*<=&lt;<=180) β€” the angle the robot can make corners at measured in degrees. Output Specification: For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible. Demo Input: ['3\n30\n60\n90\n'] Demo Output: ['NO\nYES\nYES\n'] Note: In the first test case, it is impossible to build the fence, since there is no regular polygon with angle <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/df5f4b07dd5316fde165b43657b2696e2919e791.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second test case, the fence is a regular triangle, and in the last test case β€” a square.
855
Title: Vanya and Balloons Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vanya plays a game of balloons on the field of size *n*<=Γ—<=*n*, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example: or Formally, the cross is given by three integers *r*, *c* and *d*, such that *d*<=≀<=*r*,<=*c*<=≀<=*n*<=-<=*d*<=+<=1. The normal cross consists of balloons located in cells (*x*,<=*y*) (where *x* stay for the number of the row and *y* for the number of the column), such that |*x*<=-<=*r*|Β·|*y*<=-<=*c*|<==<=0 and |*x*<=-<=*r*|<=+<=|*y*<=-<=*c*|<=&lt;<=*d*. Rotated cross consists of balloons located in cells (*x*,<=*y*), such that |*x*<=-<=*r*|<==<=|*y*<=-<=*c*| and |*x*<=-<=*r*|<=&lt;<=*d*. Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109<=+<=7. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the number of rows and columns in the table with balloons. The each of the following *n* lines contains *n* characters '0', '1', '2' or '3'Β β€” the description of the values in balloons. Output Specification: Print the maximum possible product modulo 109<=+<=7. Note, that you are not asked to maximize the remainder modulo 109<=+<=7, but to find the maximum value and print it this modulo. Demo Input: ['4\n1233\n0213\n2020\n0303\n', '5\n00300\n00300\n33333\n00300\n00300\n', '5\n00003\n02030\n00300\n03020\n30000\n', '5\n21312\n10003\n10002\n10003\n23231\n', '5\n12131\n12111\n12112\n21311\n21212\n'] Demo Output: ['108\n', '19683\n', '108\n', '3\n', '24\n'] Note: In the first sample, the maximum product is achieved for a rotated cross with a center in the cell (3, 3) and radius 1: 2Β·2Β·3Β·3Β·3 = 108.
856
Title: Plus and xor Time Limit: 0 seconds Memory Limit: 256 megabytes Problem Description: Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different. For example, if *X*<==<=10910<==<=11011012, *Y*<==<=4110<==<=1010012, then: Write a program, which takes two non-negative integers *A* and *B* as an input and finds two non-negative integers *X* and *Y*, which satisfy the following conditions: - *A*<==<=*X*<=+<=*Y* - *B*Β <==<=Β *X* xor *Y*, where xor is bitwise exclusive or. - *X* is the smallest number among all numbers for which the first two conditions are true. Input Specification: The first line contains integer number *A* and the second line contains integer number *B* (0<=≀<=*A*,<=*B*<=≀<=264<=-<=1). Output Specification: The only output line should contain two integer non-negative numbers *X* and *Y*. Print the only number -1 if there is no answer. Demo Input: ['142\n76\n'] Demo Output: ['33 109\n'] Note: none
857
Title: Try and Catch Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that. The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: 1. The try operator. It opens a new try-catch-block. 1. The catch(&lt;exception_type&gt;, &lt;message&gt;) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type &lt;exception_type&gt;. When we activate this block, the screen displays the &lt;message&gt;. If at the given moment there is no open try-catch-block, then we can't use the catch operator. The exceptions can occur in the program in only one case: when we use the throw operator. The throw(&lt;exception_type&gt;) operator creates the exception of the given type. Let's suggest that as a result of using some throw operator the program created an exception of type *a*. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type *a* as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception". To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator. Your task is: given a program in VPL, determine, what message will be displayed on the screen. Input Specification: The first line contains a single integer: *n* (1<=≀<=*n*<=≀<=105) the number of lines in the program. Next *n* lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces. The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark. The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols. Length of any line in the input file does not exceed 50 symbols. Output Specification: Print the message the screen will show after the given program is executed. Demo Input: ['8\ntry\n try\n throw ( AE ) \n catch ( BE, "BE in line 3")\n\n try\n catch(AE, "AE in line 5") \ncatch(AE,"AE somewhere")\n', '8\ntry\n try\n throw ( AE ) \n catch ( AE, "AE in line 3")\n\n try\n catch(BE, "BE in line 5") \ncatch(AE,"AE somewhere")\n', '8\ntry\n try\n throw ( CE ) \n catch ( BE, "BE in line 3")\n\n try\n catch(AE, "AE in line 5") \ncatch(AE,"AE somewhere")\n'] Demo Output: ['AE somewhere\n', 'AE in line 3\n', 'Unhandled Exception\n'] Note: In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE. In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere") In the third sample there is no blocks that can be activated by an exception of type CE.
858
Title: Growing Mushrooms Time Limit: None seconds Memory Limit: None megabytes Problem Description: Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch. Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts *t*1 seconds and the second part lasts *t*2 seconds. The first and the second part are separated by a little break. After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of *v**i* meters per second. After *t*1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by *k* percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of *u**i* meters per second. After a *t*2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary. Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds *a**i* and *b**i*, then there are two strategies: he either uses speed *a**i* before the break and speed *b**i* after it, or vice versa. Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results. The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier). Input Specification: The first input line contains four integer numbers *n*, *t*1, *t*2, *k* (1<=≀<=*n*,<=*t*1,<=*t*2<=≀<=1000;Β 1<=≀<=*k*<=≀<=100) β€” the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly. Each of the following *n* lines contains two integers. The *i*-th (1<=≀<=*i*<=≀<=*n*) line contains space-separated integers *a**i*, *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=1000) β€” the speeds which the participant number *i* chose. Output Specification: Print the final results' table: *n* lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate. Demo Input: ['2 3 3 50\n2 4\n4 2\n', '4 1 1 1\n544 397\n280 101\n280 101\n693 970\n'] Demo Output: ['1 15.00\n2 15.00\n', '4 1656.07\n1 937.03\n2 379.99\n3 379.99\n'] Note: - First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 &gt; 4Β·3Β·0.5 + 2Β·3.
859
Title: Next Test Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Β«PolygonΒ» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test. You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests. Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=3000) β€” the amount of previously added tests. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=3000) β€” indexes of these tests. Output Specification: Output the required default value for the next test index. Demo Input: ['3\n1 7 2\n'] Demo Output: ['3\n'] Note: none
860
Title: Vasya and Basketball Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of *d* meters, and a throw is worth 3 points if the distance is larger than *d* meters, where *d* is some non-negative integer. Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of *d*. Help him to do that. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=2Β·105) β€” the number of throws of the first team. Then follow *n* integer numbers β€” the distances of throws *a**i* (1<=≀<=*a**i*<=≀<=2Β·109). Then follows number *m* (1<=≀<=*m*<=≀<=2Β·105) β€” the number of the throws of the second team. Then follow *m* integer numbers β€” the distances of throws of *b**i* (1<=≀<=*b**i*<=≀<=2Β·109). Output Specification: Print two numbers in the format a:b β€” the score that is possible considering the problem conditions where the result of subtraction *a*<=-<=*b* is maximum. If there are several such scores, find the one in which number *a* is maximum. Demo Input: ['3\n1 2 3\n2\n5 6\n', '5\n6 7 8 9 10\n5\n1 2 3 4 5\n'] Demo Output: ['9:6\n', '15:10\n'] Note: none
861
Title: Restoring Increasing Sequence Time Limit: None seconds Memory Limit: None megabytes Problem Description: Peter wrote on the board a strictly increasing sequence of positive integers *a*1,<=*a*2,<=...,<=*a**n*. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input Specification: The first line of the input contains integer *n* (1<=≀<=*n*<=≀<=105) β€” the length of the sequence. Next *n* lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output Specification: If the answer exists, print in the first line "YES" (without the quotes). Next *n* lines must contain the sequence of positive integers β€” a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Demo Input: ['3\n?\n18\n1?\n', '2\n??\n?\n', '5\n12224\n12??5\n12226\n?0000\n?00000\n'] Demo Output: ['YES\n1\n18\n19\n', 'NO\n', 'YES\n12224\n12225\n12226\n20000\n100000\n'] Note: none
862
Title: Beavermuncher-0xFF Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: "Eat a beaver, save a tree!" β€” That will be the motto of ecologists' urgent meeting in Beaverley Hills. And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end. In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science. The prototype is ready, you now need to urgently carry out its experiments in practice. You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of *n* vertices, the *i*-th vertex contains *k**i* beavers. "Beavermuncher-0xFF" works by the following principle: being at some vertex *u*, it can go to the vertex *v*, if they are connected by an edge, and eat exactly one beaver located at the vertex *v*. It is impossible to move to the vertex *v* if there are no beavers left in *v*. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops. Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy. It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled. The root of the tree is located at the vertex *s*. This means that the "Beavermuncher-0xFF" begins its mission at the vertex *s* and it must return there at the end of experiment, because no one is going to take it down from a high place. Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex. Input Specification: The first line contains integer *n* β€” the number of vertices in the tree (1<=≀<=*n*<=≀<=105). The second line contains *n* integers *k**i* (1<=≀<=*k**i*<=≀<=105) β€” amounts of beavers on corresponding vertices. Following *n*<=-<=1 lines describe the tree. Each line contains two integers separated by space. These integers represent two vertices connected by an edge. Vertices are numbered from 1 to *n*. The last line contains integer *s* β€” the number of the starting vertex (1<=≀<=*s*<=≀<=*n*). Output Specification: Print the maximum number of beavers munched by the "Beavermuncher-0xFF". Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d). Demo Input: ['5\n1 3 1 3 2\n2 5\n3 4\n4 5\n1 5\n4\n', '3\n2 1 1\n3 2\n1 2\n3\n'] Demo Output: ['6\n', '2\n'] Note: none
863
Title: Oleg and chess Time Limit: None seconds Memory Limit: None megabytes Problem Description: Oleg the bank client solves an interesting chess problem: place on *n*<=Γ—<=*n* chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell. Remind that a rook standing in the cell (*a*,<=*b*) beats a rook standing in the cell (*x*,<=*y*) if and only if *a*<==<=*x* or *b*<==<=*y*. Unfortunately (of fortunately?) for Oleg the answer in this problem was always *n*, so the task bored Oleg soon. He decided to make it more difficult by removing some cells from the board. If a cell is deleted, Oleg can't put a rook there, but rooks do beat each other "through" deleted cells. Oleg deletes the cells in groups, namely, he repeatedly choose a rectangle with sides parallel to the board sides and deletes all the cells inside the rectangle. Formally, if he chooses a rectangle, lower left cell of which has coordinates (*x*1,<=*y*1), and upper right cell of which has coordinates (*x*2,<=*y*2), then he deletes all such cells with coordinates (*x*,<=*y*) that *x*1<=≀<=*x*<=≀<=*x*2 and *y*1<=≀<=*y*<=≀<=*y*2. It is guaranteed that no cell is deleted twice, i.e. the chosen rectangles do not intersect. This version of the problem Oleg can't solve, and his friend Igor is busy at a conference, so he can't help Oleg. You are the last hope for Oleg! Help him: given the size of the board and the deleted rectangles find the maximum possible number of rooks that could be placed on the board so that no two rooks beat each other. Input Specification: The first line contains single integer *n* (1<=<=≀<=<=*n*<=≀<=<=10000)Β β€” the size of the board. The second line contains single integer *q* (0<=<=≀<=<=*q*<=<=≀<=<=10000)Β β€” the number of deleted rectangles. The next *q* lines contain the information about the deleted rectangles. Each of these lines contains four integers *x*1, *y*1, *x*2 and *y*2 (1<=<=≀<=*x*1<=≀<=*x*2<=≀<=*n*, 1<=<=≀<=*y*1<=≀<=*y*2<=≀<=*n*)Β β€” the coordinates of the lower left and the upper right cells of a deleted rectangle. If is guaranteed that the rectangles do not intersect. Output Specification: In the only line print the maximum number of rooks Oleg can place on the board so that no two rooks beat each other. Demo Input: ['5\n5\n1 1 2 1\n1 3 1 5\n4 1 5 5\n2 5 2 5\n3 2 3 5\n', '8\n4\n2 2 4 6\n1 8 1 8\n7 1 8 2\n5 4 6 8\n'] Demo Output: ['3\n', '8\n'] Note: Here is the board and the example of rooks placement in the first example: <img class="tex-graphics" src="https://espresso.codeforces.com/5455db405c55b6478627065011376e58257f95a0.png" style="max-width: 100.0%;max-height: 100.0%;"/>
864
Title: Least Cost Bracket Sequence Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: This is yet another problem on regular bracket sequences. A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence. For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. Input Specification: The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5Β·104. Then there follow *m* lines, where *m* is the number of characters "?" in the pattern. Each line contains two integer numbers *a**i* and *b**i* (1<=≀<=*a**i*,<=<=*b**i*<=≀<=106), where *a**i* is the cost of replacing the *i*-th character "?" with an opening bracket, and *b**i* β€” with a closing one. Output Specification: Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. Demo Input: ['(??)\n1 2\n2 8\n'] Demo Output: ['4\n()()\n'] Note: none
865
Title: Apple Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a rooted tree with *n* vertices. In each leaf vertex there's a single integer β€” the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf. A tree is balanced if for every vertex *v* of the tree all its subtrees, corresponding to the children of vertex *v*, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples. Input Specification: The first line contains integer *n* (2<=≀<=*n*<=≀<=105), showing the number of vertices in the tree. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=108), *a**i* is the number of apples in the vertex number *i*. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow *n*<=-<=1 lines, describing the tree edges. Each line contains a pair of integers *x**i*,<=*y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*,<=*x**i*<=β‰ <=*y**i*) β€” the vertices connected by an edge. The vertices are indexed from 1 to *n*. Vertex 1 is the root. Output Specification: Print a single integer β€” the minimum number of apples to remove in order to make the tree balanced. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier. Demo Input: ['6\n0 0 12 13 5 6\n1 2\n1 3\n1 4\n2 5\n2 6\n'] Demo Output: ['6'] Note: none
866
Title: Candy Bags Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies. Help him give *n* bags of candies to each brother so that all brothers got the same number of candies. Input Specification: The single line contains a single integer *n* (*n* is even, 2<=≀<=*n*<=≀<=100) β€” the number of Gerald's brothers. Output Specification: Let's assume that Gerald indexes his brothers with numbers from 1 to *n*. You need to print *n* lines, on the *i*-th line print *n* integers β€” the numbers of candies in the bags for the *i*-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to *n*2. You can print the numbers in the lines in any order. It is guaranteed that the solution exists at the given limits. Demo Input: ['2\n'] Demo Output: ['1 4\n2 3\n'] Note: The sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.
867
Title: Diversity Time Limit: None seconds Memory Limit: None megabytes Problem Description: Calculate the minimum number of characters you need to change in the string *s*, so that it contains at least *k* different letters, or print that it is impossible. String *s* consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too. Input Specification: First line of input contains string *s*, consisting only of lowercase Latin letters (1<=≀<=|*s*|<=≀<=1000, |*s*| denotes the length of *s*). Second line of input contains integer *k* (1<=≀<=*k*<=≀<=26). Output Specification: Print single line with a minimum number of necessary changes, or the word Β«impossibleΒ» (without quotes) if it is impossible. Demo Input: ['yandex\n6\n', 'yahoo\n5\n', 'google\n7\n'] Demo Output: ['0\n', '1\n', 'impossible\n'] Note: In the first test case string contains 6 different letters, so we don't need to change anything. In the second test case string contains 4 different letters: {'*a*', '*h*', '*o*', '*y*'}. To get 5 different letters it is necessary to change one occurrence of '*o*' to some letter, which doesn't occur in the string, for example, {'*b*'}. In the third test case, it is impossible to make 7 different letters because the length of the string is 6.
868
Title: Soroban Time Limit: None seconds Memory Limit: None megabytes Problem Description: You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban β€” an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction. Soroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm: - Set the value of a digit equal to 0. - If the go-dama is shifted to the right, add 5. - Add the number of ichi-damas shifted to the left. Thus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720. Write the program that prints the way Soroban shows the given number *n*. Input Specification: The first line contains a single integer *n* (0<=≀<=*n*<=&lt;<=109). Output Specification: Print the description of the decimal digits of number *n* from the last one to the first one (as mentioned on the picture in the statement), one per line. Print the beads as large English letters 'O', rod pieces as character '-' and the reckoning bar as '|'. Print as many rods, as many digits are in the decimal representation of number *n* without leading zeroes. We can assume that number 0 has no leading zeroes. Demo Input: ['2\n', '13\n', '720\n'] Demo Output: ['O-|OO-OO\n', 'O-|OOO-O\nO-|O-OOO\n', 'O-|-OOOO\nO-|OO-OO\n-O|OO-OO\n'] Note: none
869
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: ZS the Coder has drawn an undirected graph of *n* vertices numbered from 0 to *n*<=-<=1 and *m* edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices *s* and *t* in the resulting graph is exactly *L*. Can you help him? Input Specification: The first line contains five integers *n*,<=*m*,<=*L*,<=*s*,<=*t* (2<=≀<=*n*<=≀<=1000,<=<=1<=≀<=*m*<=≀<=10<=000,<=<=1<=≀<=*L*<=≀<=109,<=<=0<=≀<=*s*,<=*t*<=≀<=*n*<=-<=1,<=<=*s*<=β‰ <=*t*)Β β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, *m* lines describing the edges of the graph follow. *i*-th of them contains three integers, *u**i*,<=*v**i*,<=*w**i* (0<=≀<=*u**i*,<=*v**i*<=≀<=*n*<=-<=1,<=<=*u**i*<=β‰ <=*v**i*,<=<=0<=≀<=*w**i*<=≀<=109). *u**i* and *v**i* denote the endpoints of the edge and *w**i* denotes its weight. If *w**i* is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Specification: Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next *m* lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. *i*-th of them should contain three integers *u**i*, *v**i* and *w**i*, denoting an edge between vertices *u**i* and *v**i* of weight *w**i*. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between *s* and *t* must be equal to *L*. If there are multiple solutions, print any of them. Demo Input: ['5 5 13 0 4\n0 1 5\n2 1 2\n3 2 3\n1 4 0\n4 3 4\n', '2 1 123456789 0 1\n0 1 0\n', '2 1 999999999 1 0\n0 1 1000000000\n'] Demo Output: ['YES\n0 1 5\n2 1 2\n3 2 3\n1 4 8\n4 3 4\n', 'YES\n0 1 123456789\n', 'NO\n'] Note: Here's how the graph in the first sample case looks like : In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
870
Title: Mr. Kitayuta's Colorful Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mr. Kitayuta has just bought an undirected graph with *n* vertices and *m* edges. The vertices of the graph are numbered from 1 to *n*. Each edge, namely edge *i*, has a color *c**i*, connecting vertex *a**i* and *b**i*. Mr. Kitayuta wants you to process the following *q* queries. In the *i*-th query, he gives you two integers - *u**i* and *v**i*. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex *u**i* and vertex *v**i* directly or indirectly. Input Specification: The first line of the input contains space-separated two integers - *n* and *m*(2<=≀<=*n*<=≀<=105,<=1<=≀<=*m*<=≀<=105), denoting the number of the vertices and the number of the edges, respectively. The next *m* lines contain space-separated three integers - *a**i*, *b**i*(1<=≀<=*a**i*<=&lt;<=*b**i*<=≀<=*n*) and *c**i*(1<=≀<=*c**i*<=≀<=*m*). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if *i*<=β‰ <=*j*,<=(*a**i*,<=*b**i*,<=*c**i*)<=β‰ <=(*a**j*,<=*b**j*,<=*c**j*). The next line contains a integer- *q*(1<=≀<=*q*<=≀<=105), denoting the number of the queries. Then follows *q* lines, containing space-separated two integers - *u**i* and *v**i*(1<=≀<=*u**i*,<=*v**i*<=≀<=*n*). It is guaranteed that *u**i*<=β‰ <=*v**i*. Output Specification: For each query, print the answer in a separate line. Demo Input: ['4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4\n', '5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4\n'] Demo Output: ['2\n1\n0\n', '1\n1\n1\n1\n2\n'] Note: Let's consider the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
871
Title: Matchmaker Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus has *n* markers and *m* marker caps. Each marker is described by two numbers: *x**i* is the color and *y**i* is the diameter. Correspondingly, each cap is described by two numbers: *a**j* is the color and *b**j* is the diameter. Cap (*a**j*,<=*b**j*) can close marker (*x**i*,<=*y**i*) only if their diameters match, that is, *b**j*<==<=*y**i*. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, *a**j*<==<=*x**i*. Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers. Input Specification: The first input line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the number of markers and the number of caps, correspondingly. Next *n* lines describe the markers. The *i*-th line contains two space-separated integers *x**i*, *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=1000) β€” the *i*-th marker's color and diameter, correspondingly. Next *m* lines describe the caps. The *j*-th line contains two space-separated integers *a**j*, *b**j* (1<=≀<=*a**j*,<=*b**j*<=≀<=1000) β€” the color and diameter of the *j*-th cap, correspondingly. Output Specification: Print two space-separated integers *u*,<=*v*, where *u* is the number of closed markers and *v* is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum. Demo Input: ['3 4\n1 2\n3 4\n2 4\n5 4\n2 4\n1 1\n1 2\n', '2 2\n1 2\n2 1\n3 4\n5 1\n'] Demo Output: ['3 2\n', '1 0\n'] Note: In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed β€” the first and the third markers.
872
Title: Toy Army Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of *n* men (*n* is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore. The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends. You are asked to calculate the maximum total number of soldiers that may be killed during the game. Input Specification: The input data consist of a single integer *n* (2<=≀<=*n*<=≀<=108, *n* is even). Please note that before the game starts there are 2*n* soldiers on the fields. Output Specification: Print a single number β€” a maximum total number of soldiers that could be killed in the course of the game in three turns. Demo Input: ['2\n', '4\n'] Demo Output: ['3\n', '6\n'] Note: The first sample test: 1) Valera's soldiers 1 and 2 shoot at Arcady's soldier 1. 2) Arcady's soldier 2 shoots at Valera's soldier 1. 3) Valera's soldier 1 shoots at Arcady's soldier 2. There are 3 soldiers killed in total: Valera's soldier 1 and Arcady's soldiers 1 and 2.
873
Title: Edo and Magnets Time Limit: None seconds Memory Limit: None megabytes Problem Description: Edo has got a collection of *n* refrigerator magnets! He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers. Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes. Now he wants to remove no more than *k* magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of ​​the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan. Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (*x*1, *y*1) and the upper right corner (*x*2, *y*2), then its center is located at (, ) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator. The sides of the refrigerator door must also be parallel to coordinate axes. Input Specification: The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=100<=000, 0<=≀<=*k*<=≀<=*min*(10,<=*n*<=-<=1))Β β€” the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator. Next *n* lines describe the initial plan of placing magnets. Each line contains four integers *x*1,<=*y*1,<=*x*2,<=*y*2 (1<=≀<=*x*1<=&lt;<=*x*2<=≀<=109, 1<=≀<=*y*1<=&lt;<=*y*2<=≀<=109)Β β€” the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide. Output Specification: Print a single integerΒ β€” the minimum area of the door of refrigerator, which can be used to place at least *n*<=-<=*k* magnets, preserving the relative positions. Demo Input: ['3 1\n1 1 2 2\n2 2 3 3\n3 3 4 4\n', '4 1\n1 1 2 2\n1 9 2 10\n9 9 10 10\n9 1 10 2\n', '3 0\n1 1 2 2\n1 1 1000000000 1000000000\n1 3 8 12\n'] Demo Output: ['1\n', '64\n', '249999999000000001\n'] Note: In the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly. In the second test sample it doesn't matter which magnet to remove, the answer will not change β€” we need a fridge with door width 8 and door height 8. In the third sample you cannot remove anything as *k* = 0.
874
Title: Gravity Flip Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the *n* columns after the gravity switch! Input Specification: The first line of input contains an integer *n* (1<=≀<=*n*<=≀<=100), the number of the columns in the box. The next line contains *n* space-separated integer numbers. The *i*-th number *a**i* (1<=≀<=*a**i*<=≀<=100) denotes the number of cubes in the *i*-th column. Output Specification: Output *n* integer numbers separated by spaces, where the *i*-th number is the amount of cubes in the *i*-th column after the gravity switch. Demo Input: ['4\n3 2 1 2\n', '3\n2 3 8\n'] Demo Output: ['1 2 2 3 \n', '2 3 8 \n'] Note: The first example case is shown on the figure. The top cube of the first column falls to the top of the last column; the top cube of the second column falls to the top of the third column; the middle cube of the first column falls to the top of the second column. In the second example case the gravity switch does not change the heights of the columns.
875
Title: Candies Time Limit: None seconds Memory Limit: None megabytes Problem Description: After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself. This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeatsΒ β€” next day Vasya eats $k$ candies again, and PetyaΒ β€” $10\%$ of the candies left in a box, and so on. If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all. Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer. Input Specification: The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$)Β β€” the initial amount of candies in the box. Output Specification: Output a single integerΒ β€” the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got. Demo Input: ['68\n'] Demo Output: ['3\n'] Note: In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first): $68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$. In total, Vasya would eat $39$ candies, while PetyaΒ β€” $29$.
876
Title: Vasya the Architect Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once Vasya played bricks. All the bricks in the set had regular cubical shape. Vasya vas a talented architect, however the tower he built kept falling apart. Let us consider the building process. Vasya takes a brick and puts it on top of the already built tower so that the sides of the brick are parallel to the sides of the bricks he has already used. Let's introduce a Cartesian coordinate system on the horizontal plane, where Vasya puts the first brick. Then the projection of brick number *i* on the plane is a square with sides parallel to the axes of coordinates with opposite corners in points (*x**i*,<=1,<=*y**i*,<=1) and (*x**i*,<=2,<=*y**i*,<=2). The bricks are cast from homogeneous plastic and the weight of a brick *a*<=Γ—<=*a*<=Γ—<=*a* is *a*3 grams. It is guaranteed that Vasya puts any brick except the first one on the previous one, that is the area of intersection of the upper side of the previous brick and the lower side of the next brick is always positive. We (Vasya included) live in a normal world where the laws of physical statics work. And that is why, perhaps, if we put yet another brick, the tower will collapse under its own weight. Vasya puts the cubes consecutively one on top of the other until at least one cube loses the balance and falls down. If it happens, Vasya gets upset and stops the construction. Print the number of bricks in the maximal stable tower, that is the maximal number *m* satisfying the condition that all the towers consisting of bricks 1, 2, ..., *k* for every integer *k* from 1 to *m* remain stable. Input Specification: The first input file contains an integer *n* (1<=≀<=*n*<=≀<=100) which is the number of bricks. Each of the next *n* lines contains four numbers *x**i*,<=1,<=*y**i*,<=1,<=*x**i*,<=2,<=*y**i*,<=2 (*x**i*,<=1<=β‰ <=*x**i*,<=2,<=|*x**i*,<=1<=-<=*x**i*,<=2|<==<=|*y**i*,<=1<=-<=*y**i*,<=2|) which are the coordinates of the opposite angles of the base of the brick number *i*. The coordinates are integers and their absolute value does not exceed 50. The cubes are given in the order Vasya puts them. It is guaranteed that the area of intersection of the upper side of the brick number *i*<=-<=1 and the lower side of the brick number *i* is strictly strictly greater than zero for all *i*<=β‰₯<=2. Output Specification: Print the number of bricks in the maximal stable tower. Demo Input: ['2\n0 0 3 3\n1 0 4 3\n', '2\n0 0 3 3\n2 0 5 3\n', '3\n0 0 3 3\n1 0 4 3\n2 0 5 3\n'] Demo Output: ['2\n', '1\n', '3\n'] Note: none
877
Title: Beads Time Limit: 5 seconds Memory Limit: 64 megabytes Problem Description: One Martian boy called Zorg wants to present a string of beads to his friend from the Earth β€” Masha. He knows that Masha likes two colours: blue and red, β€” and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue β€” instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover. It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 β€” for a blue one. From two strings the Martian puts earlier the string with a red bead in the *i*-th position, providing that the second string has a blue bead in the *i*-th position, and the first two beads *i*<=-<=1 are identical. At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index *k*. All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha. Input Specification: The input file contains two integers *n* and *k* (2<=≀<=*n*<=≀<=50;1<=≀<=*k*<=≀<=1016) β€”the length of a string of beads, and the index of the string, chosen by Zorg. Output Specification: Output the *k*-th string of beads, putting 0 for a red bead, and 1 β€” for a blue one. If it s impossible to find the required string, output the only number -1. Demo Input: ['4 4\n'] Demo Output: ['0101\n'] Note: Let's consider the example of strings of length 4 β€” 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string β€” 0101.
878
Title: Pythagorean Triples Time Limit: None seconds Memory Limit: None megabytes Problem Description: Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples. For example, triples (3,<=4,<=5), (5,<=12,<=13) and (6,<=8,<=10) are Pythagorean triples. Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse. Katya had no problems with completing this task. Will you do the same? Input Specification: The only line of the input contains single integer *n* (1<=≀<=*n*<=≀<=109)Β β€” the length of some side of a right triangle. Output Specification: Print two integers *m* and *k* (1<=≀<=*m*,<=*k*<=≀<=1018), such that *n*, *m* and *k* form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer *n*, print <=-<=1 in the only line. If there are many answers, print any of them. Demo Input: ['3\n', '6\n', '1\n', '17\n', '67\n'] Demo Output: ['4 5', '8 10', '-1', '144 145', '2244 2245'] Note: Illustration for the first sample.
879
Title: Frogs and mosquitoes Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* frogs sitting on the coordinate axis *Ox*. For each frog two values *x**i*,<=*t**i* are known β€” the position and the initial length of the tongue of the *i*-th frog (it is guaranteed that all positions *x**i* are different). *m* mosquitoes one by one are landing to the coordinate axis. For each mosquito two values are known *p**j* β€” the coordinate of the position where the *j*-th mosquito lands and *b**j* β€” the size of the *j*-th mosquito. Frogs and mosquitoes are represented as points on the coordinate axis. The frog can eat mosquito if mosquito is in the same position with the frog or to the right, and the distance between them is not greater than the length of the tongue of the frog. If at some moment several frogs can eat a mosquito the leftmost frog will eat it (with minimal *x**i*). After eating a mosquito the length of the tongue of a frog increases with the value of the size of eaten mosquito. It's possible that after it the frog will be able to eat some other mosquitoes (the frog should eat them in this case). For each frog print two values β€” the number of eaten mosquitoes and the length of the tongue after landing all mosquitoes and after eating all possible mosquitoes by frogs. Each mosquito is landing to the coordinate axis only after frogs eat all possible mosquitoes landed before. Mosquitoes are given in order of their landing to the coordinate axis. Input Specification: First line contains two integers *n*,<=*m* (1<=≀<=*n*,<=*m*<=≀<=2Β·105) β€” the number of frogs and mosquitoes. Each of the next *n* lines contains two integers *x**i*,<=*t**i* (0<=≀<=*x**i*,<=*t**i*<=≀<=109) β€” the position and the initial length of the tongue of the *i*-th frog. It is guaranteed that all *x**i* are different. Next *m* lines contain two integers each *p**j*,<=*b**j* (0<=≀<=*p**j*,<=*b**j*<=≀<=109) β€” the position and the size of the *j*-th mosquito. Output Specification: Print *n* lines. The *i*-th line should contain two integer values *c**i*,<=*l**i* β€” the number of mosquitoes eaten by the *i*-th frog and the length of the tongue of the *i*-th frog. Demo Input: ['4 6\n10 2\n15 0\n6 1\n0 1\n110 10\n1 1\n6 0\n15 10\n14 100\n12 2\n', '1 2\n10 2\n20 2\n12 1\n'] Demo Output: ['3 114\n1 10\n1 1\n1 2\n', '1 3\n'] Note: none
880
Title: Subtractions Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5). You've got some number of pairs (*a**i*,<=*b**i*). How many operations will be performed for each of them? Input Specification: The first line contains the number of pairs *n* (1<=<=≀<=<=*n*<=<=≀<=<=1000). Then follow *n* lines, each line contains a pair of positive integers *a**i*,<=*b**i* (1<=<=≀<=<=*a**i*,<=<=*b**i*<=<=≀<=<=109). Output Specification: Print the sought number of operations for each pair on a single line. Demo Input: ['2\n4 17\n7 987654321\n'] Demo Output: ['8\n141093479\n'] Note: none
881
Title: Imbalanced Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array *a* consisting of *n* elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1,<=4,<=1] is 9, because there are 6 different subsegments of this array: - [1] (from index 1 to index 1), imbalance value is 0; - [1,<=4] (from index 1 to index 2), imbalance value is 3; - [1,<=4,<=1] (from index 1 to index 3), imbalance value is 3; - [4] (from index 2 to index 2), imbalance value is 0; - [4,<=1] (from index 2 to index 3), imbalance value is 3; - [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array *a*. Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=106) β€” size of the array *a*. The second line contains *n* integers *a*1,<=*a*2... *a**n* (1<=≀<=*a**i*<=≀<=106) β€” elements of the array. Output Specification: Print one integer β€” the imbalance value of *a*. Demo Input: ['3\n1 4 1\n'] Demo Output: ['9\n'] Note: none
882
Title: Minesweeper Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it? He needs your help to check it. A Minesweeper field is a rectangle $n \times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell: - if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs. - if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i.Β e. a cell has at most $8$ neighboring cells). Input Specification: The first line contains two integers $n$ and $m$ ($1 \le n, m \le 100$) β€” the sizes of the field. The next $n$ lines contain the description of the field. Each line contains $m$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $1$ to $8$, inclusive. Output Specification: Print "YES", if the field is valid and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrarily. Demo Input: ['3 3\n111\n1*1\n111\n', '2 4\n*.*.\n1211\n'] Demo Output: ['YES', 'NO'] Note: In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1. You can read more about Minesweeper in [Wikipedia's article](https://en.wikipedia.org/wiki/Minesweeper_(video_game)).
883
Title: Block Towers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. *n* of the students use pieces made of two blocks and *m* of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers. Input Specification: The first line of the input contains two space-separated integers *n* and *m* (0<=≀<=*n*,<=*m*<=≀<=1<=000<=000, *n*<=+<=*m*<=&gt;<=0)Β β€” the number of students using two-block pieces and the number of students using three-block pieces, respectively. Output Specification: Print a single integer, denoting the minimum possible height of the tallest tower. Demo Input: ['1 3\n', '3 2\n', '5 0\n'] Demo Output: ['9\n', '8\n', '10\n'] Note: In the first case, the student using two-block pieces can make a tower of height 4, and the students using three-block pieces can make towers of height 3, 6, and 9 blocks. The tallest tower has a height of 9 blocks. In the second case, the students can make towers of heights 2, 4, and 8 with two-block pieces and towers of heights 3 and 6 with three-block pieces, for a maximum height of 8 blocks.
884
Title: Drazil and Park Time Limit: None seconds Memory Limit: None megabytes Problem Description: Drazil is a monkey. He lives in a circular park. There are *n* trees around the park. The distance between the *i*-th tree and (*i*<=+<=1)-st trees is *d**i*, the distance between the *n*-th tree and the first tree is *d**n*. The height of the *i*-th tree is *h**i*. Drazil starts each day with the morning run. The morning run consists of the following steps: - Drazil chooses two different trees - He starts with climbing up the first tree - Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it - Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees. If the two trees Drazil chooses are *x*-th and *y*-th, we can estimate the energy the morning run takes to him as 2(*h**x*<=+<=*h**y*)<=+<=*dist*(*x*,<=*y*). Since there are children on exactly one of two arcs connecting *x* and *y*, the distance *dist*(*x*,<=*y*) between trees *x* and *y* is uniquely defined. Now, you know that on the *i*-th day children play between *a**i*-th tree and *b**i*-th tree. More formally, if *a**i*<=≀<=*b**i*, children play around the trees with indices from range [*a**i*,<=*b**i*], otherwise they play around the trees with indices from . Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day. Input Specification: The first line contains two integer *n* and *m* (3<=≀<=*n*<=≀<=105, 1<=≀<=*m*<=≀<=105), denoting number of trees and number of days, respectively. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≀<=*d**i*<=≀<=109), the distances between consecutive trees. The third line contains *n* integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≀<=*h**i*<=≀<=109), the heights of trees. Each of following *m* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children. Output Specification: For each day print the answer in a separate line. Demo Input: ['5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5\n', '3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1\n'] Demo Output: ['12\n16\n18\n', '17\n22\n11\n'] Note: none
885
Title: Kefa and Dishes Time Limit: None seconds Memory Limit: None megabytes Problem Description: When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were *n* dishes. Kefa knows that he needs exactly *m* dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the *i*-th dish gives him *a**i* units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself *k* rules of eating food of the following type β€” if he eats dish *x* exactly before dish *y* (there should be no other dishes between *x* and *y*), then his satisfaction level raises by *c*. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! Input Specification: The first line of the input contains three space-separated numbers, *n*, *m* and *k* (1<=≀<=*m*<=≀<=*n*<=≀<=18, 0<=≀<=*k*<=≀<=*n*<=*<=(*n*<=-<=1)) β€” the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains *n* space-separated numbers *a**i*, (0<=≀<=*a**i*<=≀<=109) β€” the satisfaction he gets from the *i*-th dish. Next *k* lines contain the rules. The *i*-th rule is described by the three numbers *x**i*, *y**i* and *c**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*, 0<=≀<=*c**i*<=≀<=109). That means that if you eat dish *x**i* right before dish *y**i*, then the Kefa's satisfaction increases by *c**i*. It is guaranteed that there are no such pairs of indexes *i* and *j* (1<=≀<=*i*<=&lt;<=*j*<=≀<=*k*), that *x**i*<==<=*x**j* and *y**i*<==<=*y**j*. Output Specification: In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. Demo Input: ['2 2 1\n1 1\n2 1 1\n', '4 3 2\n1 2 3 4\n2 1 5\n3 4 2\n'] Demo Output: ['3\n', '12\n'] Note: In the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule. In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.
886
Title: Sagheer and Kindergarten Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sagheer is working at a kindergarten. There are *n* children and *m* different toys. These children use well-defined protocols for playing with the toys: - Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set.- If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever.- Children request toys at distinct moments of time. No two children request a toy at the same time.- If a child is granted a toy, he never gives it back until he finishes playing with his lovely set.- If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting.- If two children are waiting for the same toy, then the child who requested it first will take the toy first. Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy. Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set. Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child *x* that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child *x* is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child *x* will make his last request, how many children will start crying? You will be given the scenario and *q* independent queries. Each query will be of the form *x* *y* meaning that the last request of the child *x* is for the toy *y*. Your task is to help Sagheer find the size of the maximal crying set when child *x* makes his last request. Input Specification: The first line contains four integers *n*, *m*, *k*, *q* (1<=≀<=*n*,<=*m*,<=*k*,<=*q*<=≀<=105)Β β€” the number of children, toys, scenario requests and queries. Each of the next *k* lines contains two integers *a*, *b* (1<=≀<=*a*<=≀<=*n* and 1<=≀<=*b*<=≀<=*m*)Β β€” a scenario request meaning child *a* requests toy *b*. The requests are given in the order they are made by children. Each of the next *q* lines contains two integers *x*, *y* (1<=≀<=*x*<=≀<=*n* and 1<=≀<=*y*<=≀<=*m*)Β β€” the request to be added to the scenario meaning child *x* will request toy *y* just after getting the toy he is waiting for (if any). It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request. Output Specification: For each query, print on a single line the number of children who will start crying when child *x* makes his last request for toy *y*. Please answer all queries independent of each other. Demo Input: ['3 3 5 1\n1 1\n2 2\n3 3\n1 2\n2 3\n3 1\n', '5 4 7 2\n1 1\n2 2\n2 1\n5 1\n3 3\n4 4\n4 1\n5 3\n5 4\n'] Demo Output: ['3\n', '0\n2\n'] Note: In the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying. In the second example, at the beginning, child *i* is holding toy *i* for 1 ≀ *i* ≀ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now: - In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play.- In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
887
Title: Sagheer, the Hausmeister Time Limit: None seconds Memory Limit: None megabytes Problem Description: Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off. The building consists of *n* floors with stairs at the left and the right sides. Each floor has *m* rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with *n* rows and *m*<=+<=2 columns, where the first and the last columns represent the stairs, and the *m* columns in the middle represent rooms. Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights. Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off. Input Specification: The first line contains two integers *n* and *m* (1<=≀<=*n*<=≀<=15 and 1<=≀<=*m*<=≀<=100) β€” the number of floors and the number of rooms in each floor, respectively. The next *n* lines contains the building description. Each line contains a binary string of length *m*<=+<=2 representing a floor (the left stairs, then *m* rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0. Output Specification: Print a single integer β€” the minimum total time needed to turn off all the lights. Demo Input: ['2 2\n0010\n0100\n', '3 4\n001000\n000010\n000010\n', '4 3\n01110\n01110\n01110\n01110\n'] Demo Output: ['5\n', '12\n', '18\n'] Note: In the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs. In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor. In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor.
888
Title: Polycarp's Picture Gallery Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Polycarp loves not only to take pictures, but also to show his photos to friends. On his personal website he has recently installed a widget that can display *n* photos with the scroll option. At each moment of time the widget displays exactly one photograph with the option showing the previous/next one. From the first photo, you can switch to the second one or to the *n*-th one, from the second photo you can switch to the third one or to the first one, etc. Thus, navigation is performed in a cycle. Polycarp's collection consists of *m* photo albums, the *i*-th album contains *a**i* photos. Polycarp wants to choose *n* photos and put them on a new widget. To make watching the photos interesting to the visitors, he is going to post pictures so that no two photos from one album were neighboring (each photo will have exactly two neighbors, the first photo's neighbors are the second and the *n*-th one). Help Polycarp compile a photo gallery. Select *n* photos from his collection and put them in such order that no two photos from one album went one after the other. Input Specification: The first line contains two integers *n* and *m* (3<=≀<=*n*<=≀<=1000, 1<=≀<=*m*<=≀<=40), where *n* is the number of photos on the widget, and *m* is the number of albums. The second line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≀<=*a**i*<=≀<=1000), where *a**i* is the number of photos in the *i*-th album. Output Specification: Print the single number -1 if there is no solution. Otherwise, print *n* numbers *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* represents the number of the album of the *i*-th picture in the widget. The albums are numbered from 1 in the order of their appearance in the input. If there are several solutions, print any of them. Demo Input: ['4 3\n1 3 5\n', '10 2\n5 5\n', '10 3\n1 10 3\n'] Demo Output: ['3 1 3 2\n', '2 1 2 1 2 1 2 1 2 1\n', '-1\n'] Note: none
889
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true: - Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager. Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*. What is the minimum number of groups that must be formed? Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=2000) β€” the number of employees. The next *n* lines contain the integers *p**i* (1<=≀<=*p**i*<=≀<=*n* or *p**i*<==<=-1). Every *p**i* denotes the immediate manager for the *i*-th employee. If *p**i* is -1, that means that the *i*-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (*p**i*<=β‰ <=*i*). Also, there will be no managerial cycles. Output Specification: Print a single integer denoting the minimum number of groups that will be formed in the party. Demo Input: ['5\n-1\n1\n2\n1\n-1\n'] Demo Output: ['3\n'] Note: For the first example, three groups are sufficient, for example: - Employee 1 - Employees 2 and 4 - Employees 3 and 5
890
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Permutation *p* is an ordered set of integers *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*, consisting of *n* distinct positive integers not larger than *n*. We'll denote as *n* the length of permutation *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*. Your task is to find such permutation *p* of length *n*, that the group of numbers |*p*1<=-<=*p*2|,<=|*p*2<=-<=*p*3|,<=...,<=|*p**n*<=-<=1<=-<=*p**n*| has exactly *k* distinct elements. Input Specification: The single line of the input contains two space-separated positive integers *n*, *k* (1<=≀<=*k*<=&lt;<=*n*<=≀<=105). Output Specification: Print *n* integers forming the permutation. If there are multiple answers, print any of them. Demo Input: ['3 2\n', '3 1\n', '5 2\n'] Demo Output: ['1 3 2\n', '1 2 3\n', '1 3 2 4 5\n'] Note: By |*x*| we denote the absolute value of number *x*.
891
Title: Beautiful Sets of Points Time Limit: None seconds Memory Limit: None megabytes Problem Description: Manao has invented a new mathematical term β€” a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 1. For any two points from the set, the distance between them is a non-integer. Consider all points (*x*,<=*y*) which satisfy the inequations: 0<=≀<=*x*<=≀<=*n*; 0<=≀<=*y*<=≀<=*m*; *x*<=+<=*y*<=&gt;<=0. Choose their subset of maximum size such that it is also a beautiful set of points. Input Specification: The single line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100). Output Specification: In the first line print a single integer β€” the size *k* of the found beautiful set. In each of the next *k* lines print a pair of space-separated integers β€” the *x*- and *y*- coordinates, respectively, of a point from the set. If there are several optimal solutions, you may print any of them. Demo Input: ['2 2\n', '4 3\n'] Demo Output: ['3\n0 1\n1 2\n2 0\n', '4\n0 3\n2 1\n3 0\n4 2\n'] Note: Consider the first sample. The distance between points (0, 1) and (1, 2) equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bfe16f27ebc966df6f10ba356a1547b6e7242dd7.png" style="max-width: 100.0%;max-height: 100.0%;"/>, between (0, 1) and (2, 0) β€” <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/23d63d8a57cddda72562a512c05111054cd85870.png" style="max-width: 100.0%;max-height: 100.0%;"/>, between (1, 2) and (2, 0) β€” <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/23d63d8a57cddda72562a512c05111054cd85870.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.
892
Title: Jeff and Digits Time Limit: None seconds Memory Limit: None megabytes Problem Description: Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=103). The next line contains *n* integers *a*1, *a*2, ..., *a**n* (*a**i*<==<=0 or *a**i*<==<=5). Number *a**i* represents the digit that is written on the *i*-th card. Output Specification: In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Demo Input: ['4\n5 0 5 0\n', '11\n5 5 5 5 5 5 5 5 0 5 5\n'] Demo Output: ['0\n', '5555555550\n'] Note: In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90.
893
Title: Cactusophobia Time Limit: None seconds Memory Limit: None megabytes Problem Description: Tree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle. Vasya has an edge cactus, each edge of this graph has some color. Vasya would like to remove the minimal number of edges in such way that his cactus turned to a tree. Vasya wants to make it in such a way that there were edges of as many different colors in the resulting tree, as possible. Help him to find how many different colors can the resulting tree have. Input Specification: The first line contains two integers: *n*, *m* (2<=≀<=*n*<=≀<=10<=000)Β β€” the number of vertices and the number of edges in Vasya's graph, respectively. The following *m* lines contain three integers each: *u*, *v*, *c* (1<=≀<=*u*,<=*v*<=≀<=*n*, *u*<=β‰ <=*v*, 1<=≀<=*c*<=≀<=*m*)Β β€” the numbers of vertices connected by the corresponding edge, and its color. It is guaranteed that the described graph is indeed an edge cactus. Output Specification: Output one integer: the maximal number of different colors that the resulting tree can have. Demo Input: ['4 4\n1 2 4\n2 3 1\n3 4 2\n4 2 3\n', '7 9\n1 2 1\n2 3 4\n3 1 5\n1 4 5\n4 5 2\n5 1 6\n1 6 4\n6 7 6\n7 1 3\n'] Demo Output: ['3\n', '6\n'] Note: none
894
Title: Eugeny and Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries: - Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries. Input Specification: The first line contains integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=2Β·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (*a**i*<==<=-1,<=1). Next *m* lines contain Eugene's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*). Output Specification: Print *m* integers β€” the responses to Eugene's queries in the order they occur in the input. Demo Input: ['2 3\n1 -1\n1 1\n1 2\n2 2\n', '5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n'] Demo Output: ['0\n1\n0\n', '0\n1\n0\n1\n0\n'] Note: none
895
Title: Mystic Carvings Time Limit: None seconds Memory Limit: None megabytes Problem Description: The polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are *n* lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered 1,<=2,<=...,<=2*n* counter-clockwise along the circumference. No two lines share an endpoint. Now a group of 6 polar bears (Alice, Bob, Carol, Dave, Eve, Frank) are going to build caves on the endpoints. Each polar bear would build a cave and live in it. No two polar bears can build a cave on the same endpoints. Alice and Bob is a pair of superstitious lovers. They believe the lines are carved by aliens (or humans, which are pretty much the same thing to polar bears), and have certain spiritual power. Therefore they want to build their caves on two endpoints which are connected by a line. The same for Carol and Dave, Eve and Frank. The distance between two caves X and Y is defined as one plus minimum number of other caves one need to pass through in order to travel from X to Y along the boundary of the ice (endpoints without caves are not counted). To ensure fairness, the distances between the three pairs of lovers have to be the same (that is, the distance between Alice and Bob, the distance between Carol and Dave, and the distance between Eve and Frank are the same). The figures below show two different configurations, where the dots on the circle are the endpoints. The configuration on the left is not valid. Although each pair of lovers (A and B, C and D, E and F) is connected a line, the distance requirement is not satisfied. The distance between A and B is 2 (one can go from A to B in the clockwise direction passing through F). The distance between E and F is also 2. However, the distance between C and D is 1 (one can go from C to D in the counter-clockwise direction without passing through any other caves). The configuration on the right is valid. All three pairs have the same distance 1. Count the number of ways to build the caves under the requirements. Two configurations are considered the same if the same set of 6 endpoints are used. Input Specification: The first line contains integer *n*(3<=≀<=*n*<=≀<=105) β€” the number of lines. Each of the following *n* lines contains two integers *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=2*n*), which means that there is a line carved on the ice connecting the *a**i*–th and *b**i*–th endpoint. It's guaranteed that each endpoints touches exactly one line. Output Specification: Print the number of ways to build the caves. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['4\n5 4\n1 2\n6 7\n8 3\n', '8\n1 7\n2 4\n3 9\n5 11\n6 8\n10 16\n13 15\n14 12\n'] Demo Output: ['2\n', '6\n'] Note: The second sample corresponds to the figure in the problem statement.
896
Title: Idempotent functions Time Limit: None seconds Memory Limit: None megabytes Problem Description: Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1,<=2,<=...,<=*n*} is such function , that for any the formula *g*(*g*(*x*))<==<=*g*(*x*) holds. Let's denote as *f*(*k*)(*x*) the function *f* applied *k* times to the value *x*. More formally, *f*(1)(*x*)<==<=*f*(*x*), *f*(*k*)(*x*)<==<=*f*(*f*(*k*<=-<=1)(*x*)) for each *k*<=&gt;<=1. You are given some function . Your task is to find minimum positive integer *k* such that function *f*(*k*)(*x*) is idempotent. Input Specification: In the first line of the input there is a single integer *n* (1<=≀<=*n*<=≀<=200) β€” the size of function *f* domain. In the second line follow *f*(1),<=*f*(2),<=...,<=*f*(*n*) (1<=≀<=*f*(*i*)<=≀<=*n* for each 1<=≀<=*i*<=≀<=*n*), the values of a function. Output Specification: Output minimum *k* such that function *f*(*k*)(*x*) is idempotent. Demo Input: ['4\n1 2 2 4\n', '3\n2 3 3\n', '3\n2 3 1\n'] Demo Output: ['1\n', '2\n', '3\n'] Note: In the first sample test function *f*(*x*) = *f*<sup class="upper-index">(1)</sup>(*x*) is already idempotent since *f*(*f*(1)) = *f*(1) = 1, *f*(*f*(2)) = *f*(2) = 2, *f*(*f*(3)) = *f*(3) = 2, *f*(*f*(4)) = *f*(4) = 4. In the second sample test: - function *f*(*x*) = *f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1)) = 3 but *f*(1) = 2; - function *f*(*x*) = *f*<sup class="upper-index">(2)</sup>(*x*) is idempotent since for any *x* it is true that *f*<sup class="upper-index">(2)</sup>(*x*) = 3, so it is also true that *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(*x*)) = 3. In the third sample test: - function *f*(*x*) = *f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1)) = 3 but *f*(1) = 2; - function *f*(*f*(*x*)) = *f*<sup class="upper-index">(2)</sup>(*x*) isn't idempotent because *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(1)) = 2 but *f*<sup class="upper-index">(2)</sup>(1) = 3; - function *f*(*f*(*f*(*x*))) = *f*<sup class="upper-index">(3)</sup>(*x*) is idempotent since it is identity function: *f*<sup class="upper-index">(3)</sup>(*x*) = *x* for any <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/46a8c73444c646004dfde04451775e7af924d108.png" style="max-width: 100.0%;max-height: 100.0%;"/> meaning that the formula *f*<sup class="upper-index">(3)</sup>(*f*<sup class="upper-index">(3)</sup>(*x*)) = *f*<sup class="upper-index">(3)</sup>(*x*) also holds.
897
Title: Appleman and Card Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Appleman has *n* cards. Each card has an uppercase letter written on it. Toastman must choose *k* cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card *i* you should calculate how much Toastman's cards have the letter equal to letter on *i*th, then sum up all these quantities, such a number of coins Appleman should give to Toastman. Given the description of Appleman's cards. What is the maximum number of coins Toastman can get? Input Specification: The first line contains two integers *n* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=105). The next line contains *n* uppercase letters without spaces β€” the *i*-th letter describes the *i*-th card of the Appleman. Output Specification: Print a single integer – the answer to the problem. Demo Input: ['15 10\nDZFDFZDFDDDDDDF\n', '6 4\nYJSNPI\n'] Demo Output: ['82\n', '4\n'] Note: In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
898
Title: Generous Kefa Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* β€” lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset β€” print Β«YESΒ», if he can, and Β«NOΒ», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all. Input Specification: The first line contains two integers *n* and *k* (1<=≀<=*n*,<=*k*<=≀<=100) β€” the number of baloons and friends. Next line contains string *s* β€” colors of baloons. Output Specification: Answer to the task β€” Β«YESΒ» or Β«NOΒ» in a single line. You can choose the case (lower or upper) for each letter arbitrary. Demo Input: ['4 2\naabb\n', '6 3\naacaab\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second. In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is Β«NOΒ».
899