task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Guess Your Way Out! Time Limit: None seconds Memory Limit: None megabytes Problem Description: Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height *h*. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2*h*. The exit is located at some node *n* where 1<=≀<=*n*<=≀<=2*h*, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: - Character 'L' means "go to the left child of the current node"; - Character 'R' means "go to the right child of the current node"; - If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; - If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; - If he reached a leaf node that is not the exit, he returns to the parent of the current node; - If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Specification: Input consists of two integers *h*,<=*n* (1<=≀<=*h*<=≀<=50, 1<=≀<=*n*<=≀<=2*h*). Output Specification: Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Demo Input: ['1 2\n', '2 3\n', '3 6\n', '10 1024\n'] Demo Output: ['2', '5', '10', '2046'] Note: A perfect binary tree of height *h* is a binary tree consisting of *h* + 1 levels. Level 0 consists of a single node called root, level *h* consists of 2<sup class="upper-index">*h*</sup> nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <img class="tex-graphics" src="https://espresso.codeforces.com/e9d0715dc8cd9b4f6ac7a0fb137563f857660adc.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,100
Title: Eyes Closed Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya and Petya were tired of studying so they decided to play a game. Before the game begins Vasya looks at array *a* consisting of *n* integers. As soon as he remembers all elements of *a* the game begins. Vasya closes his eyes and Petya does *q* actions of one of two types: 1) Petya says 4 integers *l*1,<=*r*1,<=*l*2,<=*r*2Β β€” boundaries of two non-intersecting segments. After that he swaps one random element from the [*l*1,<=*r*1] segment with another random element from the [*l*2,<=*r*2] segment. 2) Petya asks Vasya the sum of the elements of *a* in the [*l*,<=*r*] segment. Vasya is a mathematician so he answers Petya the mathematical expectation of the sum of the elements in the segment. Your task is to write a program which will answer the second type questions as Vasya would do it. In other words your program should print the mathematical expectation of the sum of the elements of *a* in the [*l*,<=*r*] segment for every second type query. Input Specification: The first line contains two integers *n*,<=*q* (2<=≀<=*n*<=≀<=105,<=1<=≀<=*q*<=≀<=105) Β β€” the number of elements in the array and the number of queries you need to handle. The second line contains *n* integers *a**i* (1<=≀<=*a**i*<=≀<=109) Β β€” elements of the array. The next *q* lines contain Petya's actions of type 1 or 2. If it is a type 1 action then the line contains 5 integers 1,<=*l*1,<=*r*1,<=*l*2,<=*r*2 (1<=≀<=*l*1<=≀<=*r*1<=≀<=*n*,<=1<=≀<=*l*2<=≀<=*r*2<=≀<=*n*). If it is a type 2 query then the line contains 3 integers 2,<=*l*,<=*r* (1<=≀<=*l*<=≀<=*r*<=≀<=*n*). It is guaranteed that there is at least one type 2 query and segments [*l*1,<=*r*1],<=[*l*2,<=*r*2] don't have common elements. Output Specification: For each type 2 query print one real numberΒ β€” the mathematical expectation of the sum of elements in the segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=4 Β β€” formally, the answer is correct if where *x* is jury's answer and *y* is yours. Demo Input: ['4 4\n1 1 2 2\n1 2 2 3 3\n2 1 2\n1 1 2 3 4\n2 1 2\n', '10 5\n1 1 1 1 1 2 2 2 2 2\n1 1 5 6 10\n2 1 5\n1 1 5 6 10\n1 1 5 6 10\n2 6 10\n', '10 10\n1 2 3 4 5 6 7 8 9 10\n1 1 5 6 10\n1 1 5 6 10\n2 1 5\n1 1 3 6 9\n2 1 3\n1 5 7 8 10\n1 1 1 10 10\n2 1 5\n2 7 10\n2 1 10\n'] Demo Output: ['3.0000000\n3.0000000\n', '6.0000000\n8.0400000\n', '23.0000000\n14.0000000\n28.0133333\n21.5733333\n55.0000000\n'] Note: none
1,101
Title: CGCDSSQ Time Limit: None seconds Memory Limit: None megabytes Problem Description: Given a sequence of integers *a*1,<=...,<=*a**n* and *q* queries *x*1,<=...,<=*x**q* on it. For each query *x**i* you have to count the number of pairs (*l*,<=*r*) such that 1<=≀<=*l*<=≀<=*r*<=≀<=*n* and *gcd*(*a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*)<==<=*x**i*. is a greatest common divisor of *v*1,<=*v*2,<=...,<=*v**n*, that is equal to a largest positive integer that divides all *v**i*. Input Specification: The first line of the input contains integer *n*, (1<=≀<=*n*<=≀<=105), denoting the length of the sequence. The next line contains *n* space separated integers *a*1,<=...,<=*a**n*, (1<=≀<=*a**i*<=≀<=109). The third line of the input contains integer *q*, (1<=≀<=*q*<=≀<=3<=Γ—<=105), denoting the number of queries. Then follows *q* lines, each contain an integer *x**i*, (1<=≀<=*x**i*<=≀<=109). Output Specification: For each query print the result in a separate line. Demo Input: ['3\n2 6 3\n5\n1\n2\n3\n4\n6\n', '7\n10 20 3 15 1000 60 16\n10\n1\n2\n3\n4\n5\n6\n10\n20\n60\n1000\n'] Demo Output: ['1\n2\n2\n0\n1\n', '14\n0\n2\n2\n2\n0\n2\n2\n1\n1\n'] Note: none
1,102
Title: Information Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* employees working in company "X" (let's number them from 1 to *n* for convenience). Initially the employees didn't have any relationships among each other. On each of *m* next days one of the following events took place: - either employee *y* became the boss of employee *x* (at that, employee *x* didn't have a boss before); - or employee *x* gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive); - or comes a request of type "determine whether employee *x* signs certain documents". Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies. Input Specification: The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the number of employees and the number of events. Each of the next *m* lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event *t* (1<=≀<=*t*<=≀<=3). - If *t*<==<=1, then next follow two integers *x* and *y* (1<=≀<=*x*,<=*y*<=≀<=*n*) β€” numbers of the company employees. It is guaranteed that employee *x* doesn't have the boss currently. - If *t*<==<=2, then next follow integer *x* (1<=≀<=*x*<=≀<=*n*) β€” the number of the employee who got a document packet. - If *t*<==<=3, then next follow two integers *x* and *i* (1<=≀<=*x*<=≀<=*n*;Β 1<=≀<=*i*<=≀<=[number of packets that have already been given]) β€” the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order. It is guaranteed that the input has at least one query of the third type. Output Specification: For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes. Demo Input: ['4 9\n1 4 3\n2 4\n3 3 1\n1 2 3\n2 2\n3 1 2\n1 3 1\n2 2\n3 1 3\n'] Demo Output: ['YES\nNO\nYES\n'] Note: none
1,103
Title: Jury Meeting Time Limit: None seconds Memory Limit: None megabytes Problem Description: Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are *n*<=+<=1 cities consecutively numbered from 0 to *n*. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to *n* there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires *k* days of work. For all of these *k* days each of the *n* jury members should be present in Metropolis to be able to work on problems. You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day. Gather everybody for *k* days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for *k* days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than *k* days. Input Specification: The first line of input contains three integers *n*, *m* and *k* (1<=≀<=*n*<=≀<=105, 0<=≀<=*m*<=≀<=105, 1<=≀<=*k*<=≀<=106). The *i*-th of the following *m* lines contains the description of the *i*-th flight defined by four integers *d**i*, *f**i*, *t**i* and *c**i* (1<=≀<=*d**i*<=≀<=106, 0<=≀<=*f**i*<=≀<=*n*, 0<=≀<=*t**i*<=≀<=*n*, 1<=≀<=*c**i*<=≀<=106, exactly one of *f**i* and *t**i* equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost. Output Specification: Output the only integer that is the minimum cost of gathering all jury members in city 0 for *k* days and then sending them back to their home cities. If it is impossible to gather everybody in Metropolis for *k* days and then send them back to their home cities, output "-1" (without the quotes). Demo Input: ['2 6 5\n1 1 0 5000\n3 2 0 5500\n2 2 0 6000\n15 0 2 9000\n9 0 1 7000\n8 0 2 6500\n', '2 4 5\n1 2 0 5000\n2 1 0 4500\n2 1 0 3000\n8 0 1 6000\n'] Demo Output: ['24500\n', '-1\n'] Note: The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more. In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
1,104
Title: Find Amir Time Limit: None seconds Memory Limit: None megabytes Problem Description: A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are *n* schools numerated from 1 to *n*. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools *i* and *j* costs and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=105)Β β€” the number of schools. Output Specification: Print single integer: the minimum cost of tickets needed to visit all schools. Demo Input: ['2\n', '10\n'] Demo Output: ['0\n', '4\n'] Note: In the first example we can buy a ticket between the schools that costs <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c67d72010e0498bfd065a6a38fdeaec90358507b.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
1,105
Title: Merge Equal Elements Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a sequence of positive integers *a*1,<=*a*2,<=...,<=*a**n*. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to *x*, delete both and insert a single integer *x*<=+<=1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements. For example, if the initial sequence is [5,<=2,<=1,<=1,<=2,<=2], then after the first operation you get [5,<=2,<=2,<=2,<=2], after the second β€” [5,<=3,<=2,<=2], after the third β€” [5,<=3,<=3], and finally after the fourth you get [5,<=4]. After that there are no equal consecutive elements left in the sequence, so you stop the process. Determine the final sequence after you stop performing the operation. Input Specification: The first line contains a single integer *n* (2<=≀<=*n*<=≀<=2Β·105) β€” the number of elements in the sequence. The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109). Output Specification: In the first line print a single integer *k* β€” the number of elements in the sequence after you stop performing the operation. In the second line print *k* integersΒ β€” the sequence after you stop performing the operation. Demo Input: ['6\n5 2 1 1 2 2\n', '4\n1000000000 1000000000 1000000000 1000000000\n', '7\n4 10 22 11 12 5 6\n'] Demo Output: ['2\n5 4 ', '1\n1000000002 ', '7\n4 10 22 11 12 5 6 '] Note: The first example is described in the statements. In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002]. In the third example there are no two equal consecutive elements initially, so the sequence does not change.
1,106
Title: Table with Letters - 2 Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya has recently started to learn English. Now he needs to remember how to write English letters. He isn't sure about some of them, so he decided to train a little. He found a sheet of squared paper and began writing arbitrary English letters there. In the end Vasya wrote *n* lines containing *m* characters each. Thus, he got a rectangular *n*<=Γ—<=*m* table, each cell of the table contained some English letter. Let's number the table rows from top to bottom with integers from 1 to *n*, and columns β€” from left to right with integers from 1 to *m*. After that Vasya looked at the resulting rectangular table and wondered, how many subtables are there, that matches both following conditions: - the subtable contains at most *k* cells with "a" letter; - all letters, located in all four corner cells of the subtable, are equal. Formally, a subtable's definition is as follows. It is defined by four integers *x*1,<=*y*1,<=*x*2,<=*y*2 such that 1<=≀<=*x*1<=&lt;<=*x*2<=≀<=*n*, 1<=≀<=*y*1<=&lt;<=*y*2<=≀<=*m*. Then the subtable contains all such cells (*x*,<=*y*) (*x* is the row number, *y* is the column number), for which the following inequality holds *x*1<=≀<=*x*<=≀<=*x*2,<=*y*1<=≀<=*y*<=≀<=*y*2. The corner cells of the table are cells (*x*1,<=*y*1), (*x*1,<=*y*2), (*x*2,<=*y*1), (*x*2,<=*y*2). Vasya is already too tired after he's been writing letters to a piece of paper. That's why he asks you to count the value he is interested in. Input Specification: The first line contains three integers *n*,<=*m*,<=*k* (2<=≀<=*n*,<=*m*<=≀<=400;Β 0<=≀<=*k*<=≀<=*n*Β·*m*). Next *n* lines contain *m* characters each β€” the given table. Each character of the table is a lowercase English letter. Output Specification: Print a single integer β€” the number of required subtables. Demo Input: ['3 4 4\naabb\nbaab\nbaab\n', '4 5 1\nababa\nccaca\nccacb\ncbabc\n'] Demo Output: ['2\n', '1\n'] Note: There are two suitable subtables in the first sample: the first one's upper left corner is cell (2, 2) and lower right corner is cell (3, 3), the second one's upper left corner is cell (2, 1) and lower right corner is cell (3, 4).
1,107
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned. If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible. Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=50) β€” the number of tasks. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=108), where *a**i* represents the amount of power required for the *i*-th task. The third line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≀<=*b**i*<=≀<=100), where *b**i* is the number of processors that *i*-th task will utilize. Output Specification: Print a single integer value β€” the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up. Demo Input: ['6\n8 10 9 9 8 10\n1 1 1 1 1 1\n', '6\n8 10 9 9 8 10\n1 10 5 5 1 10\n'] Demo Output: ['9000\n', '1160\n'] Note: In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9. In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.
1,108
Title: Bags and Coins Time Limit: None seconds Memory Limit: None megabytes Problem Description: When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions: A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible? The answer is quite simple. The third bag contains a coin and two other bags. This problem is a generalization of the childhood puzzle. You have *n* bags. You know that the first bag contains *a*1 coins, the second bag contains *a*2 coins, ..., the *n*-th bag contains *a**n* coins. In total, there are *s* coins. Find the way to arrange the bags and coins so that they match the described scenario or else state that it is impossible to do. Input Specification: The first line contains two integers *n* and *s* (1<=≀<=*n*,<=*s*<=≀<=70000) β€” the number of bags and the total number of coins. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=70000), where *a**i* shows the number of coins in the *i*-th bag. Output Specification: If the answer doesn't exist, print -1. Otherwise, print *n* lines, on the *i*-th line print the contents of the *i*-th bag. The first number in the line, *c**i* (0<=≀<=*c**i*<=≀<=*a**i*), must represent the number of coins lying directly in the *i*-th bag (the coins in the bags that are in the *i*-th bag are not taken into consideration). The second number in the line, *k**i* (0<=≀<=*k**i*<=&lt;<=*n*) must represent the number of bags that lie directly in the *i*-th bag (the bags that are inside the bags lying in the *i*-th bag are not taken into consideration). Next, the line must contain *k**i* integers β€” the numbers of the bags that are lying directly in the *i*-th bag. The total number of coins in the solution must equal *s*. If we count the total number of coins the *i*-th bag in the solution has, we should get *a**i*. No bag can directly lie in more than one bag. The bags can be nested in more than one level (see the second test case). If there are multiple correct answers, you can print any of them. Demo Input: ['3 3\n1 3 1\n', '3 3\n1 3 1\n', '1 2\n1\n', '8 10\n2 7 3 4 1 3 1 2\n'] Demo Output: ['1 0\n1 2 3 1\n1 0\n', '1 0\n2 1 3\n0 1 1\n', '-1\n', '2 0\n1 2 1 4\n0 2 7 8\n0 2 5 6\n1 0\n3 0\n1 0\n2 0\n'] Note: The pictures below show two possible ways to solve one test case from the statement. The left picture corresponds to the first test case, the right picture corresponds to the second one.
1,109
Title: Drinks Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has. Find the volume fraction of orange juice in the final drink. Input Specification: The first input line contains a single integer *n* (1<=≀<=*n*<=≀<=100) β€” the number of orange-containing drinks in Vasya's fridge. The second line contains *n* integers *p**i* (0<=≀<=*p**i*<=≀<=100) β€” the volume fraction of orange juice in the *i*-th drink, in percent. The numbers are separated by a space. Output Specification: Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10<=<=-<=4. Demo Input: ['3\n50 50 100\n', '4\n0 25 50 75\n'] Demo Output: ['66.666666666667\n', '37.500000000000\n'] Note: Note to the first sample: let's assume that Vasya takes *x* milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c1fac6e64d3a8ee6a5ac138cbe51e60039b22473.png" style="max-width: 100.0%;max-height: 100.0%;"/> milliliters. The total cocktail's volume equals 3Β·*x* milliliters, so the volume fraction of the juice in the cocktail equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ceb0664e55a1f9f5fa1243ec74680a4665a4d58d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, that is, 66.(6) percent.
1,110
Title: 80-th Level Archeology Time Limit: None seconds Memory Limit: None megabytes Problem Description: Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of *n* words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section). The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph *x* (1<=≀<=*x*<=≀<=*c*<=-<=1) is replaced with hieroglyph (*x*<=+<=1), and hieroglyph *c* is replaced with hieroglyph 1. Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically. Input Specification: The first line of the input contains two integers *n* and *c* (2<=≀<=*n*<=≀<=500<=000, 1<=≀<=*c*<=≀<=106)Β β€” the number of words, written on the lock, and the number of different hieroglyphs. Each of the following *n* lines contains the description of one word. The *i*-th of these lines starts with integer *l**i* (1<=≀<=*l**i*<=≀<=500<=000), that denotes the length of the *i*-th word, followed by *l**i* integers *w**i*,<=1, *w**i*,<=2, ..., *w**i*,<=*l**i* (1<=≀<=*w**i*,<=*j*<=≀<=*c*)Β β€” the indices of hieroglyphs that make up the *i*-th word. Hieroglyph with index 1 is the smallest in the alphabet and with index *c*Β β€” the biggest. It's guaranteed, that the total length of all words doesn't exceed 106. Output Specification: If it is possible to open the door by rotating the round switch, print integer *x* (0<=≀<=*x*<=≀<=*c*<=-<=1) that defines the required number of clockwise rotations. If there are several valid *x*, print any of them. If it is impossible to open the door by this method, print <=-<=1. Demo Input: ['4 3\n2 3 2\n1 1\n3 2 3 1\n4 2 3 1 2\n', '2 5\n2 4 2\n2 4 2\n', '4 4\n1 2\n1 3\n1 4\n1 2\n'] Demo Output: ['1\n', '0\n', '-1\n'] Note: Word *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ..., *a*<sub class="lower-index">*m*</sub> of length *m* is lexicographically not greater than word *b*<sub class="lower-index">1</sub>, *b*<sub class="lower-index">2</sub>, ..., *b*<sub class="lower-index">*k*</sub> of length *k*, if one of two conditions hold: - at first position *i*, such that *a*<sub class="lower-index">*i*</sub> ≠ *b*<sub class="lower-index">*i*</sub>, the character *a*<sub class="lower-index">*i*</sub> goes earlier in the alphabet than character *b*<sub class="lower-index">*i*</sub>, i.e. *a* has smaller character in the first position where they differ; - if there is no such position *i* and *m* ≀ *k*, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word. In the first sample, after the round switch is rotated 1 position clockwise the words look as follows: In the second sample, words are already sorted in lexicographical order. In the last sample, one can check that no shift of the alphabet will work.
1,111
Title: Script Generation Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series. There are *n* single men and *n* single women among the main characters. An opinion poll showed that viewers like several couples, and a marriage of any of them will make the audience happy. The Smart Beaver formalized this fact as *k* triples of numbers (*h*,<=*w*,<=*r*), where *h* is the index of the man, *w* is the index of the woman, and *r* is the measure of the audience's delight in case of the marriage of this couple. The same poll showed that the marriage of any other couple will leave the audience indifferent, so the screenwriters decided not to include any such marriages in the plot. The script allows you to arrange several marriages between the heroes or not to arrange marriages at all. A subset of some of the *k* marriages is considered acceptable if each man and each woman is involved in at most one marriage of the subset (the series won't allow any divorces). The value of the acceptable set of marriages is the total delight the spectators will get from the marriages included in this set. Obviously, there is a finite number of acceptable sets, and they all describe some variants of the script. The screenwriters do not want to choose a set with maximum value β€” it would make the plot too predictable. So the Smart Beaver offers the following option: sort all the acceptable sets in increasing order of value and choose the *t*-th set from the sorted list. Thus, *t*<==<=1 corresponds to a plot without marriages, *t*<==<=2 β€” to a single marriage resulting in minimal delight for the audience, and so on. Help the Beaver to implement the algorithm for selecting the desired set. Input Specification: The first input line contains integers *n*, *k* and *t* (1<=≀<=*k*<=≀<=*min*(100,<=*n*2), 1<=≀<=*t*<=≀<=2Β·105), separated by single spaces. Next *k* lines contain triples of integers (*h*,<=*w*,<=*r*) (1<=≀<=*h*,<=*w*<=≀<=*n*;Β 1<=≀<=*r*<=≀<=1000), separated by single spaces, which describe the possible marriages. It is guaranteed that the input data is correct: *t* doesn't exceed the total number of acceptable sets, and each pair (*h*,<=*w*) is present in at most one triple. The input limitations for getting 30 points are: - 1<=≀<=*n*<=≀<=5 The input limitations for getting 100 points are: - 1<=≀<=*n*<=≀<=20 Output Specification: Print a single number β€” the value of the *t*-th acceptable variant. Demo Input: ['2 4 3\n1 1 1\n1 2 2\n2 1 3\n2 2 7\n', '2 4 7\n1 1 1\n1 2 2\n2 1 3\n2 2 7\n'] Demo Output: ['2\n', '8\n'] Note: The figure shows 7 acceptable sets of marriages that exist in the first sample.
1,112
Title: Triangular numbers Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number). Your task is to find out if a given integer is a triangular number. Input Specification: The first line contains the single number *n* (1<=≀<=*n*<=≀<=500) β€” the given integer. Output Specification: If the given integer is a triangular number output YES, otherwise output NO. Demo Input: ['1\n', '2\n', '3\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n'] Note: none
1,113
Title: Beautiful Decomposition Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera considers a number beautiful, if it equals 2*k* or -2*k* for some integer *k* (*k*<=β‰₯<=0). Recently, the math teacher asked Valera to represent number *n* as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number *n* into beautiful summands, you need to find the size of the decomposition which has the fewest summands. Input Specification: The first line contains string *s* (1<=≀<=|*s*|<=≀<=106), that is the binary representation of number *n* without leading zeroes (*n*<=&gt;<=0). Output Specification: Print a single integer β€” the minimum amount of beautiful numbers that give a total of *n*. Demo Input: ['10\n', '111\n', '1101101\n'] Demo Output: ['1\n', '2\n', '4\n'] Note: In the first sample *n* = 2 is a beautiful number. In the second sample *n* = 7 and Valera can decompose it into sum 2<sup class="upper-index">3</sup> + ( - 2<sup class="upper-index">0</sup>). In the third sample *n* = 109 can be decomposed into the sum of four summands as follows: 2<sup class="upper-index">7</sup> + ( - 2<sup class="upper-index">4</sup>) + ( - 2<sup class="upper-index">2</sup>) + 2<sup class="upper-index">0</sup>.
1,114
Title: Choosing The Commander Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires. Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors. Each warrior is represented by his personality β€” an integer number *p**i*. Each commander has two characteristics β€” his personality *p**j* and leadership *l**j* (both are integer numbers). Warrior *i* respects commander *j* only if ( is the bitwise excluding OR of *x* and *y*). Initially Vova's army is empty. There are three different types of events that can happen with the army: - 1Β *p**i* β€” one warrior with personality *p**i* joins Vova's army; - 2Β *p**i* β€” one warrior with personality *p**i* leaves Vova's army; - 3Β *p**i*Β *l**i* β€” Vova tries to hire a commander with personality *p**i* and leadership *l**i*. For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire. Input Specification: The first line contains one integer *q* (1<=≀<=*q*<=≀<=100000) β€” the number of events. Then *q* lines follow. Each line describes the event: - 1Β *p**i* (1<=≀<=*p**i*<=≀<=108) β€” one warrior with personality *p**i* joins Vova's army; - 2Β *p**i* (1<=≀<=*p**i*<=≀<=108) β€” one warrior with personality *p**i* leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment); - 3Β *p**i*Β *l**i* (1<=≀<=*p**i*,<=*l**i*<=≀<=108) β€” Vova tries to hire a commander with personality *p**i* and leadership *l**i*. There is at least one event of this type. Output Specification: For each event of the third type print one integer β€” the number of warriors who respect the commander Vova tries to hire in the event. Demo Input: ['5\n1 3\n1 4\n3 6 3\n2 4\n3 6 3\n'] Demo Output: ['1\n0\n'] Note: In the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him (<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3d8e4cd0a5c3c0cdc8b35097f3dc7317604240a6.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and 2 &lt; 3, but <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4e3eeab99fa495ecdcd103c68de47dd72943016f.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and 5 β‰₯ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.
1,115
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Greg has a weighed directed graph, consisting of *n* vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: - The game consists of *n* steps. - On the *i*-th step Greg removes vertex number *x**i* from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. - Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that *d*(*i*,<=*v*,<=*u*) is the shortest path between vertices *v* and *u* in the graph that formed before deleting vertex *x**i*, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=500) β€” the number of vertices in the graph. Next *n* lines contain *n* integers each β€” the graph adjacency matrix: the *j*-th number in the *i*-th line *a**ij* (1<=≀<=*a**ij*<=≀<=105,<=*a**ii*<==<=0) represents the weight of the edge that goes from vertex *i* to vertex *j*. The next line contains *n* distinct integers: *x*1,<=*x*2,<=...,<=*x**n* (1<=≀<=*x**i*<=≀<=*n*) β€” the vertices that Greg deletes. Output Specification: Print *n* integers β€” the *i*-th number equals the required sum before the *i*-th step. 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 of the %I64d specifier. Demo Input: ['1\n0\n1\n', '2\n0 5\n4 0\n1 2\n', '4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3\n'] Demo Output: ['0 ', '9 0 ', '17 23 404 0 '] Note: none
1,116
Title: Dark Assembly Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed. The Dark Assembly consists of *n* senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to 10%. Senators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If strictly more than half of the senators take a positive decision, the player's proposal is approved. If the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to *A*<=/<=(*A*<=+<=*B*), where *A* is the sum of levels of all player's characters and *B* is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved. Senators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by 10%. It's worth to mention that loyalty cannot exceed 100%. The player can take no more than *k* sweets to the courtroom. Candies should be given to the senators before the start of voting. Determine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way. Input Specification: The first line contains three integers *n*, *k* and *A* (1<=≀<=*n*,<=*k*<=≀<=8, 1<=≀<=*A*<=≀<=9999). Then *n* lines follow. The *i*-th of them contains two numbers β€” *b**i* and *l**i* β€” the *i*-th senator's level and his loyalty. The levels of all senators are integers in range from 1 to 9999 (inclusive). The loyalties of all senators are integers in range from 0 to 100 (inclusive) and all of them are divisible by 10. Output Specification: Print one real number with precision 10<=-<=6 β€” the maximal possible probability that the Dark Assembly approves the player's proposal for the best possible distribution of candies among the senators. Demo Input: ['5 6 100\n11 80\n14 90\n23 70\n80 30\n153 70\n', '5 3 100\n11 80\n14 90\n23 70\n80 30\n153 70\n', '1 3 20\n20 20\n'] Demo Output: ['1.0000000000\n', '0.9628442962\n', '0.7500000000\n'] Note: In the first sample the best way of candies' distribution is giving them to first three of the senators. It ensures most of votes. It the second sample player should give all three candies to the fifth senator.
1,117
Title: Playing on Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of *n* vertices and *m* edges without loops and multiple edges. Let's define the operation of contraction two vertices *a* and *b* that are not connected by an edge. As a result of this operation vertices *a* and *b* are deleted and instead of them a new vertex *x* is added into the graph, and also edges are drawn from it to all vertices that were connected with *a* or with *b* (specifically, if the vertex was connected with both *a* and *b*, then also exactly one edge is added from *x* to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (*n*<=-<=1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length *k* (*k*<=β‰₯<=0) is a connected graph whose vertices can be numbered with integers from 1 to *k*<=+<=1 so that the edges of the graph connect all pairs of vertices (*i*,<=*i*<=+<=1) (1<=≀<=*i*<=≀<=*k*) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input Specification: The first line contains two integers *n*,<=*m* (1<=≀<=*n*<=≀<=1000, 0<=≀<=*m*<=≀<=100<=000) β€” the number of vertices and the number of edges in the original graph. Next *m* lines contain the descriptions of edges in the format *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a**i*<=β‰ <=*b**i*), which means that there is an edge between vertices *a**i* and *b**i*. It is guaranteed that there is at most one edge between each pair of vertexes. Output Specification: If it is impossible to obtain a chain from the given graph, print <=-<=1. Otherwise, print the maximum possible number of edges in the resulting chain. Demo Input: ['5 4\n1 2\n2 3\n3 4\n3 5\n', '4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4\n', '4 2\n1 3\n2 4\n'] Demo Output: ['3\n', '-1\n', '2\n'] Note: In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
1,118
Title: Extract Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given string *s*. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string *s*=";;" contains three empty words separated by ';'. You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string *a*. String *a* should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string *s*). By all other words you should build string *b* in the same way (the order of numbers should remain the same as in the string *s*). Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not. For example, for the string aba,123;1a;0 the string *a* would be equal to "123,0" and string *b* would be equal to "aba,1a". Input Specification: The only line of input contains the string *s* (1<=≀<=|*s*|<=≀<=105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. Output Specification: Print the string *a* to the first line and string *b* to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. Demo Input: ['aba,123;1a;0\n', '1;;01,a0,\n', '1\n', 'a\n'] Demo Output: ['"123,0"\n"aba,1a"\n', '"1"\n",01,a0,"\n', '"1"\n-\n', '-\n"a"\n'] Note: In the second example the string *s* contains five words: "1", "", "01", "a0", "".
1,119
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Shuseki Kingdom is the world's leading nation for innovation and technology. There are *n* cities in the kingdom, numbered from 1 to *n*. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city *x* to city *y* cannot be used to travel from city *y* to city *x*. The transportation within each city is extremely developed, therefore if a pipe from city *x* to city *y* and a pipe from city *y* to city *z* are both constructed, people will be able to travel from city *x* to city *z* instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the *m* pairs of city (*a**i*,<=*b**i*) (1<=≀<=*i*<=≀<=*m*) is important. He is planning to construct teleportation pipes so that for each important pair (*a**i*,<=*b**i*), it will be possible to travel from city *a**i* to city *b**i* by using one or more teleportation pipes (but not necessarily from city *b**i* to city *a**i*). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input Specification: The first line contains two space-separated integers *n* and *m* (2<=≀<=*n*<=≀<=105,<=1<=≀<=*m*<=≀<=105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following *m* lines describe the important pairs. The *i*-th of them (1<=≀<=*i*<=≀<=*m*) contains two space-separated integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*), denoting that it must be possible to travel from city *a**i* to city *b**i* by using one or more teleportation pipes (but not necessarily from city *b**i* to city *a**i*). It is guaranteed that all pairs (*a**i*,<=*b**i*) are distinct. Output Specification: Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Demo Input: ['4 5\n1 2\n1 3\n1 4\n2 3\n2 4\n', '4 6\n1 2\n1 4\n2 3\n2 4\n3 2\n3 4\n'] Demo Output: ['3\n', '4\n'] Note: For the first sample, one of the optimal ways to construct pipes is shown in the image below: For the second sample, one of the optimal ways is shown below:
1,120
Title: Trees Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: On Bertown's main street *n* trees are growing, the tree number *i* has the height of *a**i* meters (1<=≀<=*i*<=≀<=*n*). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the *n*-th one) should be equal to each other, the heights of the 2-nd and the (*n*<=-<=1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105) which is the number of trees. The second line contains integers *a**i* (1<=≀<=*a**i*<=≀<=105) which are the heights of the trees. Output Specification: Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful. Demo Input: ['3\n2 2 2\n', '4\n1 2 2 1\n'] Demo Output: ['1\n', '0\n'] Note: none
1,121
Title: Hamming Distance Sum Time Limit: None seconds Memory Limit: None megabytes Problem Description: Genos needs your help. He was asked to solve the following programming problem by Saitama: The length of some string *s* is denoted |*s*|. The Hamming distance between two strings *s* and *t* of equal length is defined as , where *s**i* is the *i*-th character of *s* and *t**i* is the *i*-th character of *t*. For example, the Hamming distance between string "0011" and string "0110" is |0<=-<=0|<=+<=|0<=-<=1|<=+<=|1<=-<=1|<=+<=|1<=-<=0|<==<=0<=+<=1<=+<=0<=+<=1<==<=2. Given two binary strings *a* and *b*, find the sum of the Hamming distances between *a* and all contiguous substrings of *b* of length |*a*|. Input Specification: The first line of the input contains binary string *a* (1<=≀<=|*a*|<=≀<=200<=000). The second line of the input contains binary string *b* (|*a*|<=≀<=|*b*|<=≀<=200<=000). Both strings are guaranteed to consist of characters '0' and '1' only. Output Specification: Print a single integerΒ β€” the sum of Hamming distances between *a* and all contiguous substrings of *b* of length |*a*|. Demo Input: ['01\n00111\n', '0011\n0110\n'] Demo Output: ['3\n', '2\n'] Note: For the first sample case, there are four contiguous substrings of *b* of length |*a*|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3. The second sample case is described in the statement.
1,122
Title: Knight Tournament Time Limit: None seconds Memory Limit: None megabytes Problem Description: Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: - There are *n* knights participating in the tournament. Each knight was assigned his unique number β€” an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won β€” the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*. Write the code that calculates for each knight, the name of the knight that beat him. Input Specification: The first line contains two integers *n*, *m* (2<=≀<=*n*<=≀<=3Β·105;Β 1<=≀<=*m*<=≀<=3Β·105) β€” the number of knights and the number of fights. Each of the following *m* lines contains three integers *l**i*,<=*r**i*,<=*x**i* (1<=≀<=*l**i*<=&lt;<=*r**i*<=≀<=*n*;Β *l**i*<=≀<=*x**i*<=≀<=*r**i*) β€” the description of the *i*-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle. Output Specification: Print *n* integers. If the *i*-th knight lost, then the *i*-th number should equal the number of the knight that beat the knight number *i*. If the *i*-th knight is the winner, then the *i*-th number must equal 0. Demo Input: ['4 3\n1 2 1\n1 3 3\n1 4 4\n', '8 4\n3 5 4\n3 7 6\n2 8 8\n1 8 1\n'] Demo Output: ['3 1 4 0 ', '0 8 4 6 4 8 6 1 '] Note: Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
1,123
Title: Flipping Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Iahub got bored, so he invented a game to be played on paper. He writes *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices *i* and *j* (1<=≀<=*i*<=≀<=*j*<=≀<=*n*) and flips all values *a**k* for which their positions are in range [*i*,<=*j*] (that is *i*<=≀<=*k*<=≀<=*j*). Flip the value of *x* means to apply operation *x*<==<=1 - *x*. The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. Input Specification: The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=100). In the second line of the input there are *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. It is guaranteed that each of those *n* values is either 0 or 1. Output Specification: Print an integer β€” the maximal number of 1s that can be obtained after exactly one move. Demo Input: ['5\n1 0 0 1 0\n', '4\n1 0 0 1\n'] Demo Output: ['4\n', '4\n'] Note: In the first case, flip the segment from 2 to 5 (*i* = 2, *j* = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1]. In the second case, flipping only the second and the third element (*i* = 2, *j* = 3) will turn all numbers into 1.
1,124
Title: Levko and Permutation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Levko loves permutations very much. A permutation of length *n* is a sequence of distinct positive integers, each is at most *n*. Let’s assume that value *gcd*(*a*,<=*b*) shows the greatest common divisor of numbers *a* and *b*. Levko assumes that element *p**i* of permutation *p*1,<=*p*2,<=... ,<=*p**n* is good if *gcd*(*i*,<=*p**i*)<=&gt;<=1. Levko considers a permutation beautiful, if it has exactly *k* good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them. Input Specification: The single line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=105, 0<=≀<=*k*<=≀<=*n*). Output Specification: In a single line print either any beautiful permutation or -1, if such permutation doesn’t exist. If there are multiple suitable permutations, you are allowed to print any of them. Demo Input: ['4 2\n', '1 1\n'] Demo Output: ['2 4 3 1', '-1\n'] Note: In the first sample elements 4 and 3 are good because *gcd*(2, 4) = 2 &gt; 1 and *gcd*(3, 3) = 3 &gt; 1. Elements 2 and 1 are not good because *gcd*(1, 2) = 1 and *gcd*(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful. The second sample has no beautiful permutations.
1,125
Title: Key races Time Limit: None seconds Memory Limit: None megabytes Problem Description: Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds. If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows: 1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw. Given the length of the text and the information about participants, determine the result of the game. Input Specification: The first line contains five integers *s*, *v*1, *v*2, *t*1, *t*2 (1<=≀<=*s*,<=*v*1,<=*v*2,<=*t*1,<=*t*2<=≀<=1000)Β β€” the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant. Output Specification: If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship". Demo Input: ['5 1 2 1 2\n', '3 3 1 1 1\n', '4 5 3 1 5\n'] Demo Output: ['First\n', 'Second\n', 'Friendship\n'] Note: In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participantΒ β€” in 14 milliseconds. So, the first wins. In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participantΒ β€” in 5 milliseconds. So, the second wins. In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participantΒ β€” in 22 milliseconds. So, it is be a draw.
1,126
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alexandra has a paper strip with *n* numbers on it. Let's call them *a**i* from left to right. Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: - Each piece should contain at least *l* numbers.- The difference between the maximal and the minimal number on the piece should be at most *s*. Please help Alexandra to find the minimal number of pieces meeting the condition above. Input Specification: The first line contains three space-separated integers *n*,<=*s*,<=*l* (1<=≀<=*n*<=≀<=105,<=0<=≀<=*s*<=≀<=109,<=1<=≀<=*l*<=≀<=105). The second line contains *n* integers *a**i* separated by spaces (<=-<=109<=≀<=*a**i*<=≀<=109). Output Specification: Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. Demo Input: ['7 2 2\n1 3 1 2 4 1 2\n', '7 2 2\n1 100 1 100 1 100 1\n'] Demo Output: ['3\n', '-1\n'] Note: For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2]. For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.
1,127
Title: Maximum Control (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets. The Galaxy contains *N* planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets. A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits. Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every *K*<==<=1,<=2,<=3,<=...,<=*N*, the maximum number of planets that can be controlled with a fleet consisting of *K* ships. Input Specification: The first line of the input contains an integer *N* (1<=≀<=*N*<=≀<=105) – the number of planets in the galaxy. The next *N*<=-<=1 lines describe the hyperspace tunnels between the planets. Each of the *N*<=-<=1 lines contains two space-separated integers *u* and *v* (1<=≀<=*u*,<=*v*<=≀<=*N*) indicating that there is a bidirectional hyperspace tunnel between the planets *u* and *v*. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets. Output Specification: On a single line, print *N* space-separated integers. The *K*-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of *K* ships. Demo Input: ['3\n1 2\n2 3\n', '4\n1 2\n3 2\n4 2\n'] Demo Output: ['1 3 3 ', '1 3 4 4 '] Note: Consider the first example. If *K* = 1, then Heidi can only send one ship to some planet and control it. However, for *K* β‰₯ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
1,128
Title: Vasily the Bear and Triangle Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he asks you to find two points *A*<==<=(*x*1,<=*y*1) and *C*<==<=(*x*2,<=*y*2), such that the following conditions hold: - the coordinates of points: *x*1, *x*2, *y*1, *y*2 are integers. Besides, the following inequation holds: *x*1<=&lt;<=*x*2; - the triangle formed by point *A*, *B* and *C* is rectangular and isosceles ( is right); - all points of the favorite rectangle are located inside or on the border of triangle *ABC*; - the area of triangle *ABC* is as small as possible. Help the bear, find the required points. It is not so hard to proof that these points are unique. Input Specification: The first line contains two integers *x*,<=*y* (<=-<=109<=≀<=*x*,<=*y*<=≀<=109,<=*x*<=β‰ <=0,<=*y*<=β‰ <=0). Output Specification: Print in the single line four integers *x*1,<=*y*1,<=*x*2,<=*y*2 β€” the coordinates of the required points. Demo Input: ['10 5\n', '-10 5\n'] Demo Output: ['0 15 15 0\n', '-15 0 0 15\n'] Note: <img class="tex-graphics" src="https://espresso.codeforces.com/a9ea2088c4294ce8f23801562fda36b830df2c3f.png" style="max-width: 100.0%;max-height: 100.0%;"/> Figure to the first sample
1,129
Title: Common ancestor Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are *n* permissible substitutions. The substitution *a**i*-&gt;*b**i**c**i* means that any one symbol *a**i* can be replaced with two symbols *b**i**c**i*. Every substitution could happen an unlimited number of times. They say that two creatures with DNA sequences *s*1 and *s*2 can have a common ancestor if there exists such a DNA sequence *s*3 that throughout evolution it can result in *s*1 and *s*2, perhaps after a different number of stages. Your task is to find out by the given *s*1 and *s*2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestor’s DNA. Input Specification: The first line contains a non-empty DNA sequence *s*1, the second line contains a non-empty DNA sequence *s*2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer *n* (0<=≀<=*n*<=≀<=50) β€” the number of permissible substitutions. Then follow *n* lines each of which describes a substitution in the format *a**i*-&gt;*b**i**c**i*. The characters *a**i*, *b**i*, and *c**i* are lowercase Latin letters. Lines *s*1 and *s*2 can coincide, the list of substitutions can contain similar substitutions. Output Specification: If *s*1 and *s*2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence *s*3, from which *s*1 and *s*2 could have evolved. Demo Input: ['ababa\naba\n2\nc-&gt;ba\nc-&gt;cc\n', 'ababa\naba\n7\nc-&gt;ba\nc-&gt;cc\ne-&gt;ab\nz-&gt;ea\nb-&gt;ba\nd-&gt;dd\nd-&gt;ab\n', 'ababa\naba\n1\nc-&gt;ba\n'] Demo Output: ['2\n', '1\n', '-1\n'] Note: none
1,130
Title: Package Delivery Time Limit: None seconds Memory Limit: None megabytes Problem Description: Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point *d*. Johnny's truck has a gas tank that holds exactly *n* liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are *m* gas stations located at various points along the way to the district center. The *i*-th station is located at the point *x**i* on the number line and sells an unlimited amount of fuel at a price of *p**i* dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery. Input Specification: The first line of input contains three space separated integers *d*, *n*, and *m* (1<=≀<=*n*<=≀<=*d*<=≀<=109, 1<=≀<=*m*<=≀<=200 000)Β β€” the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively. Each of the next *m* lines contains two integers *x**i*, *p**i* (1<=≀<=*x**i*<=≀<=*d*<=-<=1, 1<=≀<=*p**i*<=≀<=106)Β β€” the position and cost of gas at the *i*-th gas station. It is guaranteed that the positions of the gas stations are distinct. Output Specification: Print a single integerΒ β€” the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1. Demo Input: ['10 4 4\n3 5\n5 8\n6 3\n8 4\n', '16 5 2\n8 2\n5 1\n'] Demo Output: ['22\n', '-1\n'] Note: In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2Β·5 + 4Β·3 = 22 dollars. In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
1,131
Title: Magazine Ad Time Limit: None seconds Memory Limit: None megabytes Problem Description: The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this: There are space-separated non-empty words of lowercase and uppercase Latin letters. There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding. The ad can occupy no more that *k* lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it. You should write a program that will find minimal width of the ad. Input Specification: The first line contains number *k* (1<=≀<=*k*<=≀<=105). The second line contains the text of the ad β€” non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters. Output Specification: Output minimal width of the ad. Demo Input: ['4\ngarage for sa-le\n', '4\nEdu-ca-tion-al Ro-unds are so fun\n'] Demo Output: ['7\n', '10\n'] Note: Here all spaces are replaced with dots. In the first example one of possible results after all word wraps looks like this: The second example:
1,132
Title: Transportation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera came to Japan and bought many robots for his research. He's already at the airport, the plane will fly very soon and Valera urgently needs to bring all robots to the luggage compartment. The robots are self-propelled (they can potentially move on their own), some of them even have compartments to carry other robots. More precisely, for the *i*-th robot we know value *c**i* β€” the number of robots it can carry. In this case, each of *c**i* transported robots can additionally carry other robots. However, the robots need to be filled with fuel to go, so Valera spent all his last money and bought *S* liters of fuel. He learned that each robot has a restriction on travel distances. Thus, in addition to features *c**i*, the *i*-th robot has two features *f**i* and *l**i* β€” the amount of fuel (in liters) needed to move the *i*-th robot, and the maximum distance that the robot can go. Due to the limited amount of time and fuel, Valera wants to move the maximum number of robots to the luggage compartment. He operates as follows. - First Valera selects some robots that will travel to the luggage compartment on their own. In this case the total amount of fuel required to move all these robots must not exceed *S*. - Then Valera seats the robots into the compartments, so as to transport as many robots as possible. Note that if a robot doesn't move by itself, you can put it in another not moving robot that is moved directly or indirectly by a moving robot. - After that all selected and seated robots along with Valera go to the luggage compartment and the rest robots will be lost. There are *d* meters to the luggage compartment. Therefore, the robots that will carry the rest, must have feature *l**i* of not less than *d*. During the moving Valera cannot stop or change the location of the robots in any way. Help Valera calculate the maximum number of robots that he will be able to take home, and the minimum amount of fuel he will have to spend, because the remaining fuel will come in handy in Valera's research. Input Specification: The first line contains three space-separated integers *n*,<=*d*,<=*S* (1<=≀<=*n*<=≀<=105,<=1<=≀<=*d*,<=*S*<=≀<=109). The first number represents the number of robots, the second one β€” the distance to the luggage compartment and the third one β€” the amount of available fuel. Next *n* lines specify the robots. The *i*-th line contains three space-separated integers *c**i*,<=*f**i*,<=*l**i* (0<=≀<=*c**i*,<=*f**i*,<=*l**i*<=≀<=109) β€” the *i*-th robot's features. The first number is the number of robots the *i*-th robot can carry, the second number is the amount of fuel needed for the *i*-th robot to move and the third one shows the maximum distance the *i*-th robot can go. Output Specification: Print two space-separated integers β€” the maximum number of robots Valera can transport to the luggage compartment and the minimum amount of fuel he will need for that. If Valera won't manage to get any robots to the luggage compartment, print two zeroes. Demo Input: ['3 10 10\n0 12 10\n1 6 10\n0 1 1\n', '2 7 10\n3 12 10\n5 16 8\n', '4 8 10\n0 12 3\n1 1 0\n0 3 11\n1 6 9\n'] Demo Output: ['2 6\n', '0 0\n', '4 9\n'] Note: none
1,133
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the *m* friends found *n* different kinds of milk on the menu, that's why they ordered *n* bottles β€” one bottle of each kind. We know that the volume of milk in each bottle equals *w*. When the bottles were brought in, they decided to pour all the milk evenly among the *m* cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem β€” and what is actually the way to do it? Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible! Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup. Input Specification: The only input data file contains three integers *n*, *w* and *m* (1<=≀<=*n*<=≀<=50, 100<=≀<=*w*<=≀<=1000, 2<=≀<=*m*<=≀<=50), where *n* stands for the number of ordered bottles, *w* stands for the volume of each of them and *m* stands for the number of friends in the company. Output Specification: Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO". If there is a solution, then print *m* more lines, where the *i*-th of them describes the content of the *i*-th student's cup. The line should consist of one or more pairs that would look like "*b* *v*". Each such pair means that *v* (*v*<=&gt;<=0) units of milk were poured into the *i*-th cup from bottle *b* (1<=≀<=*b*<=≀<=*n*). All numbers *b* on each line should be different. If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point. Demo Input: ['2 500 3\n', '4 100 5\n', '4 100 7\n', '5 500 2\n'] Demo Output: ['YES\n1 333.333333\n2 333.333333\n2 166.666667 1 166.666667\n', 'YES\n3 20.000000 4 60.000000\n1 80.000000\n4 40.000000 2 40.000000\n3 80.000000\n2 60.000000 1 20.000000\n', 'NO\n', 'YES\n4 250.000000 5 500.000000 2 500.000000\n3 500.000000 1 500.000000 4 250.000000\n'] Note: none
1,134
Title: Oath of the Night's Watch Time Limit: None seconds Memory Limit: None megabytes Problem Description: "Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." β€” The Night's Watch oath. With that begins the watch of Jon Snow. He is assigned the task to support the stewards. This time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him. Can you find how many stewards will Jon support? Input Specification: First line consists of a single integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of stewards with Jon Snow. Second line consists of *n* space separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109) representing the values assigned to the stewards. Output Specification: Output a single integer representing the number of stewards which Jon will feed. Demo Input: ['2\n1 5\n', '3\n1 2 5\n'] Demo Output: ['0', '1'] Note: In the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5. In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.
1,135
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in *t* minutes. There is a straight road of length *s* from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point *s*. There are *k* gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly. There are *n* cars in the rental service, *i*-th of them is characterized with two integers *c**i* and *v**i*Β β€” the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity *v**i*. All cars are completely fueled at the car rental service. Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times. Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in *t* minutes. Assume that all cars are completely fueled initially. Input Specification: The first line contains four positive integers *n*, *k*, *s* and *t* (1<=≀<=*n*<=≀<=2Β·105, 1<=≀<=*k*<=≀<=2Β·105, 2<=≀<=*s*<=≀<=109, 1<=≀<=*t*<=≀<=2Β·109)Β β€” the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next *n* lines contains two positive integers *c**i* and *v**i* (1<=≀<=*c**i*,<=*v**i*<=≀<=109)Β β€” the price of the *i*-th car and its fuel tank capacity. The next line contains *k* distinct integers *g*1,<=*g*2,<=...,<=*g**k* (1<=≀<=*g**i*<=≀<=*s*<=-<=1)Β β€” the positions of the gas stations on the road in arbitrary order. Output Specification: Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in *t* minutes). If there is no appropriate car, print -1. Demo Input: ['3 1 8 10\n10 8\n5 7\n11 9\n3\n', '2 2 10 18\n10 4\n20 6\n5 3\n'] Demo Output: ['10\n', '20\n'] Note: In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
1,136
Title: Presents Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there. If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift. Now Petya wants to know for each friend *i* the number of a friend who has given him a gift. Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=100) β€” the quantity of friends Petya invited to the party. The second line contains *n* space-separated integers: the *i*-th number is *p**i* β€” the number of a friend who gave a gift to friend number *i*. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves. Output Specification: Print *n* space-separated integers: the *i*-th number should equal the number of the friend who gave a gift to friend number *i*. Demo Input: ['4\n2 3 4 1\n', '3\n1 3 2\n', '2\n1 2\n'] Demo Output: ['4 1 2 3\n', '1 3 2\n', '1 2\n'] Note: none
1,137
Title: Weird Subtraction Process Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have two variables *a* and *b*. Consider the following sequence of actions performed with these variables: 1. If *a*<==<=0 or *b*<==<=0, end the process. Otherwise, go to step 2;1. If *a*<=β‰₯<=2Β·*b*, then set the value of *a* to *a*<=-<=2Β·*b*, and repeat step 1. Otherwise, go to step 3;1. If *b*<=β‰₯<=2Β·*a*, then set the value of *b* to *b*<=-<=2Β·*a*, and repeat step 1. Otherwise, end the process. Initially the values of *a* and *b* are positive integers, and so the process will be finite. You have to determine the values of *a* and *b* after the process ends. Input Specification: The only line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=1018). *n* is the initial value of variable *a*, and *m* is the initial value of variable *b*. Output Specification: Print two integers β€” the values of *a* and *b* after the end of the process. Demo Input: ['12 5\n', '31 12\n'] Demo Output: ['0 1\n', '7 12\n'] Note: Explanations to the samples: 1. *a* = 12, *b* = 5 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> *a* = 2, *b* = 5 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> *a* = 2, *b* = 1 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> *a* = 0, *b* = 1;1. *a* = 31, *b* = 12 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> *a* = 7, *b* = 12.
1,138
Title: Ghosts Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way. There are $n$ ghosts in the universe, they move in the $OXY$ plane, each one of them has its own velocity that does not change in time: $\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j}$ where $V_{x}$ is its speed on the $x$-axis and $V_{y}$ is on the $y$-axis. A ghost $i$ has experience value $EX_i$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time. As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $GX = \sum_{i=1}^{n} EX_i$ will never increase. Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $T$, and magically all the ghosts were aligned on a line of the form $y = a \cdot x + b$. You have to compute what will be the experience index of the ghost kind $GX$ in the indefinite future, this is your task for today. Note that when Tameem took the picture, $GX$ may already be greater than $0$, because many ghosts may have scared one another at any moment between $[-\infty, T]$. Input Specification: The first line contains three integers $n$, $a$ and $b$ ($1 \leq n \leq 200000$, $1 \leq |a| \leq 10^9$, $0 \le |b| \le 10^9$)Β β€” the number of ghosts in the universe and the parameters of the straight line. Each of the next $n$ lines contains three integers $x_i$, $V_{xi}$, $V_{yi}$ ($-10^9 \leq x_i \leq 10^9$, $-10^9 \leq V_{x i}, V_{y i} \leq 10^9$), where $x_i$ is the current $x$-coordinate of the $i$-th ghost (and $y_i = a \cdot x_i + b$). It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all $(i,j)$ $x_i \neq x_j$ for $i \ne j$. Output Specification: Output one line: experience index of the ghost kind $GX$ in the indefinite future. Demo Input: ['4 1 1\n1 -1 -1\n2 1 1\n3 1 1\n4 -1 -1\n', '3 1 0\n-1 1 0\n0 0 -1\n1 -1 -2\n', '3 1 0\n0 0 0\n1 0 0\n2 0 0\n'] Demo Output: ['8\n', '6\n', '0\n'] Note: There are four collisions $(1,2,T-0.5)$, $(1,3,T-1)$, $(2,4,T+1)$, $(3,4,T+0.5)$, where $(u,v,t)$ means a collision happened between ghosts $u$ and $v$ at moment $t$. At each collision, each ghost gained one experience point, this means that $GX = 4 \cdot 2 = 8$. In the second test, all points will collide when $t = T + 1$. The red arrow represents the 1-st ghost velocity, orange represents the 2-nd ghost velocity, and blue represents the 3-rd ghost velocity.
1,139
Title: Petya and Countryside Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=Γ—<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section. Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1<=Γ—<=5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture: As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him. Input Specification: The first line contains a positive integer *n* (1<=≀<=*n*<=≀<=1000). The second line contains *n* positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000. Output Specification: Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section. Demo Input: ['1\n2\n', '5\n1 2 1 2 1\n', '8\n1 2 1 1 1 3 3 4\n'] Demo Output: ['1\n', '3\n', '6\n'] Note: none
1,140
Title: Digital Root Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Not long ago Billy came across such a problem, where there were given three natural numbers *A*, *B* and *C* from the range [1,<=*N*], and it was asked to check whether the equation *AB*<==<=*C* is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root *d*(*x*) of the number *x* is the sum *s*(*x*) of all the digits of this number, if *s*(*x*)<=≀<=9, otherwise it is *d*(*s*(*x*)). For example, a digital root of the number 6543 is calculated as follows: *d*(6543)<==<=*d*(6<=+<=5<=+<=4<=+<=3)<==<=*d*(18)<==<=9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. *d*(*xy*)<==<=*d*(*d*(*x*)*d*(*y*)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes. Input Specification: The first line contains the only number *N* (1<=≀<=*N*<=≀<=106). Output Specification: Output one number β€” the amount of required *A*, *B* and *C* from the range [1,<=*N*]. Demo Input: ['4\n', '5\n'] Demo Output: ['2\n', '6\n'] Note: For the first sample the required triples are (3, 4, 3) and (4, 3, 3).
1,141
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as *n* consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than *t* time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional *k* kilos of sweets. Cindy Lou wants to know the minimum number of *k* kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of *k*. Input Specification: The first line of the input contains two space-separated integers *n* and *t* (2<=≀<=*n*<=≀<=5Β·105,<=1<=≀<=*t*<=≀<=109). The second line of the input contains *n* characters, the *i*-th of them equals "H" (if the *i*-th segment contains a house), "S" (if the *i*-th segment contains a shop) or "." (if the *i*-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output Specification: If there isn't a single value of *k* that makes it possible to give sweets to everybody in at most *t* units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of *k*. Demo Input: ['6 6\nHSHSHS\n', '14 100\n...HHHSSS...SH\n', '23 50\nHHSS.......SSHHHHHHHHHH\n'] Demo Output: ['1\n', '0\n', '8\n'] Note: In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home.
1,142
Title: Kostya the Sculptor Time Limit: None seconds Memory Limit: None megabytes Problem Description: Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has *n* stones which are rectangular parallelepipeds. The edges sizes of the *i*-th of them are *a**i*, *b**i* and *c**i*. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar. Input Specification: The first line contains the integer *n* (1<=≀<=*n*<=≀<=105). *n* lines follow, in the *i*-th of which there are three integers *a**i*,<=*b**i* and *c**i* (1<=≀<=*a**i*,<=*b**i*,<=*c**i*<=≀<=109)Β β€” the lengths of edges of the *i*-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones. Output Specification: In the first line print *k* (1<=≀<=*k*<=≀<=2) the number of stones which Zahar has chosen. In the second line print *k* distinct integers from 1 to *n*Β β€” the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to *n* in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them. Demo Input: ['6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4\n', '7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7\n'] Demo Output: ['1\n1\n', '2\n1 5\n'] Note: In the first example we can connect the pairs of stones: - 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 - 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. - 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 - 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 - 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: - 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 - 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 - 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 - 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 - 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 - 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
1,143
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is *h*1 and height of Abol is *h*2. Each second, Mike waters Abol and Xaniar. So, if height of Xaniar is *h*1 and height of Abol is *h*2, after one second height of Xaniar will become and height of Abol will become where *x*1,<=*y*1,<=*x*2 and *y*2 are some integer numbers and denotes the remainder of *a* modulo *b*. Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is *a*1 and height of Abol is *a*2. Mike has asked you for your help. Calculate the minimum time or say it will never happen. Input Specification: The first line of input contains integer *m* (2<=≀<=*m*<=≀<=106). The second line of input contains integers *h*1 and *a*1 (0<=≀<=*h*1,<=*a*1<=&lt;<=*m*). The third line of input contains integers *x*1 and *y*1 (0<=≀<=*x*1,<=*y*1<=&lt;<=*m*). The fourth line of input contains integers *h*2 and *a*2 (0<=≀<=*h*2,<=*a*2<=&lt;<=*m*). The fifth line of input contains integers *x*2 and *y*2 (0<=≀<=*x*2,<=*y*2<=&lt;<=*m*). It is guaranteed that *h*1<=β‰ <=*a*1 and *h*2<=β‰ <=*a*2. Output Specification: Print the minimum number of seconds until Xaniar reaches height *a*1 and Abol reaches height *a*2 or print -1 otherwise. Demo Input: ['5\n4 2\n1 1\n0 1\n2 3\n', '1023\n1 2\n1 0\n1 2\n1 1\n'] Demo Output: ['3\n', '-1\n'] Note: In the first sample, heights sequences are following: Xaniar: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/85da629b05969e7a8a6636d995b8fe7a0494e8f4.png" style="max-width: 100.0%;max-height: 100.0%;"/> Abol: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ea95da14490864ae8b8bfcd4a8b7c02ad3a666b3.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,144
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Natasha travels around Mars in the Mars rover. But suddenly it broke down, namelyΒ β€” the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $1$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output. There are four types of logical elements: [AND](https://en.wikipedia.org/wiki/Logical_conjunction) ($2$ inputs), [OR](https://en.wikipedia.org/wiki/Logical_disjunction) ($2$ inputs), [XOR](https://en.wikipedia.org/wiki/Exclusive_or) ($2$ inputs), [NOT](https://en.wikipedia.org/wiki/Negation) ($1$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input. For each input, determine what the output will be if Natasha changes this input. Input Specification: The first line contains a single integer $n$ ($2 \le n \le 10^6$)Β β€” the number of vertices in the graph (both inputs and elements). The $i$-th of the next $n$ lines contains a description of $i$-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows ($0$ or $1$), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have $2$ inputs, whereas "NOT" has $1$ input. The vertices are numbered from one. It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex $1$. Output Specification: Print a string of characters '0' and '1' (without quotes)Β β€” answers to the problem for each input in the ascending order of their vertex indices. Demo Input: ['10\nAND 9 4\nIN 1\nIN 1\nXOR 6 5\nAND 3 7\nIN 0\nNOT 10\nIN 1\nIN 1\nAND 2 8\n'] Demo Output: ['10110'] Note: The original scheme from the example (before the input is changed): <img class="tex-graphics" src="https://espresso.codeforces.com/4507113582d40356e140857daa04318b91197f46.png" style="max-width: 100.0%;max-height: 100.0%;"/> Green indicates bits '1', yellow indicates bits '0'. If Natasha changes the input bit $2$ to $0$, then the output will be $1$. If Natasha changes the input bit $3$ to $0$, then the output will be $0$. If Natasha changes the input bit $6$ to $1$, then the output will be $1$. If Natasha changes the input bit $8$ to $0$, then the output will be $1$. If Natasha changes the input bit $9$ to $0$, then the output will be $0$.
1,145
Title: New Game with a Chess Piece Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump *k* squares diagonally down and to the right. The player who can’t move the piece loses. The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size. Input Specification: The first input line contains two integers *t* and *k* (1<=≀<=*t*<=≀<=20, 1<=≀<=*k*<=≀<=109). Each of the following *t* lines contains two numbers *n*, *m* β€” the board’s length and width (1<=≀<=*n*,<=*m*<=≀<=109). Output Specification: Output *t* lines that can determine the outcomes of the game on every board. Write Β«+Β» if the first player is a winner, and Β«-Β» otherwise. Demo Input: ['10 2\n1 1\n1 2\n2 1\n2 2\n1 3\n2 3\n3 1\n3 2\n3 3\n4 3\n'] Demo Output: ['-\n+\n+\n-\n-\n+\n-\n+\n+\n+\n'] Note: none
1,146
Title: Analysis of Pathes in Functional Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to *n*<=-<=1. Graph is given as the array *f*0,<=*f*1,<=...,<=*f**n*<=-<=1, where *f**i* β€” the number of vertex to which goes the only arc from the vertex *i*. Besides you are given array with weights of the arcs *w*0,<=*w*1,<=...,<=*w**n*<=-<=1, where *w**i* β€” the arc weight from *i* to *f**i*. Also you are given the integer *k* (the length of the path) and you need to find for each vertex two numbers *s**i* and *m**i*, where: - *s**i* β€” the sum of the weights of all arcs of the path with length equals to *k* which starts from the vertex *i*; - *m**i* β€” the minimal weight from all arcs on the path with length *k* which starts from the vertex *i*. The length of the path is the number of arcs on this path. Input Specification: The first line contains two integers *n*,<=*k* (1<=≀<=*n*<=≀<=105,<=1<=≀<=*k*<=≀<=1010). The second line contains the sequence *f*0,<=*f*1,<=...,<=*f**n*<=-<=1 (0<=≀<=*f**i*<=&lt;<=*n*) and the third β€” the sequence *w*0,<=*w*1,<=...,<=*w**n*<=-<=1 (0<=≀<=*w**i*<=≀<=108). Output Specification: Print *n* lines, the pair of integers *s**i*, *m**i* in each line. Demo Input: ['7 3\n1 2 3 4 3 2 6\n6 3 1 4 2 2 3\n', '4 4\n0 1 2 3\n0 1 2 3\n', '5 3\n1 2 3 4 0\n4 1 2 14 3\n'] Demo Output: ['10 1\n8 1\n7 1\n10 2\n8 2\n7 1\n9 3\n', '0 0\n4 1\n8 2\n12 3\n', '7 1\n17 1\n19 2\n21 3\n8 1\n'] Note: none
1,147
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1,<=2,<=...,<=*n*} is such function , that for any the formula *g*(*g*(*x*))<==<=*g*(*x*) holds. Let's denote as *f*(*k*)(*x*) the function *f* applied *k* times to the value *x*. More formally, *f*(1)(*x*)<==<=*f*(*x*), *f*(*k*)(*x*)<==<=*f*(*f*(*k*<=-<=1)(*x*)) for each *k*<=&gt;<=1. You are given some function . Your task is to find minimum positive integer *k* such that function *f*(*k*)(*x*) is idempotent. Input Specification: In the first line of the input there is a single integer *n* (1<=≀<=*n*<=≀<=200) β€” the size of function *f* domain. In the second line follow *f*(1),<=*f*(2),<=...,<=*f*(*n*) (1<=≀<=*f*(*i*)<=≀<=*n* for each 1<=≀<=*i*<=≀<=*n*), the values of a function. Output Specification: Output minimum *k* such that function *f*(*k*)(*x*) is idempotent. Demo Input: ['4\n1 2 2 4\n', '3\n2 3 3\n', '3\n2 3 1\n'] Demo Output: ['1\n', '2\n', '3\n'] Note: In the first sample test function *f*(*x*) = *f*<sup class="upper-index">(1)</sup>(*x*) is already idempotent since *f*(*f*(1)) = *f*(1) = 1, *f*(*f*(2)) = *f*(2) = 2, *f*(*f*(3)) = *f*(3) = 2, *f*(*f*(4)) = *f*(4) = 4. In the second sample test: - function *f*(*x*) = *f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1)) = 3 but *f*(1) = 2; - function *f*(*x*) = *f*<sup class="upper-index">(2)</sup>(*x*) is idempotent since for any *x* it is true that *f*<sup class="upper-index">(2)</sup>(*x*) = 3, so it is also true that *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(*x*)) = 3. In the third sample test: - function *f*(*x*) = *f*<sup class="upper-index">(1)</sup>(*x*) isn't idempotent because *f*(*f*(1)) = 3 but *f*(1) = 2; - function *f*(*f*(*x*)) = *f*<sup class="upper-index">(2)</sup>(*x*) isn't idempotent because *f*<sup class="upper-index">(2)</sup>(*f*<sup class="upper-index">(2)</sup>(1)) = 2 but *f*<sup class="upper-index">(2)</sup>(1) = 3; - function *f*(*f*(*f*(*x*))) = *f*<sup class="upper-index">(3)</sup>(*x*) is idempotent since it is identity function: *f*<sup class="upper-index">(3)</sup>(*x*) = *x* for any <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/46a8c73444c646004dfde04451775e7af924d108.png" style="max-width: 100.0%;max-height: 100.0%;"/> meaning that the formula *f*<sup class="upper-index">(3)</sup>(*f*<sup class="upper-index">(3)</sup>(*x*)) = *f*<sup class="upper-index">(3)</sup>(*x*) also holds.
1,148
Title: The Golden Age Time Limit: None seconds Memory Limit: None megabytes Problem Description: Unlucky year in Berland is such a year that its number *n* can be represented as *n*<==<=*x**a*<=+<=*y**b*, where *a* and *b* are non-negative integer numbers. For example, if *x*<==<=2 and *y*<==<=3 then the years 4 and 17 are unlucky (4<==<=20<=+<=31, 17<==<=23<=+<=32<==<=24<=+<=30) and year 18 isn't unlucky as there is no such representation for it. Such interval of years that there are no unlucky years in it is called The Golden Age. You should write a program which will find maximum length of The Golden Age which starts no earlier than the year *l* and ends no later than the year *r*. If all years in the interval [*l*,<=*r*] are unlucky then the answer is 0. Input Specification: The first line contains four integer numbers *x*, *y*, *l* and *r* (2<=≀<=*x*,<=*y*<=≀<=1018, 1<=≀<=*l*<=≀<=*r*<=≀<=1018). Output Specification: Print the maximum length of The Golden Age within the interval [*l*,<=*r*]. If all years in the interval [*l*,<=*r*] are unlucky then print 0. Demo Input: ['2 3 1 10\n', '3 5 10 22\n', '2 3 3 5\n'] Demo Output: ['1\n', '8\n', '0\n'] Note: In the first example the unlucky years are 2, 3, 4, 5, 7, 9 and 10. So maximum length of The Golden Age is achived in the intervals [1, 1], [6, 6] and [8, 8]. In the second example the longest Golden Age is the interval [15, 22].
1,149
Title: Functions On The Segments Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have an array *f* of *n* functions.The function *f**i*(*x*) (1<=≀<=*i*<=≀<=*n*) is characterized by parameters: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 and take values: - *y*1, if *x*<=≀<=*x*1. - *a*Β·*x*<=+<=*b*, if *x*1<=&lt;<=*x*<=≀<=*x*2. - *y*2, if *x*<=&gt;<=*x*2. There are *m* queries. Each query is determined by numbers *l*, *r* and *x*. For a query with number *i* (1<=≀<=*i*<=≀<=*m*), you need to calculate the sum of all *f**j*(*x**i*) where *l*<=≀<=*j*<=≀<=*r*. The value of *x**i* is calculated as follows: *x**i*<==<=(*x*<=+<=*last*) mod 109, where *last* is the answer to the query with number *i*<=-<=1. The value of *last* equals 0 if *i*<==<=1. Input Specification: First line contains one integer number *n* (1<=≀<=*n*<=≀<=75000). Each of the next *n* lines contains six integer numbers: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 (0<=≀<=*x*1<=&lt;<=*x*2<=≀<=2Β·105, 0<=≀<=*y*1,<=*y*2<=≀<=109, 0<=≀<=*a*,<=*b*<=≀<=104). Next line contains one integer number *m* (1<=≀<=*m*<=≀<=500000). Each of the next *m* lines contains three integer numbers: *l*, *r* and *x* (1<=≀<=*l*<=≀<=*r*<=≀<=*n*, 0<=≀<=*x*<=≀<=109). Output Specification: none Demo Input: ['1\n1 2 1 4 5 10\n1\n1 1 2\n', '3\n2 5 1 1 1 4\n3 6 8 2 5 7\n1 3 5 1 4 10\n3\n1 3 3\n2 3 2\n1 2 5\n'] Demo Output: ['13\n', '19\n17\n11\n'] Note: none
1,150
Title: Ilya and Queries Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam. You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<=*r**i* (1<=≀<=*l**i*<=&lt;<=*r**i*<=≀<=*n*). The answer to the query *l**i*,<=*r**i* is the number of such integers *i* (*l**i*<=≀<=*i*<=&lt;<=*r**i*), that *s**i*<==<=*s**i*<=+<=1. Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem. Input Specification: The first line contains string *s* of length *n* (2<=≀<=*n*<=≀<=105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of queries. Each of the next *m* lines contains the description of the corresponding query. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≀<=*l**i*<=&lt;<=*r**i*<=≀<=*n*). Output Specification: Print *m* integers β€” the answers to the queries in the order in which they are given in the input. Demo Input: ['......\n4\n3 4\n2 3\n1 6\n2 6\n', '#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4\n'] Demo Output: ['1\n1\n5\n4\n', '1\n1\n2\n2\n0\n'] Note: none
1,151
Title: Pashmak and Parmida's problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak. There is a sequence *a* that consists of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Let's denote *f*(*l*,<=*r*,<=*x*) the number of indices *k* such that: *l*<=≀<=*k*<=≀<=*r* and *a**k*<==<=*x*. His task is to calculate the number of pairs of indicies *i*,<=*j* (1<=≀<=*i*<=&lt;<=*j*<=≀<=*n*) such that *f*(1,<=*i*,<=*a**i*)<=&gt;<=*f*(*j*,<=*n*,<=*a**j*). Help Pashmak with the test. Input Specification: The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=106). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109). Output Specification: Print a single integer β€” the answer to the problem. Demo Input: ['7\n1 2 1 1 2 2 1\n', '3\n1 1 1\n', '5\n1 2 3 4 5\n'] Demo Output: ['8\n', '1\n', '0\n'] Note: none
1,152
Title: New task Time Limit: None seconds Memory Limit: None megabytes Problem Description: On the 228-th international Uzhlyandian Wars strategic game tournament teams from each country are called. The teams should consist of 5 participants. The team of Uzhlyandia will consist of soldiers, because there are no gamers. Masha is a new minister of defense and gaming. The prime duty of the minister is to calculate the efficiency of the Uzhlandian army. The army consists of *n* soldiers standing in a row, enumerated from 1 to *n*. For each soldier we know his skill in Uzhlyandian Wars: the *i*-th soldier's skill is *a**i*. It was decided that the team will consist of three players and two assistants. The skills of players should be same, and the assistants' skills should not be greater than the players' skill. Moreover, it is important for Masha that one of the assistants should stand in the row to the left of the players, and the other one should stand in the row to the right of the players. Formally, a team is five soldiers with indexes *i*, *j*, *k*, *l*, *p*, such that 1<=≀<=*i*<=&lt;<=*j*<=&lt;<=*k*<=&lt;<=*l*<=&lt;<=*p*<=≀<=*n* and *a**i*<=≀<=*a**j*<==<=*a**k*<==<=*a**l*<=β‰₯<=*a**p*. The efficiency of the army is the number of different teams Masha can choose. Two teams are considered different if there is such *i* such that the *i*-th soldier is a member of one team, but not a member of the other team. Initially, all players are able to be players. For some reasons, sometimes some soldiers become unable to be players. Sometimes some soldiers, that were unable to be players, become able to be players. At any time any soldier is able to be an assistant. Masha wants to control the efficiency of the army, so she asked you to tell her the number of different possible teams modulo 1000000007 (109<=+<=7) after each change. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=105)Β β€” the number of soldiers in Uzhlyandia. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109)Β β€” the soldiers' skills. The third line contains single integer *m* (1<=≀<=*m*<=≀<=105)Β β€” the number of changes. The next *m* lines contain the changes, each change is described with two integers *t* and *x* (1<=≀<=*t*<=≀<=2, 1<=≀<=*x*<=≀<=*n*) on a separate line. If *t*<==<=1, then the *x*-th soldier is unable to be a player after this change. If *t*<==<=2, then the *x*-th soldier is able to be a player after this change. It is guaranteed that before each query of the first type the soldier is able to be a player, and before each query of the second type the soldier is unable to be a player. Output Specification: Print *m* integersΒ β€” the number of distinct teams after each change. Print the answers modulo 1000000007 (109<=+<=7). Demo Input: ['6\n1 1 1 1 1 1\n2\n1 3\n2 3\n', '8\n3 4 4 2 4 5 4 1\n3\n1 5\n2 5\n1 2\n'] Demo Output: ['1\n6\n', '1\n6\n2\n'] Note: In the first example, after the first change the only team consists of soldiers [1, 2, 4, 5, 6]. After the second change any five soldiers can form a team. In the first example after the first change the only team is soldiers [1, 2, 3, 7, 8]. After the second change the possible teams are: [1, 2, 3, 5, 7], [1, 2, 3, 5, 8], [1, 2, 3, 7, 8], [1, 2, 5, 7, 8], [1, 3, 5, 7, 8], [2, 3, 5, 7, 8]. After the third change the possible teams are: [1, 3, 5, 7, 8], [2, 3, 5, 7, 8].
1,153
Title: Word Correction Time Limit: None seconds Memory Limit: None megabytes Problem Description: Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct. You are given a word *s*. Can you predict what will it become after correction? In this problem letters a, e, i, o, u and y are considered to be vowels. Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=100) β€” the number of letters in word *s* before the correction. The second line contains a string *s* consisting of exactly *n* lowercase Latin letters β€” the word before the correction. Output Specification: Output the word *s* after the correction. Demo Input: ['5\nweird\n', '4\nword\n', '5\naaeaa\n'] Demo Output: ['werd\n', 'word\n', 'a\n'] Note: Explanations of the examples: 1. There is only one replace: weird <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> werd;1. No replace needed since there are no two consecutive vowels;1. aaeaa <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aeaa <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aaa <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aa <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> a.
1,154
Title: Duff and Meat Time Limit: None seconds Memory Limit: None megabytes Problem Description: Duff is addicted to meat! Malek wants to keep her happy for *n* days. In order to be happy in *i*-th day, she needs to eat exactly *a**i* kilograms of meat. There is a big shop uptown and Malek wants to buy meat for her from there. In *i*-th day, they sell meat for *p**i* dollars per kilogram. Malek knows all numbers *a*1,<=...,<=*a**n* and *p*1,<=...,<=*p**n*. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future. Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for *n* days. Input Specification: The first line of input contains integer *n* (1<=≀<=*n*<=≀<=105), the number of days. In the next *n* lines, *i*-th line contains two integers *a**i* and *p**i* (1<=≀<=*a**i*,<=*p**i*<=≀<=100), the amount of meat Duff needs and the cost of meat in that day. Output Specification: Print the minimum money needed to keep Duff happy for *n* days, in one line. Demo Input: ['3\n1 3\n2 2\n3 1\n', '3\n1 3\n2 1\n3 2\n'] Demo Output: ['10\n', '8\n'] Note: In the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day. In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.
1,155
Title: Network Topology Time Limit: None seconds Memory Limit: None megabytes Problem Description: This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of *n* computers, some of them are connected by a cable. The computers are indexed by integers from 1 to *n*. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input Specification: The first line contains two space-separated integers *n* and *m* (4<=≀<=*n*<=≀<=105;Β 3<=≀<=*m*<=≀<=105) β€” the number of nodes and edges in the graph, correspondingly. Next *m* lines contain the description of the graph's edges. The *i*-th line contains a space-separated pair of integers *x**i*, *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*) β€” the numbers of nodes that are connected by the *i*-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output Specification: In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Demo Input: ['4 3\n1 2\n2 3\n3 4\n', '4 4\n1 2\n2 3\n3 4\n4 1\n', '4 3\n1 2\n1 3\n1 4\n', '4 4\n1 2\n2 3\n3 1\n1 4\n'] Demo Output: ['bus topology\n', 'ring topology\n', 'star topology\n', 'unknown topology\n'] Note: none
1,156
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Π•ΡΡ‚ΡŒ *n*-ΠΏΠΎΠ΄ΡŠΠ΅Π·Π΄Π½Ρ‹ΠΉ Π΄ΠΎΠΌ, Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ подъСздС ΠΏΠΎ *m* этаТСй, ΠΈ Π½Π° ΠΊΠ°ΠΆΠ΄ΠΎΠΌ этаТС ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ подъСзда Ρ€ΠΎΠ²Π½ΠΎ *k* ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€. Π’Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ, Π² Π΄ΠΎΠΌΠ΅ всСго *n*Β·*m*Β·*k* ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€. Они ΠΏΡ€ΠΎΠ½ΡƒΠΌΠ΅Ρ€ΠΎΠ²Π°Π½Ρ‹ СстСствСнным ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ ΠΎΡ‚ 1 Π΄ΠΎ *n*Β·*m*Β·*k*, Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ пСрвая ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π° Π½Π° ΠΏΠ΅Ρ€Π²ΠΎΠΌ этаТС Π² ΠΏΠ΅Ρ€Π²ΠΎΠΌ подъСздС ΠΈΠΌΠ΅Π΅Ρ‚ Π½ΠΎΠΌΠ΅Ρ€ 1, пСрвая ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π° Π½Π° Π²Ρ‚ΠΎΡ€ΠΎΠΌ этаТС ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ подъСзда ΠΈΠΌΠ΅Π΅Ρ‚ Π½ΠΎΠΌΠ΅Ρ€ *k*<=+<=1 ΠΈ Ρ‚Π°ΠΊ Π΄Π°Π»Π΅Π΅. ΠžΡΠΎΠ±Π΅Π½Π½ΠΎΡΡ‚ΡŒ этого Π΄ΠΎΠΌΠ° состоит Π² Ρ‚ΠΎΠΌ, Ρ‡Ρ‚ΠΎ ΠΎΠ½ ΠΊΡ€ΡƒΠ³Π»Ρ‹ΠΉ. Π’ΠΎ Π΅ΡΡ‚ΡŒ Ссли ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΡ‚ΡŒ Π΅Π³ΠΎ ΠΏΠΎ часовой стрСлкС, Ρ‚ΠΎ послС подъСзда Π½ΠΎΠΌΠ΅Ρ€ 1 слСдуСт подъСзд Π½ΠΎΠΌΠ΅Ρ€ 2, Π·Π°Ρ‚Π΅ΠΌ подъСзд Π½ΠΎΠΌΠ΅Ρ€ 3 ΠΈ Ρ‚Π°ΠΊ Π΄Π°Π»Π΅Π΅ Π΄ΠΎ подъСзда Π½ΠΎΠΌΠ΅Ρ€ *n*. ПослС подъСзда Π½ΠΎΠΌΠ΅Ρ€ *n* снова ΠΈΠ΄Ρ‘Ρ‚ подъСзд Π½ΠΎΠΌΠ΅Ρ€ 1. Π­Π΄Π²Π°Ρ€Π΄ ΠΆΠΈΠ²Ρ‘Ρ‚ Π² ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π΅ Π½ΠΎΠΌΠ΅Ρ€ *a*, Π° ΠΠ°Ρ‚Π°ΡˆΠ°Β β€” Π² ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Π΅ Π½ΠΎΠΌΠ΅Ρ€ *b*. ΠŸΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ Π½Π° 1 этаТ Π²Π²Π΅Ρ€Ρ… ΠΈΠ»ΠΈ Π²Π½ΠΈΠ· ΠΏΠΎ лСстницС Π·Π°Π½ΠΈΠΌΠ°Π΅Ρ‚ 5 сСкунд, ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ ΠΎΡ‚ Π΄Π²Π΅Ρ€ΠΈ подъСзда ΠΊ Π΄Π²Π΅Ρ€ΠΈ сосСднСго ΠΏΠΎΠ΄ΡŠΠ΅Π·Π΄Π°Β β€” 15 сСкунд, Π° ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ Π² ΠΏΡ€Π΅Π΄Π΅Π»Π°Ρ… ΠΎΠ΄Π½ΠΎΠ³ΠΎ этаТа ΠΎΠ΄Π½ΠΎΠ³ΠΎ подъСзда происходит ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ. Π’Π°ΠΊΠΆΠ΅ Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ подъСздС Π΄ΠΎΠΌΠ° Π΅ΡΡ‚ΡŒ Π»ΠΈΡ„Ρ‚. Он устроСн ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ: ΠΎΠ½ всСгда ΠΏΡ€ΠΈΠ΅Π·ΠΆΠ°Π΅Ρ‚ Ρ€ΠΎΠ²Π½ΠΎ Ρ‡Π΅Ρ€Π΅Π· 10 сСкунд послС Π²Ρ‹Π·ΠΎΠ²Π°, Π° Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅ΡΡ‚ΠΈΡ‚ΡŒ пассаТира Π½Π° ΠΎΠ΄ΠΈΠ½ этаТ Π²Π²Π΅Ρ€Ρ… ΠΈΠ»ΠΈ Π²Π½ΠΈΠ·, Π»ΠΈΡ„Ρ‚ Ρ‚Ρ€Π°Ρ‚ΠΈΡ‚ Ρ€ΠΎΠ²Π½ΠΎ 1 сСкунду. Посадка ΠΈ высадка происходят ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ. ΠŸΠΎΠΌΠΎΠ³ΠΈΡ‚Π΅ Π­Π΄Π²Π°Ρ€Π΄Ρƒ Π½Π°ΠΉΡ‚ΠΈ минимальноС врСмя, Π·Π° ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ ΠΎΠ½ смоТСт Π΄ΠΎΠ±Ρ€Π°Ρ‚ΡŒΡΡ Π΄ΠΎ ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ ΠΠ°Ρ‚Π°ΡˆΠΈ. Π‘Ρ‡ΠΈΡ‚Π°ΠΉΡ‚Π΅, Ρ‡Ρ‚ΠΎ Π­Π΄Π²Π°Ρ€Π΄ ΠΌΠΎΠΆΠ΅Ρ‚ Π²Ρ‹ΠΉΡ‚ΠΈ ΠΈΠ· подъСзда Ρ‚ΠΎΠ»ΡŒΠΊΠΎ с ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ этаТа ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰Π΅Π³ΠΎ подъСзда (это происходит ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ). Если Π­Π΄Π²Π°Ρ€Π΄ стоит ΠΏΠ΅Ρ€Π΅Π΄ Π΄Π²Π΅Ρ€ΡŒΡŽ ΠΊΠ°ΠΊΠΎΠ³ΠΎ-Ρ‚ΠΎ подъСзда, ΠΎΠ½ ΠΌΠΎΠΆΠ΅Ρ‚ Π·Π°ΠΉΡ‚ΠΈ Π² Π½Π΅Π³ΠΎ ΠΈ сразу окаТСтся Π½Π° ΠΏΠ΅Ρ€Π²ΠΎΠΌ этаТС этого подъСзда (это Ρ‚Π°ΠΊΠΆΠ΅ происходит ΠΌΠ³Π½ΠΎΠ²Π΅Π½Π½ΠΎ). Π­Π΄Π²Π°Ρ€Π΄ ΠΌΠΎΠΆΠ΅Ρ‚ Π²Ρ‹Π±ΠΈΡ€Π°Ρ‚ΡŒ, Π² ΠΊΠ°ΠΊΠΎΠΌ Π½Π°ΠΏΡ€Π°Π²Π»Π΅Π½ΠΈΠΈ ΠΈΠ΄Ρ‚ΠΈ Π²ΠΎΠΊΡ€ΡƒΠ³ Π΄ΠΎΠΌΠ°. Input Specification: Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… ΡΠ»Π΅Π΄ΡƒΡŽΡ‚ Ρ‚Ρ€ΠΈ числа *n*, *m*, *k* (1<=≀<=*n*,<=*m*,<=*k*<=≀<=1000)Β β€” количСство подъСздов Π² Π΄ΠΎΠΌΠ΅, количСство этаТСй Π² ΠΊΠ°ΠΆΠ΄ΠΎΠΌ подъСздС ΠΈ количСство ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€ Π½Π° ΠΊΠ°ΠΆΠ΄ΠΎΠΌ этаТС ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ подъСзда соотвСтствСнно. Π’ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΉ строкС Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… записаны Π΄Π²Π° числа *a* ΠΈ *b* (1<=≀<=*a*,<=*b*<=≀<=*n*Β·*m*Β·*k*)Β β€” Π½ΠΎΠΌΠ΅Ρ€Π° ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€, Π² ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… ΠΆΠΈΠ²ΡƒΡ‚ Π­Π΄Π²Π°Ρ€Π΄ ΠΈ ΠΠ°Ρ‚Π°ΡˆΠ°, соотвСтствСнно. ГарантируСтся, Ρ‡Ρ‚ΠΎ эти Π½ΠΎΠΌΠ΅Ρ€Π° Ρ€Π°Π·Π»ΠΈΡ‡Π½Ρ‹. Output Specification: Π’Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ СдинствСнноС Ρ†Π΅Π»ΠΎΠ΅ число — минимальноС врСмя (Π² сСкундах), Π·Π° ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ Π­Π΄Π²Π°Ρ€Π΄ смоТСт Π΄ΠΎΠ±Ρ€Π°Ρ‚ΡŒΡΡ ΠΎΡ‚ своСй ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ Π΄ΠΎ ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ ΠΠ°Ρ‚Π°ΡˆΠΈ. Demo Input: ['4 10 5\n200 6\n', '3 1 5\n7 2\n'] Demo Output: ['39\n', '15\n'] Note: Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΌ тСстовом ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ Π­Π΄Π²Π°Ρ€Π΄ находится Π² 4 подъСздС Π½Π° 10 этаТС, Π° ΠΠ°Ρ‚Π°ΡˆΠ° находится Π² 1 подъСздС Π½Π° 2 этаТС. ΠŸΠΎΡΡ‚ΠΎΠΌΡƒ Π­Π΄Π²Π°Ρ€Π΄Ρƒ Π²Ρ‹Π³ΠΎΠ΄Π½ΠΎ сначала ΡΠΏΡƒΡΡ‚ΠΈΡ‚ΡŒΡΡ Π½Π° Π»ΠΈΡ„Ρ‚Π΅ Π½Π° ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ этаТ (Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 19 сСкунд, ΠΈΠ· ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… 10Β β€” Π½Π° ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠ΅ ΠΈ 9Β β€” Π½Π° ΠΏΠΎΠ΅Π·Π΄ΠΊΡƒ Π½Π° Π»ΠΈΡ„Ρ‚Π΅), Π·Π°Ρ‚Π΅ΠΌ ΠΎΠ±ΠΎΠΉΡ‚ΠΈ Π΄ΠΎΠΌ ΠΏΡ€ΠΎΡ‚ΠΈΠ² часовой стрСлки Π΄ΠΎ подъСзда Π½ΠΎΠΌΠ΅Ρ€ 1 (Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 15 сСкунд), ΠΈ Π½Π°ΠΊΠΎΠ½Π΅Ρ† ΠΏΠΎΠ΄Π½ΡΡ‚ΡŒΡΡ ΠΏΠΎ лСстницС Π½Π° этаТ Π½ΠΎΠΌΠ΅Ρ€ 2 (Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 5 сСкунд). Π’Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ, ΠΎΡ‚Π²Π΅Ρ‚ Ρ€Π°Π²Π΅Π½ 19 + 15 + 5 = 39. Π’ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΌ тСстовом ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ Π­Π΄Π²Π°Ρ€Π΄ ΠΆΠΈΠ²Ρ‘Ρ‚ Π² подъСздС 2 Π½Π° этаТС 1, Π° ΠΠ°Ρ‚Π°ΡˆΠ° находится Π² подъСздС 1 Π½Π° этаТС 1. ΠŸΠΎΡΡ‚ΠΎΠΌΡƒ Π­Π΄Π²Π°Ρ€Π΄Ρƒ Π²Ρ‹Π³ΠΎΠ΄Π½ΠΎ просто ΠΎΠ±ΠΎΠΉΡ‚ΠΈ Π΄ΠΎΠΌ ΠΏΠΎ часовой стрСлкС Π΄ΠΎ подъСзда 1, Π½Π° это ΠΎΠ½ ΠΏΠΎΡ‚Ρ€Π°Ρ‚ΠΈΡ‚ 15 сСкунд.
1,157
Title: Prince's Problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem. You are given a tree with $n$ vertices. In each vertex $v$ there is positive integer $a_{v}$. You have to answer $q$ queries. Each query has a from $u$ $v$ $x$. You have to calculate $\prod_{w \in P} gcd(x, a_{w}) \mod (10^{9} + 7)$, where $P$ is a set of vertices on path from $u$ to $v$. In other words, you are to calculate the product of $gcd(x, a_{w})$ for all vertices $w$ on the path from $u$ to $v$. As it might be large, compute it modulo $10^9+7$. Here $gcd(s, t)$ denotes the greatest common divisor of $s$ and $t$. Note that the numbers in vertices do not change after queries. I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them. Input Specification: In the first line of input there is one integer $n$ ($1 \le n \le 10^{5}$)Β β€” the size of the tree. In the next $n-1$ lines the edges of the tree are described. The $i$-th edge is described with two integers $u_{i}$ and $v_{i}$ ($1 \le u_{i}, v_{i} \le n$) and it connects the vertices $u_{i}$ and $v_{i}$. It is guaranteed that graph with these edges is a tree. In the next line there are $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_{v} \le 10^{7}$). In the next line there is one integer $q$ ($1 \le q \le 10^{5}$)Β β€” the number of queries. And in the next $q$ lines the queries are described. Each query is described with three integers $u_{i}$, $v_{i}$ and $x_{i}$ ($1 \le u_{i}, v_{i} \le n$, $1 \le x_{i} \le 10^{7}$). Output Specification: Print $q$ numbersΒ β€” the answers to the queries in the order they are given in the input. Print each answer modulo $10^9+7 = 1000000007$. Print each number on a separate line. Demo Input: ['4\n1 2\n1 3\n1 4\n6 4 9 5\n3\n2 3 6\n2 3 2\n3 4 7\n', '6\n1 2\n2 3\n2 4\n1 5\n5 6\n100000 200000 500000 40000 800000 250000\n3\n3 5 10000000\n6 2 3500000\n4 1 64000\n'] Demo Output: ['36\n4\n1\n', '196000\n12250\n999998215\n'] Note: none
1,158
Title: Friends Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have *n* friends and you want to take *m* pictures of them. Exactly two of your friends should appear in each picture and no two pictures should contain the same pair of your friends. So if you have *n*<==<=3 friends you can take 3 different pictures, each containing a pair of your friends. Each of your friends has an attractiveness level which is specified by the integer number *a**i* for the *i*-th friend. You know that the attractiveness of a picture containing the *i*-th and the *j*-th friends is equal to the exclusive-or (*xor* operation) of integers *a**i* and *a**j*. You want to take pictures in a way that the total sum of attractiveness of your pictures is maximized. You have to calculate this value. Since the result may not fit in a 32-bit integer number, print it modulo 1000000007 (109<=+<=7). Input Specification: The first line of input contains two integers *n* and *m* β€” the number of friends and the number of pictures that you want to take. Next line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109) β€” the values of attractiveness of the friends. Output Specification: The only line of output should contain an integer β€” the optimal total sum of attractiveness of your pictures. Demo Input: ['3 1\n1 2 3\n', '3 2\n1 2 3\n', '3 3\n1 2 3\n'] Demo Output: ['3\n', '5\n', '6\n'] Note: none
1,159
Title: Dependency management Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity. A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version β€” positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies. You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored. More formal, choose such a set of projects of minimum possible size that the following conditions hold: - Polycarp's project is chosen; - Polycarp's project depends (directly or indirectly) on all other projects in the set; - no two projects share the name; - for each project *x* that some other project in the set depends on we have either *x* or some *y* with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order. Input Specification: The first line contains an only integer *n* (1<=≀<=*n*<=≀<=1<=000) β€” the number of projects in Vaja. The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to *n*<=-<=1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding. It's guaranteed that there are no cyclic dependencies. Output Specification: Output all Polycarp's project's dependencies in lexicographical order. Demo Input: ['4\na 3\n2\nb 1\nc 1\n\xa0\nb 2\n0\n\xa0\nb 1\n1\nb 2\n\xa0\nc 1\n1\nb 2\n', '9\ncodehorses 5\n3\nwebfrmk 6\nmashadb 1\nmashadb 2\n\xa0\ncommons 2\n0\n\xa0\nmashadb 3\n0\n\xa0\nwebfrmk 6\n2\nmashadb 3\ncommons 2\n\xa0\nextra 4\n1\nextra 3\n\xa0\nextra 3\n0\n\xa0\nextra 1\n0\n\xa0\nmashadb 1\n1\nextra 3\n\xa0\nmashadb 2\n1\nextra 1\n', '3\nabc 1\n2\nabc 3\ncba 2\n\nabc 3\n0\n\ncba 2\n0\n'] Demo Output: ['2\nb 1\nc 1\n', '4\ncommons 2\nextra 1\nmashadb 2\nwebfrmk 6\n', '1\ncba 2\n'] Note: The first sample is given in the pic below. Arrow from *A* to *B* means that *B* directly depends on *A*. Projects that Polycarp's project Β«aΒ» (version 3) depends on are painted black. The second sample is again given in the pic below. Arrow from *A* to *B* means that *B* directly depends on *A*. Projects that Polycarp's project Β«codehorsesΒ» (version 5) depends on are paint it black. Note that Β«extra 1Β» is chosen instead of Β«extra 3Β» since Β«mashadb 1Β» and all of its dependencies are ignored due to Β«mashadb 2Β».
1,160
Title: Bear and Isomorphic Points Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bearland is a big square on the plane. It contains all points with coordinates not exceeding 106 by the absolute value. There are *n* houses in Bearland. The *i*-th of them is located at the point (*x**i*,<=*y**i*). The *n* points are distinct, but some subsets of them may be collinear. Bear Limak lives in the first house. He wants to destroy his house and build a new one somewhere in Bearland. Bears don't like big changes. For every three points (houses) *p**i*, *p**j* and *p**k*, the sign of their cross product (*p**j*<=-<=*p**i*)<=Γ—<=(*p**k*<=-<=*p**i*) should be the same before and after the relocation. If it was negative/positive/zero, it should still be negative/positive/zero respectively. This condition should be satisfied for all triples of indices (*i*,<=*j*,<=*k*), possibly equal to each other or different than 1. Additionally, Limak isn't allowed to build the house at the point where some other house already exists (but it can be the point where his old house was). In the formula above, we define the difference and the cross product of points (*a**x*,<=*a**y*) and (*b**x*,<=*b**y*) as: Consider a set of possible new placements of Limak's house. Your task is to find the area of that set of points. Formally, let's say that Limak chooses the new placement randomly (each coordinate is chosen independently uniformly at random from the interval [<=-<=106,<=106]). Let *p* denote the probability of getting the allowed placement of new house. Let *S* denote the area of Bearland (*S*<==<=4Β·1012). Your task is to find *p*Β·*S*. Input Specification: The first line of the input contains an integer *T* (1<=≀<=*T*<=≀<=500)Β β€” the number of test cases. The description of the test cases follows. The first line of the description of a test case contains an integer *n* (3<=≀<=*n*<=≀<=200<=000)Β β€” the number of houses. The *i*-th of the next *n* lines contains two integers *x**i* and *y**i* (<=-<=106<=≀<=*x**i*,<=*y**i*<=≀<=106)Β β€” coordinates of the *i*-th house. No two houses are located at the same point in the same test case. Limak lives in the first house. The sum of *n* won't exceed 200<=000. Output Specification: Print one real value, denoting the area of the set of points that are possible new placements of Limak's house. Your answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=6. More precisely, let the jury's answer be *b*, and your answer be *a*. Then your answer will be accepted if and only if . Demo Input: ['4\n4\n5 3\n0 1\n10 1\n3 51\n3\n-999123 700000\n-950000 123456\n-950000 987654\n3\n2 3\n10 -1\n-4 6\n5\n1 3\n5 2\n6 1\n4 4\n-3 3\n'] Demo Output: ['250.000000000000\n100000000000.000000000000\n0.000000000000\n6.562500000000\n'] Note: In the sample test, there are 4 test cases. In the first test case, there are four houses and Limak's one is in (5, 3). The set of valid new placements form a triangle with vertices in points (0, 1), (10, 1) and (3, 51), without its sides. The area of such a triangle is 250. In the second test case, the set of valid new placements form a rectangle of width 50 000 and height 2 000 000. Don't forget that the new placement must be inside the big square that represents Bearland. In the third test case, the three given points are collinear. Each cross product is equal to 0 and it should be 0 after the relocation as well. Hence, Limak's new house must lie on the line that goes through the given points. Since it must also be inside the big square, new possible placements are limited to some segment (excluding the two points where the other houses are). The area of any segment is 0.
1,161
Title: Three Parts of the Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. More formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then: $$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$ $$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$ $$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$ The sum of an empty array is $0$. Your task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. Input Specification: The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β€” the number of elements in the array $d$. The second line of the input contains $n$ integers $d_1, d_2, \dots, d_n$ ($1 \le d_i \le 10^9$) β€” the elements of the array $d$. Output Specification: Print a single integer β€” the maximum possible value of $sum_1$, considering that the condition $sum_1 = sum_3$ must be met. Obviously, at least one valid way to split the array exists (use $a=c=0$ and $b=n$). Demo Input: ['5\n1 3 1 1 4\n', '5\n1 3 2 1 4\n', '3\n4 1 2\n'] Demo Output: ['5\n', '4\n', '0\n'] Note: In the first example there is only one possible splitting which maximizes $sum_1$: $[1, 3, 1], [~], [1, 4]$. In the second example the only way to have $sum_1=4$ is: $[1, 3], [2, 1], [4]$. In the third example there is only one way to split the array: $[~], [4, 1, 2], [~]$.
1,162
Title: Median on Segments (General Case Edition) Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an integer sequence $a_1, a_2, \dots, a_n$. Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$. The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used. For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence. Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$. Input Specification: The first line contains integers $n$ and $m$ ($1 \le n,m \le 2\cdot10^5$) β€” the length of the given sequence and the required value of the median. The second line contains an integer sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2\cdot10^5$). Output Specification: Print the required number. Demo Input: ['5 4\n1 4 5 60 4\n', '3 1\n1 1 1\n', '15 2\n1 2 3 1 2 3 1 2 3 1 2 3 1 2 3\n'] Demo Output: ['8\n', '6\n', '97\n'] Note: In the first example, the suitable pairs of indices are: $(1, 3)$, $(1, 4)$, $(1, 5)$, $(2, 2)$, $(2, 3)$, $(2, 5)$, $(4, 5)$ and $(5, 5)$.
1,163
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Scott Lang is at war with Darren Cross. There are *n* chairs in a hall where they are, numbered with 1,<=2,<=...,<=*n* from left to right. The *i*-th chair is located at coordinate *x**i*. Scott is on chair number *s* and Cross is on chair number *e*. Scott can jump to all other chairs (not only neighboring chairs). He wants to start at his position (chair number *s*), visit each chair exactly once and end up on chair number *e* with Cross. As we all know, Scott can shrink or grow big (grow big only to his normal size), so at any moment of time he can be either small or large (normal). The thing is, he can only shrink or grow big while being on a chair (not in the air while jumping to another chair). Jumping takes time, but shrinking and growing big takes no time. Jumping from chair number *i* to chair number *j* takes |*x**i*<=-<=*x**j*| seconds. Also, jumping off a chair and landing on a chair takes extra amount of time. If Scott wants to jump to a chair on his left, he can only be small, and if he wants to jump to a chair on his right he should be large. Jumping off the *i*-th chair takes: - *c**i* extra seconds if he's small. - *d**i* extra seconds otherwise (he's large). Also, landing on *i*-th chair takes: - *b**i* extra seconds if he's small. - *a**i* extra seconds otherwise (he's large). In simpler words, jumping from *i*-th chair to *j*-th chair takes exactly: - |*x**i*<=-<=*x**j*|<=+<=*c**i*<=+<=*b**j* seconds if *j*<=&lt;<=*i*. - |*x**i*<=-<=*x**j*|<=+<=*d**i*<=+<=*a**j* seconds otherwise (*j*<=&gt;<=*i*). Given values of *x*, *a*, *b*, *c*, *d* find the minimum time Scott can get to Cross, assuming he wants to visit each chair exactly once. Input Specification: The first line of the input contains three integers *n*,<=*s* and *e* (2<=≀<=*n*<=≀<=5000,<=1<=≀<=*s*,<=*e*<=≀<=*n*,<=*s*<=β‰ <=*e*)Β β€” the total number of chairs, starting and ending positions of Scott. The second line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (1<=≀<=*x*1<=&lt;<=*x*2<=&lt;<=...<=&lt;<=*x**n*<=≀<=109). The third line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a*1,<=*a*2,<=...,<=*a**n*<=≀<=109). The fourth line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≀<=*b*1,<=*b*2,<=...,<=*b**n*<=≀<=109). The fifth line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≀<=*c*1,<=*c*2,<=...,<=*c**n*<=≀<=109). The sixth line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≀<=*d*1,<=*d*2,<=...,<=*d**n*<=≀<=109). Output Specification: Print the minimum amount of time Scott needs to get to the Cross while visiting each chair exactly once. Demo Input: ['7 4 3\n8 11 12 16 17 18 20\n17 16 20 2 20 5 13\n17 8 8 16 12 15 13\n12 4 16 4 15 7 6\n8 14 2 11 17 12 8\n'] Demo Output: ['139\n'] Note: In the sample testcase, an optimal solution would be <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5bbd3e094ffa5a72e263dfaec7aeaff795bc22a3.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Spent time would be 17 + 24 + 23 + 20 + 33 + 22 = 139.
1,164
Title: Mashmokh and ACM Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following. A sequence of *l* integers *b*1,<=*b*2,<=...,<=*b**l* (1<=≀<=*b*1<=≀<=*b*2<=≀<=...<=≀<=*b**l*<=≀<=*n*) is called good if each number divides (without a remainder) by the next number in the sequence. More formally for all *i* (1<=≀<=*i*<=≀<=*l*<=-<=1). Given *n* and *k* find the number of good sequences of length *k*. As the answer can be rather large print it modulo 1000000007 (109<=+<=7). Input Specification: The first line of input contains two space-separated integers *n*,<=*k*Β (1<=≀<=*n*,<=*k*<=≀<=2000). Output Specification: Output a single integer β€” the number of good sequences of length *k* modulo 1000000007 (109<=+<=7). Demo Input: ['3 2\n', '6 4\n', '2 1\n'] Demo Output: ['5\n', '39\n', '2\n'] Note: In the first sample the good sequences are: [1, 1], [2, 2], [3, 3], [1, 2], [1, 3].
1,165
Title: Underground Lab 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.
1,166
Title: Han Solo and Lazer Gun Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (*x*,<=*y*) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (*x*0,<=*y*0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (*x*0,<=*y*0). Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers. The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. Input Specification: The first line contains three integers *n*, *x*0 ΠΈ *y*0 (1<=≀<=*n*<=≀<=1000, <=-<=104<=≀<=*x*0,<=*y*0<=≀<=104) β€” the number of stormtroopers on the battle field and the coordinates of your gun. Next *n* lines contain two integers each *x**i*, *y**i* (<=-<=104<=≀<=*x**i*,<=*y**i*<=≀<=104) β€” the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. Output Specification: Print a single integer β€” the minimum number of shots Han Solo needs to destroy all the stormtroopers. Demo Input: ['4 0 0\n1 1\n2 2\n2 0\n-1 -1\n', '2 1 2\n1 1\n1 0\n'] Demo Output: ['2\n', '1\n'] Note: Explanation to the first and second samples from the statement, respectively:
1,167
Title: Interview Time Limit: None seconds Memory Limit: None megabytes Problem Description: Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function *f*(*x*,<=*l*,<=*r*) as a bitwise OR of integers *x**l*,<=*x**l*<=+<=1,<=...,<=*x**r*, where *x**i* is the *i*-th element of the array *x*. You are given two arrays *a* and *b* of length *n*. You need to determine the maximum value of sum *f*(*a*,<=*l*,<=*r*)<=+<=*f*(*b*,<=*l*,<=*r*) among all possible 1<=≀<=*l*<=≀<=*r*<=≀<=*n*. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the length of the arrays. The second line contains *n* integers *a**i* (0<=≀<=*a**i*<=≀<=109). The third line contains *n* integers *b**i* (0<=≀<=*b**i*<=≀<=109). Output Specification: Print a single integerΒ β€” the maximum value of sum *f*(*a*,<=*l*,<=*r*)<=+<=*f*(*b*,<=*l*,<=*r*) among all possible 1<=≀<=*l*<=≀<=*r*<=≀<=*n*. Demo Input: ['5\n1 2 4 3 2\n2 3 3 12 1\n', '10\n13 2 7 11 8 4 9 8 5 1\n5 7 18 9 2 3 0 11 8 6\n'] Demo Output: ['22', '46'] Note: Bitwise OR of two non-negative integers *a* and *b* is the number *c* = *a* *OR* *b*, such that each of its digits in binary notation is 1 if and only if at least one of *a* or *b* have 1 in the corresponding position in binary notation. In the first sample, one of the optimal answers is *l* = 2 and *r* = 4, because *f*(*a*, 2, 4) + *f*(*b*, 2, 4) = (2 *OR* 4 *OR* 3) + (3 *OR* 3 *OR* 12) = 7 + 15 = 22. Other ways to get maximum value is to choose *l* = 1 and *r* = 4, *l* = 1 and *r* = 5, *l* = 2 and *r* = 4, *l* = 2 and *r* = 5, *l* = 3 and *r* = 4, or *l* = 3 and *r* = 5. In the second sample, the maximum value is obtained for *l* = 1 and *r* = 9.
1,168
Title: After Training Time Limit: None seconds Memory Limit: None megabytes Problem Description: After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has *n* balls and *m* baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to *m*, correspondingly. The balls are numbered with numbers from 1 to *n*. Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where *i* is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number. For every ball print the number of the basket where it will go according to Valeric's scheme. Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on. Input Specification: The first line contains two space-separated integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the number of balls and baskets, correspondingly. Output Specification: Print *n* numbers, one per line. The *i*-th line must contain the number of the basket for the *i*-th ball. Demo Input: ['4 3\n', '3 1\n'] Demo Output: ['2\n1\n3\n2\n', '1\n1\n1\n'] Note: none
1,169
Title: Ace It! Time Limit: None seconds Memory Limit: None megabytes Problem Description: The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid"). Output a single integer. Input Specification: The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid"). Output Specification: Output a single integer. Demo Input: ['A221033\n', 'A223635\n', 'A232726\n'] Demo Output: ['21\n', '22\n', '23\n'] Note: none
1,170
Title: Battlefield Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya lagged behind at the University and got to the battlefield. Just joking! He's simply playing some computer game. The field is a flat platform with *n* trenches dug on it. The trenches are segments on a plane parallel to the coordinate axes. No two trenches intersect. There is a huge enemy laser far away from Vasya. The laser charges for *a* seconds, and then shoots continuously for *b* seconds. Then, it charges for *a* seconds again. Then it shoots continuously for *b* seconds again and so on. Vasya knows numbers *a* and *b*. He also knows that while the laser is shooting, Vasya must be in the trench, but while the laser is charging, Vasya can safely move around the field. The main thing is to have time to hide in the trench before the shot. If Vasya reaches the trench exactly at the moment when the laser starts shooting, we believe that Vasya managed to hide. Coincidentally, the length of any trench in meters numerically does not exceed *b*. Initially, Vasya is at point *A*. He needs to get to point *B*. Vasya moves at speed 1 meter per second in either direction. You can get in or out of the trench at any its point. Getting in or out of the trench takes no time. It is also possible to move in the trench, without leaving it. What is the minimum time Vasya needs to get from point *A* to point *B*, if at the initial time the laser has just started charging? If Vasya cannot get from point *A* to point *B*, print -1. If Vasya reaches point *B* at the moment when the laser begins to shoot, it is believed that Vasya managed to reach point *B*. Input Specification: The first line contains two space-separated integers: *a* and *b* (1<=≀<=*a*,<=*b*<=≀<=1000), β€” the duration of charging and the duration of shooting, in seconds. The second line contains four space-separated integers: *A**x*, *A**y*, *B**x*, *B**y* (<=-<=104<=≀<=*A**x*,<=*A**y*,<=*B**x*,<=*B**y*<=≀<=104) β€” the coordinates of points *А* and *B*. It is guaranteed that points *A* and *B* do not belong to any trench. The third line contains a single integer: *n* (1<=≀<=*n*<=≀<=1000), β€” the number of trenches. Each of the following *n* lines contains four space-separated integers: *x*1, *y*1, *x*2, *y*2 (<=-<=104<=≀<=*x**i*,<=*y**i*<=≀<=104) β€” the coordinates of ends of the corresponding trench. All coordinates are given in meters. It is guaranteed that for any trench either *x*1<==<=*x*2, or *y*1<==<=*y*2. No two trenches intersect. The length of any trench in meters doesn't exceed *b* numerically. Output Specification: If Vasya can get from point *A* to point *B*, print the minimum time he will need for it. Otherwise, print number -1. The answer will be considered correct if the absolute or relative error does not exceed 10<=-<=4 Demo Input: ['2 4\n0 5 6 5\n3\n0 0 0 4\n1 1 4 1\n6 0 6 4\n', '5 10\n0 0 10 10\n1\n5 0 5 9\n'] Demo Output: ['19.0000000000\n', '-1\n'] Note: none
1,171
Title: Safe Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Vasya tries to break in a safe. He knows that a code consists of *n* numbers, and every number is a 0 or a 1. Vasya has made *m* attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya β€” calculate how many possible code variants are left that do not contradict the previous system responses. Input Specification: The first input line contains two integers *n* and *m* (6<=≀<=*n*<=≀<=35,<=1<=≀<=*m*<=≀<=10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow *m* lines, each containing space-separated *s**i* and *c**i* which correspondingly indicate Vasya’s attempt (a line containing *n* numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively). Output Specification: Print the single number which indicates how many possible code variants that do not contradict the *m* system responses are left. Demo Input: ['6 2\n000000 2\n010100 4\n', '6 3\n000000 2\n010100 4\n111100 0\n', '6 3\n000000 2\n010100 4\n111100 2\n'] Demo Output: ['6\n', '0\n', '1\n'] Note: none
1,172
Title: Beautiful Road Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: A long time ago in some country in Asia were civil wars. Each of *n* cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city. Road making was difficult, so the country had few roads, exactly *n*<=-<=1. Also you could reach any city from any other city going on those roads. Even during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them. Recently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly *n*(*n*<=-<=1) attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees. Input Specification: The first line contains an integer *n* (2<=≀<=*n*<=≀<=105), which represents the number of cities. Next *n*<=-<=1 lines contain three integers each: the numbers of cities *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*), connected by the *i*-th road and the number of days *d**i* the army spends to go on it (1<=≀<=*d**i*<=≀<=109). The lengths of several roads may coincide. Output Specification: Print on the first line two integers β€” the number of beautiful trees on the most beautiful road and the number of the most beautiful roads. Print on the second line the list of the most beautiful roads in the sorted order by the numbers' increasing. The roads are numbered from 1 to *n*<=-<=1 in the order in which they are given in the input data. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator). Demo Input: ['2\n2 1 5\n', '6\n1 2 1\n1 3 5\n3 4 2\n3 5 3\n3 6 4\n'] Demo Output: ['2 1\n1 \n', '16 1\n2 \n'] Note: none
1,173
Title: Noise Level Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Berland's capital has the form of a rectangle with sizes *n*<=Γ—<=*m* quarters. All quarters are divided into three types: - regular (labeled with the character '.') β€” such quarters do not produce the noise but are not obstacles to the propagation of the noise; - sources of noise (labeled with an uppercase Latin letter from 'A' to 'Z') β€” such quarters are noise sources and are not obstacles to the propagation of the noise; - heavily built-up (labeled with the character '*') β€” such quarters are soundproofed, the noise does not penetrate into them and they themselves are obstacles to the propagation of noise. A quarter labeled with letter 'A' produces *q* units of noise. A quarter labeled with letter 'B' produces 2Β·*q* units of noise. And so on, up to a quarter labeled with letter 'Z', which produces 26Β·*q* units of noise. There can be any number of quarters labeled with each letter in the city. When propagating from the source of the noise, the noise level is halved when moving from one quarter to a quarter that shares a side with it (when an odd number is to be halved, it's rounded down). The noise spreads along the chain. For example, if some quarter is located at a distance 2 from the noise source, then the value of noise which will reach the quarter is divided by 4. So the noise level that comes from the source to the quarter is determined solely by the length of the shortest path between them. Heavily built-up quarters are obstacles, the noise does not penetrate into them. The noise level in quarter is defined as the sum of the noise from all sources. To assess the quality of life of the population of the capital of Berland, it is required to find the number of quarters whose noise level exceeds the allowed level *p*. Input Specification: The first line contains four integers *n*, *m*, *q* and *p* (1<=≀<=*n*,<=*m*<=≀<=250, 1<=≀<=*q*,<=*p*<=≀<=106) β€” the sizes of Berland's capital, the number of noise units that a quarter 'A' produces, and the allowable noise level. Each of the following *n* lines contains *m* characters β€” the description of the capital quarters, in the format that was described in the statement above. It is possible that in the Berland's capital there are no quarters of any type. Output Specification: Print the number of quarters, in which the noise level exceeds the allowed level *p*. Demo Input: ['3 3 100 140\n...\nA*.\n.B.\n', '3 3 2 8\nB*.\nBB*\nBBB\n', '3 4 5 4\n..*B\n..**\nD...\n'] Demo Output: ['3\n', '4\n', '7\n'] Note: The illustration to the first example is in the main part of the statement.
1,174
Title: Lineland Mail Time Limit: None seconds Memory Limit: None megabytes Problem Description: All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* β€” a coordinate on the *Ox* axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in). Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city. For each city calculate two values ​​*min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city Input Specification: The first line of the input contains integer *n* (2<=≀<=*n*<=≀<=105) β€” the number of cities in Lineland. The second line contains the sequence of *n* distinct integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=109<=≀<=*x**i*<=≀<=109), where *x**i* is the *x*-coordinate of the *i*-th city. All the *x**i*'s are distinct and follow in ascending order. Output Specification: Print *n* lines, the *i*-th line must contain two integers *min**i*,<=*max**i*, separated by a space, where *min**i* is the minimum cost of sending a letter from the *i*-th city, and *max**i* is the maximum cost of sending a letter from the *i*-th city. Demo Input: ['4\n-5 -2 2 7\n', '2\n-1 1\n'] Demo Output: ['3 12\n3 9\n4 7\n5 12\n', '2 2\n2 2\n'] Note: none
1,175
Title: Mancala Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction. Note that the counter-clockwise order means if the player takes the stones from hole $i$, he will put one stone in the $(i+1)$-th hole, then in the $(i+2)$-th, etc. If he puts a stone in the $14$-th hole, the next one will be put in the first hole. After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli. Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move. Input Specification: The only line contains 14 integers $a_1, a_2, \ldots, a_{14}$ ($0 \leq a_i \leq 10^9$)Β β€” the number of stones in each hole. It is guaranteed that for any $i$ ($1\leq i \leq 14$) $a_i$ is either zero or odd, and there is at least one stone in the board. Output Specification: Output one integer, the maximum possible score after one move. Demo Input: ['0 1 1 0 0 0 0 0 0 7 0 0 0 0\n', '5 1 1 1 1 0 0 0 0 0 0 0 0 0\n'] Demo Output: ['4\n', '8\n'] Note: In the first test case the board after the move from the hole with $7$ stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to $4$.
1,176
Title: Tricky Alchemy Time Limit: None seconds Memory Limit: None megabytes Problem Description: During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, greenΒ β€” one yellow and one blue, and for a blue ball, three blue crystals are enough. Right now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls. Input Specification: The first line features two integers *A* and *B* (0<=≀<=*A*,<=*B*<=≀<=109), denoting the number of yellow and blue crystals respectively at Grisha's disposal. The next line contains three integers *x*, *y* and *z* (0<=≀<=*x*,<=*y*,<=*z*<=≀<=109)Β β€” the respective amounts of yellow, green and blue balls to be obtained. Output Specification: Print a single integerΒ β€” the minimum number of crystals that Grisha should acquire in addition. Demo Input: ['4 3\n2 1 1\n', '3 9\n1 1 3\n', '12345678 87654321\n43043751 1000000000 53798715\n'] Demo Output: ['2\n', '1\n', '2147483648\n'] Note: In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue.
1,177
Title: High Load Time Limit: None seconds Memory Limit: None megabytes Problem Description: Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of *n* nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly *k* of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability. Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes. Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible. Input Specification: The first line contains two integers *n* and *k* (3<=≀<=*n*<=≀<=2Β·105, 2<=≀<=*k*<=≀<=*n*<=-<=1)Β β€” the total number of nodes and the number of exit-nodes. Note that it is always possible to build at least one network with *n* nodes and *k* exit-nodes within the given constraints. Output Specification: In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next *n*<=-<=1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to *n*. Exit-nodes can have any ids. If there are multiple answers, print any of them. Demo Input: ['3 2\n', '5 3\n'] Demo Output: ['2\n1 2\n2 3\n', '3\n1 2\n2 3\n3 4\n3 5\n'] Note: In the first example the only network is shown on the left picture. In the second example one of optimal networks is shown on the right picture. Exit-nodes are highlighted.
1,178
Title: Sysadmin Bob Time Limit: 0 seconds Memory Limit: 256 megabytes Problem Description: Email address in Berland is a string of the form *A*@*B*, where *A* and *B* are arbitrary strings consisting of small Latin letters. Bob is a system administrator in Β«BersoftΒ» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once. Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that. Input Specification: The first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters Β«@Β». Output Specification: If there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them. Demo Input: ['a@aa@a\n', 'a@a@a\n', '@aa@a\n'] Demo Output: ['a@a,a@a\n', 'No solution\n', 'No solution\n'] Note: none
1,179
Title: Sea and Islands Time Limit: None seconds Memory Limit: None megabytes Problem Description: A map of some object is a rectangular field consisting of *n* rows and *n* columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly *k* islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island). Find a way to cover some cells with sand so that exactly *k* islands appear on the *n*<=Γ—<=*n* map, or determine that no such way exists. Input Specification: The single line contains two positive integers *n*, *k* (1<=≀<=*n*<=≀<=100, 0<=≀<=*k*<=≀<=*n*2) β€” the size of the map and the number of islands you should form. Output Specification: If the answer doesn't exist, print "NO" (without the quotes) in a single line. Otherwise, print "YES" in the first line. In the next *n* lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal *n*. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands. Demo Input: ['5 2\n', '5 25\n'] Demo Output: ['YES\nSSSSS\nLLLLL\nSSSSS\nLLLLL\nSSSSS\n', 'NO\n'] Note: none
1,180
Title: Equalize the Remainders Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array consisting of $n$ integers $a_1, a_2, \dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$. In a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$. Let's calculate $c_r$ ($0 \le r \le m-1)$ β€” the number of elements having remainder $r$ when divided by $m$. In other words, for each remainder, let's find the number of corresponding elements in $a$ with that remainder. Your task is to change the array in such a way that $c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}$. Find the minimum number of moves to satisfy the above requirement. Input Specification: The first line of input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5, 1 \le m \le n$). It is guaranteed that $m$ is a divisor of $n$. The second line of input contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$), the elements of the array. Output Specification: In the first line, print a single integer β€” the minimum number of moves required to satisfy the following condition: for each remainder from $0$ to $m - 1$, the number of elements of the array having this remainder equals $\frac{n}{m}$. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed $10^{18}$. Demo Input: ['6 3\n3 2 0 6 10 12\n', '4 2\n0 1 2 3\n'] Demo Output: ['3\n3 2 0 7 10 14 \n', '0\n0 1 2 3 \n'] Note: none
1,181
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to *n*. Everyone has exactly one crush, *i*-th person's crush is person with the number *crush**i*. Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person *x* wants to start a round, he calls *crush**x* and says: "Oww...wwf" (the letter w is repeated *t* times) and cuts off the phone immediately. If *t*<=&gt;<=1 then *crush**x* calls *crush**crush**x* and says: "Oww...wwf" (the letter w is repeated *t*<=-<=1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (*t*<==<=1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest *t* (*t*<=β‰₯<=1) such that for each person *x*, if *x* starts some round and *y* becomes the Joon-Joon of the round, then by starting from *y*, *x* would become the Joon-Joon of the round. Find such *t* for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. *crush**i*<==<=*i*). Input Specification: The first line of input contains integer *n* (1<=≀<=*n*<=≀<=100)Β β€” the number of people in Arpa's land. The second line contains *n* integers, *i*-th of them is *crush**i* (1<=≀<=*crush**i*<=≀<=*n*)Β β€” the number of *i*-th person's crush. Output Specification: If there is no *t* satisfying the condition, print -1. Otherwise print such smallest *t*. Demo Input: ['4\n2 3 1 4\n', '4\n4 4 4 4\n', '4\n2 1 4 3\n'] Demo Output: ['3\n', '-1\n', '1\n'] Note: In the first sample suppose *t* = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if *x* is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when *x* is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.
1,182
Title: Paths and Trees Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows. Let's assume that we are given a connected weighted undirected graph *G*<==<=(*V*,<=*E*) (here *V* is the set of vertices, *E* is the set of edges). The shortest-path tree from vertex *u* is such graph *G*1<==<=(*V*,<=*E*1) that is a tree with the set of edges *E*1 that is the subset of the set of edges of the initial graph *E*, and the lengths of the shortest paths from *u* to any vertex to *G* and to *G*1 are the same. You are given a connected weighted undirected graph *G* and vertex *u*. Your task is to find the shortest-path tree of the given graph from vertex *u*, the total weight of whose edges is minimum possible. Input Specification: The first line contains two numbers, *n* and *m* (1<=≀<=*n*<=≀<=3Β·105, 0<=≀<=*m*<=≀<=3Β·105) β€” the number of vertices and edges of the graph, respectively. Next *m* lines contain three integers each, representing an edge β€” *u**i*,<=*v**i*,<=*w**i* β€” the numbers of vertices connected by an edge and the weight of the edge (*u**i*<=β‰ <=*v**i*,<=1<=≀<=*w**i*<=≀<=109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices. The last line of the input contains integer *u* (1<=≀<=*u*<=≀<=*n*) β€” the number of the start vertex. Output Specification: In the first line print the minimum total weight of the edges of the tree. In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order. If there are multiple answers, print any of them. Demo Input: ['3 3\n1 2 1\n2 3 1\n1 3 2\n3\n', '4 4\n1 2 1\n2 3 1\n3 4 1\n4 1 2\n4\n'] Demo Output: ['2\n1 2 \n', '4\n2 3 4 \n'] Note: In the first sample there are two possible shortest path trees: - with edges 1 – 3 and 2 – 3 (the total weight is 3); - with edges 1 – 2 and 2 – 3 (the total weight is 2); And, for example, a tree with edges 1 – 2 and 1 – 3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1.
1,183
Title: Morning run Time Limit: None seconds Memory Limit: None megabytes Problem Description: People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly *l* meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning. The stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed β€” exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet. The company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by *t* time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for *t* time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once. Input Specification: The first line of the input contains three integers *n*, *l*, *t* (1<=≀<=*n*<=≀<=106,<=1<=≀<=*l*<=≀<=109,<=1<=≀<=*t*<=≀<=109). The next line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*<=&lt;<=*l*), here *a**i* is the clockwise distance from the start line to the *i*-th runner's starting position. Output Specification: Print a single real number β€” the answer to the problem with absolute or relative error of at most 10<=-<=6. Demo Input: ['2 5 1\n0 2\n', '3 7 3\n0 1 6\n'] Demo Output: ['0.2500000000\n', '1.5000000000\n'] Note: There are two runners in the first example. If the first runner run clockwise direction, then in 1 time unit he will be 1m away from the start line. If the second runner run counter-clockwise direction then in 1 time unit he will be also 1m away from the start line. And it is the only possible way to meet. We assume that each running direction is equiprobable, so the answer for the example is equal to 0.5Β·0.5 = 0.25.
1,184
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not. Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days. Input Specification: In the only line of input data there is a non-empty string *s* consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |*s*|) does not exceed 200<=000 characters. Output Specification: If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer *k* (1<=≀<=*k*<=≀<=|*s*|), the resulting number of subsequences. In the *i*-th of following *k* lines first print the integer *l**i* (1<=≀<=*l**i*<=≀<=|*s*|), which is the length of the *i*-th subsequence, and then *l**i* indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to *n* must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of *k*. Demo Input: ['0010100\n', '111\n'] Demo Output: ['3\n3 1 3 4\n3 2 5 6\n1 7\n', '-1\n'] Note: none
1,185
Title: Cartons of milk Time Limit: None seconds Memory Limit: None megabytes Problem Description: Olya likes milk very much. She drinks *k* cartons of milk each day if she has at least *k* and drinks all of them if she doesn't. But there's an issueΒ β€” expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's fridge contains a carton past its expiry date, she throws it away. Olya hates throwing out cartons, so when she drinks a carton, she chooses the one which expires the fastest. It's easy to understand that this strategy minimizes the amount of cartons thrown out and lets her avoid it if it's even possible. The main issue Olya has is the one of buying new cartons. Currently, there are *n* cartons of milk in Olya's fridge, for each one an expiration date is known (how soon does it expire, measured in days). In the shop that Olya visited there are *m* cartons, and the expiration date is known for each of those cartons as well. Find the maximum number of cartons Olya can buy so that she wouldn't have to throw away any cartons. Assume that Olya drank no cartons today. Input Specification: In the first line there are three integers *n*, *m*, *k* (1<=≀<=*n*,<=*m*<=≀<=106, 1<=≀<=*k*<=≀<=*n*<=+<=*m*)Β β€” the amount of cartons in Olya's fridge, the amount of cartons in the shop and the number of cartons Olya drinks each day. In the second line there are *n* integers *f*1,<=*f*2,<=...,<=*f**n* (0<=≀<=*f**i*<=≀<=107)Β β€” expiration dates of the cartons in Olya's fridge. The expiration date is expressed by the number of days the drinking of this carton can be delayed. For example, a 0 expiration date means it must be drunk today, 1Β β€” no later than tomorrow, etc. In the third line there are *m* integers *s*1,<=*s*2,<=...,<=*s**m* (0<=≀<=*s**i*<=≀<=107)Β β€” expiration dates of the cartons in the shop in a similar format. Output Specification: If there's no way for Olya to drink the cartons she already has in her fridge, print -1. Otherwise, in the first line print the maximum number *x* of cartons which Olya can buy so that she wouldn't have to throw a carton away. The next line should contain exactly *x* integersΒ β€” the numbers of the cartons that should be bought (cartons are numbered in an order in which they are written in the input, starting with 1). Numbers should not repeat, but can be in arbitrary order. If there are multiple correct answers, print any of them. Demo Input: ['3 6 2\n1 0 1\n2 0 2 0 0 2\n', '3 1 2\n0 0 0\n1\n', '2 1 2\n0 1\n0\n'] Demo Output: ['3\n1 2 3', '-1', '1\n1 '] Note: In the first example *k* = 2 and Olya has three cartons with expiry dates 0, 1 and 1 (they expire today, tomorrow and tomorrow), and the shop has 3 cartons with expiry date 0 and 3 cartons with expiry date 2. Olya can buy three cartons, for example, one with the expiry date 0 and two with expiry date 2. In the second example all three cartons Olya owns expire today and it means she would have to throw packets away regardless of whether she buys an extra one or not. In the third example Olya would drink *k* = 2 cartons today (one she alreay has in her fridge and one from the shop) and the remaining one tomorrow.
1,186
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gennady is one of the best child dentists in Berland. Today *n* children got an appointment with him, they lined up in front of his office. All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to *n* in the order they go in the line. Every child is associated with the value of his cofidence *p**i*. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor. While Gennady treats the teeth of the *i*-th child, the child is crying with the volume of *v**i*. At that the confidence of the first child in the line is reduced by the amount of *v**i*, the second one β€” by value *v**i*<=-<=1, and so on. The children in the queue after the *v**i*-th child almost do not hear the crying, so their confidence remains unchanged. If at any point in time the confidence of the *j*-th child is less than zero, he begins to cry with the volume of *d**j* and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the *j*-th one in the line is reduced by the amount of *d**j*. All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office. Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order. Input Specification: The first line of the input contains a positive integer *n* (1<=≀<=*n*<=≀<=4000) β€” the number of kids in the line. Next *n* lines contain three integers each *v**i*,<=*d**i*,<=*p**i* (1<=≀<=*v**i*,<=*d**i*,<=*p**i*<=≀<=106) β€” the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the *i*-th child. Output Specification: In the first line print number *k* β€” the number of children whose teeth Gennady will cure. In the second line print *k* integers β€” the numbers of the children who will make it to the end of the line in the increasing order. Demo Input: ['5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2\n', '5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9\n'] Demo Output: ['2\n1 3 ', '4\n1 2 4 5 '] Note: In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to  - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit. In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,  - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.
1,187
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them. There are *n* planets in their universe numbered from 1 to *n*. Rick is in planet number *s* (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial. By default he can not open any portal by this gun. There are *q* plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more. Plans on the website have three types: 1. With a plan of this type you can open a portal from planet *v* to planet *u*. 1. With a plan of this type you can open a portal from planet *v* to any planet with index in range [*l*,<=*r*]. 1. With a plan of this type you can open a portal from any planet with index in range [*l*,<=*r*] to planet *v*. Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet. Input Specification: The first line of input contains three integers *n*, *q* and *s* (1<=≀<=*n*,<=*q*<=≀<=105, 1<=≀<=*s*<=≀<=*n*) β€” number of planets, number of plans and index of earth respectively. The next *q* lines contain the plans. Each line starts with a number *t*, type of that plan (1<=≀<=*t*<=≀<=3). If *t*<==<=1 then it is followed by three integers *v*, *u* and *w* where *w* is the cost of that plan (1<=≀<=*v*,<=*u*<=≀<=*n*, 1<=≀<=*w*<=≀<=109). Otherwise it is followed by four integers *v*, *l*, *r* and *w* where *w* is the cost of that plan (1<=≀<=*v*<=≀<=*n*, 1<=≀<=*l*<=≀<=*r*<=≀<=*n*, 1<=≀<=*w*<=≀<=109). Output Specification: In the first and only line of output print *n* integers separated by spaces. *i*-th of them should be minimum money to get from earth to *i*-th planet, or <=-<=1 if it's impossible to get to that planet. Demo Input: ['3 5 1\n2 3 2 3 17\n2 3 2 2 16\n2 2 2 3 3\n3 3 1 1 12\n1 3 3 17\n', '4 3 1\n3 4 1 3 12\n2 2 3 4 10\n1 2 4 16\n'] Demo Output: ['0 28 12 \n', '0 -1 -1 12 \n'] Note: In the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2.
1,188
Title: Camping Groups Time Limit: None seconds Memory Limit: None megabytes Problem Description: A club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups. Club member *i* has a responsibility value *r**i* and an age value *a**i*. A group is a non-empty subset of club members with one member known as group leader. A group leader should be one of the most responsible members of the group (his responsibility value is not less than responsibility of any other group member) and his age absolute difference with any other group member should not exceed *k*. Some club members are friends and want to be in the same group. They also like their group to be as large as possible. Now you should write a program that answers a series of questions like "What's the largest size of a group containing club member *x* and club member *y*?". It's possible for *x* or *y* to be the group leader. Input Specification: The first line contains two integers *n* and *k* (2<=≀<=*n*<=≀<=105,<=0<=≀<=*k*<=≀<=109) β€” the number of club members and the age restriction for one group. The next line contains integer numbers *r*1,<=*r*2,<=...,<=*r**n* (1<=≀<=*r**i*<=≀<=109) separated by space: *r**i* denotes the *i*-th club member's responsibility. In the same way there are integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109) in the third line: *a**i* denotes the *i*-th club member's age. The next line contains an integer *q* denoting the number of questions that you should answer (1<=≀<=*q*<=≀<=105). The next *q* lines describe the questions. Each line contains two space-separated integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*,<=*x**i*<=β‰ <=*y**i*) β€” the indices of the club members that should end up in the same group. Output Specification: For each question print the maximum size of the group in a line. If making such a group is impossible print -1 instead. Demo Input: ['5 1\n1 5 4 1 2\n4 4 3 2 2\n4\n5 3\n2 3\n2 5\n4 1\n'] Demo Output: ['4\n3\n-1\n4\n'] Note: In the first query the largest group with members 3 and 5 is {1, 3, 4, 5} where member 3 is the leader. In the second query member 2 should be the leader so the group will be {1, 2, 3}. In the third query the leader of the group should have age 3 so the only leader can be member 3, who is less responsible than member 2. So making a group is impossible. The group for the fourth query is the same as first query.
1,189
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Jzzhu is the president of country A. There are *n* cities numbered from 1 to *n* in his country. City 1 is the capital of A. Also there are *m* roads connecting the cities. One can go from city *u**i* to *v**i* (and vise versa) using the *i*-th road, the length of this road is *x**i*. Finally, there are *k* train routes in the country. One can use the *i*-th train route to go from capital of the country to city *s**i* (and vise versa), the length of this route is *y**i*. Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. Input Specification: The first line contains three integers *n*,<=*m*,<=*k* (2<=≀<=*n*<=≀<=105;Β 1<=≀<=*m*<=≀<=3Β·105;Β 1<=≀<=*k*<=≀<=105). Each of the next *m* lines contains three integers *u**i*,<=*v**i*,<=*x**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*;Β *u**i*<=β‰ <=*v**i*;Β 1<=≀<=*x**i*<=≀<=109). Each of the next *k* lines contains two integers *s**i* and *y**i* (2<=≀<=*s**i*<=≀<=*n*;Β 1<=≀<=*y**i*<=≀<=109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. Output Specification: Output a single integer representing the maximum number of the train routes which can be closed. Demo Input: ['5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5\n', '2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3\n'] Demo Output: ['2\n', '2\n'] Note: none
1,190
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You work in a big office. It is a 9Β floor building with an elevator that can accommodate up to 4Β people. It is your responsibility to manage this elevator. Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator. According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order. The elevator has two commands: - Go up or down one floor. The movement takes 1 second. - Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1. You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1. Input Specification: The first line contains an integer *n* (1<=≀<=*n*<=≀<=2000)Β β€” the number of employees. The *i*-th of the next *n* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=9, *a**i*<=β‰ <=*b**i*)Β β€” the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator. Output Specification: Print a single integerΒ β€” the minimal possible time in seconds. Demo Input: ['2\n3 5\n5 3\n', '2\n5 3\n3 5\n'] Demo Output: ['10', '12'] Note: <img class="tex-graphics" src="https://espresso.codeforces.com/1b7e25450a0703db67675fea25386865f0290049.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 2 <img class="tex-graphics" src="https://espresso.codeforces.com/0f585328ada5689c39e5a7263a792979c00fb01a.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 3 <img class="tex-graphics" src="https://espresso.codeforces.com/61f0c2263487060af2083a06cedf6641d234e31b.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 5 <img class="tex-graphics" src="https://espresso.codeforces.com/4f5d7a22c1f2af851019589a1232851ced924fbf.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 6 <img class="tex-graphics" src="https://espresso.codeforces.com/4602434598e4844e9532caef51583bd84886b067.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 7 <img class="tex-graphics" src="https://espresso.codeforces.com/c1924de28ca19fe1346617380752126a2d4bbb75.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 9 <img class="tex-graphics" src="https://espresso.codeforces.com/2e58cd09a6a459da60780a790c49da336d0b2783.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 10
1,191
Title: Ants Time Limit: None seconds Memory Limit: None megabytes Problem Description: It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (*x*, *y*) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (*x*<=+<=1, *y*), (*x*<=-<=1, *y*), (*x*, *y*<=+<=1), (*x*, *y*<=-<=1) β€” one ant in each direction. No other ant movements will happen. Ants never interfere with each other. Scientists have put a colony of *n* ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops. Input Specification: First input line contains integers *n* (0<=≀<=*n*<=≀<=30000) and *t* (1<=≀<=*t*<=≀<=50000), where *n* is the number of ants in the colony and *t* is the number of queries. Each of the next *t* lines contains coordinates of a query junction: integers *x**i*, *y**i* (<=-<=109<=≀<=*x**i*,<=*y**i*<=≀<=109). Queries may coincide. It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end). Output Specification: Print *t* integers, one per line β€” the number of ants at the corresponding junctions when the movement of the ants stops. Demo Input: ['1 3\n0 1\n0 0\n0 -1\n', '6 5\n0 -2\n0 -1\n0 0\n0 1\n0 2\n'] Demo Output: ['0\n1\n0\n', '0\n1\n2\n1\n0\n'] Note: In the first sample the colony consists of the one ant, so nothing happens at all. In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.
1,192
Title: Xenia and Weights Time Limit: None seconds Memory Limit: None megabytes Problem Description: Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of *m* weights on the scalepans. Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes *i*-th should be different from the (*i*<=+<=1)-th weight for any *i* (1<=≀<=*i*<=&lt;<=*m*). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan. You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay *m* weights on ​​the scales or to say that it can't be done. Input Specification: The first line contains a string consisting of exactly ten zeroes and ones: the *i*-th (*i*<=β‰₯<=1) character in the line equals "1" if Xenia has *i* kilo weights, otherwise the character equals "0". The second line contains integer *m* (1<=≀<=*m*<=≀<=1000). Output Specification: In the first line print "YES", if there is a way to put *m* weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put *m* weights on the scales, then print in the next line *m* integers β€” the weights' weights in the order you put them on the scales. If there are multiple solutions, you can print any of them. Demo Input: ['0000000101\n3\n', '1000000000\n2\n'] Demo Output: ['YES\n8 10 8\n', 'NO\n'] Note: none
1,193
Title: Comparing Strings Time Limit: None seconds Memory Limit: None megabytes Problem Description: Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not. Input Specification: The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length. Output Specification: Print "YES", if the dwarves belong to the same race. Otherwise, print "NO". Demo Input: ['ab\nba\n', 'aa\nab\n'] Demo Output: ['YES\n', 'NO\n'] Note: - First example: you can simply swap two letters in string "ab". So we get "ba". - Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".
1,194
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are $n$ banknote denominations on Mars: the value of $i$-th banknote is $a_i$. Natasha has an infinite number of banknotes of each denomination. Martians have $k$ fingers on their hands, so they use a number system with base $k$. In addition, the Martians consider the digit $d$ (in the number system with base $k$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $k$ is $d$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet. Determine for which values $d$ Natasha can make the Martians happy. Natasha can use only her banknotes. Martians don't give her change. Input Specification: The first line contains two integers $n$ and $k$ ($1 \le n \le 100\,000$, $2 \le k \le 100\,000$)Β β€” the number of denominations of banknotes and the base of the number system on Mars. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$)Β β€” denominations of banknotes on Mars. All numbers are given in decimal notation. Output Specification: On the first line output the number of values $d$ for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation. Demo Input: ['2 8\n12 20\n', '3 10\n10 20 30\n'] Demo Output: ['2\n0 4 ', '1\n0 '] Note: Consider the first test case. It uses the octal number system. If you take one banknote with the value of $12$, you will get $14_8$ in octal system. The last digit is $4_8$. If you take one banknote with the value of $12$ and one banknote with the value of $20$, the total value will be $32$. In the octal system, it is $40_8$. The last digit is $0_8$. If you take two banknotes with the value of $20$, the total value will be $40$, this is $50_8$ in the octal system. The last digit is $0_8$. No other digits other than $0_8$ and $4_8$ can be obtained. Digits $0_8$ and $4_8$ could also be obtained in other ways. The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
1,195
Title: Filya and Homework Time Limit: None seconds Memory Limit: None megabytes Problem Description: Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help. Filya is given an array of non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. First, he pick an integer *x* and then he adds *x* to some elements of the array (no more than once), subtract *x* from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal. Now he wonders if it's possible to pick such integer *x* and change some elements of the array using this *x* in order to make all elements equal. Input Specification: The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of integers in the Filya's array. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109)Β β€” elements of the array. Output Specification: If it's impossible to make all elements of the array equal using the process given in the problem statement, then print "NO" (without quotes) in the only line of the output. Otherwise print "YES" (without quotes). Demo Input: ['5\n1 3 3 2 1\n', '5\n1 2 3 4 5\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample Filya should select *x* = 1, then add it to the first and the last elements of the array and subtract from the second and the third elements.
1,196
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≀<=*i*,<=*j*<=≀<=*n* and *a**i*<=β‰₯<=*a**j*. Input Specification: The first line contains integer *n*Β β€” the length of the sequence (1<=≀<=*n*<=≀<=2Β·105). The second line contains *n* space-separated integers *a**i* (1<=≀<=*a**i*<=≀<=106). Output Specification: Print the answer to the problem. Demo Input: ['3\n3 4 5\n'] Demo Output: ['2\n'] Note: none
1,197
Title: Cows and Poker Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN". Find the number of cows that can currently show their hands without affecting any betting decisions. Input Specification: The first line contains a single integer, *n* (2<=≀<=*n*<=≀<=2Β·105). The second line contains *n* characters, each either "A", "I", or "F". The *i*-th character is "A" if the *i*-th player's status is "ALLIN", "I" if the *i*-th player's status is "IN", or "F" if the *i*-th player's status is "FOLDED". Output Specification: The first line should contain a single integer denoting the number of players that can currently show their hands. Demo Input: ['6\nAFFAAA\n', '3\nAFI\n'] Demo Output: ['4\n', '1\n'] Note: In the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.
1,198
Title: Numbers Joke Time Limit: None seconds Memory Limit: None megabytes Problem Description: The input contains a single integer *a* (1<=≀<=*a*<=≀<=30). Output a single integer. Input Specification: The input contains a single integer *a* (1<=≀<=*a*<=≀<=30). Output Specification: Output a single integer. Demo Input: ['3\n'] Demo Output: ['27\n'] Note: none
1,199