task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Alex and broken contest Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name. It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita". Names are case sensitive. Input Specification: The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 — the name of the problem. Output Specification: Print "YES", if problem is from this contest, and "NO" otherwise. Demo Input: ['Alex_and_broken_contest\n', 'NikitaAndString\n', 'Danil_and_Olya\n'] Demo Output: ['NO', 'YES', 'NO'] Note: none
900
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: It is known that there are *k* fish species in the polar ocean, numbered from 1 to *k*. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the *i*-th type of fish be *w**i*, then 0<=&lt;<=*w*1<=≤<=*w*2<=≤<=...<=≤<=*w**k* holds. Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights *w**i* (not necessary integers), such that the fish caught by Alice has a strictly larger total weight? Input Specification: The first line contains three integers *n*,<=*m*,<=*k* (1<=≤<=*n*,<=*m*<=≤<=105,<=1<=≤<=*k*<=≤<=109) — the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains *n* integers each from 1 to *k*, the list of fish type caught by Alice. The third line contains *m* integers each from 1 to *k*, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species. Output Specification: Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise. Demo Input: ['3 3 3\n2 2 2\n1 1 3\n', '4 7 9\n5 2 7 3\n3 5 2 7 3 8 7\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample, if *w*<sub class="lower-index">1</sub> = 1, *w*<sub class="lower-index">2</sub> = 2, *w*<sub class="lower-index">3</sub> = 2.5, then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5. In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.
901
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Levko has an array that consists of integers: *a*1,<=*a*2,<=... ,<=*a**n*. But he doesn’t like this array at all. Levko thinks that the beauty of the array *a* directly depends on value *c*(*a*), which can be calculated by the formula: It’s time to change the world and Levko is going to change his array for the better. To be exact, Levko wants to change the values of at most *k* array elements (it is allowed to replace the values by any integers). Of course, the changes should make the array as beautiful as possible. Help Levko and calculate what minimum number *c*(*a*) he can reach. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2000). The second line contains space-separated integers *a*1,<=*a*2,<=... ,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109). Output Specification: A single number — the minimum value of *c*(*a*) Levko can get. Demo Input: ['5 2\n4 7 4 7 4\n', '3 1\n-100 0 100\n', '6 3\n1 2 3 7 8 9\n'] Demo Output: ['0\n', '100\n', '1\n'] Note: In the first sample Levko can change the second and fourth elements and get array: 4, 4, 4, 4, 4. In the third sample he can get array: 1, 2, 3, 4, 5, 6.
902
Title: Parking Lot Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as *L* meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than *b* meters and the distance between his car and the one in front of his will be no less than *f* meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point *L*. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car. Input Specification: The first line contains three integers *L*, *b* и *f* (10<=≤<=*L*<=≤<=100000,<=1<=≤<=*b*,<=*f*<=≤<=100). The second line contains an integer *n* (1<=≤<=*n*<=≤<=100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000. Output Specification: For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone. Demo Input: ['30 1 2\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4\n', '30 1 1\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4\n', '10 1 1\n1\n1 12\n'] Demo Output: ['0\n6\n11\n17\n23\n', '0\n6\n11\n17\n6\n', '-1\n'] Note: none
903
Title: Eevee Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon. You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it. Input Specification: First line contains an integer *n* (6<=≤<=*n*<=≤<=8) – the length of the string. Next line contains a string consisting of *n* characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword). Output Specification: Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter). Demo Input: ['7\nj......\n', '7\n...feon\n', '7\n.l.r.o.\n'] Demo Output: ['jolteon\n', 'leafeon\n', 'flareon\n'] Note: Here's a set of names in a form you can paste into your solution: ["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"] {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}
904
Title: none 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
905
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix *a* with *n* lines and *m* columns. Let number *a*[*i*][*j*] represents the calories burned by performing workout at the cell of gym in the *i*-th line and the *j*-th column. Iahub starts with workout located at line 1 and column 1. He needs to finish with workout *a*[*n*][*m*]. After finishing workout *a*[*i*][*j*], he can go to workout *a*[*i*<=+<=1][*j*] or *a*[*i*][*j*<=+<=1]. Similarly, Iahubina starts with workout *a*[*n*][1] and she needs to finish with workout *a*[1][*m*]. After finishing workout from cell *a*[*i*][*j*], she goes to either *a*[*i*][*j*<=+<=1] or *a*[*i*<=-<=1][*j*]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout. If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs. Input Specification: The first line of the input contains two integers *n* and *m* (3<=≤<=*n*,<=*m*<=≤<=1000). Each of the next *n* lines contains *m* integers: *j*-th number from *i*-th line denotes element *a*[*i*][*j*] (0<=≤<=*a*[*i*][*j*]<=≤<=105). Output Specification: The output contains a single number — the maximum total gain possible. Demo Input: ['3 3\n100 100 100\n100 1 100\n100 100 100\n'] Demo Output: ['800'] Note: Iahub will choose exercises *a*[1][1] → *a*[1][2] → *a*[2][2] → *a*[3][2] → *a*[3][3]. Iahubina will choose exercises *a*[3][1] → *a*[2][1] → *a*[2][2] → *a*[2][3] → *a*[1][3].
906
Title: LCIS Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: This problem differs from one which was on the online contest. The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=&lt;<=*a**i*<=+<=1 for *i*<=&lt;<=*n*. The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements. You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=500) — the length of the first sequence. The second line contains *n* space-separated integers from the range [0,<=109] — elements of the first sequence. The third line contains an integer *m* (1<=≤<=*m*<=≤<=500) — the length of the second sequence. The fourth line contains *m* space-separated integers from the range [0,<=109] — elements of the second sequence. Output Specification: In the first line output *k* — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any. Demo Input: ['7\n2 3 1 6 5 4 6\n4\n1 3 5 6\n', '5\n1 2 0 2 1\n3\n1 0 1\n'] Demo Output: ['3\n3 5 6 \n', '2\n0 1 \n'] Note: none
907
Title: Maxim and Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (*m*<=+<=1)<=×<=(*m*<=+<=1): Maxim asks you to count, how many numbers *m* (1<=≤<=*m*<=≤<=*n*) are there, such that the sum of values in the cells in the row number *m*<=+<=1 of the resulting matrix equals *t*. Expression (*x* *xor* *y*) means applying the operation of bitwise excluding "OR" to numbers *x* and *y*. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal — by "xor". Input Specification: A single line contains two integers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=1012,<=*t*<=≤<=*n*<=+<=1). Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Specification: In a single line print a single integer — the answer to the problem. Demo Input: ['1 1\n', '3 2\n', '3 3\n', '1000000000000 1048576\n'] Demo Output: ['1\n', '1\n', '0\n', '118606527258\n'] Note: none
908
Title: Convenient For Everybody Time Limit: None seconds Memory Limit: None megabytes Problem Description: In distant future on Earth day lasts for *n* hours and that's why there are *n* timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to *n* are used, i.e. there is no time "0 hours", instead of it "*n* hours" is used. When local time in the 1-st timezone is 1 hour, local time in the *i*-th timezone is *i* hours. Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are *a**i* people from *i*-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than *s* hours 00 minutes local time and ends not later than *f* hours 00 minutes local time. Values *s* and *f* are equal for all time zones. If the contest starts at *f* hours 00 minutes local time, the person won't participate in it. Help platform select such an hour, that the number of people who will participate in the contest is maximum. Input Specification: The first line contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the number of hours in day. The second line contains *n* space-separated integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=10<=000), where *a**i* is the number of people in the *i*-th timezone who want to participate in the contest. The third line contains two space-separated integers *s* and *f* (1<=≤<=*s*<=&lt;<=*f*<=≤<=*n*). Output Specification: Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them. Demo Input: ['3\n1 2 3\n1 3\n', '5\n1 2 3 4 1\n1 3\n'] Demo Output: ['3\n', '4\n'] Note: In the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate. In second example only people from the third and the fourth timezones will participate.
909
Title: Visiting a Friend Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point *m* on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport. Formally, a teleport located at point *x* with limit *y* can move Pig from point *x* to any point within the segment [*x*;<=*y*], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100,<=1<=≤<=*m*<=≤<=100) — the number of teleports and the location of the friend's house. The next *n* lines contain information about teleports. The *i*-th of these lines contains two integers *a**i* and *b**i* (0<=≤<=*a**i*<=≤<=*b**i*<=≤<=*m*), where *a**i* is the location of the *i*-th teleport, and *b**i* is its limit. It is guaranteed that *a**i*<=≥<=*a**i*<=-<=1 for every *i* (2<=≤<=*i*<=≤<=*n*). Output Specification: Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). Demo Input: ['3 5\n0 2\n2 4\n3 5\n', '3 7\n0 4\n2 5\n6 7\n'] Demo Output: ['YES\n', 'NO\n'] Note: The first example is shown on the picture below: Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives. The second example is shown on the picture below: You can see that there is no path from Pig's house to his friend's house that uses only teleports.
910
Title: Bicycle Race Time Limit: None seconds Memory Limit: None megabytes Problem Description: Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the *Ox* axis from west to east, and the *Oy* axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa). Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored. Help Maria get ready for the competition — determine the number of dangerous turns on the track. Input Specification: The first line of the input contains an integer *n* (4<=≤<=*n*<=≤<=1000) — the number of straight sections of the track. The following (*n*<=+<=1)-th line contains pairs of integers (*x**i*,<=*y**i*) (<=-<=10<=000<=≤<=*x**i*,<=*y**i*<=≤<=10<=000). The first of these points is the starting position. The *i*-th straight section of the track begins at the point (*x**i*,<=*y**i*) and ends at the point (*x**i*<=+<=1,<=*y**i*<=+<=1). It is guaranteed that: - the first straight section is directed to the north; - the southernmost (and if there are several, then the most western of among them) point of the track is the first point; - the last point coincides with the first one (i.e., the start position); - any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); - no pair of points (except for the first and last one) is the same; - no two adjacent straight sections are directed in the same direction or in opposite directions. Output Specification: Print a single integer — the number of dangerous turns on the track. Demo Input: ['6\n0 0\n0 1\n1 1\n1 2\n2 2\n2 0\n0 0\n', '16\n1 1\n1 5\n3 5\n3 7\n2 7\n2 9\n6 9\n6 7\n5 7\n5 3\n4 3\n4 4\n3 4\n3 2\n5 2\n5 1\n1 1\n'] Demo Output: ['1\n', '6\n'] Note: The first sample corresponds to the picture: The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.
911
Title: Inna and New Matrix of Candies Time Limit: None seconds Memory Limit: None megabytes Problem Description: Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload". The field for the new game is a rectangle table of size *n*<=×<=*m*. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs: - some dwarf in one of the chosen lines is located in the rightmost cell of his row; - some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells. Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game. Input Specification: The first line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=1000; 2<=≤<=*m*<=≤<=1000). Next *n* lines each contain *m* characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S". Output Specification: In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field. Demo Input: ['3 4\n*G*S\nG**S\n*G*S\n', '1 3\nS*G\n'] Demo Output: ['2\n', '-1\n'] Note: none
912
Title: Falling Anvils Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height *p* of the potential victim vary in the range [0;*a*] and the direction of the wind *q* vary in the range [<=-<=*b*;*b*]. *p* and *q* could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the *p* and *q* coefficients are chosen equiprobably and independently in their ranges. Input Specification: The first line contains integer *t* (1<=≤<=*t*<=≤<=10000) — amount of testcases. Each of the following *t* lines contain two space-separated integers *a* and *b* (0<=≤<=*a*,<=*b*<=≤<=106). Pretests contain all the tests with 0<=&lt;<=*a*<=&lt;<=10,<=0<=≤<=*b*<=&lt;<=10. Output Specification: Print *t* lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10<=-<=6. Demo Input: ['2\n4 2\n1 2\n'] Demo Output: ['0.6250000000\n0.5312500000\n'] Note: none
913
Title: What is for dinner? Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing". For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap). It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner. We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one. Input Specification: The first line contains three integers *n*, *m*, *k* (1<=≤<=*m*<=≤<=*n*<=≤<=1000,<=0<=≤<=*k*<=≤<=106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow *n* lines, each containing two integers: *r* (1<=≤<=*r*<=≤<=*m*) — index of the row, where belongs the corresponding tooth, and *c* (0<=≤<=*c*<=≤<=106) — its residual viability. It's guaranteed that each tooth row has positive amount of teeth. Output Specification: In the first line output the maximum amount of crucians that Valerie can consume for dinner. Demo Input: ['4 3 18\n2 3\n1 2\n3 6\n2 3\n', '2 2 13\n1 13\n2 12\n'] Demo Output: ['11\n', '13\n'] Note: none
914
Title: Binary Blocks Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an image, that can be represented with a 2-d *n* by *m* grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer *k*<=&gt;<=1 and split the image into *k* by *k* blocks. If *n* and *m* are not divisible by *k*, the image is padded with only zeros on the right and bottom so that they are divisible by *k*. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some *k*. More specifically, the steps are to first choose *k*, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this *k*. The image must be compressible in that state. Input Specification: The first line of input will contain two integers *n*,<=*m* (2<=≤<=*n*,<=*m*<=≤<=2<=500), the dimensions of the image. The next *n* lines of input will contain a binary string with exactly *m* characters, representing the image. Output Specification: Print a single integer, the minimum number of pixels needed to toggle to make the image compressible. Demo Input: ['3 5\n00100\n10110\n11001\n'] Demo Output: ['5\n'] Note: We first choose *k* = 2. The image is padded as follows: We can toggle the image to look as follows: We can see that this image is compressible for *k* = 2.
915
Title: Code Parsing Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string *s*, consisting of characters "x" and "y", and uses two following operations at runtime: 1. Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. 1. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string *s*, and the algorithm works as follows: 1. If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. 1. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string *s*. Input Specification: The first line contains a non-empty string *s*. It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string. Output Specification: In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string *s*. Demo Input: ['x\n', 'yxyxy\n', 'xxxxxy\n'] Demo Output: ['x\n', 'y\n', 'xxxx\n'] Note: In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change. In the second test the transformation will be like this: 1. string "yxyxy" transforms into string "xyyxy"; 1. string "xyyxy" transforms into string "xyxyy"; 1. string "xyxyy" transforms into string "xxyyy"; 1. string "xxyyy" transforms into string "xyy"; 1. string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".
916
Title: Binary String Constructing Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \le i &lt; n$) such that $s_i \ne s_{i + 1}$. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices $i$ such that $1 \le i &lt; n$ and $s_i \ne s_{i + 1}$ ($i = 1, 2, 3, 4$). For the string "111001" there are two such indices $i$ ($i = 3, 5$). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input Specification: The first line of the input contains three integers $a$, $b$ and $x$ ($1 \le a, b \le 100, 1 \le x &lt; a + b)$. Output Specification: Print only one string $s$, where $s$ is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Demo Input: ['2 2 1\n', '3 3 3\n', '5 3 6\n'] Demo Output: ['1100\n', '101100\n', '01010100\n'] Note: All possible answers for the first example: - 1100; - 0011. All possible answers for the second example: - 110100; - 101100; - 110010; - 100110; - 011001; - 001101; - 010011; - 001011.
917
Title: Ping-Pong Time Limit: None seconds Memory Limit: None megabytes Problem Description: In this problem at each moment you have a set of intervals. You can move from interval (*a*,<=*b*) from our set to interval (*c*,<=*d*) from our set if and only if *c*<=&lt;<=*a*<=&lt;<=*d* or *c*<=&lt;<=*b*<=&lt;<=*d*. Also there is a path from interval *I*1 from our set to interval *I*2 from our set if there is a sequence of successive moves starting from *I*1 so that we can reach *I*2. Your program should handle the queries of the following two types: 1. "1 x y" (*x*<=&lt;<=*y*) — add the new interval (*x*,<=*y*) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.1. "2 a b" (*a*<=≠<=*b*) — answer the question: is there a path from *a*-th (one-based) added interval to *b*-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input Specification: The first line of the input contains integer *n* denoting the number of queries, (1<=≤<=*n*<=≤<=105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output Specification: For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Demo Input: ['5\n1 1 5\n1 5 11\n2 1 2\n1 2 9\n2 1 2\n'] Demo Output: ['NO\nYES\n'] Note: none
918
Title: Bearish Fanpages Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is a social website with *n* fanpages, numbered 1 through *n*. There are also *n* companies, and the *i*-th company owns the *i*-th fanpage. Recently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow. The website doesn’t allow a situation where *i* follows *j* and at the same time *j* follows *i*. Also, a fanpage can't follow itself. Let’s say that fanpage *i* follows some other fanpage *j*0. Also, let’s say that *i* is followed by *k* other fanpages *j*1,<=*j*2,<=...,<=*j**k*. Then, when people visit fanpage *i* they see ads from *k*<=+<=2 distinct companies: *i*,<=*j*0,<=*j*1,<=...,<=*j**k*. Exactly *t**i* people subscribe (like) the *i*-th fanpage, and each of them will click exactly one add. For each of *k*<=+<=1 companies *j*0,<=*j*1,<=...,<=*j**k*, exactly people will click their ad. Remaining people will click an ad from company *i* (the owner of the fanpage). The total income of the company is equal to the number of people who click ads from this copmany. Limak and Radewoosh ask you for help. Initially, fanpage *i* follows fanpage *f**i*. Your task is to handle *q* queries of three types: - 1 i j — fanpage *i* follows fanpage *j* from now. It's guaranteed that *i* didn't follow *j* just before the query. Note an extra constraint for the number of queries of this type (below, in the Input section). - 2 i — print the total income of the *i*-th company. - 3 — print two integers: the smallest income of one company and the biggest income of one company. Input Specification: The first line of the input contains two integers *n* and *q* (3<=≤<=*n*<=≤<=100<=000, 1<=≤<=*q*<=≤<=100<=000) — the number of fanpages and the number of queries, respectively. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=1012) where *t**i* denotes the number of people subscribing the *i*-th fanpage. The third line contains *n* integers *f*1,<=*f*2,<=...,<=*f**n* (1<=≤<=*f**i*<=≤<=*n*). Initially, fanpage *i* follows fanpage *f**i*. Then, *q* lines follow. The *i*-th of them describes the *i*-th query. The first number in the line is an integer *type**i* (1<=≤<=*type**i*<=≤<=3) — the type of the query. There will be at most 50<=000 queries of the first type. There will be at least one query of the second or the third type (so, the output won't be empty). It's guaranteed that at each moment a fanpage doesn't follow itself, and that no two fanpages follow each other. Output Specification: For each query of the second type print one integer in a separate line - the total income of the given company. For each query of the third type print two integers in a separate line - the minimum and the maximum total income, respectively. Demo Input: ['5 12\n10 20 30 40 50\n2 3 4 5 2\n2 1\n2 2\n2 3\n2 4\n2 5\n1 4 2\n2 1\n2 2\n2 3\n2 4\n2 5\n3\n'] Demo Output: ['10\n36\n28\n40\n36\n9\n57\n27\n28\n29\n9 57\n'] Note: In the sample test, there are 5 fanpages. The *i*-th of them has *i*·10 subscribers. On drawings, numbers of subscribers are written in circles. An arrow from *A* to *B* means that *A* follows *B*. The left drawing shows the initial situation. The first company gets income <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/aa287c04033fd5717b34060017a16ed1930b6a77.png" style="max-width: 100.0%;max-height: 100.0%;"/> from its own fanpage, and gets income <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/545b52a4f4acc0a81e4c81f01a57750f8d8a5045.png" style="max-width: 100.0%;max-height: 100.0%;"/> from the 2-nd fanpage. So, the total income is 5 + 5 = 10. After the first query ("2 1") you should print 10. The right drawing shows the situation after a query "1 4 2" (after which fanpage 4 follows fanpage 2). Then, the first company still gets income 5 from its own fanpage, but now it gets only <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/08e222f472ebd19466616b7774c41626722a1995.png" style="max-width: 100.0%;max-height: 100.0%;"/> from the 2-nd fanpage. So, the total income is 5 + 4 = 9 now.
919
Title: Minimum Modular Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have been given *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n*. You can remove at most *k* of them. Find the minimum modular *m* (*m*<=&gt;<=0), so that for every pair of the remaining integers (*a**i*,<=*a**j*), the following unequality holds: . Input Specification: The first line contains two integers *n* and *k* (1<=<=≤<=*n*<=<=≤<=5000,<=0<=≤<=*k*<=≤<=4), which we have mentioned above. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106). Output Specification: Print a single positive integer — the minimum *m*. Demo Input: ['7 0\n0 2 3 6 7 12 18\n', '7 1\n0 2 3 6 7 12 18\n'] Demo Output: ['13\n', '7\n'] Note: none
920
Title: Erasing Substrings Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *s*, initially consisting of *n* lowercase Latin letters. After that, you perform *k* operations with it, where . During *i*-th operation you must erase some substring of length exactly 2*i*<=-<=1 from *s*. Print the lexicographically minimal string you may obtain after performing *k* such operations. Input Specification: The only line contains one string *s* consisting of *n* lowercase Latin letters (1<=≤<=*n*<=≤<=5000). Output Specification: Print the lexicographically minimal string you may obtain after performing *k* operations. Demo Input: ['adcbca\n', 'abacabadabacaba\n'] Demo Output: ['aba\n', 'aabacaba\n'] Note: Possible operations in examples: 1. adcbca <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> adcba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aba; 1. abacabadabacaba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> abcabadabacaba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aabadabacaba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aabacaba.
921
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has *n* cities connected by *n*<=-<=1 undirected roads, and for any two cities there always exists a path between them. Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost. There are enough officers of each rank. But there is a special rule must obey: if *x* and *y* are two distinct cities and their officers have the same rank, then on the simple path between *x* and *y* there must be a city *z* that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer. Help Ciel to make a valid plan, and if it's impossible, output "Impossible!". Input Specification: The first line contains an integer *n* (2<=≤<=*n*<=≤<=105) — the number of cities in Tree Land. Each of the following *n*<=-<=1 lines contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*,<=*a*<=≠<=*b*) — they mean that there will be an undirected road between *a* and *b*. Consider all the cities are numbered from 1 to *n*. It guaranteed that the given graph will be a tree. Output Specification: If there is a valid plane, output *n* space-separated characters in a line — *i*-th character is the rank of officer in the city with number *i*. Otherwise output "Impossible!". Demo Input: ['4\n1 2\n1 3\n1 4\n', '10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n'] Demo Output: ['A B B B\n', 'D C B A D C B D C D\n'] Note: In the first example, for any two officers of rank 'B', an officer with rank 'A' will be on the path between them. So it is a valid solution.
922
Title: Anastasia and pebbles Time Limit: None seconds Memory Limit: None megabytes Problem Description: Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only two pockets. She can put at most *k* pebbles in each pocket at the same time. There are *n* different pebble types in the park, and there are *w**i* pebbles of the *i*-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day. Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105, 1<=≤<=*k*<=≤<=109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (1<=≤<=*w**i*<=≤<=104) — number of pebbles of each type. Output Specification: The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles. Demo Input: ['3 2\n2 3 4\n', '5 4\n3 1 8 9 7\n'] Demo Output: ['3\n', '5\n'] Note: In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day. Optimal sequence of actions in the second sample case: - In the first day Anastasia collects 8 pebbles of the third type. - In the second day she collects 8 pebbles of the fourth type. - In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type. - In the fourth day she collects 7 pebbles of the fifth type. - In the fifth day she collects 1 pebble of the second type.
923
Title: Hobbits' Party Time Limit: None seconds Memory Limit: None megabytes Problem Description: Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are *n* hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number *n*, to indicate the GP's maximum duration and the guest lists for each day. Input Specification: The first line contains an integer *n* (3<=≤<=*n*<=≤<=10000), representing the number of hobbits. Output Specification: In the first output line print a number *k* — the maximum duration of GP in days. Then on *k* lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to *n*. Demo Input: ['4\n', '5\n'] Demo Output: ['3\n1 2 \n1 3 \n2 3 \n', '3\n1 2 \n1 3 \n2 3 \n'] Note: none
924
Title: Teodor is not a liar! Time Limit: None seconds Memory Limit: None megabytes Problem Description: Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;*m*] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha. Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point *x**i*, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions. Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice. Input Specification: First line of input contains two integer numbers: *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about. *i*th of next *n* lines contains two integer numbers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*m*) — left and right ends of *i*th segment in the picture. Note that that left and right ends of segment can be the same point. It is guaranteed that there is no integer point, that belongs to all segments. Output Specification: Single line of output should contain one integer number *k* – size of largest set (*x**i*,<=*cnt*(*x**i*)) where all *x**i* are different, 1<=≤<=*x**i*<=≤<=*m*, and *cnt*(*x**i*) is amount of segments, containing point with coordinate *x**i*, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know *n*). Demo Input: ['2 4\n1 2\n3 4\n', '4 6\n1 3\n2 3\n4 6\n5 6\n'] Demo Output: ['4\n', '5\n'] Note: First example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows *cnt*(*x*<sub class="lower-index">*i*</sub>) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment. In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him.
925
Title: Spyke Chatting Time Limit: None seconds Memory Limit: None megabytes Problem Description: The R2 company has *n* employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke. R2 has *m* Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the *k*-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification. The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee. Input Specification: The first line contains three space-separated integers *n*, *m* and *k* (2<=≤<=*n*<=≤<=2·104; 1<=≤<=*m*<=≤<=10; 1<=≤<=*k*<=≤<=2·105) — the number of the employees, the number of chats and the number of events in the log, correspondingly. Next *n* lines contain matrix *a* of size *n*<=×<=*m*, consisting of numbers zero and one. The element of this matrix, recorded in the *j*-th column of the *i*-th line, (let's denote it as *a**ij*) equals 1, if the *i*-th employee is the participant of the *j*-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to *n* and the chats are numbered from 1 to *m*. Next *k* lines contain the description of the log events. The *i*-th line contains two space-separated integers *x**i* and *y**i* (1<=≤<=*x**i*<=≤<=*n*; 1<=≤<=*y**i*<=≤<=*m*) which mean that the employee number *x**i* sent one message to chat number *y**i*. It is guaranteed that employee number *x**i* is a participant of chat *y**i*. It is guaranteed that each chat contains at least two employees. Output Specification: Print in the single line *n* space-separated integers, where the *i*-th integer shows the number of message notifications the *i*-th employee receives. Demo Input: ['3 4 5\n1 1 1 1\n1 0 1 1\n1 1 0 0\n1 1\n3 1\n1 3\n2 4\n3 2\n', '4 3 4\n0 1 1\n1 0 1\n1 1 1\n0 0 0\n1 2\n2 1\n3 1\n1 3\n'] Demo Output: ['3 3 1 ', '0 2 3 0 '] Note: none
926
Title: Kalila and Dimna in the Logging Industry Time Limit: None seconds Memory Limit: None megabytes Problem Description: Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut *n* trees with heights *a*1,<=*a*2,<=...,<=*a**n*. They bought a chain saw from a shop. Each time they use the chain saw on the tree number *i*, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is *i* (the tree that have height *a**i* in the beginning), then the cost of charging the chain saw would be *b**i*. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each *i* &lt; *j*, *a**i*<=&lt;<=*a**j* and *b**i*<=&gt;<=*b**j* and also *b**n*<==<=0 and *a*1<==<=1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you? Input Specification: The first line of input contains an integer *n* (1<=≤<=*n*<=≤<=105). The second line of input contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). The third line of input contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (0<=≤<=*b**i*<=≤<=109). It's guaranteed that *a*1<==<=1, *b**n*<==<=0, *a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n* and *b*1<=&gt;<=*b*2<=&gt;<=...<=&gt;<=*b**n*. Output Specification: The only line of output must contain the minimum cost of cutting all the trees completely. 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: ['5\n1 2 3 4 5\n5 4 3 2 0\n', '6\n1 2 3 10 20 30\n6 5 4 3 2 0\n'] Demo Output: ['25\n', '138\n'] Note: none
927
Title: Jury Size Time Limit: None seconds Memory Limit: None megabytes Problem Description: In 2013, the writers of Berland State University should prepare problems for *n* Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to *n*. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number *i* should be prepared by *p**i* people for *t**i* days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it. For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd. In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time. Input Specification: The first line contains integer *n* — the number of Olympiads in 2013 (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains four integers *m**i*, *d**i*, *p**i* and *t**i* — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the *i*-th Olympiad (1<=≤<=*m**i*<=≤<=12, *d**i*<=≥<=1, 1<=≤<=*p**i*,<=*t**i*<=≤<=100), *d**i* doesn't exceed the number of days in month *m**i*. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year. Output Specification: Print a single number — the minimum jury size. Demo Input: ['2\n5 23 1 2\n3 13 2 3\n', '3\n12 9 2 1\n12 8 1 3\n12 8 2 2\n', '1\n1 10 1 13\n'] Demo Output: ['2\n', '3\n', '1\n'] Note: none
928
Title: Tractor College Time Limit: None seconds Memory Limit: None megabytes Problem Description: While most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college — the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Those who score lower marks are unfortunately expelled. The college has *n* students, and oddly enough, each of them can be on scholarship. The size of the scholarships varies each term. Since the end-of-the-term exam has just ended, it's time to determine the size of the scholarship to the end of next term. The monthly budget for the scholarships of the Tractor college is *s* rubles. To distribute the budget optimally, you must follow these rules: - The students who received the same mark for the exam, should receive the same scholarship;- Let us denote the size of the scholarship (in roubles) for students who have received marks 3, 4 and 5 for the exam, as *k*3, *k*4 and *k*5, respectively. The values *k*3, *k*4 and *k*5 must be integers and satisfy the inequalities 0<=≤<=*k*3<=≤<=*k*4<=≤<=*k*5;- Let's assume that *c*3, *c*4, *c*5 show how many students received marks 3, 4 and 5 for the exam, respectively. The budget of the scholarship should be fully spent on them, that is, *c*3·*k*3<=+<=*c*4·*k*4<=+<=*c*5·*k*5<==<=*s*;- Let's introduce function — the value that shows how well the scholarships are distributed between students. In the optimal distribution function *f*(*k*3,<=*k*4,<=*k*5) takes the minimum possible value. Given the results of the exam, and the budget size *s*, you have to find the optimal distribution of the scholarship. Input Specification: The first line has two integers *n*, *s* (3<=≤<=*n*<=≤<=300,<=1<=≤<=*s*<=≤<=3·105) — the number of students and the budget size for the scholarship, respectively. The second line contains *n* integers, where the *i*-th number represents the mark that the *i*-th student got for the exam. It is guaranteed that at each mark was given to at least one student. Output Specification: On a single line print three integers *k*3, *k*4 and *k*5 — the sought values that represent the optimal distribution of the scholarships. If there are multiple optimal answers, print any of them. If there is no answer, print -1. Demo Input: ['5 11\n3 4 3 5 5\n', '6 15\n5 3 3 4 4 5\n'] Demo Output: ['1 3 3\n', '-1\n'] Note: none
929
Title: Sign on Fence Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bizon the Champion has recently finished painting his wood fence. The fence consists of a sequence of *n* panels of 1 meter width and of arbitrary height. The *i*-th panel's height is *h**i* meters. The adjacent planks follow without a gap between them. After Bizon painted the fence he decided to put a "for sale" sign on it. The sign will be drawn on a rectangular piece of paper and placed on the fence so that the sides of the sign are parallel to the fence panels and are also aligned with the edges of some panels. Bizon the Champion introduced the following constraints for the sign position: 1. The width of the sign should be exactly *w* meters. 1. The sign must fit into the segment of the fence from the *l*-th to the *r*-th panels, inclusive (also, it can't exceed the fence's bound in vertical direction). The sign will be really pretty, So Bizon the Champion wants the sign's height to be as large as possible. You are given the description of the fence and several queries for placing sign. For each query print the maximum possible height of the sign that can be placed on the corresponding segment of the fence with the given fixed width of the sign. Input Specification: The first line of the input contains integer *n* — the number of panels in the fence (1<=≤<=*n*<=≤<=105). The second line contains *n* space-separated integers *h**i*, — the heights of the panels (1<=≤<=*h**i*<=≤<=109). The third line contains an integer *m* — the number of the queries (1<=≤<=*m*<=≤<=105). The next *m* lines contain the descriptions of the queries, each query is represented by three integers *l*, *r* and *w* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, 1<=≤<=*w*<=≤<=*r*<=-<=*l*<=+<=1) — the segment of the fence and the width of the sign respectively. Output Specification: For each query print the answer on a separate line — the maximum height of the sign that can be put in the corresponding segment of the fence with all the conditions being satisfied. Demo Input: ['5\n1 2 2 3 3\n3\n2 5 3\n2 5 2\n1 5 5\n'] Demo Output: ['2\n3\n1\n'] Note: The fence described in the sample looks as follows: The possible positions for the signs for all queries are given below.
930
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Again, there are hard times in Berland! Many towns have such tensions that even civil war is possible. There are *n* towns in Reberland, some pairs of which connected by two-way roads. It is not guaranteed that it is possible to reach one town from any other town using these roads. Towns *s* and *t* announce the final break of any relationship and intend to rule out the possibility of moving between them by the roads. Now possibly it is needed to close several roads so that moving from *s* to *t* using roads becomes impossible. Each town agrees to spend money on closing no more than one road, therefore, the total number of closed roads will be no more than two. Help them find set of no more than two roads such that there will be no way between *s* and *t* after closing these roads. For each road the budget required for its closure was estimated. Among all sets find such that the total budget for the closure of a set of roads is minimum. Input Specification: The first line of the input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=1000, 0<=≤<=*m*<=≤<=30<=000) — the number of towns in Berland and the number of roads. The second line contains integers *s* and *t* (1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*) — indices of towns which break up the relationships. Then follow *m* lines, each of them contains three integers *x**i*, *y**i* and *w**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, 1<=≤<=*w**i*<=≤<=109) — indices of towns connected by the *i*-th road, and the budget on its closure. All roads are bidirectional. It is allowed that the pair of towns is connected by more than one road. Roads that connect the city to itself are allowed. Output Specification: In the first line print the minimum budget required to break up the relations between *s* and *t*, if it is allowed to close no more than two roads. In the second line print the value *c* (0<=≤<=*c*<=≤<=2) — the number of roads to be closed in the found solution. In the third line print in any order *c* diverse integers from 1 to *m* — indices of closed roads. Consider that the roads are numbered from 1 to *m* in the order they appear in the input. If it is impossible to make towns *s* and *t* disconnected by removing no more than 2 roads, the output should contain a single line -1. If there are several possible answers, you may print any of them. Demo Input: ['6 7\n1 6\n2 1 6\n2 3 5\n3 4 9\n4 6 4\n4 6 5\n4 5 1\n3 1 3\n', '6 7\n1 6\n2 3 1\n1 2 2\n1 3 3\n4 5 4\n3 6 5\n4 6 6\n1 5 7\n', '5 4\n1 5\n2 1 3\n3 2 1\n3 4 4\n4 5 2\n', '2 3\n1 2\n1 2 734458840\n1 2 817380027\n1 2 304764803\n'] Demo Output: ['8\n2\n2 7\n', '9\n2\n4 5\n', '1\n1\n2\n', '-1\n'] Note: none
931
Title: Missile Silos Time Limit: None seconds Memory Limit: None megabytes Problem Description: A country called Berland consists of *n* cities, numbered with integer numbers from 1 to *n*. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance *l* from the capital. The capital is located in the city with number *s*. The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly *l*. Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob. Input Specification: The first line contains three integers *n*, *m* and *s* (2<=≤<=*n*<=≤<=105, , 1<=≤<=*s*<=≤<=*n*) — the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. *s*. Then *m* lines contain the descriptions of roads. Each of them is described by three integers *v**i*, *u**i*, *w**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*, *v**i*<=≠<=*u**i*, 1<=≤<=*w**i*<=≤<=1000), where *v**i*, *u**i* are numbers of the cities connected by this road and *w**i* is its length. The last input line contains integer *l* (0<=≤<=*l*<=≤<=109) — the distance from the capital to the missile silos. It is guaranteed that: - between any two cities no more than one road exists; - each road connects two different cities; - from each city there is at least one way to any other city by the roads. Output Specification: Print the single number — the number of Super Duper Secret Missile Silos that are located in Berland. Demo Input: ['4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2\n', '5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4\n'] Demo Output: ['3\n', '3\n'] Note: In the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3). In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
932
Title: Marlin Time Limit: None seconds Memory Limit: None megabytes Problem Description: The city of Fishtopia can be imagined as a grid of $4$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $(1,1)$, people who stay there love fishing at the Tuna pond at the bottom-right cell $(4, n)$. The second village is located at $(4, 1)$ and its people love the Salmon pond at $(1, n)$. The mayor of Fishtopia wants to place $k$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells. A person can move from one cell to another if those cells are not occupied by hotels and share a side. Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? Input Specification: The first line of input contain two integers, $n$ and $k$ ($3 \leq n \leq 99$, $0 \leq k \leq 2\times(n-2)$), $n$ is odd, the width of the city, and the number of hotels to be placed, respectively. Output Specification: Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $4$ lines that describe the city, each line should have $n$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. Demo Input: ['7 2\n', '5 3\n'] Demo Output: ['YES\n.......\n.#.....\n.#.....\n.......\n', 'YES\n.....\n.###.\n.....\n.....\n'] Note: none
933
Title: Buying Sets Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: The Hexadecimal virus loves playing with number sets — intersecting them, uniting them. One beautiful day she was surprised to find out that Scuzzy, her spherical pet cat, united all sets in one and ate the result! Something had to be done quickly and Hexadecimal rushed to the market. The market has *n* sets of numbers on sale. The virus wants to buy the following collection of sets: the number of sets in the collection should be exactly the same as the number of numbers in the union of all bought sets. Moreover, Hexadecimal wants to buy the cheapest suitable collection of set. Yet nothing's so easy! As Mainframe is a kingdom of pure rivalry markets, we know that the union of any *k* sets contains no less than *k* distinct numbers (for every positive integer *k*). Help the virus choose the suitable collection of sets. The collection can be empty. Input Specification: The first line contains the only number *n* (1<=≤<=*n*<=≤<=300) — the number of sets available in the market. Next *n* lines describe the goods: first we are given *m**i* (1<=≤<=*m**i*<=≤<=*n*) — the number of distinct numbers in the *i*-th set, then follow *m**i* numbers — the set's elements. We know that the set's elements are distinct positive integers and they do not exceed *n*. The last line contains *n* integers whose absolute values do not exceed 106 — the price of each set. Output Specification: Print a single number — the minimum price the virus will have to pay for such a collection of *k* sets that union of the collection's sets would have exactly *k* distinct numbers (). Demo Input: ['3\n1 1\n2 2 3\n1 3\n10 20 -3\n', '5\n2 1 2\n2 2 3\n2 3 4\n2 4 5\n2 5 1\n1 -1 1 -1 1\n', '5\n2 1 2\n2 2 3\n2 3 4\n2 4 5\n2 5 1\n-1 1 -1 1 -1\n'] Demo Output: ['-3\n', '0\n', '-1\n'] Note: none
934
Title: Comments Time Limit: None seconds Memory Limit: None megabytes Problem Description: A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment. When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: - at first, the text of the comment is written; - after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); - after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). For example, if the comments look like: then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: - at first, print a integer *d* — the maximum depth of nesting comments; - after that print *d* lines, the *i*-th of them corresponds to nesting level *i*; - for the *i*-th row print comments of nesting level *i* in the order of their appearance in the Policarp's comments feed, separated by space. Input Specification: The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas. It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros. The length of the whole string does not exceed 106. It is guaranteed that given structure of comments is valid. Output Specification: Print comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input. Demo Input: ['hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\n', 'a,5,A,0,a,0,A,0,a,0,A,0\n', 'A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0\n'] Demo Output: ['3\nhello test one \nok bye two \na b \n', '2\na \nA a A a A \n', '4\nA K M \nB F H L N O \nC D G I P \nE J \n'] Note: The first example is explained in the statements.
935
Title: Flag 2 Time Limit: 2 seconds Memory Limit: 128 megabytes Problem Description: According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field *n*<=×<=*m*, each square should be wholly painted one of 26 colours. The following restrictions are set: - In each row at most two different colours can be used. - No two adjacent squares can be painted the same colour. Pay attention, please, that in one column more than two different colours can be used. Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag. Input Specification: The first input line contains 2 integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following *n* lines contains *m* characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square. Output Specification: In the first line output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard. The following *n* lines should contain one of the possible variants of the new flag. Don't forget that the variant of the flag, proposed by you, should be derived from the old flag with the minimum amount of repainted squares. If the answer isn't unique, output any. Demo Input: ['3 4\naaaa\nbbbb\ncccc\n', '3 3\naba\naba\nzzz\n'] Demo Output: ['6\nabab\nbaba\nacac\n', '4\naba\nbab\nzbz\n'] Note: none
936
Title: On Changing Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a rooted tree consisting of *n* vertices numbered from 1 to *n*. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come *q* queries, each query has one of the two types: - The format of the query: 1 *v* *x* *k*. In response to the query, you need to add to the number at vertex *v* number *x*; to the numbers at the descendants of vertex *v* at distance 1, add *x*<=-<=*k*; and so on, to the numbers written in the descendants of vertex *v* at distance *i*, you need to add *x*<=-<=(*i*·*k*). The distance between two vertices is the number of edges in the shortest path between these vertices. - The format of the query: 2 *v*. In reply to the query you should print the number written in vertex *v* modulo 1000000007 (109<=+<=7). Process the queries given in the input. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105) — the number of vertices in the tree. The second line contains *n*<=-<=1 integers *p*2,<=*p*3,<=... *p**n* (1<=≤<=*p**i*<=&lt;<=*i*), where *p**i* is the number of the vertex that is the parent of vertex *i* in the tree. The third line contains integer *q* (1<=≤<=*q*<=≤<=3·105) — the number of queries. Next *q* lines contain the queries, one per line. The first number in the line is *type*. It represents the type of the query. If *type*<==<=1, then next follow space-separated integers *v*,<=*x*,<=*k* (1<=≤<=*v*<=≤<=*n*; 0<=≤<=*x*<=&lt;<=109<=+<=7; 0<=≤<=*k*<=&lt;<=109<=+<=7). If *type*<==<=2, then next follows integer *v* (1<=≤<=*v*<=≤<=*n*) — the vertex where you need to find the value of the number. Output Specification: For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109<=+<=7). Demo Input: ['3\n1 1\n3\n1 1 2 1\n2 1\n2 2\n'] Demo Output: ['2\n1\n'] Note: You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory).
937
Title: Interview with Oleg Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers. The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here. To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length. Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking! Input Specification: The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100) — the length of the interview. The second line contains the string *s* of length *n*, consisting of lowercase English letters. Output Specification: Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences. Demo Input: ['7\naogogob\n', '13\nogogmgogogogo\n', '9\nogoogoogo\n'] Demo Output: ['a***b\n', '***gmg***\n', '*********\n'] Note: The first sample contains one filler word ogogo, so the interview for printing is "a***b". The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***".
938
Title: Balance Time Limit: None seconds Memory Limit: None megabytes Problem Description: A system of *n* vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals *e*. Volume of each vessel equals *v* liters. Of course, the amount of the water in any vessel cannot exceed *v* liters in the process of transfusions. Given the initial amounts *a**i* of water in the vessels and the desired amounts *b**i* find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·*n*2. Input Specification: First line of the input contains integers *n*, *v*, *e* (1<=≤<=*n*<=≤<=300, 1<=≤<=*v*<=≤<=109, 0<=≤<=*e*<=≤<=50000). Next two lines contain *n* integers each: initial *a**i* and the desired amounts *b**i* of water in corresponding vessels (0<=≤<=*a**i*,<=*b**i*<=≤<=*v*). Next *e* lines describe one tube each in the format *x* *y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*) for a tube between vessels number *x* and *y*. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to *n* in some way. Output Specification: Print "NO" (without quotes), if such sequence of transfusions does not exist. Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions *k* (*k* should not exceed 2·*n*2). In the following *k* lines print transfusions in the format *x* *y* *d* (transfusion of *d* liters from the vessel number *x* to the vessel number *y*, *x* and *y* must be distinct). For all transfusions *d* must be a non-negative integer. Demo Input: ['2 10 1\n1 9\n5 5\n1 2\n', '2 10 0\n5 2\n4 2\n', '2 10 0\n4 2\n4 2\n'] Demo Output: ['1\n2 1 4\n', 'NO\n', '0\n'] Note: none
939
Title: Win or Freeze Time Limit: None seconds Memory Limit: None megabytes Problem Description: You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer *q*. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself. The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move. Input Specification: The first line contains the only integer *q* (1<=≤<=*q*<=≤<=1013). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Output Specification: In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them. Demo Input: ['6\n', '30\n', '1\n'] Demo Output: ['2\n', '1\n6\n', '1\n0\n'] Note: Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.
940
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has *n* clock stations, station number *i* is at point (*x**i*,<=*y**i*) of the plane. As the player visits station number *i*, he increases the current time on his timer by *a**i*. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow. A player spends *d*·*dist* time units to move between stations, where *dist* is the distance the player has covered and *d* is some constant. The distance between stations *i* and *j* is determined as |*x**i*<=-<=*x**j*|<=+<=|*y**i*<=-<=*y**j*|. Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units). Now Yaroslav is wondering, how much money he needs to get to station *n*. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small. Input Specification: The first line contains integers *n* and *d* (3<=≤<=*n*<=≤<=100,<=103<=≤<=*d*<=≤<=105) — the number of stations and the constant from the statement. The second line contains *n*<=-<=2 integers: *a*2,<=*a*3,<=...,<=*a**n*<=-<=1 (1<=≤<=*a**i*<=≤<=103). The next *n* lines contain the coordinates of the stations. The *i*-th of them contains two integers *x**i*, *y**i* (-100<=≤<=*x**i*,<=*y**i*<=≤<=100). It is guaranteed that no two stations are located at the same point. Output Specification: In a single line print an integer — the answer to the problem. Demo Input: ['3 1000\n1000\n0 0\n0 1\n0 3\n', '3 1000\n1000\n1 0\n1 1\n1 2\n'] Demo Output: ['2000\n', '1000\n'] Note: none
941
Title: Co-prime Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array of *n* elements, you must make it a co-prime array in as few moves as possible. In each move you can insert any positive integral number you want not greater than 109 in any place in the array. An array is co-prime if any two adjacent numbers of it are co-prime. In the number theory, two integers *a* and *b* are said to be co-prime if the only positive integer that divides both of them is 1. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — the number of elements in the given array. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the elements of the array *a*. Output Specification: Print integer *k* on the first line — the least number of elements needed to add to the array *a* to make it co-prime. The second line should contain *n*<=+<=*k* integers *a**j* — the elements of the array *a* after adding *k* elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array *a* by adding *k* elements to it. If there are multiple answers you can print any one of them. Demo Input: ['3\n2 7 28\n'] Demo Output: ['1\n2 7 9 28\n'] Note: none
942
Title: Mahmoud and Ehab and the even-odd game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer *n* and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer *a* and subtract it from *n* such that: - 1<=≤<=*a*<=≤<=*n*. - If it's Mahmoud's turn, *a* has to be even, but if it's Ehab's turn, *a* has to be odd. If the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally? Input Specification: The only line contains an integer *n* (1<=≤<=*n*<=≤<=109), the number at the beginning of the game. Output Specification: Output "Mahmoud" (without quotes) if Mahmoud wins and "Ehab" (without quotes) otherwise. Demo Input: ['1\n', '2\n'] Demo Output: ['Ehab', 'Mahmoud'] Note: In the first sample, Mahmoud can't choose any integer *a* initially because there is no positive even integer less than or equal to 1 so Ehab wins. In the second sample, Mahmoud has to choose *a* = 2 and subtract it from *n*. It's Ehab's turn and *n* = 0. There is no positive odd integer less than or equal to 0 so Mahmoud wins.
943
Title: Santa Claus and a Palindrome Time Limit: None seconds Memory Limit: None megabytes Problem Description: Santa Claus likes palindromes very much. There was his birthday recently. *k* of his friends came to him to congratulate him, and each of them presented to him a string *s**i* having the same length *n*. We denote the beauty of the *i*-th string by *a**i*. It can happen that *a**i* is negative — that means that Santa doesn't find this string beautiful at all. Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length *n*. Recall that a palindrome is a string that doesn't change after one reverses it. Since the empty string is a palindrome too, the answer can't be negative. Even if all *a**i*'s are negative, Santa can obtain the empty string. Input Specification: The first line contains two positive integers *k* and *n* divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1<=≤<=*k*,<=*n*<=≤<=100<=000; *n*·*k* <=≤<=100<=000). *k* lines follow. The *i*-th of them contains the string *s**i* and its beauty *a**i* (<=-<=10<=000<=≤<=*a**i*<=≤<=10<=000). The string consists of *n* lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties. Output Specification: In the only line print the required maximum possible beauty. Demo Input: ['7 3\nabb 2\naaa -3\nbba -1\nzyz -4\nabb 5\naaa 7\nxyx 4\n', '3 1\na 1\na 2\na 3\n', '2 5\nabcde 10000\nabcde 10000\n'] Demo Output: ['12\n', '6\n', '0\n'] Note: In the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).
944
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with *n* rows and *m* columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column. To win the level, after all the moves, the number in the cell at the *i*-th row and *j*-th column should be equal to *g**i*,<=*j*. Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! Input Specification: The first line of input contains two integers, *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100), the number of rows and the number of columns in the grid, respectively. The next *n* lines each contain *m* integers. In particular, the *j*-th integer in the *i*-th of these rows contains *g**i*,<=*j* (0<=≤<=*g**i*,<=*j*<=≤<=500). Output Specification: If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer *k*, the minimum number of moves necessary to beat the level. The next *k* lines should each contain one of the following, describing the moves in the order they must be done: - row *x*, (1<=≤<=*x*<=≤<=*n*) describing a move of the form "choose the *x*-th row". - col *x*, (1<=≤<=*x*<=≤<=*m*) describing a move of the form "choose the *x*-th column". If there are multiple optimal solutions, output any one of them. Demo Input: ['3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1\n', '3 3\n0 0 0\n0 1 0\n0 0 0\n', '3 3\n1 1 1\n1 1 1\n1 1 1\n'] Demo Output: ['4\nrow 1\nrow 1\ncol 4\nrow 3\n', '-1\n', '3\nrow 1\nrow 2\nrow 3\n'] Note: In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center. In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.
945
Title: String Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day in the IT lesson Anna and Maria learned about the lexicographic order. String *x* is lexicographically less than string *y*, if either *x* is a prefix of *y* (and *x*<=≠<=*y*), or there exists such *i* (1<=≤<=*i*<=≤<=*min*(|*x*|,<=|*y*|)), that *x**i*<=&lt;<=*y**i*, and for any *j* (1<=≤<=*j*<=&lt;<=*i*) *x**j*<==<=*y**j*. Here |*a*| denotes the length of the string *a*. The lexicographic comparison of strings is implemented by operator &lt; in modern programming languages​​. The teacher gave Anna and Maria homework. She gave them a string of length *n*. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the *k*-th string from the list. Help Anna and Maria do the homework. Input Specification: The first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer *k* (1<=≤<=*k*<=≤<=105). Output Specification: Print the string Anna and Maria need — the *k*-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than *k*, print a string saying "No such line." (without the quotes). Demo Input: ['aa\n2\n', 'abc\n5\n', 'abab\n7\n'] Demo Output: ['a\n', 'bc\n', 'b\n'] Note: In the second sample before string "bc" follow strings "a", "ab", "abc", "b".
946
Title: Homework Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of *n* small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than *k* characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than *k* characters are deleted. You also have to find any possible way to delete the characters. Input Specification: The first input data line contains a string whose length is equal to *n* (1<=≤<=*n*<=≤<=105). The string consists of lowercase Latin letters. The second line contains the number *k* (0<=≤<=*k*<=≤<=105). Output Specification: Print on the first line the only number *m* — the least possible number of different characters that could remain in the given string after it loses no more than *k* characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly *m* distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly *m* distinct characters, print any of them. Demo Input: ['aaaaa\n4\n', 'abacaba\n4\n', 'abcdefgh\n10\n'] Demo Output: ['1\naaaaa\n', '1\naaaa\n', '0\n\n'] Note: In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length. In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string. In the third sample you are given a line whose length is equal to 8, and *k* = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string.
947
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly *n* exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a student can take the exam for the *i*-th subject on the day number *a**i*. However, Valera has made an arrangement with each teacher and the teacher of the *i*-th subject allowed him to take an exam before the schedule time on day *b**i* (*b**i*<=&lt;<=*a**i*). Thus, Valera can take an exam for the *i*-th subject either on day *a**i*, or on day *b**i*. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number *a**i*. Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date. Input Specification: The first line contains a single positive integer *n* (1<=≤<=*n*<=≤<=5000) — the number of exams Valera will take. Each of the next *n* lines contains two positive space-separated integers *a**i* and *b**i* (1<=≤<=*b**i*<=&lt;<=*a**i*<=≤<=109) — the date of the exam in the schedule and the early date of passing the *i*-th exam, correspondingly. Output Specification: Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date. Demo Input: ['3\n5 2\n3 1\n4 2\n', '3\n6 1\n5 2\n4 3\n'] Demo Output: ['2\n', '6\n'] Note: In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5. In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject.
948
Title: Polycarp and Hay Time Limit: None seconds Memory Limit: None megabytes Problem Description: The farmer Polycarp has a warehouse with hay, which can be represented as an *n*<=×<=*m* rectangular table, where *n* is the number of rows, and *m* is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the *i*-th row and the *j*-th column is equal to an integer *a**i*,<=*j* and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1<=×<=1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack. Polycarp wants the following requirements to hold after the reorganization: - the total amount of hay remaining in the warehouse must be equal to *k*, - the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same, - the height of at least one stack must remain the same as it was, - for the stability of the remaining structure all the stacks should form one connected region. The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area. Help Polycarp complete this challenging task or inform that it is impossible. Input Specification: The first line of the input contains three integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=1000) and *k* (1<=≤<=*k*<=≤<=1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization. Then *n* lines follow, each containing *m* positive integers *a**i*,<=*j* (1<=≤<=*a**i*,<=*j*<=≤<=109), where *a**i*,<=*j* is equal to the number of cubic meters of hay making the hay stack on the *i*-th row and *j*-th column of the table. Output Specification: In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next *n* lines print *m* numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered. If there are multiple answers, print any of them. Demo Input: ['2 3 35\n10 4 9\n9 9 7\n', '4 4 50\n5 9 1 1\n5 1 1 5\n5 1 5 5\n5 5 7 1\n', '2 4 12\n1 1 3 1\n1 6 2 4\n'] Demo Output: ['YES\n7 0 7 \n7 7 7 \n', 'YES\n5 5 0 0 \n5 0 0 5 \n5 0 5 5 \n5 5 5 0 \n', 'NO\n'] Note: In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value *k* = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
949
Title: Pride Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have an array *a* with length *n*, you can perform operations. Each operation is like this: choose two adjacent elements from *a*, say *x* and *y*, and replace one of them with *gcd*(*x*,<=*y*), where *gcd* denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). What is the minimum number of operations you need to make all of the elements equal to 1? Input Specification: The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=2000) — the number of elements in the array. The second line contains *n* space separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the elements of the array. Output Specification: Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1. Demo Input: ['5\n2 2 3 4 6\n', '4\n2 4 6 8\n', '3\n2 6 9\n'] Demo Output: ['5\n', '-1\n', '4\n'] Note: In the first sample you can turn all numbers to 1 using the following 5 moves: - [2, 2, 3, 4, 6]. - [2, 1, 3, 4, 6] - [2, 1, 3, 1, 6] - [2, 1, 1, 1, 6] - [1, 1, 1, 1, 6] - [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
950
Title: Trees in a Row Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Queen of England has *n* trees growing in a row in her garden. At that, the *i*-th (1<=≤<=*i*<=≤<=*n*) tree from the left has height *a**i* meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all *i* (1<=≤<=*i*<=&lt;<=*n*), *a**i*<=+<=1<=-<=*a**i*<==<=*k*, where *k* is the number the Queen chose. Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes? Input Specification: The first line contains two space-separated integers: *n*, *k* (1<=≤<=*n*,<=*k*<=≤<=1000). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000) — the heights of the trees in the row. Output Specification: In the first line print a single integer *p* — the minimum number of minutes the gardener needs. In the next *p* lines print the description of his actions. If the gardener needs to increase the height of the *j*-th (1<=≤<=*j*<=≤<=*n*) tree from the left by *x* (*x*<=≥<=1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the *j*-th (1<=≤<=*j*<=≤<=*n*) tree from the left by *x* (*x*<=≥<=1) meters, print on the corresponding line "- j x". If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them. Demo Input: ['4 1\n1 2 1 5\n', '4 1\n1 2 3 4\n'] Demo Output: ['2\n+ 3 2\n- 4 1\n', '0\n'] Note: none
951
Title: Reducing Fractions Time Limit: None seconds Memory Limit: None megabytes Problem Description: To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. Input Specification: The first input line contains two space-separated integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=107) — the numbers that are multiplied to produce the numerator. The third line contains *m* space-separated integers: *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=107) — the numbers that are multiplied to produce the denominator. Output Specification: Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print *n**out*,<=*m**out* must satisfy the inequality 1<=≤<=*n**out*,<=*m**out*<=≤<=105, and the actual values in the sets *a**out*,<=*i* and *b**out*,<=*i* must satisfy the inequality 1<=≤<=*a**out*,<=*i*,<=*b**out*,<=*i*<=≤<=107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer *x* (*x*<=&gt;<=1), that the numerator and the denominator of the printed fraction are divisible by *x*. If there are several matching answers, print any of them. Demo Input: ['3 2\n100 5 2\n50 10\n', '4 3\n2 5 10 20\n100 1 3\n'] Demo Output: ['2 3\n2 1\n1 1 1\n', '1 1\n20\n3\n'] Note: In the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1. In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3.
952
Title: Spit Problem Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the amount of camels in the zoo. Each of the following *n* lines contains two integers *x**i* and *d**i* (<=-<=104<=≤<=*x**i*<=≤<=104,<=1<=≤<=|*d**i*|<=≤<=2·104) — records in Bob's notepad. *x**i* is a position of the *i*-th camel, and *d**i* is a distance at which the *i*-th camel spitted. Positive values of *d**i* correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position. Output Specification: If there are two camels, which spitted at each other, output YES. Otherwise, output NO. Demo Input: ['2\n0 1\n1 -1\n', '3\n0 1\n1 1\n2 -2\n', '5\n2 -10\n3 10\n0 5\n5 -5\n10 1\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n'] Note: none
953
Title: Martian Food Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Have you ever tasted Martian food? Well, you should. Their signature dish is served on a completely black plate with the radius of *R*, flat as a pancake. First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of *r* and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians. Then a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians. Further, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius. Each of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border. To determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the *k*-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy? Input Specification: The first line contains integer *t* (1<=≤<=*t*<=≤<=104) — amount of testcases. Each of the following *t* lines contain three positive integers: the radii of the plate and a portion of the Golden Honduras *R* and *r* (1<=≤<=*r*<=&lt;<=*R*<=≤<=104) and the number *k* (1<=≤<=*k*<=≤<=104). In the pretests 1<=≤<=*k*<=≤<=2. Output Specification: Print *t* lines — the radius of the *k*-th portion of the Green Bull Terrier for each test. The absolute or relative error of the answer should not exceed 10<=-<=6. Demo Input: ['2\n4 3 1\n4 2 2\n'] Demo Output: ['0.9230769231\n0.6666666667\n'] Note: Dish from the first sample looks like this: <img class="tex-graphics" src="https://espresso.codeforces.com/e15f6caf257ceae8305cd82507b96dfac1b579ee.png" style="max-width: 100.0%;max-height: 100.0%;"/> Dish from the second sample looks like this: <img class="tex-graphics" src="https://espresso.codeforces.com/625a74ccb42332c9df05a22f8e17f81f086476d5.png" style="max-width: 100.0%;max-height: 100.0%;"/>
954
Title: Party Lemonade Time Limit: None seconds Memory Limit: None megabytes Problem Description: A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity. Your favorite store sells lemonade in bottles of *n* different volumes at different costs. A single bottle of type *i* has volume 2*i*<=-<=1 liters and costs *c**i* roubles. The number of bottles of each type in the store can be considered infinite. You want to buy at least *L* liters of lemonade. How many roubles do you have to spend? Input Specification: The first line contains two integers *n* and *L* (1<=≤<=*n*<=≤<=30; 1<=≤<=*L*<=≤<=109) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively. The second line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=109) — the costs of bottles of different types. Output Specification: Output a single integer — the smallest number of roubles you have to pay in order to buy at least *L* liters of lemonade. Demo Input: ['4 12\n20 30 70 90\n', '4 3\n10000 1000 100 10\n', '4 3\n10 100 1000 10000\n', '5 787787787\n123456789 234567890 345678901 456789012 987654321\n'] Demo Output: ['150\n', '10\n', '30\n', '44981600785557577\n'] Note: In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles. In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles. In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.
955
Title: MUH and Cube Walls Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights. Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of *w* towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of *n* towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of *w* contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification). Your task is to count the number of segments where Horace can "see an elephant". Input Specification: The first line contains two integers *n* and *w* (1<=≤<=*n*,<=*w*<=≤<=2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the heights of the towers in the bears' wall. The third line contains *w* integers *b**i* (1<=≤<=*b**i*<=≤<=109) — the heights of the towers in the elephant's wall. Output Specification: Print the number of segments in the bears' wall where Horace can "see an elephant". Demo Input: ['13 5\n2 4 5 5 4 3 2 2 2 3 3 2 1\n3 4 4 3 2\n'] Demo Output: ['2'] Note: The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
956
Title: Minimum Sum Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya has *n* positive integers *a*1,<=*a*2,<=...,<=*a**n*. His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'. Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1<=000) — the number of Petya's numbers. Each of the following lines contains non-empty string *s**i* consisting of lowercase Latin letters from 'a' to 'j' — the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters. Output Specification: Determine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests. Demo Input: ['3\nab\nde\naj\n', '5\nabcdef\nghij\nbdef\naccbd\ng\n', '3\naa\njj\naa\n'] Demo Output: ['47\n', '136542\n', '44\n'] Note: In the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10, 23, 14]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration. In the second example the numbers after the restoration can look like: [120468, 3579, 2468, 10024, 3]. In the second example the numbers after the restoration can look like: [11, 22, 11].
957
Title: Pillars Time Limit: None seconds Memory Limit: None megabytes Problem Description: Marmot found a row with *n* pillars. The *i*-th pillar has the height of *h**i* meters. Starting from one pillar *i*1, Marmot wants to jump on the pillars *i*2, ..., *i**k*. (1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n*). From a pillar *i* Marmot can jump on a pillar *j* only if *i*<=&lt;<=*j* and |*h**i*<=-<=*h**j*|<=≥<=*d*, where |*x*| is the absolute value of the number *x*. Now Marmot is asking you find out a jump sequence with maximal length and print it. Input Specification: The first line contains two integers *n* and *d* (1<=≤<=*n*<=≤<=105, 0<=≤<=*d*<=≤<=109). The second line contains *n* numbers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=1015). Output Specification: The first line should contain one integer *k*, the maximal length of a jump sequence. The second line should contain *k* integers *i*1,<=*i*2,<=...,<=*i**k* (1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n*), representing the pillars' indices from the maximal length jump sequence. If there is more than one maximal length jump sequence, print any. Demo Input: ['5 2\n1 3 6 7 4\n', '10 3\n2 1 3 6 9 11 7 3 20 18\n'] Demo Output: ['4\n1 2 3 5 \n', '6\n1 4 6 7 8 9 \n'] Note: In the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.
958
Title: Writing Code Time Limit: None seconds Memory Limit: None megabytes Problem Description: Programmers working on a large project have just received a task to write exactly *m* lines of code. There are *n* programmers working on a project, the *i*-th of them makes exactly *a**i* bugs in every line of code that he writes. Let's call a sequence of non-negative integers *v*1,<=*v*2,<=...,<=*v**n* a plan, if *v*1<=+<=*v*2<=+<=...<=+<=*v**n*<==<=*m*. The programmers follow the plan like that: in the beginning the first programmer writes the first *v*1 lines of the given task, then the second programmer writes *v*2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most *b* bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer *mod*. Input Specification: The first line contains four integers *n*, *m*, *b*, *mod* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*b*<=≤<=500; 1<=≤<=*mod*<=≤<=109<=+<=7) — the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=500) — the number of bugs per line for each programmer. Output Specification: Print a single integer — the answer to the problem modulo *mod*. Demo Input: ['3 3 3 100\n1 1 1\n', '3 6 5 1000000007\n1 2 3\n', '3 5 6 11\n1 2 1\n'] Demo Output: ['10\n', '0\n', '0\n'] Note: none
959
Title: Square Table Time Limit: None seconds Memory Limit: None megabytes Problem Description: While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size *n*<=×<=*m*, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square. Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100)  — the size of the table. Output Specification: Print the table that meets the condition: *n* lines containing *m* integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer. Demo Input: ['1 1\n', '1 2\n'] Demo Output: ['1', '3 4'] Note: none
960
Title: Dima and Figure Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures. A piece of squared paper of size *n*<=×<=*m* is represented by a table, consisting of *n* rows and *m* columns. All squares are white on blank squared paper. Dima defines a picture as an image on a blank piece of paper, obtained by painting some squares black. The picture portrays one of Dima's favorite figures, if the following conditions hold: - The picture contains at least one painted cell; - All painted cells form a connected set, that is, you can get from any painted cell to any other one (you can move from one cell to a side-adjacent one); - The minimum number of moves needed to go from the painted cell at coordinates (*x*1,<=*y*1) to the painted cell at coordinates (*x*2,<=*y*2), moving only through the colored cells, equals |*x*1<=-<=*x*2|<=+<=|*y*1<=-<=*y*2|. Now Dima is wondering: how many paintings are on an *n*<=×<=*m* piece of paper, that depict one of his favorite figures? Count this number modulo 1000000007 (109<=+<=7). Input Specification: The first line contains two integers *n* and *m* — the sizes of the piece of paper (1<=≤<=*n*,<=*m*<=≤<=150). Output Specification: In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109<=+<=7). Demo Input: ['2 2\n', '3 4\n'] Demo Output: ['13\n', '571\n'] Note: none
961
Title: Buy Low Sell High Time Limit: None seconds Memory Limit: None megabytes Problem Description: You can perfectly predict the price of a certain stock for the next *N* days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the *N* days you would like to again own zero shares, but want to have as much money as possible. Input Specification: Input begins with an integer *N* (2<=≤<=*N*<=≤<=3·105), the number of days. Following this is a line with exactly *N* integers *p*1,<=*p*2,<=...,<=*p**N* (1<=≤<=*p**i*<=≤<=106). The price of one share of stock on the *i*-th day is given by *p**i*. Output Specification: Print the maximum amount of money you can end up with at the end of *N* days. Demo Input: ['9\n10 5 4 7 9 12 6 2 10\n', '20\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4\n'] Demo Output: ['20\n', '41\n'] Note: In the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is  - 5 - 4 + 9 + 12 - 2 + 10 = 20.
962
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut *n* trees with heights *a*1,<=*a*2,<=...,<=*a**n*. They bought a chain saw from a shop. Each time they use the chain saw on the tree number *i*, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is *i* (the tree that have height *a**i* in the beginning), then the cost of charging the chain saw would be *b**i*. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each *i* &lt; *j*, *a**i*<=&lt;<=*a**j* and *b**i*<=&gt;<=*b**j* and also *b**n*<==<=0 and *a*1<==<=1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you? Input Specification: The first line of input contains an integer *n* (1<=≤<=*n*<=≤<=105). The second line of input contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). The third line of input contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (0<=≤<=*b**i*<=≤<=109). It's guaranteed that *a*1<==<=1, *b**n*<==<=0, *a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n* and *b*1<=&gt;<=*b*2<=&gt;<=...<=&gt;<=*b**n*. Output Specification: The only line of output must contain the minimum cost of cutting all the trees completely. 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: ['5\n1 2 3 4 5\n5 4 3 2 0\n', '6\n1 2 3 10 20 30\n6 5 4 3 2 0\n'] Demo Output: ['25\n', '138\n'] Note: none
963
Title: Display Size Time Limit: None seconds Memory Limit: None megabytes Problem Description: A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that: - there are exactly *n* pixels on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible. Input Specification: The first line contains the positive integer *n* (1<=≤<=*n*<=≤<=106) — the number of pixels display should have. Output Specification: Print two integers — the number of rows and columns on the display. Demo Input: ['8\n', '64\n', '5\n', '999999\n'] Demo Output: ['2 4\n', '8 8\n', '1 5\n', '999 1001\n'] Note: In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels. In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels. In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels.
964
Title: The Monster Time Limit: None seconds Memory Limit: None megabytes Problem Description: A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times *b*,<=*b*<=+<=*a*,<=*b*<=+<=2*a*,<=*b*<=+<=3*a*,<=... and Morty screams at times *d*,<=*d*<=+<=*c*,<=*d*<=+<=2*c*,<=*d*<=+<=3*c*,<=.... The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time. Input Specification: The first line of input contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=100). The second line contains two integers *c* and *d* (1<=≤<=*c*,<=*d*<=≤<=100). Output Specification: Print the first time Rick and Morty will scream at the same time, or <=-<=1 if they will never scream at the same time. Demo Input: ['20 2\n9 19\n', '2 1\n16 12\n'] Demo Output: ['82\n', '-1\n'] Note: In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82. In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
965
Title: Queries on a String Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *s* and should process *m* queries. Each query is described by two 1-based indices *l**i*, *r**i* and integer *k**i*. It means that you should cyclically shift the substring *s*[*l**i*... *r**i*] *k**i* times. The queries should be processed one after another in the order they are given. One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right. For example, if the string *s* is abacaba and the query is *l*1<==<=3,<=*r*1<==<=6,<=*k*1<==<=1 then the answer is abbacaa. If after that we would process the query *l*2<==<=1,<=*r*2<==<=4,<=*k*2<==<=2 then we would get the string baabcaa. Input Specification: The first line of the input contains the string *s* (1<=≤<=|*s*|<=≤<=10<=000) in its initial state, where |*s*| stands for the length of *s*. It contains only lowercase English letters. Second line contains a single integer *m* (1<=≤<=*m*<=≤<=300) — the number of queries. The *i*-th of the next *m* lines contains three integers *l**i*, *r**i* and *k**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=|*s*|,<=1<=≤<=*k**i*<=≤<=1<=000<=000) — the description of the *i*-th query. Output Specification: Print the resulting string *s* after processing all *m* queries. Demo Input: ['abacaba\n2\n3 6 1\n1 4 2\n'] Demo Output: ['baabcaa\n'] Note: The sample is described in problem statement.
966
Title: Secret Combination Time Limit: None seconds Memory Limit: None megabytes Problem Description: You got a box with a combination lock. The lock has a display showing *n* digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068. You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of digits on the display. The second line contains *n* digits — the initial state of the display. Output Specification: Print a single line containing *n* digits — the desired state of the display containing the smallest possible number. Demo Input: ['3\n579\n', '4\n2014\n'] Demo Output: ['024\n', '0142\n'] Note: none
967
Title: Kojiro and Furrari Time Limit: None seconds Memory Limit: None megabytes Problem Description: Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her. Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point *f* of a coordinate line, and Johanna is at point *e*. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers *t**i* and *x**i* — the number of the gas type and its position. One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly *s* liters of fuel (regardless of the type of fuel). At the moment of departure from point *f* Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than *s* liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right. To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from *f* to *e*, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95. Write a program that can for the *m* possible positions of the start *f**i* minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95. Input Specification: The first line of the input contains four positive integers *e*,<=*s*,<=*n*,<=*m* (1<=≤<=*e*,<=*s*<=≤<=109,<=1<=≤<=*n*,<=*m*<=≤<=2·105) — the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points. Next *n* lines contain two integers each *t**i*,<=*x**i* (1<=≤<=*t**i*<=≤<=3,<=<=-<=109<=≤<=*x**i*<=≤<=109), representing the type of the *i*-th gas station (1 represents Regular-92, 2 — Premium-95 and 3 — Super-98) and the position on a coordinate line of the *i*-th gas station. Gas stations don't necessarily follow in order from left to right. The last line contains *m* integers *f**i* (<=-<=109<=≤<=*f**i*<=&lt;<=*e*). Start positions don't necessarily follow in order from left to right. No point of the coordinate line contains more than one gas station. It is possible that some of points *f**i* or point *e* coincide with a gas station. Output Specification: Print exactly *m* lines. The *i*-th of them should contain two integers — the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point *f**i*. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value. If there is no way to get to Johanna from point *f**i*, the *i*-th line should look like that "-1 -1" (two numbers minus one without the quotes). Demo Input: ['8 4 1 1\n2 4\n0\n', '9 3 2 3\n2 3\n1 6\n-1 0 1\n', '20 9 2 4\n1 5\n2 10\n-1 0 1 2\n'] Demo Output: ['0 4\n', '-1 -1\n3 3\n3 2\n', '-1 -1\n-1 -1\n-1 -1\n-1 -1\n'] Note: none
968
Title: George and Interesting Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: - The graph doesn't contain any multiple arcs; - There is vertex *v* (we'll call her the center), such that for any vertex of graph *u*, the graph contains arcs (*u*,<=*v*) and (*v*,<=*u*). Please note that the graph also contains loop (*v*,<=*v*). - The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex *u* is the number of arcs that go out of *u*, the indegree of vertex *u* is the number of arcs that go in *u*. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of *n* vertices and *m* arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input Specification: The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*<=≤<=500,<=1<=≤<=*m*<=≤<=1000) — the number of vertices and arcs in the presented graph. Each of the next *m* lines contains two space-separated integers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) — the descriptions of the graph's arcs. Pair (*a**i*,<=*b**i*) means that the graph contains an arc from vertex number *a**i* to vertex number *b**i*. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through *n*. Output Specification: Print a single integer — the answer to George's question. Demo Input: ['3 7\n1 1\n2 2\n3 1\n1 3\n3 2\n2 3\n3 3\n', '3 6\n1 1\n2 2\n3 1\n3 2\n2 3\n3 3\n', '3 1\n2 2\n'] Demo Output: ['0\n', '1\n', '6\n'] Note: For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3.
969
Title: Help Shrek and Donkey Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Shrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds *m* cards and the Donkey holds *n* cards (the players do not see each other's cards), and one more card lies on the table face down so that both players cannot see it as well. Thus, at the beginning of the game there are overall *m*<=+<=*n*<=+<=1 cards. Besides, the players know which cards the pack of cards consists of and their own cards (but they do not know which card lies on the table and which ones the other player has). The players move in turn and Shrek starts. During a move a player can: - Try to guess which card is lying on the table. If he guesses correctly, the game ends and he wins. If his guess is wrong, the game also ends but this time the other player wins.- Name any card from the pack. If the other player has such card, he must show it and put it aside (so that this card is no longer used in the game). If the other player doesn't have such card, he says about that. Help Shrek assuming the pills are good in quality and that both players using them start playing in the optimal manner. Input Specification: The first line contains space-separated integers *m* and *n* (0<=≤<=*m*,<=*n*<=≤<=1000). Output Specification: Print space-separated probabilities that Shrek wins and Donkey wins correspondingly; the absolute error should not exceed 10<=-<=9. Demo Input: ['0 3\n', '1 0\n', '1 1\n'] Demo Output: ['0.25 0.75\n', '1 0\n', '0.5 0.5\n'] Note: none
970
Title: Dima and Trap Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal... Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node. A trap graph is an undirected graph consisting of *n* nodes and *m* edges. For edge number *k*, Dima denoted a range of integers from *l**k* to *r**k* (*l**k*<=≤<=*r**k*). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it *x*), then Seryozha must go some way from the starting node with number 1 to the final node with number *n*. At that, Seryozha can go along edge *k* only if *l**k*<=≤<=*x*<=≤<=*r**k*. Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the *n*-th one as the number of integers *x*, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible! Input Specification: The first line of the input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=103,<=0<=≤<=*m*<=≤<=3·103). Then follow *m* lines describing the edges. Each line contains four integers *a**k*, *b**k*, *l**k* and *r**k* (1<=≤<=*a**k*,<=*b**k*<=≤<=*n*,<=1<=≤<=*l**k*<=≤<=*r**k*<=≤<=106). The numbers mean that in the trap graph the *k*-th edge connects nodes *a**k* and *b**k*, this edge corresponds to the range of integers from *l**k* to *r**k*. Note that the given graph can have loops and multiple edges. Output Specification: In a single line of the output print an integer — the maximum loyalty among all paths from the first node to the *n*-th one. If such paths do not exist or the maximum loyalty equals 0, print in a single line "Nice work, Dima!" without the quotes. Demo Input: ['4 4\n1 2 1 10\n2 4 3 5\n1 3 1 5\n2 4 2 7\n', '5 6\n1 2 1 10\n2 5 11 20\n1 4 2 5\n1 3 10 11\n3 4 12 10000\n4 5 6 6\n'] Demo Output: ['6\n', 'Nice work, Dima!\n'] Note: Explanation of the first example. Overall, we have 2 ways to get from node 1 to node 4: first you must go along the edge 1-2 with range [1-10], then along one of the two edges 2-4. One of them contains range [3-5], that is, we can pass through with numbers 3, 4, 5. So the loyalty of such path is 3. If we go along edge 2-4 with range [2-7], then we can pass through with numbers 2, 3, 4, 5, 6, 7. The loyalty is 6. That is the answer. The edge 1-2 have no influence on the answer because its range includes both ranges of the following edges.
971
Title: Grandfather Dovlet’s calculator Time Limit: None seconds Memory Limit: None megabytes Problem Description: Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)). Max starts to type all the values from *a* to *b*. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator. For example if *a*<==<=1 and *b*<==<=3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12. Input Specification: The only line contains two integers *a*,<=*b* (1<=≤<=*a*<=≤<=*b*<=≤<=106) — the first and the last number typed by Max. Output Specification: Print the only integer *a* — the total number of printed segments. Demo Input: ['1 3\n', '10 15\n'] Demo Output: ['12\n', '39\n'] Note: none
972
Title: Reflection Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: For each positive integer *n* consider the integer ψ(*n*) which is obtained from *n* by replacing every digit *a* in the decimal notation of *n* with the digit (9<=<=-<=<=*a*). We say that ψ(*n*) is the reflection of *n*. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals 0, reflection of 91 equals 8. Let us call the weight of the number the product of the number and its reflection. Thus, the weight of the number 10 is equal to 10·89<==<=890. Your task is to find the maximum weight of the numbers in the given range [*l*,<=*r*] (boundaries are included). Input Specification: Input contains two space-separated integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=109) — bounds of the range. Output Specification: Output should contain single integer number: maximum value of the product *n*·ψ(*n*), where *l*<=≤<=*n*<=≤<=*r*. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d). Demo Input: ['3 7\n', '1 1\n', '8 10\n'] Demo Output: ['20', '8', '890'] Note: In the third sample weight of 8 equals 8·1 = 8, weight of 9 equals 9·0 = 0, weight of 10 equals 890. Thus, maximum value of the product is equal to 890.
973
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sergey attends lessons of the *N*-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the *N*-ish language. Sentences of the *N*-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of *N*-ish. The spelling rules state that *N*-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair. Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa". Input Specification: The first line contains a non-empty string *s*, consisting of lowercase Latin letters — that's the initial sentence in *N*-ish, written by Sergey. The length of string *s* doesn't exceed 105. The next line contains integer *k* (0<=≤<=*k*<=≤<=13) — the number of forbidden pairs of letters. Next *k* lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair. Output Specification: Print the single number — the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters. Demo Input: ['ababa\n1\nab\n', 'codeforces\n2\ndo\ncs\n'] Demo Output: ['2\n', '1\n'] Note: In the first sample you should remove two letters b. In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
974
Title: Worms Time Limit: None seconds Memory Limit: None megabytes Problem Description: It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch. Marmot brought Mole *n* ordered piles of worms such that *i*-th pile contains *a**i* worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to *a*1, worms in second pile are labeled with numbers *a*1<=+<=1 to *a*1<=+<=*a*2 and so on. See the example for a better understanding. Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained. Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105), the number of piles. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=103, *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<=≤<=106), where *a**i* is the number of worms in the *i*-th pile. The third line contains single integer *m* (1<=≤<=*m*<=≤<=105), the number of juicy worms said by Marmot. The fourth line contains *m* integers *q*1,<=*q*2,<=...,<=*q**m* (1<=≤<=*q**i*<=≤<=*a*1<=+<=*a*2<=+<=...<=+<=*a**n*), the labels of the juicy worms. Output Specification: Print *m* lines to the standard output. The *i*-th line should contain an integer, representing the number of the pile where the worm labeled with the number *q**i* is. Demo Input: ['5\n2 7 3 4 9\n3\n1 25 11\n'] Demo Output: ['1\n5\n3\n'] Note: For the sample input: - The worms with labels from [1, 2] are in the first pile. - The worms with labels from [3, 9] are in the second pile. - The worms with labels from [10, 12] are in the third pile. - The worms with labels from [13, 16] are in the fourth pile. - The worms with labels from [17, 25] are in the fifth pile.
975
Title: XOR on Segment Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got an array *a*, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. You are allowed to perform two operations on this array: 1. Calculate the sum of current array elements on the segment [*l*,<=*r*], that is, count value *a**l*<=+<=*a**l*<=+<=1<=+<=...<=+<=*a**r*. 1. Apply the xor operation with a given number *x* to each array element on the segment [*l*,<=*r*], that is, execute . This operation changes exactly *r*<=-<=*l*<=+<=1 array elements. Expression means applying bitwise xor operation to numbers *x* and *y*. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor". You've got a list of *m* operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the size of the array. The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=106) — the original array. The third line contains integer *m* (1<=≤<=*m*<=≤<=5·104) — the number of operations with the array. The *i*-th of the following *m* lines first contains an integer *t**i* (1<=≤<=*t**i*<=≤<=2) — the type of the *i*-th query. If *t**i*<==<=1, then this is the query of the sum, if *t**i*<==<=2, then this is the query to change array elements. If the *i*-th operation is of type 1, then next follow two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). If the *i*-th operation is of type 2, then next follow three integers *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*x**i*<=≤<=106). The numbers on the lines are separated by single spaces. Output Specification: For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input. 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: ['5\n4 10 3 13 7\n8\n1 2 4\n2 1 3 3\n1 2 4\n1 3 3\n2 2 5 5\n1 1 5\n2 1 2 10\n1 2 3\n', '6\n4 7 4 0 7 3\n5\n2 2 3 8\n1 1 5\n2 3 5 1\n2 4 5 6\n1 2 3\n'] Demo Output: ['26\n22\n0\n34\n11\n', '38\n28\n'] Note: none
976
Title: Art Union Time Limit: None seconds Memory Limit: None megabytes Problem Description: A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time. Order is important everywhere, so the painters' work is ordered by the following rules: - Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=&lt;<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale. Input Specification: The first line of the input contains integers *m*,<=*n* (1<=≤<=*m*<=≤<=50000,<=1<=≤<=*n*<=≤<=5), where *m* is the number of pictures and *n* is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains *n* integers *t**i*1,<=*t**i*2,<=...,<=*t**in* (1<=≤<=*t**ij*<=≤<=1000), where *t**ij* is the time the *j*-th painter needs to work on the *i*-th picture. Output Specification: Print the sequence of *m* integers *r*1,<=*r*2,<=...,<=*r**m*, where *r**i* is the moment when the *n*-th painter stopped working on the *i*-th picture. Demo Input: ['5 1\n1\n2\n3\n4\n5\n', '4 2\n2 5\n3 1\n5 3\n10 1\n'] Demo Output: ['1 3 6 10 15 ', '7 8 13 21 '] Note: none
977
Title: Soldier and Cards Time Limit: None seconds Memory Limit: None megabytes Problem Description: Two bored soldiers are playing card war. Their card deck consists of exactly *n* cards, numbered from 1 to *n*, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game. The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins. You have to calculate how many fights will happen and who will win the game, or state that game won't end. Input Specification: First line contains a single integer *n* (2<=≤<=*n*<=≤<=10), the number of cards. Second line contains integer *k*1 (1<=≤<=*k*1<=≤<=*n*<=-<=1), the number of the first soldier's cards. Then follow *k*1 integers that are the values on the first soldier's cards, from top to bottom of his stack. Third line contains integer *k*2 (*k*1<=+<=*k*2<==<=*n*), the number of the second soldier's cards. Then follow *k*2 integers that are the values on the second soldier's cards, from top to bottom of his stack. All card values are different. Output Specification: If somebody wins in this game, print 2 integers where the first one stands for the number of fights before end of game and the second one is 1 or 2 showing which player has won. If the game won't end and will continue forever output <=-<=1. Demo Input: ['4\n2 1 3\n2 4 2\n', '3\n1 2\n2 1 3\n'] Demo Output: ['6 2', '-1'] Note: First sample: Second sample:
978
Title: Insomnia cure Time Limit: None seconds Memory Limit: None megabytes Problem Description: «One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic. How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons? Input Specification: Input data contains integer numbers *k*,<=*l*,<=*m*,<=*n* and *d*, each number in a separate line (1<=≤<=*k*,<=*l*,<=*m*,<=*n*<=≤<=10, 1<=≤<=*d*<=≤<=105). Output Specification: Output the number of damaged dragons. Demo Input: ['1\n2\n3\n4\n12\n', '2\n3\n4\n5\n24\n'] Demo Output: ['12\n', '17\n'] Note: In the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough. In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed.
979
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to *n*, then we can formalize the popular model of abduction, known as the (*a*,<=*b*)-Cowavan Raid: first they steal a cow number *a*, then number *a*<=+<=*b*, then — number *a*<=+<=2·*b*, and so on, until the number of an abducted cow exceeds *n*. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made *p* scenarios of the (*a*,<=*b*)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen. Input Specification: The first line contains the only positive integer *n* (1<=≤<=*n*<=≤<=3·105) — the number of cows in the cowavan. The second number contains *n* positive integer *w**i*, separated by spaces, where the *i*-th number describes the mass of the *i*-th cow in the cowavan (1<=≤<=*w**i*<=≤<=109). The third line contains the only positive integer *p* — the number of scenarios of (*a*,<=*b*)-raids (1<=≤<=*p*<=≤<=3·105). Each following line contains integer parameters *a* and *b* of the corresponding scenario (1<=≤<=*a*,<=*b*<=≤<=*n*). Output Specification: Print for each scenario of the (*a*,<=*b*)-raid the total mass of cows, that can be stolen using only this scenario. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams of the %I64d specificator. Demo Input: ['3\n1 2 3\n2\n1 1\n1 2\n', '4\n2 3 5 7\n3\n1 3\n2 3\n2 2\n'] Demo Output: ['6\n4\n', '9\n3\n10\n'] Note: none
980
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer *x* on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing. Nikita made *m* operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the *i*-th step he remembers an operation he made *p**i*-th. In other words, he remembers the operations in order of some permutation *p*1,<=*p*2,<=...,<=*p**m*. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him! Input Specification: The first line contains the integer *m* (1<=≤<=*m*<=≤<=105) — the number of operations Nikita made. The next *m* lines contain the operations Nikita remembers. The *i*-th line starts with two integers *p**i* and *t**i* (1<=≤<=*p**i*<=≤<=*m*, *t**i*<==<=0 or *t**i*<==<=1) — the index of operation he remembers on the step *i*, and the type of the operation. *t**i* equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer *x**i* (1<=≤<=*x**i*<=≤<=106) — the integer added to the stack. It is guaranteed that each integer from 1 to *m* is present exactly once among integers *p**i*. Output Specification: Print *m* integers. The integer *i* should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to *i*. If the stack is empty after performing all these operations, print -1. Demo Input: ['2\n2 1 2\n1 0\n', '3\n1 1 2\n2 1 3\n3 0\n', '5\n5 0\n4 0\n3 1 1\n2 1 1\n1 1 2\n'] Demo Output: ['2\n2\n', '2\n3\n2\n', '-1\n-1\n-1\n-1\n2\n'] Note: In the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same. In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed. In the third example Nikita remembers the operations in the reversed order.
981
Title: First Digit Law Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law). Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are *N* random variables, the *i*-th of which can take any integer value from some segment [*L**i*;*R**i*] (all numbers from this segment are equiprobable). It means that the value of the *i*-th quantity can be equal to any integer number from a given interval [*L**i*;*R**i*] with probability 1<=/<=(*R**i*<=-<=*L**i*<=+<=1). The Hedgehog wants to know the probability of the event that the first digits of at least *K*% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD — most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least *K* per cent of those *N* values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one. Input Specification: The first line contains number *N* which is the number of random variables (1<=≤<=*N*<=≤<=1000). Then follow *N* lines containing pairs of numbers *L**i*,<=*R**i*, each of whom is a description of a random variable. It is guaranteed that 1<=≤<=*L**i*<=≤<=*R**i*<=≤<=1018. The last line contains an integer *K* (0<=≤<=*K*<=≤<=100). All the numbers in the input file are integers. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d). Output Specification: Print the required probability. Print the fractional number with such a precision that the relative or absolute error of the result won't exceed 10<=-<=9. Demo Input: ['1\n1 2\n50\n', '2\n1 2\n9 11\n50\n'] Demo Output: ['0.500000000000000', '0.833333333333333'] Note: none
982
Title: Возможно, вы знаете этих людей? Time Limit: None seconds Memory Limit: None megabytes Problem Description: Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если *a* является другом *b*, то *b* также является другом *a*. В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя *x*. Пусть некоторый другой человек *y*, не являющийся другом *x* на текущий момент, является другом не менее, чем для *k*% друзей *x*. Тогда он является предполагаемым другом для *x*. У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 109. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей. Input Specification: В первой строке следуют два целых числа *m* и *k* (1<=≤<=*m*<=≤<=100, 0<=≤<=*k*<=≤<=100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом. В последующих *m* строках записано по два числа *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=109, *a**i*<=≠<=*b**i*), обозначающих идентификаторы пользователей, являющихся друзьями. Гарантируется, что каждая пара людей фигурирует в списке не более одного раза. Output Specification: Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "*id*:<= *k* *id*1 *id*2 ... *id**k*", где *id* — это id самого человека, *k* — количество его предполагаемых друзей, а *id*1, *id*2, ..., *id**k* — идентификаторы его предполагаемых друзей в возрастающем порядке. Demo Input: ['5 51\n10 23\n23 42\n39 42\n10 39\n39 58\n', '5 100\n1 2\n1 3\n1 4\n2 3\n2 4\n'] Demo Output: ['10: 1 42\n23: 1 39\n39: 1 23\n42: 1 10\n58: 2 10 42\n', '1: 0\n2: 0\n3: 1 4\n4: 1 3\n'] Note: none
983
Title: T-shirts Distribution Time Limit: None seconds Memory Limit: None megabytes Problem Description: The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size. During the registration, the organizers asked each of the *n* participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him. Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size: - the size he wanted, if he specified one size; - any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts. Input Specification: The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100<=000. The second line contains positive integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of participants. The following *n* lines contain the sizes specified by the participants, one line per participant. The *i*-th line contains information provided by the *i*-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring. Output Specification: If it is not possible to present a t-shirt to each participant, print «NO» (without quotes). Otherwise, print *n*<=+<=1 lines. In the first line print «YES» (without quotes). In the following *n* lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them. Demo Input: ['0 1 0 1 1 0\n3\nXL\nS,M\nXL,XXL\n', '1 1 2 0 1 1\n5\nS\nM\nS,M\nXXL,XXXL\nXL,XXL\n'] Demo Output: ['YES\nXL\nM\nXXL\n', 'NO\n'] Note: none
984
Title: Cross Sum Time Limit: None seconds Memory Limit: None megabytes Problem Description: Genos has been given *n* distinct lines on the Cartesian plane. Let be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter. Given a query point (*p*,<=*q*), let be the corresponding list of distances of all points in to the query point. Distance here refers to euclidean distance. As a refresher, the euclidean distance between two points (*x*1,<=*y*1) and (*x*2,<=*y*2) is . Genos is given a point (*p*,<=*q*) and a positive integer *m*. He is asked to find the sum of the *m* smallest elements in . Duplicate elements in are treated as separate elements. Genos is intimidated by Div1 E problems so he asked for your help. Input Specification: The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=50<=000) — the number of lines. The second line contains three integers *x*, *y* and *m* (|*x*|,<=|*y*|<=≤<=1<=000<=000, ) — the encoded coordinates of the query point and the integer *m* from the statement above. The query point (*p*,<=*q*) is obtained as . In other words, divide *x* and *y* by 1000 to get the actual query point. denotes the length of the list and it is guaranteed that . Each of the next *n* lines contains two integers *a**i* and *b**i* (|*a**i*|,<=|*b**i*|<=≤<=1<=000<=000) — the parameters for a line of the form: . It is guaranteed that no two lines are the same, that is (*a**i*,<=*b**i*)<=≠<=(*a**j*,<=*b**j*) if *i*<=≠<=*j*. Output Specification: Print a single real number, the sum of *m* smallest elements of . Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. To clarify, let's assume that your answer is *a* and the answer of the jury is *b*. The checker program will consider your answer correct if . Demo Input: ['4\n1000 1000 3\n1000 0\n-1000 0\n0 5000\n0 -5000\n', '2\n-1000000 -1000000 1\n1000000 -1000000\n999999 1000000\n', '3\n-1000 1000 3\n1000 0\n-1000 2000\n2000 -1000\n', '5\n-303667 189976 10\n-638 116487\n-581 44337\n1231 -756844\n1427 -44097\n8271 -838417\n'] Demo Output: ['14.282170363\n', '2000001000.999999500\n', '6.000000000\n', '12953.274911829\n'] Note: In the first sample, the three closest points have distances <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5d034d9a89435d5056a183760eb7b3b7a12cfd15.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6a579e51bf1610b7c34464ea52a3cadfb31a4f84.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample, the two lines *y* = 1000*x* - 1000 and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e4e30c00edb4440677bee169d45b6f9ac80cdac3.png" style="max-width: 100.0%;max-height: 100.0%;"/> intersect at (2000000, 1999999000). This point has a distance of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5fd08d2caf504b763ce325cdb5478fdecfe37842.png" style="max-width: 100.0%;max-height: 100.0%;"/> from ( - 1000,  - 1000). In the third sample, the three lines all intersect at the point (1, 1). This intersection point is present three times in <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8d78ee8afbfce85cba4f37a7aaca3025736e21af.png" style="max-width: 100.0%;max-height: 100.0%;"/> since it is the intersection of three pairs of lines. Since the distance between the intersection point and the query point is 2, the answer is three times that or 6.
985
Title: Makes And The Product Time Limit: None seconds Memory Limit: None megabytes Problem Description: After returning from the army Makes received a gift — an array *a* consisting of *n* positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (*i*,<= *j*,<= *k*) (*i*<=&lt;<=*j*<=&lt;<=*k*), such that *a**i*·*a**j*·*a**k* is minimum possible, are there in the array? Help him with it! Input Specification: The first line of input contains a positive integer number *n* (3<=≤<=*n*<=≤<=105) — the number of elements in array *a*. The second line contains *n* positive integer numbers *a**i* (1<=≤<=*a**i*<=≤<=109) — the elements of a given array. Output Specification: Print one number — the quantity of triples (*i*,<= *j*,<= *k*) such that *i*,<= *j* and *k* are pairwise distinct and *a**i*·*a**j*·*a**k* is minimum possible. Demo Input: ['4\n1 1 1 1\n', '5\n1 3 2 3 4\n', '6\n1 3 3 1 3 2\n'] Demo Output: ['4\n', '2\n', '1\n'] Note: In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4. In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2. In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
986
Title: A and B and Lecture Rooms Time Limit: None seconds Memory Limit: None megabytes Problem Description: A and B are preparing themselves for programming contests. The University where A and B study is a set of rooms connected by corridors. Overall, the University has *n* rooms connected by *n*<=-<=1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to *n*. Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them. As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following *m* days. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of rooms in the University. The next *n*<=-<=1 lines describe the corridors. The *i*-th of these lines (1<=≤<=*i*<=≤<=*n*<=-<=1) contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), showing that the *i*-th corridor connects rooms *a**i* and *b**i*. The next line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. Next *m* lines describe the queries. The *j*-th of these lines (1<=≤<=*j*<=≤<=*m*) contains two integers *x**j* and *y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*) that means that on the *j*-th day A will write the contest in the room *x**j*, B will write in the room *y**j*. Output Specification: In the *i*-th (1<=≤<=*i*<=≤<=*m*) line print the number of rooms that are equidistant from the rooms where A and B write contest on the *i*-th day. Demo Input: ['4\n1 2\n1 3\n2 4\n1\n2 3\n', '4\n1 2\n2 3\n2 4\n2\n1 2\n1 3\n'] Demo Output: ['1\n', '0\n2\n'] Note: in the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.
987
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Each New Year Timofey and his friends cut down a tree of *n* vertices and bring it home. After that they paint all the *n* its vertices, so that the *i*-th vertex gets color *c**i*. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input Specification: The first line contains single integer *n* (2<=≤<=*n*<=≤<=105) — the number of vertices in the tree. Each of the next *n*<=-<=1 lines contains two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*, *u*<=≠<=*v*), denoting there is an edge between vertices *u* and *v*. It is guaranteed that the given graph is a tree. The next line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=105), denoting the colors of the vertices. Output Specification: Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Demo Input: ['4\n1 2\n2 3\n3 4\n1 2 1 1\n', '3\n1 2\n2 3\n1 2 3\n', '4\n1 2\n2 3\n3 4\n1 2 1 2\n'] Demo Output: ['YES\n2', 'YES\n2', 'NO'] Note: none
988
Title: Berland Bingo Time Limit: None seconds Memory Limit: None megabytes Problem Description: Lately, a national version of a bingo game has become very popular in Berland. There are *n* players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the *i*-th player contains *m**i* numbers. During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct. You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not. Input Specification: The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of the players. Then follow *n* lines, each line describes a player's card. The line that describes a card starts from integer *m**i* (1<=≤<=*m**i*<=≤<=100) that shows how many numbers the *i*-th player's card has. Then follows a sequence of integers *a**i*,<=1,<=*a**i*,<=2,<=...,<=*a**i*,<=*m**i* (1<=≤<=*a**i*,<=*k*<=≤<=100) — the numbers on the *i*-th player's card. The numbers in the lines are separated by single spaces. It is guaranteed that all the numbers on each card are distinct. Output Specification: Print *n* lines, the *i*-th line must contain word "YES" (without the quotes), if the *i*-th player can win, and "NO" (without the quotes) otherwise. Demo Input: ['3\n1 1\n3 2 4 1\n2 10 11\n', '2\n1 1\n1 1\n'] Demo Output: ['YES\nNO\nYES\n', 'NO\nNO\n'] Note: none
989
Title: Choosing Ads Time Limit: None seconds Memory Limit: None megabytes Problem Description: One social network developer recently suggested a new algorithm of choosing ads for users. There are *n* slots which advertisers can buy. It is possible to buy a segment of consecutive slots at once. The more slots you own, the bigger are the chances your ad will be shown to users. Every time it is needed to choose ads to show, some segment of slots is picked by a secret algorithm. Then some advertisers are chosen. The only restriction is that it should be guaranteed for advertisers which own at least *p*% of slots composing this segment that their ad will be shown. From the other side, users don't like ads. So it was decided to show no more than ads at once. You are asked to develop a system to sell segments of slots and choose ads in accordance with the rules described above. Input Specification: The first line of the input contains three integers *n*, *m* and *p* (1<=≤<=*n*,<=*m*<=≤<=150<=000,<=20<=≤<=*p*<=≤<=100) — the number of slots, the number of queries to your system and threshold for which display of the ad is guaranteed. Next line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=150<=000), where the *i*-th number means id of advertiser who currently owns the *i*-th slot. Next *m* lines contain queries descriptions. Each description is of one of the following forms: - 1 l r id (1<=≤<=*l*<=≤<=*r*<=≤<=*n*,<=1<=≤<=*id*<=≤<=150 000) — advertiser *id* bought all slots in a range from *l* to *r* inclusive; - 2 l r (1<=≤<=*l*<=≤<=*r*) — you need to choose advertisers for segment [*l*,<=*r*]. Output Specification: For each query of the second type answer should be printed in a separate line. First integer of the answer should be the number of advertisements that will be shown . Next *cnt* integers should be advertisers' ids. It is allowed to print one advertiser more than once, but each advertiser that owns at least slots of the segment from *l* to *r* should be in your answer. Demo Input: ['5 9 33\n1 2 1 3 3\n2 1 5\n2 1 5\n2 1 3\n2 3 3\n1 2 4 5\n2 1 5\n2 3 5\n1 4 5 1\n2 1 5\n'] Demo Output: ['3 1 2 3\n2 1 3\n2 2 1\n3 1 1000 1000\n1 5\n2 5 3\n2 1 5'] Note: Samples demonstrate that you actually have quite a lot of freedom in choosing advertisers.
990
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward"). You are given a list of commands that will be given to the turtle. You have to change exactly *n* commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows all the commands of the modified list? Input Specification: The first line of input contains a string *commands* — the original list of commands. The string *commands* contains between 1 and 100 characters, inclusive, and contains only characters "T" and "F". The second line contains an integer *n* (1<=≤<=*n*<=≤<=50) — the number of commands you have to change in the list. Output Specification: Output the maximum distance from the starting point to the ending point of the turtle's path. The ending point of the turtle's path is turtle's coordinate after it follows all the commands of the modified list. Demo Input: ['FT\n1\n', 'FFFTFFF\n2\n'] Demo Output: ['2\n', '6\n'] Note: In the first example the best option is to change the second command ("T") to "F" — this way the turtle will cover a distance of 2 units. In the second example you have to change two commands. One of the ways to cover maximal distance of 6 units is to change the fourth command and first or last one.
991
Title: World Cup Time Limit: None seconds Memory Limit: None megabytes Problem Description: Allen wants to enter a fan zone that occupies a round square and has $n$ entrances. There already is a queue of $a_i$ people in front of the $i$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute. Allen uses the following strategy to enter the fan zone: - Initially he stands in the end of the queue in front of the first entrance. - Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone. Input Specification: The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the number of entrances. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the number of people in queues. These numbers do not include Allen. Output Specification: Print a single integer — the number of entrance that Allen will use. Demo Input: ['4\n2 3 2 0\n', '2\n10 10\n', '6\n5 2 6 5 7 4\n'] Demo Output: ['3\n', '1\n', '6\n'] Note: In the first example the number of people (not including Allen) changes as follows: $[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance. In the second example the number of people (not including Allen) changes as follows: $[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$. In the third example the number of people (not including Allen) changes as follows: $[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$.
992
Title: Shaass and Bookshelf Time Limit: None seconds Memory Limit: None megabytes Problem Description: Shaass has *n* books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the *i*-th book is *t**i* and its pages' width is equal to *w**i*. The thickness of each book is either 1 or 2. All books have the same page heights. Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. Help Shaass to find the minimum total thickness of the vertical books that we can achieve. Input Specification: The first line of the input contains an integer *n*, (1<=≤<=*n*<=≤<=100). Each of the next *n* lines contains two integers *t**i* and *w**i* denoting the thickness and width of the *i*-th book correspondingly, (1<=≤<=*t**i*<=≤<=2,<=1<=≤<=*w**i*<=≤<=100). Output Specification: On the only line of the output print the minimum total thickness of the vertical books that we can achieve. Demo Input: ['5\n1 12\n1 3\n2 15\n2 5\n2 1\n', '3\n1 10\n2 1\n2 4\n'] Demo Output: ['5\n', '3\n'] Note: none
993
Title: On a plane Time Limit: None seconds Memory Limit: None megabytes Problem Description: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of points on a plane. Each of the next *n* lines contains two real coordinates *x**i* and *y**i* of the point, specified with exactly 2 fractional digits. All coordinates are between <=-<=1000 and 1000, inclusive. Output a single real number θ — the answer to the problem statement. The absolute or relative error of your answer should be at most 10<=-<=2. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of points on a plane. Each of the next *n* lines contains two real coordinates *x**i* and *y**i* of the point, specified with exactly 2 fractional digits. All coordinates are between <=-<=1000 and 1000, inclusive. Output Specification: Output a single real number θ — the answer to the problem statement. The absolute or relative error of your answer should be at most 10<=-<=2. Demo Input: ['8\n-2.14 2.06\n-1.14 2.04\n-2.16 1.46\n-2.14 0.70\n-1.42 0.40\n-0.94 -0.48\n-1.42 -1.28\n-2.16 -1.62\n', '5\n2.26 1.44\n2.28 0.64\n2.30 -0.30\n1.58 0.66\n3.24 0.66\n', '8\n6.98 2.06\n6.40 1.12\n5.98 0.24\n5.54 -0.60\n7.16 0.30\n7.82 1.24\n8.34 0.24\n8.74 -0.76\n', '5\n10.44 2.06\n10.90 0.80\n11.48 -0.48\n12.06 0.76\n12.54 2.06\n', '8\n16.94 2.42\n15.72 2.38\n14.82 1.58\n14.88 0.50\n15.76 -0.16\n16.86 -0.20\n17.00 0.88\n16.40 0.92\n', '7\n20.62 3.00\n21.06 2.28\n21.56 1.36\n21.66 0.56\n21.64 -0.52\n22.14 2.32\n22.62 3.04\n'] Demo Output: ['5.410\n', '5.620\n', '5.480\n', '6.040\n', '6.040\n', '6.720\n'] Note: none
994
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex. The lab can be pictured as a connected graph with *n* vertices and *m* edges. *k* clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone. Each clone can visit at most vertices before the lab explodes. Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices. Input Specification: The first line contains three integers *n*, *m*, and *k* (1<=≤<=*n*<=≤<=2·105, *n*<=-<=1<=≤<=*m*<=≤<=2·105, 1<=≤<=*k*<=≤<=*n*) — the number of vertices and edges in the lab, and the number of clones. Each of the next *m* lines contains two integers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected. Output Specification: You should print *k* lines. *i*-th of these lines must start with an integer *c**i* () — the number of vertices visited by *i*-th clone, followed by *c**i* integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists. Demo Input: ['3 2 1\n2 1\n3 1\n', '5 4 2\n1 2\n1 3\n1 4\n1 5\n'] Demo Output: ['3 2 1 3\n', '3 2 1 3\n3 4 1 5'] Note: In the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone. In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
995
Title: Schedule Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, *n* groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect. The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=5000) — amount of groups, which have lessons in the room 31. Then *n* lines follow, each of them contains two integers *l**i* *r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=106) — starting and finishing times of lesson of the *i*-th group. It is possible that initially no two lessons intersect (see sample 1). Output Specification: Output integer *k* — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output *k* numbers — indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. Demo Input: ['3\n3 10\n20 30\n1 3\n', '4\n3 10\n20 30\n1 3\n1 39\n', '3\n1 5\n2 6\n3 7\n'] Demo Output: ['3\n1 2 3 ', '1\n4 ', '0\n'] Note: none
996
Title: Shower Line Time Limit: None seconds Memory Limit: None megabytes Problem Description: Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory shower door. As soon as the shower opens, the first person from the line enters the shower. After a while the first person leaves the shower and the next person enters the shower. The process continues until everybody in the line has a shower. Having a shower takes some time, so the students in the line talk as they wait. At each moment of time the students talk in pairs: the (2*i*<=-<=1)-th man in the line (for the current moment) talks with the (2*i*)-th one. Let's look at this process in more detail. Let's number the people from 1 to 5. Let's assume that the line initially looks as 23154 (person number 2 stands at the beginning of the line). Then, before the shower opens, 2 talks with 3, 1 talks with 5, 4 doesn't talk with anyone. Then 2 enters the shower. While 2 has a shower, 3 and 1 talk, 5 and 4 talk too. Then, 3 enters the shower. While 3 has a shower, 1 and 5 talk, 4 doesn't talk to anyone. Then 1 enters the shower and while he is there, 5 and 4 talk. Then 5 enters the shower, and then 4 enters the shower. We know that if students *i* and *j* talk, then the *i*-th student's happiness increases by *g**ij* and the *j*-th student's happiness increases by *g**ji*. Your task is to find such initial order of students in the line that the total happiness of all students will be maximum in the end. Please note that some pair of students may have a talk several times. In the example above students 1 and 5 talk while they wait for the shower to open and while 3 has a shower. Input Specification: The input consists of five lines, each line contains five space-separated integers: the *j*-th number in the *i*-th line shows *g**ij* (0<=≤<=*g**ij*<=≤<=105). It is guaranteed that *g**ii*<==<=0 for all *i*. Assume that the students are numbered from 1 to 5. Output Specification: Print a single integer — the maximum possible total happiness of the students. Demo Input: ['0 0 0 0 9\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n7 0 0 0 0\n', '0 43 21 18 2\n3 0 21 11 65\n5 2 0 1 4\n54 62 12 0 99\n87 64 81 33 0\n'] Demo Output: ['32\n', '620\n'] Note: In the first sample, the optimal arrangement of the line is 23154. In this case, the total happiness equals:
997
Title: Lever Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have a description of a lever as string *s*. We'll represent the string length as record |*s*|, then the lever looks as a horizontal bar with weights of length |*s*|<=-<=1 with exactly one pivot. We will assume that the bar is a segment on the *Ox* axis between points 0 and |*s*|<=-<=1. The decoding of the lever description is given below. - If the *i*-th character of the string equals "^", that means that at coordinate *i* there is the pivot under the bar. - If the *i*-th character of the string equals "=", that means that at coordinate *i* there is nothing lying on the bar. - If the *i*-th character of the string equals digit *c* (1-9), that means that at coordinate *i* there is a weight of mass *c* on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance. Input Specification: The first line contains the lever description as a non-empty string *s* (3<=≤<=|*s*|<=≤<=106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar. To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs. Output Specification: Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance. Demo Input: ['=^==\n', '9===^==1\n', '2==^7==\n', '41^52==\n'] Demo Output: ['balance\n', 'left\n', 'right\n', 'balance\n'] Note: As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever. The pictures to the examples:
998
Title: Don't fear, DravDe is kind Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A motorcade of *n* trucks, driving from city «Z» to city «З», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is described with four numbers: - *v* — value of the truck, of its passangers and cargo - *c* — amount of passanger on the truck, the driver included - *l* — total amount of people that should go into the tunnel before this truck, so that the driver can overcome his fear («if the monster appears in front of the motorcade, he'll eat them first») - *r* — total amount of people that should follow this truck, so that the driver can overcome his fear («if the monster appears behind the motorcade, he'll eat them first»). Since the road is narrow, it's impossible to escape DravDe, if he appears from one side. Moreover, the motorcade can't be rearranged. The order of the trucks can't be changed, but it's possible to take any truck out of the motorcade, and leave it near the tunnel for an indefinite period. You, as the head of the motorcade, should remove some of the trucks so, that the rest of the motorcade can move into the tunnel and the total amount of the left trucks' values is maximal. Input Specification: The first input line contains integer number *n* (1<=≤<=*n*<=≤<=105) — amount of trucks in the motorcade. The following *n* lines contain four integers each. Numbers in the *i*-th line: *v**i*,<=*c**i*,<=*l**i*,<=*r**i* (1<=≤<=*v**i*<=≤<=104,<=1<=≤<=*c**i*<=≤<=105,<=0<=≤<=*l**i*,<=*r**i*<=≤<=105) — describe the *i*-th truck. The trucks are numbered from 1, counting from the front of the motorcade. Output Specification: In the first line output number *k* — amount of trucks that will drive into the tunnel. In the second line output *k* numbers — indexes of these trucks in ascending order. Don't forget please that you are not allowed to change the order of trucks. If the answer is not unique, output any. Demo Input: ['5\n1 1 0 3\n1 1 1 2\n1 1 2 1\n1 1 3 0\n2 1 3 0\n', '5\n1 1 0 3\n10 1 2 1\n2 2 1 1\n10 1 1 2\n3 1 3 0\n'] Demo Output: ['4\n1 2 3 5 \n', '3\n1 3 5 \n'] Note: none
999