task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Fox and Box Accumulation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Fox Ciel has *n* boxes in her room. They have the same size and weight, but they might have different strength. The *i*-th box can hold at most *x**i* boxes on its top (we'll call *x**i* the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile. Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than *x**i* boxes on the top of *i*-th box. What is the minimal number of piles she needs to construct? Input Specification: The first line contains an integer *n* (1<=≀<=*n*<=≀<=100). The next line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (0<=≀<=*x**i*<=≀<=100). Output Specification: Output a single integer β€” the minimal possible number of piles. Demo Input: ['3\n0 0 10\n', '5\n0 1 2 3 4\n', '4\n0 0 0 0\n', '9\n0 1 0 2 0 1 1 2 10\n'] Demo Output: ['2\n', '1\n', '4\n', '3\n'] Note: In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2. In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom).
1,200
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: 'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form) In the other words, CNF is a formula of type , where &amp; represents a logical "AND" (conjunction), represents a logical "OR" (disjunction), and *v**ij* are some boolean variables or their negations. Each statement in brackets is called a clause, and *v**ij* are called literals. You are given a CNF containing variables *x*1,<=...,<=*x**m* and their negations. We know that each variable occurs in at most two clauses (with negation and without negation in total). Your task is to determine whether this CNF is satisfiable, that is, whether there are such values of variables where the CNF value is true. If CNF is satisfiable, then you also need to determine the values of the variables at which the CNF is true. It is guaranteed that each variable occurs at most once in each clause. Input Specification: The first line contains integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=2Β·105) β€” the number of clauses and the number variables, correspondingly. Next *n* lines contain the descriptions of each clause. The *i*-th line first contains first number *k**i* (*k**i*<=β‰₯<=1) β€” the number of literals in the *i*-th clauses. Then follow space-separated literals *v**ij* (1<=≀<=|*v**ij*|<=≀<=*m*). A literal that corresponds to *v**ij* is *x*|*v**ij*| either with negation, if *v**ij* is negative, or without negation otherwise. Output Specification: If CNF is not satisfiable, print a single line "NO" (without the quotes), otherwise print two strings: string "YES" (without the quotes), and then a string of *m* numbers zero or one β€” the values of variables in satisfying assignment in the order from *x*1 to *x**m*. Demo Input: ['2 2\n2 1 -2\n2 2 -1\n', '4 3\n1 1\n1 2\n3 -1 -2 3\n1 -3\n', '5 6\n2 1 2\n3 1 -2 3\n4 -3 5 4 6\n2 -6 -4\n1 5\n'] Demo Output: ['YES\n11\n', 'NO\n', 'YES\n100010\n'] Note: In the first sample test formula is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5a8654a57efa13b47a585b7998c9defb42712ded.png" style="max-width: 100.0%;max-height: 100.0%;"/>. One of possible answer is *x*<sub class="lower-index">1</sub> = *TRUE*, *x*<sub class="lower-index">2</sub> = *TRUE*.
1,201
Title: Yet Another Problem On a Subsequence Time Limit: None seconds Memory Limit: None megabytes Problem Description: The sequence of integers $a_1, a_2, \dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 &gt; 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ β€” are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $[2, -3, 0, 1, 4]$, $[1, 2, 3, -3, -9, 4]$ are good, and the sequences $[2, -3, 0, 1]$, $[1, 2, 3, -3 -9, 4, 1]$ β€” are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input Specification: The first line contains the number $n~(1 \le n \le 10^3)$ β€” the length of the initial sequence. The following line contains $n$ integers $a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9)$ β€” the sequence itself. Output Specification: In the single line output one integer β€” the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Demo Input: ['3\n2 1 1\n', '4\n1 1 1 1\n'] Demo Output: ['2\n', '7\n'] Note: In the first test case, two good subsequences β€” $[a_1, a_2, a_3]$ and $[a_2, a_3]$. In the second test case, seven good subsequences β€” $[a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4]$ and $[a_3, a_4]$.
1,202
Title: Modular Equations Time Limit: None seconds Memory Limit: None megabytes Problem Description: Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define *i* modulo *j* as the remainder of division of *i* by *j* and denote it by . A Modular Equation, as Hamed's teacher described, is an equation of the form in which *a* and *b* are two non-negative integers and *x* is a variable. We call a positive integer *x* for which a solution of our equation. Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations. Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers *a* and *b* determines how many answers the Modular Equation has. Input Specification: In the only line of the input two space-separated integers *a* and *b* (0<=≀<=*a*,<=*b*<=≀<=109) are given. Output Specification: If there is an infinite number of answers to our equation, print "infinity" (without the quotes). Otherwise print the number of solutions of the Modular Equation . Demo Input: ['21 5\n', '9435152 272\n', '10 10\n'] Demo Output: ['2\n', '282\n', 'infinity\n'] Note: In the first sample the answers of the Modular Equation are 8 and 16 since <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6f5ff39ebd209bf990adaf91f4b82f9687097224.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,203
Title: Ladies' Shop Time Limit: None seconds Memory Limit: None megabytes Problem Description: A ladies' shop has recently opened in the city of Ultima Thule. To get ready for the opening, the shop bought *n* bags. Each bag is characterised by the total weight *a**i* of the items you can put there. The weird thing is, you cannot use these bags to put a set of items with the total weight strictly less than *a**i*. However the weights of the items that will be sold in the shop haven't yet been defined. That's what you should determine right now. Your task is to find the set of the items' weights *p*1,<=*p*2,<=...,<=*p**k* (1<=≀<=*p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**k*), such that: 1. Any bag will be used. That is, for any *i* (1<=≀<=*i*<=≀<=*n*) there will be such set of items that their total weight will equal *a**i*. We assume that there is the infinite number of items of any weight. You can put multiple items of the same weight in one bag. 1. For any set of items that have total weight less than or equal to *m*, there is a bag into which you can put this set. Similarly, a set of items can contain multiple items of the same weight. 1. Of all sets of the items' weights that satisfy points 1 and 2, find the set with the minimum number of weights. In other words, value *k* should be as small as possible. Find and print the required set. Input Specification: The first line contains space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=106). The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*<=≀<=*m*) β€” the bags' weight limits. Output Specification: In the first line print "NO" (without the quotes) if there isn't set *p**i*, that would meet the conditions. Otherwise, in the first line print "YES" (without the quotes), in the second line print an integer *k* (showing how many numbers are in the suitable set with the minimum number of weights), in the third line print *k* space-separated integers *p*1,<=*p*2,<=...,<=*p**k* (1<=≀<=*p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**k*). If there are multiple solutions, print any of them. Demo Input: ['6 10\n5 6 7 8 9 10\n', '1 10\n1\n', '1 10\n6\n'] Demo Output: ['YES\n5\n5 6 7 8 9 \n', 'NO\n', 'YES\n1\n6 \n'] Note: none
1,204
Title: Qualifying Contest Time Limit: None seconds Memory Limit: None megabytes Problem Description: Very soon Berland will hold a School Team Programming Olympiad. From each of the *m* Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by *n* Berland students. There were at least two schoolboys participating from each of the *m* regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive. The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest. Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests. Input Specification: The first line of the input contains two integers *n* and *m* (2<=≀<=*n*<=≀<=100<=000, 1<=≀<=*m*<=≀<=10<=000, *n*<=β‰₯<=2*m*)Β β€” the number of participants of the qualifying contest and the number of regions in Berland. Next *n* lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to *m*) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the *m* regions. The surnames that only differ in letter cases, should be considered distinct. Output Specification: Print *m* lines. On the *i*-th line print the team of the *i*-th regionΒ β€” the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region. Demo Input: ['5 2\nIvanov 1 763\nAndreev 2 800\nPetrov 1 595\nSidorov 1 790\nSemenov 2 503\n', '5 2\nIvanov 1 800\nAndreev 2 763\nPetrov 1 800\nSidorov 1 800\nSemenov 2 503\n'] Demo Output: ['Sidorov Ivanov\nAndreev Semenov\n', '?\nAndreev Semenov\n'] Note: In the first sample region teams are uniquely determined. In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.
1,205
Title: Pasha and Hamsters Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pasha has two hamsters: Arthur and Alexander. Pasha put *n* apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamsters on his own. He is going to give some apples to Arthur and some apples to Alexander. It doesn't matter how many apples each hamster gets but it is important that each hamster gets only the apples he likes. It is possible that somebody doesn't get any apples. Help Pasha distribute all the apples between the hamsters. Note that Pasha wants to distribute all the apples, not just some of them. Input Specification: The first line contains integers *n*, *a*, *b* (1<=≀<=*n*<=≀<=100;Β 1<=≀<=*a*,<=*b*<=≀<=*n*) β€” the number of apples Pasha has, the number of apples Arthur likes and the number of apples Alexander likes, correspondingly. The next line contains *a* distinct integers β€” the numbers of the apples Arthur likes. The next line contains *b* distinct integers β€” the numbers of the apples Alexander likes. Assume that the apples are numbered from 1 to *n*. The input is such that the answer exists. Output Specification: Print *n* characters, each of them equals either 1 or 2. If the *i*-h character equals 1, then the *i*-th apple should be given to Arthur, otherwise it should be given to Alexander. If there are multiple correct answers, you are allowed to print any of them. Demo Input: ['4 2 3\n1 2\n2 3 4\n', '5 5 2\n3 4 1 2 5\n2 3\n'] Demo Output: ['1 1 2 2\n', '1 1 1 1 1\n'] Note: none
1,206
Title: Dominoes Time Limit: None seconds Memory Limit: None megabytes Problem Description: During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes. The teacher responded instantly at our request. He put *nm* dominoes on the table as an *n*<=Γ—<=2*m* rectangle so that each of the *n* rows contained *m* dominoes arranged horizontally. Each half of each domino contained number (0 or 1). We were taken aback, and the teacher smiled and said: "Consider some arrangement of dominoes in an *n*<=Γ—<=2*m* matrix. Let's count for each column of the matrix the sum of numbers in this column. Then among all such sums find the maximum one. Can you rearrange the dominoes in the matrix in such a way that the maximum sum will be minimum possible? Note that it is prohibited to change the orientation of the dominoes, they all need to stay horizontal, nevertheless dominoes are allowed to rotate by 180 degrees. As a reward I will give you all my dominoes". We got even more taken aback. And while we are wondering what was going on, help us make an optimal matrix of dominoes. Input Specification: The first line contains integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=103). In the next lines there is a description of the teachers' matrix. Each of next *n* lines contains *m* dominoes. The description of one domino is two integers (0 or 1), written without a space β€” the digits on the left and right half of the domino. Output Specification: Print the resulting matrix of dominoes in the format: *n* lines, each of them contains *m* space-separated dominoes. If there are multiple optimal solutions, print any of them. Demo Input: ['2 3\n01 11 00\n00 01 11\n', '4 1\n11\n10\n01\n00\n'] Demo Output: ['11 11 10\n00 00 01\n', '11\n10\n01\n00\n'] Note: Consider the answer for the first sample. There, the maximum sum among all columns equals 1 (the number of columns is 6, and not 3). Obviously, this maximum can't be less than 1, then such matrix is optimal. Note that the dominoes can be rotated by 180 degrees.
1,207
Title: Word Capitalization Time Limit: None seconds Memory Limit: None megabytes Problem Description: Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input Specification: A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103. Output Specification: Output the given word after capitalization. Demo Input: ['ApPLe\n', 'konjac\n'] Demo Output: ['ApPLe\n', 'Konjac\n'] Note: none
1,208
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?! You somehow get a test from one of these problems and now you want to know from which one. Input Specification: In the first line of input there is one integer $n$ ($10^{3} \le n \le 10^{6}$). In the second line there are $n$ distinct integers between $1$ and $n$Β β€” the permutation of size $n$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $n$Β β€” the size of the permutation. Then we randomly choose a method to generate a permutationΒ β€” the one of Petr or the one of Alex. Then we generate a permutation using chosen method. Output Specification: If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes). Demo Input: ['5\n2 4 5 1 3\n'] Demo Output: ['Petr\n'] Note: Please note that the sample is not a valid test (because of limitations for $n$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC. Due to randomness of input hacks in this problem are forbidden.
1,209
Title: Tennis Tournament Time Limit: None seconds Memory Limit: None megabytes Problem Description: A tennis tournament with *n* participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out. The tournament takes place in the following way (below, *m* is the number of the participants of the current round): - let *k* be the maximal power of the number 2 such that *k*<=≀<=*m*, - *k* participants compete in the current round and a half of them passes to the next round, the other *m*<=-<=*k* participants pass to the next round directly, - when only one participant remains, the tournament finishes. Each match requires *b* bottles of water for each participant and one bottle for the judge. Besides *p* towels are given to each participant for the whole tournament. Find the number of bottles and towels needed for the tournament. Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose). Input Specification: The only line contains three integers *n*,<=*b*,<=*p* (1<=≀<=*n*,<=*b*,<=*p*<=≀<=500) β€” the number of participants and the parameters described in the problem statement. Output Specification: Print two integers *x* and *y* β€” the number of bottles and towels need for the tournament. Demo Input: ['5 2 3\n', '8 2 4\n'] Demo Output: ['20 15\n', '35 32\n'] Note: In the first example will be three rounds: 1. in the first round will be two matches and for each match 5 bottles of water are needed (two for each of the participants and one for the judge), 1. in the second round will be only one match, so we need another 5 bottles of water, 1. in the third round will also be only one match, so we need another 5 bottles of water. So in total we need 20 bottles of water. In the second example no participant will move on to some round directly.
1,210
Title: A + B Strikes Back Time Limit: None seconds Memory Limit: None megabytes Problem Description: A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? Input Specification: The input contains two integers *a* and *b* (0<=≀<=*a*,<=*b*<=≀<=103), separated by a single space. Output Specification: Output the sum of the given integers. Demo Input: ['5 14\n', '381 492\n'] Demo Output: ['19\n', '873\n'] Note: none
1,211
Title: Almost Identity Permutations Time Limit: None seconds Memory Limit: None megabytes Problem Description: A permutation *p* of size *n* is an array such that every integer from 1 to *n* occurs exactly once in this array. Let's call a permutation an almost identity permutation iff there exist at least *n*<=-<=*k* indices *i* (1<=≀<=*i*<=≀<=*n*) such that *p**i*<==<=*i*. Your task is to count the number of almost identity permutations for given numbers *n* and *k*. Input Specification: The first line contains two integers *n* and *k* (4<=≀<=*n*<=≀<=1000, 1<=≀<=*k*<=≀<=4). Output Specification: Print the number of almost identity permutations for given *n* and *k*. Demo Input: ['4 1\n', '4 2\n', '5 3\n', '5 4\n'] Demo Output: ['1\n', '7\n', '31\n', '76\n'] Note: none
1,212
Title: Initial Bet Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are five people playing a game called "Generosity". Each person gives some non-zero number of coins *b* as an initial bet. After all players make their bets of *b* coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size *b* of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins *b* in the initial bet. Input Specification: The input consists of a single line containing five integers *c*1,<=*c*2,<=*c*3,<=*c*4 and *c*5 β€” the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0<=≀<=*c*1,<=*c*2,<=*c*3,<=*c*4,<=*c*5<=≀<=100). Output Specification: Print the only line containing a single positive integer *b* β€” the number of coins in the initial bet of each player. If there is no such value of *b*, then print the only value "-1" (quotes for clarity). Demo Input: ['2 5 4 0 4\n', '4 5 9 2 1\n'] Demo Output: ['3\n', '-1\n'] Note: In the first sample the following sequence of operations is possible: 1. One coin is passed from the fourth player to the second player; 1. One coin is passed from the fourth player to the fifth player; 1. One coin is passed from the first player to the third player; 1. One coin is passed from the fourth player to the second player.
1,213
Title: Jon Snow and his Favourite Number Time Limit: None seconds Memory Limit: None megabytes Problem Description: Jon Snow now has to fight with White Walkers. He has *n* rangers, each of which has his own strength. Also Jon Snow has his favourite number *x*. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number *x*, he might get soldiers of high strength. So, he decided to do the following operation *k* times: 1. Arrange all the rangers in a straight line in the order of increasing strengths.1. Take the bitwise XOR (is written as ) of the strength of each alternate ranger with *x* and update it's strength.1. The strength of first ranger is updated to , i.e. 7.1. The strength of second ranger remains the same, i.e. 7.1. The strength of third ranger is updated to , i.e. 11.1. The strength of fourth ranger remains the same, i.e. 11.1. The strength of fifth ranger is updated to , i.e. 13. Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations *k* times. He wants your help for this task. Can you help him? Input Specification: First line consists of three integers *n*, *k*, *x* (1<=≀<=*n*<=≀<=105, 0<=≀<=*k*<=≀<=105, 0<=≀<=*x*<=≀<=103) β€” number of rangers Jon has, the number of times Jon will carry out the operation and Jon's favourite number respectively. Second line consists of *n* integers representing the strengths of the rangers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=103). Output Specification: Output two integers, the maximum and the minimum strength of the rangers after performing the operation *k* times. Demo Input: ['5 1 2\n9 7 11 15 5\n', '2 100000 569\n605 986\n'] Demo Output: ['13 7', '986 605'] Note: none
1,214
Title: Permutation Sum Time Limit: None seconds Memory Limit: None megabytes Problem Description: Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*. Petya decided to introduce the sum operation on the set of permutations of length *n*. Let's assume that we are given two permutations of length *n*: *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n*. Petya calls the sum of permutations *a* and *b* such permutation *c* of length *n*, where *c**i*<==<=((*a**i*<=-<=1<=+<=*b**i*<=-<=1) *mod* *n*)<=+<=1 (1<=≀<=*i*<=≀<=*n*). Operation means taking the remainder after dividing number *x* by number *y*. Obviously, not for all permutations *a* and *b* exists permutation *c* that is sum of *a* and *b*. That's why Petya got sad and asked you to do the following: given *n*, count the number of such pairs of permutations *a* and *b* of length *n*, that exists permutation *c* that is sum of *a* and *b*. The pair of permutations *x*,<=*y* (*x*<=β‰ <=*y*) and the pair of permutations *y*,<=*x* are considered distinct pairs. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109<=+<=7). Input Specification: The single line contains integer *n* (1<=≀<=*n*<=≀<=16). Output Specification: In the single line print a single non-negative integer β€” the number of such pairs of permutations *a* and *b*, that exists permutation *c* that is sum of *a* and *b*, modulo 1000000007 (109<=+<=7). Demo Input: ['3\n', '5\n'] Demo Output: ['18\n', '1800\n'] Note: none
1,215
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: The "BerCorp" company has got *n* employees. These employees can use *m* approved official languages for the formal correspondence. The languages are numbered with integers from 1 to *m*. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar. Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating). Input Specification: The first line contains two integers *n* and *m* (2<=≀<=*n*,<=*m*<=≀<=100) β€” the number of employees and the number of languages. Then *n* lines follow β€” each employee's language list. At the beginning of the *i*-th line is integer *k**i* (0<=≀<=*k**i*<=≀<=*m*) β€” the number of languages the *i*-th employee knows. Next, the *i*-th line contains *k**i* integers β€” *a**ij* (1<=≀<=*a**ij*<=≀<=*m*) β€” the identifiers of languages the *i*-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces. Output Specification: Print a single integer β€” the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating). Demo Input: ['5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5\n', '8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1\n', '2 2\n1 2\n0\n'] Demo Output: ['0\n', '2\n', '1\n'] Note: In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4. In the third sample employee 2 must learn language 2.
1,216
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Imagine that you are in a building that has exactly *n* floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to *n*. Now you're on the floor number *a*. You are very bored, so you want to take the lift. Floor number *b* has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make *k* consecutive trips in the lift. Let us suppose that at the moment you are on the floor number *x* (initially, you were on floor *a*). For another trip between floors you choose some floor with number *y* (*y*<=β‰ <=*x*) and the lift travels to this floor. As you cannot visit floor *b* with the secret lab, you decided that the distance from the current floor *x* to the chosen *y* must be strictly less than the distance from the current floor *x* to floor *b* with the secret lab. Formally, it means that the following inequation must fulfill: |*x*<=-<=*y*|<=&lt;<=|*x*<=-<=*b*|. After the lift successfully transports you to floor *y*, you write down number *y* in your notepad. Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of *k* trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109<=+<=7). Input Specification: The first line of the input contains four space-separated integers *n*, *a*, *b*, *k* (2<=≀<=*n*<=≀<=5000, 1<=≀<=*k*<=≀<=5000, 1<=≀<=*a*,<=*b*<=≀<=*n*, *a*<=β‰ <=*b*). Output Specification: Print a single integer β€” the remainder after dividing the sought number of sequences by 1000000007 (109<=+<=7). Demo Input: ['5 2 4 1\n', '5 2 4 2\n', '5 3 4 1\n'] Demo Output: ['2\n', '2\n', '0\n'] Note: Two sequences *p*<sub class="lower-index">1</sub>, *p*<sub class="lower-index">2</sub>, ..., *p*<sub class="lower-index">*k*</sub> and *q*<sub class="lower-index">1</sub>, *q*<sub class="lower-index">2</sub>, ..., *q*<sub class="lower-index">*k*</sub> are distinct, if there is such integer *j* (1 ≀ *j* ≀ *k*), that *p*<sub class="lower-index">*j*</sub> ≠ *q*<sub class="lower-index">*j*</sub>. Notes to the samples: 1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| &lt; |2 - 4| and |3 - 2| &lt; |2 - 4|. 1. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip. 1. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
1,217
Title: New Year and Entity Enumeration Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an integer *m*. Let *M*<==<=2*m*<=-<=1. You are also given a set of *n* integers denoted as the set *T*. The integers will be provided in base 2 as *n* binary strings of length *m*. A set of integers *S* is called "good" if the following hold. 1. If , then . 1. If , then 1. 1. All elements of *S* are less than or equal to *M*. Here, and refer to the bitwise XOR and bitwise AND operators, respectively. Count the number of good sets *S*, modulo 109<=+<=7. Input Specification: The first line will contain two integers *m* and *n* (1<=≀<=*m*<=≀<=1<=000, 1<=≀<=*n*<=≀<=*min*(2*m*,<=50)). The next *n* lines will contain the elements of *T*. Each line will contain exactly *m* zeros and ones. Elements of *T* will be distinct. Output Specification: Print a single integer, the number of good sets modulo 109<=+<=7. Demo Input: ['5 3\n11010\n00101\n11000\n', '30 2\n010101010101010010101010101010\n110110110110110011011011011011\n'] Demo Output: ['4\n', '860616440\n'] Note: An example of a valid set *S* is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
1,218
Title: Mind the Gap Time Limit: None seconds Memory Limit: None megabytes Problem Description: These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute. He was asked to insert one takeoff in the schedule. The takeoff takes $1$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $s$ minutes from both sides. Find the earliest time when Arkady can insert the takeoff. Input Specification: The first line of input contains two integers $n$ and $s$ ($1 \le n \le 100$, $1 \le s \le 60$)Β β€” the number of landings on the schedule and the minimum allowed time (in minutes) between a landing and a takeoff. Each of next $n$ lines contains two integers $h$ and $m$ ($0 \le h \le 23$, $0 \le m \le 59$)Β β€” the time, in hours and minutes, when a plane will land, starting from current moment (i.Β e. the current time is $0$ $0$). These times are given in increasing order. Output Specification: Print two integers $h$ and $m$Β β€” the hour and the minute from the current moment of the earliest time Arkady can insert the takeoff. Demo Input: ['6 60\n0 0\n1 20\n3 21\n5 0\n19 30\n23 40\n', '16 50\n0 30\n1 20\n3 0\n4 30\n6 10\n7 50\n9 30\n11 10\n12 50\n14 30\n16 10\n17 50\n19 30\n21 10\n22 50\n23 59\n', '3 17\n0 30\n1 0\n12 0\n'] Demo Output: ['6 1\n', '24 50\n', '0 0\n'] Note: In the first example note that there is not enough time between 1:20 and 3:21, because each landing and the takeoff take one minute. In the second example there is no gaps in the schedule, so Arkady can only add takeoff after all landings. Note that it is possible that one should wait more than $24$ hours to insert the takeoff. In the third example Arkady can insert the takeoff even between the first landing.
1,219
Title: Valera and Fruits Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera loves his garden, where *n* fruit trees grow. This year he will enjoy a great harvest! On the *i*-th tree *b**i* fruit grow, they will ripen on a day number *a**i*. Unfortunately, the fruit on the tree get withered, so they can only be collected on day *a**i* and day *a**i*<=+<=1 (all fruits that are not collected in these two days, become unfit to eat). Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than *v* fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? Input Specification: The first line contains two space-separated integers *n* and *v* (1<=≀<=*n*,<=*v*<=≀<=3000) β€” the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next *n* lines contain the description of trees in the garden. The *i*-th line contains two space-separated integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=3000) β€” the day the fruits ripen on the *i*-th tree and the number of fruits on the *i*-th tree. Output Specification: Print a single integer β€” the maximum number of fruit that Valera can collect. Demo Input: ['2 3\n1 5\n2 3\n', '5 10\n3 20\n2 20\n1 20\n4 20\n5 20\n'] Demo Output: ['8\n', '60\n'] Note: In the first sample, in order to obtain the optimal answer, you should act as follows. - On the first day collect 3 fruits from the 1-st tree. - On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. - On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.
1,220
Title: Check the string Time Limit: None seconds Memory Limit: None megabytes Problem Description: A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time. You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes). Input Specification: The first and only line consists of a string $S$ ($ 1 \le |S| \le 5\,000 $). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'. Output Specification: Print "YES" or "NO", according to the condition. Demo Input: ['aaabccc\n', 'bbacc\n', 'aabc\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n'] Note: Consider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct. Consider third example: the number of 'c' is equal to the number of 'b'.
1,221
Title: Mike and Fish Time Limit: None seconds Memory Limit: None megabytes Problem Description: As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish. He has marked *n* distinct points in the plane. *i*-th point is point (*x**i*,<=*y**i*). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1. He can't find a way to perform that! Please help him. Input Specification: The first line of input contains integer *n* (1<=≀<=*n*<=≀<=2<=Γ—<=105). The next *n* lines contain the information about the points, *i*-th line contains two integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=2<=Γ—<=105), the *i*-th point coordinates. It is guaranteed that there is at least one valid answer. Output Specification: Print the answer as a sequence of *n* characters 'r' (for red) or 'b' (for blue) where *i*-th character denotes the color of the fish in the *i*-th point. Demo Input: ['4\n1 1\n1 2\n2 1\n2 2\n', '3\n1 1\n1 2\n2 1\n'] Demo Output: ['brrb\n', 'brr\n'] Note: none
1,222
Title: Santa Clauses and a Soccer Championship Time Limit: None seconds Memory Limit: None megabytes Problem Description: The country Treeland consists of *n* cities connected with *n*<=-<=1 bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly 2*k* teams from 2*k* different cities. During the first stage all teams are divided into *k* pairs. Teams of each pair play two games against each other: one in the hometown of the first team, and the other in the hometown of the other team. Thus, each of the 2*k* cities holds exactly one soccer game. However, it's not decided yet how to divide teams into pairs. It's also necessary to choose several cities to settle players in. Organizers tend to use as few cities as possible to settle the teams. Nobody wants to travel too much during the championship, so if a team plays in cities *u* and *v*, it wants to live in one of the cities on the shortest path between *u* and *v* (maybe, in *u* or in *v*). There is another constraint also: the teams from one pair must live in the same city. Summarizing, the organizers want to divide 2*k* teams into pairs and settle them in the minimum possible number of cities *m* in such a way that teams from each pair live in the same city which lies between their hometowns. Input Specification: The first line of input contains two integers *n* and *k* (2<=≀<=*n*<=≀<=2Β·105,<=2<=≀<=2*k*<=≀<=*n*)Β β€” the number of cities in Treeland and the number of pairs of teams, respectively. The following *n*<=-<=1 lines describe roads in Treeland: each of these lines contains two integers *a* and *b* (1<=≀<=*a*,<=*b*<=≀<=*n*,<=*a*<=β‰ <=*b*) which mean that there is a road between cities *a* and *b*. It's guaranteed that there is a path between any two cities. The last line contains 2*k* distinct integers *c*1,<=*c*2,<=...,<=*c*2*k* (1<=≀<=*c**i*<=≀<=*n*), where *c**i* is the hometown of the *i*-th team. All these numbers are distinct. Output Specification: The first line of output must contain the only positive integer *m* which should be equal to the minimum possible number of cities the teams can be settled in. The second line should contain *m* distinct numbers *d*1,<=*d*2,<=...,<=*d**m* (1<=≀<=*d**i*<=≀<=*n*) denoting the indices of the cities where the teams should be settled. The *k* lines should follow, the *j*-th of them should contain 3 integers *u**j*, *v**j* and *x**j*, where *u**j* and *v**j* are the hometowns of the *j*-th pair's teams, and *x**j* is the city they should live in during the tournament. Each of the numbers *c*1,<=*c*2,<=...,<=*c*2*k* should occur in all *u**j*'s and *v**j*'s exactly once. Each of the numbers *x**j* should belong to {*d*1,<=*d*2,<=...,<=*d**m*}. If there are several possible answers, print any of them. Demo Input: ['6 2\n1 2\n1 3\n2 4\n2 5\n3 6\n2 5 4 6\n'] Demo Output: ['1\n2\n5 4 2\n6 2 2\n'] Note: In the first test the orginizers can settle all the teams in the city number 2. The way to divide all teams into pairs is not important, since all requirements are satisfied anyway, because the city 2 lies on the shortest path between every two cities from {2, 4, 5, 6}.
1,223
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dreamoon loves summing up something for no reason. One day he obtains two integers *a* and *b* occasionally. He wants to calculate the sum of all nice integers. Positive integer *x* is called nice if and , where *k* is some integer number in range [1,<=*a*]. By we denote the quotient of integer division of *x* and *y*. By we denote the remainder of integer division of *x* and *y*. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1<=000<=000<=007 (109<=+<=7). Can you compute it faster than Dreamoon? Input Specification: The single line of the input contains two integers *a*, *b* (1<=≀<=*a*,<=*b*<=≀<=107). Output Specification: Print a single integer representing the answer modulo 1<=000<=000<=007 (109<=+<=7). Demo Input: ['1 1\n', '2 2\n'] Demo Output: ['0\n', '8\n'] Note: For the first sample, there are no nice integers because <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/03b1dc6bae5180f8a2d8eb85789e8b393e585970.png" style="max-width: 100.0%;max-height: 100.0%;"/> is always zero. For the second sample, the set of nice integers is {3, 5}.
1,224
Title: Military Trainings Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows. Initially, the column consists of *n* tanks sequentially numbered from 1 to *n* in the order of position in the column from its beginning to its end. During the whole exercise, exactly *n* messages must be transferred from the beginning of the column to its end. Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message β€” it is important that the last tank in the column should receive the message. After the last tank (tank number *n*) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number *n*<=-<=1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column. If the tanks were initially placed in the column in the order 1,<=2,<=...,<=*n*, then after the first message their order changes to *n*,<=1,<=...,<=*n*<=-<=1, after the second message it changes to *n*<=-<=1,<=*n*,<=1,<=...,<=*n*<=-<=2, and so on. The tanks are constructed in a very peculiar way. The tank with number *i* is characterized by one integer *a**i*, which is called the message receiving radius of this tank. Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the *i*-th in the column counting from the beginning, and the second one is the *j*-th in the column, and suppose the second tank has number *x*. Then the first tank can transmit a message to the second tank if *i*<=&lt;<=*j* and *i*<=β‰₯<=*j*<=-<=*a**x*. The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training. You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible. Input Specification: The first line contains integer *n* β€” the number of tanks in the column. Each of the next *n* lines contains one integer *a**i* (1<=≀<=*a**i*<=≀<=250000, 1<=≀<=*i*<=≀<=*n*) β€” the message receiving radii of the tanks in the order from tank 1 to tank *n* (let us remind you that initially the tanks are located in the column in ascending order of their numbers). To get the full points for the first group of tests it is sufficient to solve the problem with 2<=≀<=*n*<=≀<=300. To get the full points for the second group of tests it is sufficient to solve the problem with 2<=≀<=*n*<=≀<=10000. To get the full points for the third group of tests it is sufficient to solve the problem with 2<=≀<=*n*<=≀<=250000. Output Specification: Print a single integer β€” the minimum possible total time of transmitting the messages. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['3\n2\n1\n1\n', '5\n2\n2\n2\n2\n2\n'] Demo Output: ['5\n', '10\n'] Note: In the first sample the original order of tanks is 1, 2, 3. The first tank sends a message to the second one, then the second tank sends it to the third one β€” it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3, 1, 2. The third tank sends a message to the first one, then the first one sends it to the second one β€” it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2, 3, 1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough β€” it takes one second. Finally, the tanks return to their original order 1, 2, 3. In total, the exercise takes 5 seconds. In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds.
1,225
Title: Palindromic Supersequence Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *A*. Find a string *B*, where *B* is a palindrome and *A* is a subsequence of *B*. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest". A palindrome is a string that reads the same forward or backward. The length of string *B* should be at most 104. It is guaranteed that there always exists such string. You do not need to find the shortest answer, the only restriction is that the length of string *B* should not exceed 104. Input Specification: First line contains a string *A* (1<=≀<=|*A*|<=≀<=103) consisting of lowercase Latin letters, where |*A*| is a length of *A*. Output Specification: Output single line containing *B* consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string *B* should not exceed 104. If there are many possible *B*, print any of them. Demo Input: ['aba\n', 'ab\n'] Demo Output: ['aba', 'aabaa'] Note: In the first example, "aba" is a subsequence of "aba" which is a palindrome. In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.
1,226
Title: Jumping Ball Time Limit: None seconds Memory Limit: None megabytes Problem Description: In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of *n* bumpers. The bumpers are numbered with integers from 1 to *n* from left to right. There are two types of bumpers. They are denoted by the characters '&lt;' and '&gt;'. When the ball hits the bumper at position *i* it goes one position to the right (to the position *i*<=+<=1) if the type of this bumper is '&gt;', or one position to the left (to *i*<=-<=1) if the type of the bumper at position *i* is '&lt;'. If there is no such position, in other words if *i*<=-<=1<=&lt;<=1 or *i*<=+<=1<=&gt;<=*n*, the ball falls from the game field. Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the length of the sequence of bumpers. The second line contains the string, which consists of the characters '&lt;' and '&gt;'. The character at the *i*-th position of this string corresponds to the type of the *i*-th bumper. Output Specification: Print one integerΒ β€” the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. Demo Input: ['4\n&lt;&lt;&gt;&lt;\n', '5\n&gt;&gt;&gt;&gt;&gt;\n', '4\n&gt;&gt;&lt;&lt;\n'] Demo Output: ['2', '5', '0'] Note: In the first sample, the ball will fall from the field if starts at position 1 or position 2. In the second sample, any starting position will result in the ball falling from the field.
1,227
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is an *n*<=Γ—<=*m* rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the *i*-th row and the *j*-th column as (*i*,<=*j*). Let's define a "rectangle" as four integers *a*,<=*b*,<=*c*,<=*d* (1<=≀<=*a*<=≀<=*c*<=≀<=*n*;Β 1<=≀<=*b*<=≀<=*d*<=≀<=*m*). Rectangle denotes a set of cells of the grid {(*x*,<=*y*)Β :<=Β *a*<=≀<=*x*<=≀<=*c*,<=*b*<=≀<=*y*<=≀<=*d*}. Let's define a "good rectangle" as a rectangle that includes only the cells with zeros. You should answer the following *q* queries: calculate the number of good rectangles all of which cells are in the given rectangle. Input Specification: There are three integers in the first line: *n*, *m* and *q* (1<=≀<=*n*,<=*m*<=≀<=40,<=1<=≀<=*q*<=≀<=3Β·105). Each of the next *n* lines contains *m* characters β€” the grid. Consider grid rows are numbered from top to bottom, and grid columns are numbered from left to right. Both columns and rows are numbered starting from 1. Each of the next *q* lines contains a query β€” four integers that describe the current rectangle, *a*, *b*, *c*, *d* (1<=≀<=*a*<=≀<=*c*<=≀<=*n*;Β 1<=≀<=*b*<=≀<=*d*<=≀<=*m*). Output Specification: For each query output an answer β€” a single integer in a separate line. Demo Input: ['5 5 5\n00101\n00000\n00001\n01000\n00001\n1 2 2 4\n4 5 4 5\n1 2 5 2\n2 2 4 5\n4 2 5 3\n', '4 7 5\n0000100\n0000010\n0011000\n0000000\n1 7 2 7\n3 1 3 1\n2 3 4 5\n1 2 2 7\n2 2 4 7\n'] Demo Output: ['10\n1\n7\n34\n5\n', '3\n1\n16\n27\n52\n'] Note: For the first example, there is a 5 × 5 rectangular grid, and the first, the second, and the third queries are represented in the following image. - For the first query, there are 10 good rectangles, five 1 × 1, two 2 × 1, two 1 × 2, and one 1 × 3. - For the second query, there is only one 1 × 1 good rectangle. - For the third query, there are 7 good rectangles, four 1 × 1, two 2 × 1, and one 3 × 1.
1,228
Title: Biologist Time Limit: None seconds Memory Limit: None megabytes Problem Description: SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa. She is going to demonstrate this technique. Now SmallR has *n* dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to *n*. The cost of change for dog *i* is *v**i* RMB. By the way, this technique needs a kind of medicine which can be valid for only one day. So the experiment should be taken in one day and each dog can be changed at most once. This experiment has aroused extensive attention from all sectors of society. There are *m* rich folks which are suspicious of this experiment. They all want to bet with SmallR forcibly. If SmallR succeeds, the *i*-th rich folk will pay SmallR *w**i* RMB. But it's strange that they have a special method to determine whether SmallR succeeds. For *i*-th rich folk, in advance, he will appoint certain *k**i* dogs and certain one gender. He will think SmallR succeeds if and only if on some day the *k**i* appointed dogs are all of the appointed gender. Otherwise, he will think SmallR fails. If SmallR can't satisfy some folk that isn't her friend, she need not pay him, but if someone she can't satisfy is her good friend, she must pay *g* RMB to him as apologies for her fail. Then, SmallR hope to acquire money as much as possible by this experiment. Please figure out the maximum money SmallR can acquire. By the way, it is possible that she can't obtain any money, even will lose money. Then, please give out the minimum money she should lose. Input Specification: The first line contains three integers *n*, *m*, *g* (1<=≀<=*n*<=≀<=104,<=0<=≀<=*m*<=≀<=2000,<=0<=≀<=*g*<=≀<=104). The second line contains *n* integers, each is 0 or 1, the sex of each dog, 0 represent the female and 1 represent the male. The third line contains *n* integers *v*1,<=*v*2,<=...,<=*v**n* (0<=≀<=*v**i*<=≀<=104). Each of the next *m* lines describes a rich folk. On the *i*-th line the first number is the appointed sex of *i*-th folk (0 or 1), the next two integers are *w**i* and *k**i* (0<=≀<=*w**i*<=≀<=104,<=1<=≀<=*k**i*<=≀<=10), next *k**i* distinct integers are the indexes of appointed dogs (each index is between 1 and *n*). The last number of this line represents whether *i*-th folk is SmallR's good friend (0 β€” no or 1 β€” yes). Output Specification: Print a single integer, the maximum money SmallR can gain. Note that the integer is negative if SmallR will lose money. Demo Input: ['5 5 9\n0 1 1 1 0\n1 8 6 2 3\n0 7 3 3 2 1 1\n1 8 1 5 1\n1 0 3 2 1 4 1\n0 8 3 4 2 1 0\n1 7 2 4 1 1\n', '5 5 8\n1 0 1 1 1\n6 5 4 2 8\n0 6 3 2 3 4 0\n0 8 3 3 2 4 0\n0 0 3 3 4 1 1\n0 10 3 4 3 1 1\n0 4 3 3 4 1 1\n'] Demo Output: ['2\n', '16\n'] Note: none
1,229
Title: Save the problem! Time Limit: None seconds Memory Limit: None megabytes Problem Description: Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph. People don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change? As we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below. Input Specification: Input will consist of a single integer *A* (1<=≀<=*A*<=≀<=105), the desired number of ways. Output Specification: In the first line print integers *N* and *M* (1<=≀<=*N*<=≀<=106,<=1<=≀<=*M*<=≀<=10), the amount of change to be made, and the number of denominations, respectively. Then print *M* integers *D*1,<=*D*2,<=...,<=*D**M* (1<=≀<=*D**i*<=≀<=106), the denominations of the coins. All denominations must be distinct: for any *i*<=β‰ <=*j* we must have *D**i*<=β‰ <=*D**j*. If there are multiple tests, print any of them. You can print denominations in atbitrary order. Demo Input: ['18\n', '3\n', '314\n'] Demo Output: ['30 4\n1 5 10 25\n', '20 2\n5 2\n', '183 4\n6 5 2 139\n'] Note: none
1,230
Title: Drawing Circles is Fun Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are a set of points *S* on the plane. This set doesn't contain the origin *O*(0,<=0), and for each two distinct points in the set *A* and *B*, the triangle *OAB* has strictly positive area. Consider a set of pairs of points (*P*1,<=*P*2),<=(*P*3,<=*P*4),<=...,<=(*P*2*k*<=-<=1,<=*P*2*k*). We'll call the set good if and only if: - *k*<=β‰₯<=2. - All *P**i* are distinct, and each *P**i* is an element of *S*. - For any two pairs (*P*2*i*<=-<=1,<=*P*2*i*) and (*P*2*j*<=-<=1,<=*P*2*j*), the circumcircles of triangles *OP*2*i*<=-<=1*P*2*j*<=-<=1 and *OP*2*i**P*2*j* have a single common point, and the circumcircle of triangles *OP*2*i*<=-<=1*P*2*j* and *OP*2*i**P*2*j*<=-<=1 have a single common point. Calculate the number of good sets of pairs modulo 1000000007 (109<=+<=7). Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=1000) β€” the number of points in *S*. Each of the next *n* lines contains four integers *a**i*,<=*b**i*,<=*c**i*,<=*d**i* (0<=≀<=|*a**i*|,<=|*c**i*|<=≀<=50;Β 1<=≀<=*b**i*,<=*d**i*<=≀<=50;Β (*a**i*,<=*c**i*)<=β‰ <=(0,<=0)). These integers represent a point . No two points coincide. Output Specification: Print a single integer β€” the answer to the problem modulo 1000000007 (109<=+<=7). Demo Input: ['10\n-46 46 0 36\n0 20 -24 48\n-50 50 -49 49\n-20 50 8 40\n-15 30 14 28\n4 10 -4 5\n6 15 8 10\n-20 50 -3 15\n4 34 -16 34\n16 34 2 17\n', '10\n30 30 -26 26\n0 15 -36 36\n-28 28 -34 34\n10 10 0 4\n-8 20 40 50\n9 45 12 30\n6 15 7 35\n36 45 -8 20\n-16 34 -4 34\n4 34 8 17\n', '10\n0 20 38 38\n-30 30 -13 13\n-11 11 16 16\n30 30 0 37\n6 30 -4 10\n6 15 12 15\n-4 5 -10 25\n-16 20 4 10\n8 17 -2 17\n16 34 2 17\n'] Demo Output: ['2\n', '4\n', '10\n'] Note: none
1,231
Title: Perfect Number Time Limit: None seconds Memory Limit: None megabytes Problem Description: We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer. Input Specification: A single line with a positive integer $k$ ($1 \leq k \leq 10\,000$). Output Specification: A single number, denoting the $k$-th smallest perfect integer. Demo Input: ['1\n', '2\n'] Demo Output: ['19\n', '28\n'] Note: The first perfect integer is $19$ and the second one is $28$.
1,232
Title: World Cup Time Limit: None seconds Memory Limit: None megabytes Problem Description: The last stage of Football World Cup is played using the play-off system. There are *n* teams left in this stage, they are enumerated from 1 to *n*. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the thirdΒ β€” with the fourth, the fifthΒ β€” with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over. Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids *a* and *b* can meet. Input Specification: The only line contains three integers *n*, *a* and *b* (2<=≀<=*n*<=≀<=256, 1<=≀<=*a*,<=*b*<=≀<=*n*)Β β€” the total number of teams, and the ids of the teams that Arkady is interested in. It is guaranteed that *n* is such that in each round an even number of team advance, and that *a* and *b* are not equal. Output Specification: In the only line print "Final!" (without quotes), if teams *a* and *b* can meet in the Final. Otherwise, print a single integerΒ β€” the number of the round in which teams *a* and *b* can meet. The round are enumerated from 1. Demo Input: ['4 1 2\n', '8 2 6\n', '8 7 5\n'] Demo Output: ['1\n', 'Final!\n', '2\n'] Note: In the first example teams 1 and 2 meet in the first round. In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds. In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round.
1,233
Title: Find Maximum Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera has array *a*, consisting of *n* integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1, and function *f*(*x*), taking an integer from 0 to 2*n*<=-<=1 as its single argument. Value *f*(*x*) is calculated by formula , where value *bit*(*i*) equals one if the binary representation of number *x* contains a 1 on the *i*-th position, and zero otherwise. For example, if *n*<==<=4 and *x*<==<=11 (11<==<=20<=+<=21<=+<=23), then *f*(*x*)<==<=*a*0<=+<=*a*1<=+<=*a*3. Help Valera find the maximum of function *f*(*x*) among all *x*, for which an inequality holds: 0<=≀<=*x*<=≀<=*m*. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of array elements. The next line contains *n* space-separated integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (0<=≀<=*a**i*<=≀<=104) β€” elements of array *a*. The third line contains a sequence of digits zero and one without spaces *s*0*s*1... *s**n*<=-<=1 β€” the binary representation of number *m*. Number *m* equals . Output Specification: Print a single integer β€” the maximum value of function *f*(*x*) for all . Demo Input: ['2\n3 8\n10\n', '5\n17 0 10 2 1\n11010\n'] Demo Output: ['3\n', '27\n'] Note: In the first test case *m* = 2<sup class="upper-index">0</sup> = 1, *f*(0) = 0, *f*(1) = *a*<sub class="lower-index">0</sub> = 3. In the second sample *m* = 2<sup class="upper-index">0</sup> + 2<sup class="upper-index">1</sup> + 2<sup class="upper-index">3</sup> = 11, the maximum value of function equals *f*(5) = *a*<sub class="lower-index">0</sub> + *a*<sub class="lower-index">2</sub> = 17 + 10 = 27.
1,234
Title: Dexterina’s Lab Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim. Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0,<=*x*]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game. Womandark is coming up with a brand new and evil idea on how to thwart Dexterina’s plans, so she hasn’t got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above. Input Specification: The first line of the input contains two integers *n* (1<=≀<=*n*<=≀<=109) and *x* (1<=≀<=*x*<=≀<=100)Β β€” the number of heaps and the maximum number of objects in a heap, respectively. The second line contains *x*<=+<=1 real numbers, given with up to 6 decimal places each: *P*(0),<=*P*(1),<=... ,<=*P*(*X*). Here, *P*(*i*) is the probability of a heap having exactly *i* objects in start of a game. It's guaranteed that the sum of all *P*(*i*) is equal to 1. Output Specification: Output a single real number, the probability that the first player wins. The answer will be judged as correct if it differs from the correct answer by at most 10<=-<=6. Demo Input: ['2 2\n0.500000 0.250000 0.250000\n'] Demo Output: ['0.62500000\n'] Note: none
1,235
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (*HP*), offensive power (*ATK*) and defensive power (*DEF*). During the battle, every second the monster's HP decrease by *max*(0,<=*ATK**Y*<=-<=*DEF**M*), while Yang's HP decreases by *max*(0,<=*ATK**M*<=-<=*DEF**Y*), where index *Y* denotes Master Yang and index *M* denotes monster. Both decreases happen simultaneously Once monster's *HP*<=≀<=0 and the same time Master Yang's *HP*<=&gt;<=0, Master Yang wins. Master Yang can buy attributes from the magic shop of Cyberland: *h* bitcoins per *HP*, *a* bitcoins per *ATK*, and *d* bitcoins per *DEF*. Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win. Input Specification: The first line contains three integers *HP**Y*,<=*ATK**Y*,<=*DEF**Y*, separated by a space, denoting the initial *HP*, *ATK* and *DEF* of Master Yang. The second line contains three integers *HP**M*,<=*ATK**M*,<=*DEF**M*, separated by a space, denoting the *HP*, *ATK* and *DEF* of the monster. The third line contains three integers *h*,<=*a*,<=*d*, separated by a space, denoting the price of 1Β *HP*, 1Β *ATK* and 1Β *DEF*. All numbers in input are integer and lie between 1 and 100 inclusively. Output Specification: The only output line should contain an integer, denoting the minimum bitcoins Master Yang should spend in order to win. Demo Input: ['1 2 1\n1 100 1\n1 100 100\n', '100 100 100\n1 1 1\n1 1 1\n'] Demo Output: ['99\n', '0\n'] Note: For the first sample, prices for *ATK* and *DEF* are extremely high. Master Yang can buy 99 HP, then he can beat the monster with 1 HP left. For the second sample, Master Yang is strong enough to beat the monster, so he doesn't need to buy anything.
1,236
Title: Unfair Poll Time Limit: None seconds Memory Limit: None megabytes Problem Description: On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others. Seating in the class looks like a rectangle, where *n* rows with *m* pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the 1-st row, the 2-nd row, ..., the *n*<=-<=1-st row, the *n*-th row, the *n*<=-<=1-st row, ..., the 2-nd row, the 1-st row, the 2-nd row, ... The order of asking of pupils on the same row is always the same: the 1-st pupil, the 2-nd pupil, ..., the *m*-th pupil. During the lesson the teacher managed to ask exactly *k* questions from pupils in order described above. Sergei seats on the *x*-th row, on the *y*-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values: 1. the maximum number of questions a particular pupil is asked, 1. the minimum number of questions a particular pupil is asked, 1. how many times the teacher asked Sergei. If there is only one row in the class, then the teacher always asks children from this row. Input Specification: The first and the only line contains five integers *n*, *m*, *k*, *x* and *y* (1<=≀<=*n*,<=*m*<=≀<=100,<=1<=≀<=*k*<=≀<=1018,<=1<=≀<=*x*<=≀<=*n*,<=1<=≀<=*y*<=≀<=*m*). Output Specification: Print three integers: 1. the maximum number of questions a particular pupil is asked, 1. the minimum number of questions a particular pupil is asked, 1. how many times the teacher asked Sergei. Demo Input: ['1 3 8 1 1\n', '4 2 9 4 2\n', '5 5 25 4 3\n', '100 100 1000000000000000000 100 100\n'] Demo Output: ['3 2 3', '2 1 1', '1 1 1', '101010101010101 50505050505051 50505050505051'] Note: The order of asking pupils in the first test: 1. the pupil from the first row who seats at the first table, it means it is Sergei; 1. the pupil from the first row who seats at the second table; 1. the pupil from the first row who seats at the third table; 1. the pupil from the first row who seats at the first table, it means it is Sergei; 1. the pupil from the first row who seats at the second table; 1. the pupil from the first row who seats at the third table; 1. the pupil from the first row who seats at the first table, it means it is Sergei; 1. the pupil from the first row who seats at the second table; The order of asking pupils in the second test: 1. the pupil from the first row who seats at the first table; 1. the pupil from the first row who seats at the second table; 1. the pupil from the second row who seats at the first table; 1. the pupil from the second row who seats at the second table; 1. the pupil from the third row who seats at the first table; 1. the pupil from the third row who seats at the second table; 1. the pupil from the fourth row who seats at the first table; 1. the pupil from the fourth row who seats at the second table, it means it is Sergei; 1. the pupil from the third row who seats at the first table;
1,237
Title: Strange Sorting Time Limit: None seconds Memory Limit: None megabytes Problem Description: How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: *d*-sorting. This sorting is applied to the strings of length at least *d*, where *d* is some positive integer. The characters of the string are sorted in following manner: first come all the 0-th characters of the initial string, then the 1-st ones, then the 2-nd ones and so on, in the end go all the (*d*<=-<=1)-th characters of the initial string. By the *i*-th characters we mean all the character whose positions are exactly *i* modulo *d*. If two characters stand on the positions with the same remainder of integer division by *d*, their relative order after the sorting shouldn't be changed. The string is zero-indexed. For example, for string 'qwerty': Its 1-sorting is the string 'qwerty' (all characters stand on 0 positions), Its 2-sorting is the string 'qetwry' (characters 'q', 'e' and 't' stand on 0 positions and characters 'w', 'r' and 'y' are on 1 positions), Its 3-sorting is the string 'qrwtey' (characters 'q' and 'r' stand on 0 positions, characters 'w' and 't' stand on 1 positions and characters 'e' and 'y' stand on 2 positions), Its 4-sorting is the string 'qtwyer', Its 5-sorting is the string 'qywert'. You are given string *S* of length *n* and *m* shuffling operations of this string. Each shuffling operation accepts two integer arguments *k* and *d* and transforms string *S* as follows. For each *i* from 0 to *n*<=-<=*k* in the increasing order we apply the operation of *d*-sorting to the substring *S*[*i*..*i*<=+<=*k*<=-<=1]. Here *S*[*a*..*b*] represents a substring that consists of characters on positions from *a* to *b* inclusive. After each shuffling operation you need to print string *S*. Input Specification: The first line of the input contains a non-empty string *S* of length *n*, consisting of lowercase and uppercase English letters and digits from 0 to 9. The second line of the input contains integer *m* – the number of shuffling operations (1<=≀<=*m*Β·*n*<=≀<=106). Following *m* lines contain the descriptions of the operations consisting of two integers *k* and *d* (1<=≀<=*d*<=≀<=*k*<=≀<=*n*). Output Specification: After each operation print the current state of string *S*. Demo Input: ['qwerty\n3\n4 2\n6 3\n5 2\n'] Demo Output: ['qertwy\nqtewry\nqetyrw\n'] Note: Here is detailed explanation of the sample. The first modification is executed with arguments *k* = 4, *d* = 2. That means that you need to apply 2-sorting for each substring of length 4 one by one moving from the left to the right. The string will transform in the following manner: qwerty  →  qewrty  →  qerwty  →  qertwy Thus, string *S* equals 'qertwy' at the end of first query. The second modification is executed with arguments *k* = 6, *d* = 3. As a result of this operation the whole string *S* is replaced by its 3-sorting: qertwy  →  qtewry The third modification is executed with arguments *k* = 5, *d* = 2. qtewry  →  qertwy  →  qetyrw
1,238
Title: Pie Rules Time Limit: None seconds Memory Limit: None megabytes Problem Description: You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person. The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left. All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive? Input Specification: Input will begin with an integer *N* (1<=≀<=*N*<=≀<=50), the number of slices of pie. Following this is a line with *N* integers indicating the sizes of the slices (each between 1 and 100000, inclusive), in the order in which they must be handed out. Output Specification: Print two integers. First, the sum of the sizes of slices eaten by Alice, then the sum of the sizes of the slices eaten by Bob, assuming both players make their decisions optimally. Demo Input: ['3\n141 592 653\n', '5\n10 21 10 21 10\n'] Demo Output: ['653 733\n', '31 41\n'] Note: In the first example, Bob takes the size 141 slice for himself and gives the decider token to Alice. Then Alice gives the size 592 slice to Bob and keeps the decider token for herself, so that she can then give the size 653 slice to herself.
1,239
Title: A Serial Killer Time Limit: None seconds Memory Limit: None megabytes Problem Description: Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim. You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern. Input Specification: First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer *n* (1<=≀<=*n*<=≀<=1000), the number of days. Next *n* lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters. Output Specification: Output *n*<=+<=1 lines, the *i*-th line should contain the two persons from which the killer selects for the *i*-th murder. The (*n*<=+<=1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order. Demo Input: ['ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler\n', 'icm codeforces\n1\ncodeforces technex\n'] Demo Output: ['ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler\n', 'icm codeforces\nicm technex\n'] Note: In first example, the killer starts with ross and rachel. - After day 1, ross is killed and joey appears. - After day 2, rachel is killed and phoebe appears. - After day 3, phoebe is killed and monica appears. - After day 4, monica is killed and chandler appears.
1,240
Title: Inna and Huge Candy Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to *n* from top to bottom and the columns β€” from 1 to *m*, from left to right. We'll represent the cell on the intersection of the *i*-th row and *j*-th column as (*i*,<=*j*). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has *p* candies: the *k*-th candy is at cell (*x**k*,<=*y**k*). The time moved closer to dinner and Inna was already going to eat *p* of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix *x* times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix *y* times. And then he rotated the matrix *z* times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made! Input Specification: The first line of the input contains fix integers *n*, *m*, *x*, *y*, *z*, *p* (1<=≀<=*n*,<=*m*<=≀<=109;Β 0<=≀<=*x*,<=*y*,<=*z*<=≀<=109;Β 1<=≀<=*p*<=≀<=105). Each of the following *p* lines contains two integers *x**k*, *y**k* (1<=≀<=*x**k*<=≀<=*n*;Β 1<=≀<=*y**k*<=≀<=*m*) β€” the initial coordinates of the *k*-th candy. Two candies can lie on the same cell. Output Specification: For each of the *p* candies, print on a single line its space-separated new coordinates. Demo Input: ['3 3 3 1 1 9\n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3\n'] Demo Output: ['1 3\n1 2\n1 1\n2 3\n2 2\n2 1\n3 3\n3 2\n3 1\n'] Note: Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:
1,241
Title: Pairs of Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's assume that we have a pair of numbers (*a*,<=*b*). We can get a new pair (*a*<=+<=*b*,<=*b*) or (*a*,<=*a*<=+<=*b*) from the given pair in a single step. Let the initial pair of numbers be (1,1). Your task is to find number *k*, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals *n*. Input Specification: The input contains the only integer *n* (1<=≀<=*n*<=≀<=106). Output Specification: Print the only integer *k*. Demo Input: ['5\n', '1\n'] Demo Output: ['3\n', '0\n'] Note: The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1)  →  (1,2)  →  (3,2)  →  (5,2).
1,242
Title: Mishka and Divisors Time Limit: None seconds Memory Limit: None megabytes Problem Description: After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem. You are given integer *k* and array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers. You are to find non-empty subsequence of array elements such that the product of its elements is divisible by *k* and it contains minimum possible number of elements. Formally, you are to find a sequence of indices 1<=≀<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**m*<=≀<=*n* such that is divisible by *k* while *m* is minimum possible among all such variants. If there are more than one such subsequences, you should choose one among them, such that sum of its elements is minimum possible. Mishka quickly solved this problem. Will you do so? Input Specification: The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=1<=000, 1<=≀<=*k*<=≀<=1012). The second line of the input contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=1012)Β β€” array elements. Output Specification: Print single positive integer *m* in the first lineΒ β€” the number of elements in desired sequence. In the second line print *m* distinct integersΒ β€” the sequence of indices of given array elements, which should be taken into the desired sequence. If there are more than one such subsequence (e.g. subsequence of minimum possible number of elements and with minimum possible sum of elements), you can print any of them. If there are no such subsequences, print <=-<=1 in the only line. Demo Input: ['5 60\n2 4 6 5 2\n'] Demo Output: ['3\n4 3 1 '] Note: none
1,243
Title: Checkposts Time Limit: None seconds Memory Limit: None megabytes Problem Description: Your city has *n* junctions. There are *m* one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions. To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction *i* can protect junction *j* if either *i*<==<=*j* or the police patrol car can go to *j* from *i* and then come back to *i*. Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions. You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and in addition in minimum number of checkposts. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other. Input Specification: In the first line, you will be given an integer *n*, number of junctions (1<=≀<=*n*<=≀<=105). In the next line, *n* space-separated integers will be given. The *i**th* integer is the cost of building checkpost at the *i**th* junction (costs will be non-negative and will not exceed 109). The next line will contain an integer *m*Β (0<=≀<=*m*<=≀<=3Β·105). And each of the next *m* lines contains two integers *u**i* and *v**i*Β (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*;Β *u*<=β‰ <=*v*). A pair *u**i*,<=*v**i* means, that there is a one-way road which goes from *u**i* to *v**i*. There will not be more than one road between two nodes in the same direction. Output Specification: Print two integers separated by spaces. The first one is the minimum possible money needed to ensure the security of all the junctions. And the second one is the number of ways you can ensure the security modulo 1000000007 (109<=+<=7). Demo Input: ['3\n1 2 3\n3\n1 2\n2 3\n3 2\n', '5\n2 8 0 6 0\n6\n1 4\n1 3\n2 4\n3 4\n4 5\n5 1\n', '10\n1 3 2 2 1 3 1 4 10 10\n12\n1 2\n2 3\n3 1\n3 4\n4 5\n5 6\n5 7\n6 4\n7 3\n8 9\n9 10\n10 9\n', '2\n7 91\n2\n1 2\n2 1\n'] Demo Output: ['3 1\n', '8 2\n', '15 6\n', '7 1\n'] Note: none
1,244
Title: Encoding Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp invented a new way to encode strings. Let's assume that we have string *T*, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in *T* with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word "parallelogram" according to the given encoding principle transforms to word "qolorreraglom". Polycarpus already has two strings, *S* and *T*. He suspects that string *T* was obtained after applying the given encoding method from some substring of string *S*. Find all positions *m**i* in *S* (1<=≀<=*m**i*<=≀<=|*S*|<=-<=|*T*|<=+<=1), such that *T* can be obtained fro substring *S**m**i**S**m**i*<=+<=1... *S**m**i*<=+<=|*T*|<=-<=1 by applying the described encoding operation by using some set of pairs of English alphabet letters Input Specification: The first line of the input contains two integers, |*S*| and |*T*| (1<=≀<=|*T*|<=≀<=|*S*|<=≀<=2Β·105) β€” the lengths of string *S* and string *T*, respectively. The second and third line of the input contain strings *S* and *T*, respectively. Both strings consist only of lowercase English letters. Output Specification: Print number *k* β€” the number of suitable positions in string *S*. In the next line print *k* integers *m*1,<=*m*2,<=...,<=*m**k* β€” the numbers of the suitable positions in the increasing order. Demo Input: ['11 5\nabacabadaba\nacaba\n', '21 13\nparaparallelogramgram\nqolorreraglom\n'] Demo Output: ['3\n1 3 7\n', '1\n5\n'] Note: none
1,245
Title: As Fast As Possible Time Limit: None seconds Memory Limit: None megabytes Problem Description: On vacations *n* pupils decided to go on excursion and gather all together. They need to overcome the path with the length *l* meters. Each of the pupils will go with the speed equal to *v*1. To get to the excursion quickly, it was decided to rent a bus, which has seats for *k* people (it means that it can't fit more than *k* people at the same time) and the speed equal to *v*2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all *n* pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input Specification: The first line of the input contains five positive integers *n*, *l*, *v*1, *v*2 and *k* (1<=≀<=*n*<=≀<=10<=000, 1<=≀<=*l*<=≀<=109, 1<=≀<=*v*1<=&lt;<=*v*2<=≀<=109, 1<=≀<=*k*<=≀<=*n*)Β β€” the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Specification: Print the real numberΒ β€” the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10<=-<=6. Demo Input: ['5 10 1 2 5\n', '3 6 1 2 1\n'] Demo Output: ['5.0000000000\n', '4.7142857143\n'] Note: In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
1,246
Title: Lie or Truth Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to *a*1,<=*a*2,<=...,<=*a**n*. While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to *b*1,<=*b*2,<=...,<=*b**n*. Stepan said that he swapped only cubes which where on the positions between *l* and *r*, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions *l* and *r*, inclusive, in some way). Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother. Input Specification: The first line contains three integers *n*, *l*, *r* (1<=≀<=*n*<=≀<=105, 1<=≀<=*l*<=≀<=*r*<=≀<=*n*) β€” the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=*n*) β€” the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence *b*1,<=*b*2,<=...,<=*b**n* (1<=≀<=*b**i*<=≀<=*n*) β€” the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes. Output Specification: Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes). Demo Input: ['5 2 4\n3 4 2 3 1\n3 2 3 4 1\n', '3 1 2\n1 2 3\n3 1 2\n', '4 2 4\n1 1 1 1\n1 1 1 1\n'] Demo Output: ['TRUTH\n', 'LIE\n', 'TRUTH\n'] Note: In the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]). In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother. In the third example for any values *l* and *r* there is a situation when Stepan said the truth.
1,247
Title: Petr# Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the *s**begin* and ending with the *s**end* (it is possible *s**begin*<==<=*s**end*), the given string *t* has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him! Input Specification: The input file consists of three lines. The first line contains string *t*. The second and the third lines contain the *s**begin* and *s**end* identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters. Output Specification: Output the only number β€” the amount of different substrings of *t* that start with *s**begin* and end with *s**end*. Demo Input: ['round\nro\nou\n', 'codeforces\ncode\nforca\n', 'abababab\na\nb\n', 'aba\nab\nba\n'] Demo Output: ['1\n', '0\n', '4\n', '1\n'] Note: In the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab. In the fourth sample identificators intersect.
1,248
Title: Sheldon and Ice Pieces Time Limit: None seconds Memory Limit: None megabytes Problem Description: Do you remember how Kai constructed the word "eternity" using pieces of ice as components? Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number *t*. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry". Sheldon favourite number is *t*. He wants to have as many instances of *t* as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once. Input Specification: The first line contains integer *t* (1<=≀<=*t*<=≀<=10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9. Output Specification: Print the required number of instances. Demo Input: ['42\n23454\n', '169\n12118999\n'] Demo Output: ['2\n', '1\n'] Note: This problem contains very weak pretests.
1,249
Title: Sherlock and his girlfriend Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1. Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used. Help Sherlock complete this trivial task. Input Specification: The only line contains single integer *n* (1<=≀<=*n*<=≀<=100000)Β β€” the number of jewelry pieces. Output Specification: The first line of output should contain a single integer *k*, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of *n* space-separated integers (between 1 and *k*) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using *k* colors, you can output any of them. Demo Input: ['3\n', '4\n'] Demo Output: ['2\n1 1 2 ', '2\n2 1 1 2\n'] Note: In the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively. In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
1,250
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have written on a piece of paper an array of *n* positive integers *a*[1],<=*a*[2],<=...,<=*a*[*n*] and *m* good pairs of integers (*i*1,<=*j*1),<=(*i*2,<=*j*2),<=...,<=(*i**m*,<=*j**m*). Each good pair (*i**k*,<=*j**k*) meets the following conditions: *i**k*<=+<=*j**k* is an odd number and 1<=≀<=*i**k*<=&lt;<=*j**k*<=≀<=*n*. In one operation you can perform a sequence of actions: - take one of the good pairs (*i**k*,<=*j**k*) and some integer *v* (*v*<=&gt;<=1), which divides both numbers *a*[*i**k*] and *a*[*j**k*]; - divide both numbers by *v*, i. e. perform the assignments: and . Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations. Input Specification: The first line contains two space-separated integers *n*, *m* (2<=≀<=*n*<=≀<=100, 1<=≀<=*m*<=≀<=100). The second line contains *n* space-separated integers *a*[1],<=*a*[2],<=...,<=*a*[*n*] (1<=≀<=*a*[*i*]<=≀<=109) β€” the description of the array. The following *m* lines contain the description of good pairs. The *k*-th line contains two space-separated integers *i**k*, *j**k* (1<=≀<=*i**k*<=&lt;<=*j**k*<=≀<=*n*, *i**k*<=+<=*j**k* is an odd number). It is guaranteed that all the good pairs are distinct. Output Specification: Output the answer for the problem. Demo Input: ['3 2\n8 3 8\n1 2\n2 3\n', '3 2\n8 12 8\n1 2\n2 3\n'] Demo Output: ['0\n', '2\n'] Note: none
1,251
Title: Animals and Puzzle Time Limit: None seconds Memory Limit: None megabytes Problem Description: Owl Sonya gave a huge lake puzzle of size *n*<=Γ—<=*m* to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be emptyΒ β€” there was no picture on them. Parts with picture on it are denoted by 1, while empty parts are denoted by 0. Rows of the puzzle are numbered from top to bottom with integers from 1 to *n*, while columns are numbered from left to right with integers from 1 to *m*. Animals decided to complete the picture and play with it, as it might be even more fun! Owl and hedgehog ask each other some queries. Each query is provided by four integers *x*1, *y*1, *x*2, *y*2 which define the rectangle, where (*x*1,<=*y*1) stands for the coordinates of the up left cell of the rectangle, while (*x*2,<=*y*2) stands for the coordinates of the bottom right cell. The answer to the query is the size of the maximum square consisting of picture parts only (only parts denoted by 1) and located fully inside the query rectangle. Help Sonya and Filya answer *t* queries. Input Specification: The first line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=1000)Β β€” sizes of the puzzle. Each of the following *n* lines contains *m* integers *a**ij*. Each of them is equal to 1 if the corresponding cell contains a picture and 0 if it's empty. Next line contains an integer *t* (1<=≀<=*t*<=≀<=1<=000<=000)Β β€” the number of queries. Then follow *t* lines with queries' descriptions. Each of them contains four integers *x*1, *y*1, *x*2, *y*2 (1<=≀<=*x*1<=≀<=*x*2<=≀<=*n*, 1<=≀<=*y*1<=≀<=*y*2<=≀<=*m*)Β β€” coordinates of the up left and bottom right cells of the query rectangle. Output Specification: Print *t* lines. The *i*-th of them should contain the maximum size of the square consisting of 1-s and lying fully inside the query rectangle. Demo Input: ['3 4\n1 1 0 1\n0 1 1 0\n0 1 1 0\n5\n1 1 2 3\n2 1 3 2\n3 2 3 4\n1 1 3 4\n1 2 3 4\n'] Demo Output: ['1\n1\n1\n2\n2\n'] Note: none
1,252
Title: Petya and Tree Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up. Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node. Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result. It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths. Input Specification: The first line contains an odd integer *n* (3<=≀<=*n*<=&lt;<=105), which represents the number of tree nodes. Next *n* lines contain node descriptions. The (*i*<=+<=1)-th line contains two space-separated integers. The first number is the number of parent of the *i*-st node and the second number is the key lying in the *i*-th node. The next line contains an integer *k* (1<=≀<=*k*<=≀<=105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next *k* lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All *n*<=+<=*k* keys are distinct. All nodes are numbered from 1 to *n*. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one. Output Specification: Print *k* real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10<=-<=9. Demo Input: ['7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1\n', '3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9\n'] Demo Output: ['8.0000000000\n', '7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000\n'] Note: In the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
1,253
Title: Function Time Limit: None seconds Memory Limit: None megabytes Problem Description: Serega and Fedor play with functions. One day they came across a very interesting function. It looks like that: - *f*(1,<=*j*)<==<=*a*[*j*], 1<=≀<=*j*<=≀<=*n*. - *f*(*i*,<=*j*)<==<=*min*(*f*(*i*<=-<=1,<=*j*),<=*f*(*i*<=-<=1,<=*j*<=-<=1))<=+<=*a*[*j*], 2<=≀<=*i*<=≀<=*n*, *i*<=≀<=*j*<=≀<=*n*. Here *a* is an integer array of length *n*. Serega and Fedya want to know what values this function takes at some points. But they don't want to calculate the values manually. So they ask you to help them. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105) β€” the length of array *a*. The next line contains *n* integers: *a*[1],<=*a*[2],<=...,<=*a*[*n*] (0<=≀<=*a*[*i*]<=≀<=104). The next line contains integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of queries. Each of the next *m* lines contains two integers: *x**i*, *y**i* (1<=≀<=*x**i*<=≀<=*y**i*<=≀<=*n*). Each line means that Fedor and Serega want to know the value of *f*(*x**i*,<=*y**i*). Output Specification: Print *m* lines β€” the answers to the guys' queries. Demo Input: ['6\n2 2 3 4 3 4\n4\n4 5\n3 4\n3 4\n2 3\n', '7\n1 3 2 3 4 0 2\n4\n4 5\n2 3\n1 4\n4 6\n'] Demo Output: ['12\n9\n9\n5\n', '11\n4\n3\n0\n'] Note: none
1,254
Title: Average Sleep Time Time Limit: None seconds Memory Limit: None megabytes Problem Description: It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts *k* days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last *n* days. So now he has a sequence *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the sleep time on the *i*-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider *k* consecutive days as a week. So there will be *n*<=-<=*k*<=+<=1 weeks to take into consideration. For example, if *k*<==<=2, *n*<==<=3 and *a*<==<=[3,<=4,<=7], then the result is . You should write a program which will calculate average sleep times of Polycarp over all weeks. Input Specification: The first line contains two integer numbers *n* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=2Β·105). The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=105). Output Specification: Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10<=-<=6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Demo Input: ['3 2\n3 4 7\n', '1 1\n10\n', '8 2\n1 2 4 100000 123 456 789 1\n'] Demo Output: ['9.0000000000\n', '10.0000000000\n', '28964.2857142857\n'] Note: In the third example there are *n* - *k* + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.
1,255
Title: Mike and Fun Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an *n*<=Γ—<=*m* grid, there's exactly one bear in each cell. We denote the bear standing in column number *j* of row number *i* by (*i*,<=*j*). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for *q* rounds. In each round, Mike chooses a bear (*i*,<=*j*) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears. Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row. Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round. Input Specification: The first line of input contains three integers *n*, *m* and *q* (1<=≀<=*n*,<=*m*<=≀<=500 and 1<=≀<=*q*<=≀<=5000). The next *n* lines contain the grid description. There are *m* integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next *q* lines contain the information about the rounds. Each of them contains two integers *i* and *j* (1<=≀<=*i*<=≀<=*n* and 1<=≀<=*j*<=≀<=*m*), the row number and the column number of the bear changing his state. Output Specification: After each round, print the current score of the bears. Demo Input: ['5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3\n'] Demo Output: ['3\n4\n3\n3\n4\n'] Note: none
1,256
Title: Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got an array *a*, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a minimal by inclusion segment [*l*,<=*r*] (1<=≀<=*l*<=≀<=*r*<=≀<=*n*) such, that among numbers *a**l*,<=Β *a**l*<=+<=1,<=Β ...,<=Β *a**r* there are exactly *k* distinct numbers. Segment [*l*,<=*r*] (1<=≀<=*l*<=≀<=*r*<=≀<=*n*; *l*,<=*r* are integers) of length *m*<==<=*r*<=-<=*l*<=+<=1, satisfying the given property, is called minimal by inclusion, if there is no segment [*x*,<=*y*] satisfying the property and less then *m* in length, such that 1<=≀<=*l*<=≀<=*x*<=≀<=*y*<=≀<=*r*<=≀<=*n*. Note that the segment [*l*,<=*r*] doesn't have to be minimal in length among all segments, satisfying the given property. Input Specification: The first line contains two space-separated integers: *n* and *k* (1<=≀<=*n*,<=*k*<=≀<=105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n*Β β€” elements of the array *a* (1<=≀<=*a**i*<=≀<=105). Output Specification: Print a space-separated pair of integers *l* and *r* (1<=≀<=*l*<=≀<=*r*<=≀<=*n*) such, that the segment [*l*,<=*r*] is the answer to the problem. If the sought segment does not exist, print "-1 -1" without the quotes. If there are multiple correct answers, print any of them. Demo Input: ['4 2\n1 2 2 3\n', '8 3\n1 1 2 2 3 3 4 5\n', '7 4\n4 7 7 4 7 4 7\n'] Demo Output: ['1 2\n', '2 5\n', '-1 -1\n'] Note: In the first sample among numbers *a*<sub class="lower-index">1</sub> and *a*<sub class="lower-index">2</sub> there are exactly two distinct numbers. In the second sample segment [2, 5] is a minimal by inclusion segment with three distinct numbers, but it is not minimal in length among such segments. In the third sample there is no segment with four distinct numbers.
1,257
Title: k-Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a *k*-tree. A *k*-tree is an infinite rooted tree where: - each vertex has exactly *k* children; - each edge has some weight; - if we look at the edges that goes from some vertex to its children (exactly *k* edges), then their weights will equal 1,<=2,<=3,<=...,<=*k*. The picture below shows a part of a 3-tree. Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109<=+<=7). Input Specification: A single line contains three space-separated integers: *n*, *k* and *d* (1<=≀<=*n*,<=*k*<=≀<=100; 1<=≀<=*d*<=≀<=*k*). Output Specification: Print a single integer β€” the answer to the problem modulo 1000000007 (109<=+<=7). Demo Input: ['3 3 2\n', '3 3 3\n', '4 3 2\n', '4 5 2\n'] Demo Output: ['3\n', '1\n', '6\n', '7\n'] Note: none
1,258
Title: Posterized Time Limit: None seconds Memory Limit: None megabytes Problem Description: Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter. Their algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive). To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $k$, and each color should belong to exactly one group. Finally, the students will replace the color of each pixel in the array with that color’s assigned group key. To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $k$ to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array. Input Specification: The first line of input contains two integers $n$ and $k$ ($1 \leq n \leq 10^5$, $1 \leq k \leq 256$), the number of pixels in the image, and the maximum size of a group, respectively. The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($0 \leq p_i \leq 255$), where $p_i$ is the color of the $i$-th pixel. Output Specification: Print $n$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter. Demo Input: ['4 3\n2 14 3 4\n', '5 2\n0 2 1 255 254\n'] Demo Output: ['0 12 3 3\n', '0 1 1 254 254\n'] Note: One possible way to group colors and assign keys for the first sample: Color $2$ belongs to the group $[0,2]$, with group key $0$. Color $14$ belongs to the group $[12,14]$, with group key $12$. Colors $3$ and $4$ belong to group $[3, 5]$, with group key $3$. Other groups won't affect the result so they are not listed here.
1,259
Title: The Big Race Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of *L* meters today. Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. While watching previous races the organizers have noticed that Willman can perform only steps of length equal to *w* meters, and Bolt can perform only steps of length equal to *b* meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes). Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance *L*. Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to *t* (both are included). What is the probability that Willman and Bolt tie again today? Input Specification: The first line of the input contains three integers *t*, *w* and *b* (1<=≀<=*t*,<=*w*,<=*b*<=≀<=5Β·1018) β€” the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively. Output Specification: Print the answer to the problem as an irreducible fraction . Follow the format of the samples output. The fraction (*p* and *q* are integers, and both *p*<=β‰₯<=0 and *q*<=&gt;<=0 holds) is called irreducible, if there is no such integer *d*<=&gt;<=1, that both *p* and *q* are divisible by *d*. Demo Input: ['10 3 2\n', '7 1 2\n'] Demo Output: ['3/10\n', '3/7\n'] Note: In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
1,260
Title: Perfect Groups Time Limit: None seconds Memory Limit: None megabytes Problem Description: SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array $A$ of $n$ integers, and he needs to find the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$ for each integer $k$ between $1$ and $n$ (inclusive). Input Specification: The first line of input contains a single integer $n$ ($1 \leq n \leq 5000$), the size of the array. The second line contains $n$ integers $a_1$,$a_2$,$\dots$,$a_n$ ($-10^8 \leq a_i \leq 10^8$), the values of the array. Output Specification: Output $n$ space-separated integers, the $k$-th integer should be the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$. Demo Input: ['2\n5 5\n', '5\n5 -4 2 1 8\n', '1\n0\n'] Demo Output: ['3 0\n', '5 5 3 2 0\n', '1\n'] Note: none
1,261
Title: Meta-universe Time Limit: None seconds Memory Limit: None megabytes Problem Description: Consider infinite grid of unit cells. Some of those cells are planets. Meta-universe *M*<==<={*p*1,<=*p*2,<=...,<=*p**k*} is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet *p**i* of meta-universe *M* on it; 2) there are planets of *M* located on both sides from this row or column. In this case we can turn the meta-universe *M* into two non-empty meta-universes *M*1 and *M*2 containing planets that are located on respective sides of this row or column. A meta-universe which can't be split using operation above is called a universe. We perform such operations until all meta-universes turn to universes. Given positions of the planets in the original meta-universe, find the number of universes that are result of described process. It can be proved that each universe is uniquely identified not depending from order of splitting. Input Specification: The first line of input contains an integer *n*, (1<=≀<=*n*<=≀<=105), denoting the number of planets in the meta-universe. The next *n* lines each contain integers *x**i* and *y**i*, (<=-<=109<=≀<=*x**i*,<=*y**i*<=≀<=109), denoting the coordinates of the *i*-th planet. All planets are located in different cells. Output Specification: Print the number of resulting universes. Demo Input: ['5\n0 0\n0 2\n2 0\n2 1\n2 2\n', '8\n0 0\n1 0\n0 2\n0 3\n3 0\n3 1\n2 3\n3 3\n'] Demo Output: ['3\n', '1\n'] Note: The following figure describes the first test case:
1,262
Title: Bag of mice Time Limit: None seconds Memory Limit: None megabytes Problem Description: The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance. They take turns drawing a mouse from a bag which initially contains *w* white and *b* black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). Princess draws first. What is the probability of the princess winning? If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one. Input Specification: The only line of input data contains two integers *w* and *b* (0<=≀<=*w*,<=*b*<=≀<=1000). Output Specification: Output the probability of the princess winning. The answer is considered to be correct if its absolute or relative error does not exceed 10<=-<=9. Demo Input: ['1 3\n', '5 5\n'] Demo Output: ['0.500000000\n', '0.658730159\n'] Note: Let's go through the first sample. The probability of the princess drawing a white mouse on her first turn and winning right away is 1/4. The probability of the dragon drawing a black mouse and not winning on his first turn is 3/4 * 2/3 = 1/2. After this there are two mice left in the bag β€” one black and one white; one of them jumps out, and the other is drawn by the princess on her second turn. If the princess' mouse is white, she wins (probability is 1/2 * 1/2 = 1/4), otherwise nobody gets the white mouse, so according to the rule the dragon wins.
1,263
Title: Marmots (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population *P* from their random number before responding to Heidi's request. Also, there are now villages with as few as a single inhabitant, meaning that . Can you help Heidi find out whether a village follows a Poisson or a uniform distribution? Input Specification: Same as for the easy and medium versions. But remember that now 1<=≀<=*P*<=≀<=1000 and that the marmots may provide positive as well as negative integers. Output Specification: Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answers came from a uniform distribution. Note: none
1,264
Title: Okabe and Banana Trees Time Limit: None seconds Memory Limit: None megabytes Problem Description: Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees. Consider the point (*x*,<=*y*) in the 2D plane such that *x* and *y* are integers and 0<=≀<=*x*,<=*y*. There is a tree in such a point, and it has *x*<=+<=*y* bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation . Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point. Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely. Okabe is sure that the answer does not exceed 1018. You can trust him. Input Specification: The first line of input contains two space-separated integers *m* and *b* (1<=≀<=*m*<=≀<=1000, 1<=≀<=*b*<=≀<=10000). Output Specification: Print the maximum number of bananas Okabe can get from the trees he cuts. Demo Input: ['1 5\n', '2 3\n'] Demo Output: ['30\n', '25\n'] Note: The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas.
1,265
Title: Polygons Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got another geometrical task. You are given two non-degenerate polygons *A* and *B* as vertex coordinates. Polygon *A* is strictly convex. Polygon *B* is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line. Your task is to check whether polygon *B* is positioned strictly inside polygon *A*. It means that any point of polygon *B* should be strictly inside polygon *A*. "Strictly" means that the vertex of polygon *B* cannot lie on the side of the polygon *A*. Input Specification: The first line contains the only integer *n* (3<=≀<=*n*<=≀<=105) β€” the number of vertices of polygon *A*. Then *n* lines contain pairs of integers *x**i*,<=*y**i* (|*x**i*|,<=|*y**i*|<=≀<=109) β€” coordinates of the *i*-th vertex of polygon *A*. The vertices are given in the clockwise order. The next line contains a single integer *m* (3<=≀<=*m*<=≀<=2Β·104) β€” the number of vertices of polygon *B*. Then following *m* lines contain pairs of integers *x**j*,<=*y**j* (|*x**j*|,<=|*y**j*|<=≀<=109) β€” the coordinates of the *j*-th vertex of polygon *B*. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons *A* and *B* are non-degenerate, that polygon *A* is strictly convex, that polygon *B* has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line. Output Specification: Print on the only line the answer to the problem β€” if polygon *B* is strictly inside polygon *A*, print "YES", otherwise print "NO" (without the quotes). Demo Input: ['6\n-2 1\n0 3\n3 3\n4 1\n3 -2\n2 -2\n4\n0 1\n2 2\n3 1\n1 0\n', '5\n1 2\n4 2\n3 -3\n-2 -2\n-2 1\n4\n0 1\n1 2\n4 1\n2 -1\n', '5\n-1 2\n2 3\n4 1\n3 -2\n0 -3\n5\n1 0\n1 1\n3 1\n5 -1\n2 -1\n'] Demo Output: ['YES\n', 'NO\n', 'NO\n'] Note: none
1,266
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units. In order for production to work, it is needed to deploy two services $S_1$ and $S_2$ to process incoming requests using the servers of the department. Processing of incoming requests of service $S_i$ takes $x_i$ resource units. The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $S_i$ is deployed using $k_i$ servers, then the load is divided equally between these servers and each server requires only $x_i / k_i$ (that may be a fractional number) resource units. Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides. Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services. Input Specification: The first line contains three integers $n$, $x_1$, $x_2$ ($2 \leq n \leq 300\,000$, $1 \leq x_1, x_2 \leq 10^9$)Β β€” the number of servers that the department may use, and resource units requirements for each of the services. The second line contains $n$ space-separated integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^9$)Β β€” the number of resource units provided by each of the servers. Output Specification: If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes). Otherwise print the word "Yes" (without the quotes). In the second line print two integers $k_1$ and $k_2$ ($1 \leq k_1, k_2 \leq n$)Β β€” the number of servers used for each of the services. In the third line print $k_1$ integers, the indices of the servers that will be used for the first service. In the fourth line print $k_2$ integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them. Demo Input: ['6 8 16\n3 5 2 9 8 7\n', '4 20 32\n21 11 11 12\n', '4 11 32\n5 5 16 16\n', '5 12 20\n7 8 4 11 9\n'] Demo Output: ['Yes\n3 2\n1 2 6\n5 4', 'Yes\n1 3\n1\n2 3 4\n', 'No\n', 'No\n'] Note: In the first sample test each of the servers 1, 2 and 6 will will provide $8 / 3 = 2.(6)$ resource units and each of the servers 5, 4 will provide $16 / 2 = 8$ resource units. In the second sample test the first server will provide $20$ resource units and each of the remaining servers will provide $32 / 3 = 10.(6)$ resource units.
1,267
Title: Freezing with Style Time Limit: None seconds Memory Limit: None megabytes Problem Description: This winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as *n* junctions connected with *n*<=-<=1 bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction *v*), and the place to set up the contests (junction *u*). Besides, at the one hand, they want the participants to walk about the city and see the neighbourhood (that's why the distance between *v* and *u* should be no less than *l*). On the other hand, they don't want the participants to freeze (so the distance between *v* and *u* should be no more than *r*). Besides, for every street we know its beauty β€” some integer from 0 to 109. Your task is to choose the path that fits in the length limits and has the largest average beauty. We shall define the average beauty as a median of sequence of the beauties of all roads along the path. We can put it more formally like that: let there be a path with the length *k*. Let *a**i* be a non-decreasing sequence that contains exactly *k* elements. Each number occurs there exactly the number of times a road with such beauty occurs along on path. We will represent the path median as number *a*⌊*k*<=/<=2βŒ‹, assuming that indexation starting from zero is used. ⌊*x*βŒ‹ β€” is number *Ρ…*, rounded down to the nearest integer. For example, if *a*<==<={0,<=5,<=12}, then the median equals to 5, and if *a*<==<={0,<=5,<=7,<=12}, then the median is number 7. It is guaranteed that there will be at least one path with the suitable quantity of roads. Input Specification: The first line contains three integers *n*, *l*, *r* (1<=≀<=*l*<=≀<=*r*<=&lt;<=*n*<=≀<=105). Next *n*<=-<=1 lines contain descriptions of roads of the Nvodsk, each line contains three integers *a**i*, *b**i*, *c**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, 0<=≀<=*c**i*<=≀<=109, *a**i*<=β‰ <=*b**i*) β€” junctions *a**i* and *b**i* are connected with a street whose beauty equals *c**i*. Output Specification: Print two integers β€” numbers of the junctions, where to accommodate the participants and set up the contests, correspondingly. If there are multiple optimal variants, print any of them. Demo Input: ['6 3 4\n1 2 1\n2 3 1\n3 4 1\n4 5 1\n5 6 1\n', '6 3 4\n1 2 1\n2 3 1\n3 4 1\n4 5 2\n5 6 2\n', '5 1 4\n1 2 1\n1 3 4\n3 4 7\n3 5 2\n', '8 3 6\n1 2 9\n2 3 7\n3 4 7\n4 5 8\n5 8 2\n3 6 3\n2 7 4\n'] Demo Output: ['4 1\n', '6 3\n', '4 3\n', '5 1\n'] Note: In the first sample all roads have the same beauty. That means that all paths of the positive length have the same median. Thus, any path with length from 3 to 4, inclusive will be valid for us. In the second sample the city looks like that: 1 - 2 - 3 - 4 - 5 - 6. Two last roads are more valuable and we should choose any path that contains both of them and has the suitable length. It is either the path between 2 and 6 or the path between 3 and 6.
1,268
Title: Sereja and Cinema Time Limit: None seconds Memory Limit: None megabytes Problem Description: The cinema theater hall in Sereja's city is *n* seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for *n*<==<=4. Today it's the premiere of a movie called "Dry Hard". The tickets for all the seats have been sold. There is a very strict controller at the entrance to the theater, so all *n* people will come into the hall one by one. As soon as a person enters a cinema hall, he immediately (momentarily) takes his seat and occupies all empty slots to the left and to the right from him. If there are no empty slots, the man gets really upset and leaves. People are not very constant, so it's hard to predict the order in which the viewers will enter the hall. For some seats, Sereja knows the number of the viewer (his number in the entering queue of the viewers) that will come and take this seat. For others, it can be any order. Being a programmer and a mathematician, Sereja wonders: how many ways are there for the people to enter the hall, such that nobody gets upset? As the number can be quite large, print it modulo 1000000007 (109<=+<=7). Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105). The second line contains *n* integers, the *i*-th integer shows either the index of the person (index in the entering queue) with the ticket for the *i*-th seat or a 0, if his index is not known. It is guaranteed that all positive numbers in the second line are distinct. You can assume that the index of the person who enters the cinema hall is a unique integer from 1 to *n*. The person who has index 1 comes first to the hall, the person who has index 2 comes second and so on. Output Specification: In a single line print the remainder after dividing the answer by number 1000000007 (109<=+<=7). Demo Input: ['11\n0 0 0 0 0 0 0 0 0 0 0\n', '6\n0 3 1 0 0 0\n'] Demo Output: ['1024\n', '3\n'] Note: none
1,269
Title: Caesar's Legions Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had *n*1 footmen and *n*2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that *k*1 footmen standing successively one after another, or there are strictly more than *k*2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers. Note that all *n*1<=+<=*n*2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves. Input Specification: The only line contains four space-separated integers *n*1, *n*2, *k*1, *k*2 (1<=≀<=*n*1,<=*n*2<=≀<=100,<=1<=≀<=*k*1,<=*k*2<=≀<=10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly. Output Specification: Print the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than *k*1 footmen stand successively, and no more than *k*2 horsemen stand successively. Demo Input: ['2 1 1 10\n', '2 3 1 2\n', '2 4 1 1\n'] Demo Output: ['1\n', '5\n', '0\n'] Note: Let's mark a footman as 1, and a horseman as 2. In the first sample the only beautiful line-up is: 121 In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121
1,270
Title: Three Trees Time Limit: None seconds Memory Limit: None megabytes Problem Description: This problem consists of two subproblems: for solving subproblem E1 you will receive 11 points, and for solving subproblem E2 you will receive 13 points. A tree is an undirected connected graph containing no cycles. The distance between two nodes in an unweighted tree is the minimum number of edges that have to be traversed to get from one node to another. You are given 3 trees that have to be united into a single tree by adding two edges between these trees. Each of these edges can connect any pair of nodes from two trees. After the trees are connected, the distances between all unordered pairs of nodes in the united tree should be computed. What is the maximum possible value of the sum of these distances? Input Specification: The first line contains three space-separated integers *n*1, *n*2, *n*3 β€” the number of vertices in the first, second, and third trees, respectively. The following *n*1<=-<=1 lines describe the first tree. Each of these lines describes an edge in the first tree and contains a pair of integers separated by a single space β€” the numeric labels of vertices connected by the edge. The following *n*2<=-<=1 lines describe the second tree in the same fashion, and the *n*3<=-<=1 lines after that similarly describe the third tree. The vertices in each tree are numbered with consecutive integers starting with 1. The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. - In subproblem E1 (11 points), the number of vertices in each tree will be between 1 and 1000, inclusive. - In subproblem E2 (13 points), the number of vertices in each tree will be between 1 and 100000, inclusive. Output Specification: Print a single integer number β€” the maximum possible sum of distances between all pairs of nodes in the united tree. Demo Input: ['2 2 3\n1 2\n1 2\n1 2\n2 3\n', '5 1 4\n1 2\n2 5\n3 4\n4 2\n1 2\n1 3\n1 4\n'] Demo Output: ['56\n', '151\n'] Note: Consider the first test case. There are two trees composed of two nodes, and one tree with three nodes. The maximum possible answer is obtained if the trees are connected in a single chain of 7 vertices. In the second test case, a possible choice of new edges to obtain the maximum answer is the following: - Connect node 3 from the first tree to node 1 from the second tree; - Connect node 2 from the third tree to node 1 from the second tree.
1,271
Title: Little Elephant and Interval Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Little Elephant very much loves sums on intervals. This time he has a pair of integers *l* and *r* (*l*<=≀<=*r*). The Little Elephant has to find the number of such integers *x* (*l*<=≀<=*x*<=≀<=*r*), that the first digit of integer *x* equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not. Help him and count the number of described numbers *x* for a given pair *l* and *r*. Input Specification: The single line contains a pair of integers *l* and *r* (1<=≀<=*l*<=≀<=*r*<=≀<=1018) β€” the boundaries of the interval. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. Output Specification: On a single line print a single integer β€” the answer to the problem. Demo Input: ['2 47\n', '47 1024\n'] Demo Output: ['12\n', '98\n'] Note: In the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.
1,272
Title: Domino Principle Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put *n* dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The *i*-th domino has the coordinate *x**i* and the height *h**i*. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate *x* and height *h* leads to the fall of all dominoes on the segment [*x*<=+<=1,<=*x*<=+<=*h*<=-<=1]. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105) which is the number of dominoes. Then follow *n* lines containing two integers *x**i* and *h**i* (<=-<=108<=≀<=*x**i*<=≀<=108,<=2<=≀<=*h**i*<=≀<=108) each, which are the coordinate and height of every domino. No two dominoes stand on one point. Output Specification: Print *n* space-separated numbers *z**i* β€” the number of dominoes that will fall if Vasya pushes the *i*-th domino to the right (including the domino itself). Demo Input: ['4\n16 5\n20 5\n10 10\n18 2\n', '4\n0 10\n1 5\n9 10\n15 10\n'] Demo Output: ['3 1 4 1 ', '4 1 2 1 '] Note: none
1,273
Title: Powerful array Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: An array of positive integers *a*1,<=*a*2,<=...,<=*a**n* is given. Let us consider its arbitrary subarray *a**l*,<=*a**l*<=+<=1...,<=*a**r*, where 1<=≀<=*l*<=≀<=*r*<=≀<=*n*. For every positive integer *s* denote by *K**s* the number of occurrences of *s* into the subarray. We call the power of the subarray the sum of products *K**s*Β·*K**s*Β·*s* for every positive integer *s*. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite. You should calculate the power of *t* given subarrays. Input Specification: First line contains two integers *n* and *t* (1<=≀<=*n*,<=*t*<=≀<=200000) β€” the array length and the number of queries correspondingly. Second line contains *n* positive integers *a**i* (1<=≀<=*a**i*<=≀<=106) β€” the elements of the array. Next *t* lines contain two positive integers *l*, *r* (1<=≀<=*l*<=≀<=*r*<=≀<=*n*) each β€” the indices of the left and the right ends of the corresponding subarray. Output Specification: Output *t* lines, the *i*-th line of the output should contain single positive integer β€” the power of the *i*-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). Demo Input: ['3 2\n1 2 1\n1 2\n1 3\n', '8 3\n1 1 2 2 1 3 1 1\n2 7\n1 6\n2 7\n'] Demo Output: ['3\n6\n', '20\n20\n20\n'] Note: Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored):
1,274
Title: Restoring Table Time Limit: None seconds Memory Limit: None megabytes Problem Description: Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. He also wrote a square matrix *b* of size *n*<=Γ—<=*n*. The element of matrix *b* that sits in the *i*-th row in the *j*-th column (we'll denote it as *b**ij*) equals: - the "bitwise AND" of numbers *a**i* and *a**j* (that is, *b**ij*<==<=*a**i*Β &amp;Β *a**j*), if *i*<=β‰ <=*j*; - -1, if *i*<==<=*j*. Having written out matrix *b*, Polycarpus got very happy and wiped *a* off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly. Help Polycarpus, given matrix *b*, restore the sequence of numbers *a*1,<=*a*2,<=...,<=*a**n*, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=100) β€” the size of square matrix *b*. Next *n* lines contain matrix *b*. The *i*-th of these lines contains *n* space-separated integers: the *j*-th number represents the element of matrix *b**ij*. It is guaranteed, that for all *i* (1<=≀<=*i*<=≀<=*n*) the following condition fulfills: *b**ii* = -1. It is guaranteed that for all *i*,<=*j* (1<=≀<=*i*,<=*j*<=≀<=*n*;Β *i*<=β‰ <=*j*) the following condition fulfills: 0<=≀<=*b**ij*<=≀<=109, *b**ij*<==<=*b**ji*. Output Specification: Print *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109) β€” the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces. It is guaranteed that there is sequence *a* that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them. Demo Input: ['1\n-1\n', '3\n-1 18 0\n18 -1 0\n0 0 -1\n', '4\n-1 128 128 128\n128 -1 148 160\n128 148 -1 128\n128 160 128 -1\n'] Demo Output: ['0 ', '18 18 0 ', '128 180 148 160 '] Note: If you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation.
1,275
Title: Inna and Nine Time Limit: None seconds Memory Limit: None megabytes Problem Description: Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number *a*, consisting of digits from 1 to 9. Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9. For instance, Inna can alter number 14545181 like this: 14545181<=β†’<=1945181<=β†’<=194519<=β†’<=19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine. Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task. Input Specification: The first line of the input contains integer *a* (1<=≀<=*a*<=≀<=10100000). Number *a* doesn't have any zeroes. Output Specification: In a single line print a single integer β€” the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263<=-<=1. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['369727\n', '123456789987654321\n', '1\n'] Demo Output: ['2\n', '1\n', '1\n'] Note: Notes to the samples In the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979. In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.
1,276
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer *m*, bit depth of the game, which means that all numbers in the game will consist of *m* bits. Then he asks Peter to choose some *m*-bit number. After that, Bob computes the values of *n* variables. Each variable is assigned either a constant *m*-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. Input Specification: The first line contains two integers *n* and *m*, the number of variables and bit depth, respectively (1<=≀<=*n*<=≀<=5000; 1<=≀<=*m*<=≀<=1000). The following *n* lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: 1. Binary number of exactly *m* bits. 1. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. Output Specification: In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as *m*-bit binary numbers. Demo Input: ['3 3\na := 101\nb := 011\nc := ? XOR b\n', '5 1\na := 1\nbb := 0\ncx := ? OR a\nd := ? XOR ?\ne := d AND bb\n'] Demo Output: ['011\n100\n', '0\n0\n'] Note: In the first sample if Peter chooses a number 011<sub class="lower-index">2</sub>, then *a* = 101<sub class="lower-index">2</sub>, *b* = 011<sub class="lower-index">2</sub>, *c* = 000<sub class="lower-index">2</sub>, the sum of their values is 8. If he chooses the number 100<sub class="lower-index">2</sub>, then *a* = 101<sub class="lower-index">2</sub>, *b* = 011<sub class="lower-index">2</sub>, *c* = 111<sub class="lower-index">2</sub>, the sum of their values is 15. For the second test, the minimum and maximum sum of variables *a*, *bb*, *cx*, *d* and *e* is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.
1,277
Title: New Year Present Time Limit: None seconds Memory Limit: None megabytes Problem Description: The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put *n* empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put *a**i* coins to the *i*-th wallet from the left. Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row. Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him. Input Specification: The first line contains integer *n* (2<=≀<=*n*<=≀<=300) β€” the number of wallets. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=300). It is guaranteed that at least one *a**i* is positive. Output Specification: Print the sequence that consists of *k* (1<=≀<=*k*<=≀<=106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet *n*. As a result of the performed operations, the *i*-th wallet from the left must contain exactly *a**i* coins. If there are multiple answers, you can print any of them. Demo Input: ['2\n1 2\n', '4\n0 2 0 2\n'] Demo Output: ['PRPLRP', 'RPRRPLLPLRRRP'] Note: none
1,278
Title: Wonderful Randomized Sum Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Learn, learn and learn again β€” Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of *n* numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by <=-<=1. The second operation is to take some suffix and multiply all numbers in it by <=-<=1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations? Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105) β€” amount of elements in the sequence. The second line contains *n* integers *a**i* (<=-<=104<=≀<=*a**i*<=≀<=104) β€” the sequence itself. Output Specification: The first and the only line of the output should contain the answer to the problem. Demo Input: ['3\n-1 -2 -3\n', '5\n-4 2 0 5 0\n', '5\n-1 10 -5 10 -2\n'] Demo Output: ['6\n', '11\n', '18\n'] Note: none
1,279
Title: Boxes Packing Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mishka has got *n* empty boxes. For every *i* (1<=≀<=*i*<=≀<=*n*), *i*-th box is a cube with side length *a**i*. Mishka can put a box *i* into another box *j* if the following conditions are met: - *i*-th box is not put into another box; - *j*-th box doesn't contain any other boxes; - box *i* is smaller than box *j* (*a**i*<=&lt;<=*a**j*). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box. Help Mishka to determine the minimum possible number of visible boxes! Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=5000) β€” the number of boxes Mishka has got. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≀<=*a**i*<=≀<=109), where *a**i* is the side length of *i*-th box. Output Specification: Print the minimum possible number of visible boxes. Demo Input: ['3\n1 2 3\n', '4\n4 2 4 3\n'] Demo Output: ['1\n', '2\n'] Note: In the first example it is possible to put box 1 into box 2, and 2 into 3. In the second example Mishka can put box 2 into box 3, and box 4 into box 1.
1,280
Title: Run For Your Prize Time Limit: None seconds Memory Limit: None megabytes Problem Description: You and your friend are participating in a TV show "Run For Your Prize". At the start of the show *n* prizes are located on a straight line. *i*-th prize is located at position *a**i*. Positions of all prizes are distinct. You start at position 1, your friend β€” at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order. You know that it takes exactly 1 second to move from position *x* to position *x*<=+<=1 or *x*<=-<=1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all. Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend. What is the minimum number of seconds it will take to pick up all the prizes? Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of prizes. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (2<=≀<=*a**i*<=≀<=106<=-<=1) β€” the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order. Output Specification: Print one integer β€” the minimum number of seconds it will take to collect all prizes. Demo Input: ['3\n2 3 9\n', '2\n2 999995\n'] Demo Output: ['8\n', '5\n'] Note: In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8. In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.
1,281
Title: Word Cut Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word *w*, let's split this word into two non-empty parts *x* and *y* so, that *w*<==<=*xy*. A split operation is transforming word *w*<==<=*xy* into word *u*<==<=*yx*. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words *start* and *end*. Count in how many ways we can transform word *start* into word *end*, if we apply exactly *k* split operations consecutively to word *start*. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number *i* (1<=≀<=*i*<=≀<=*k*), that in the *i*-th operation of the first sequence the word splits into parts *x* and *y*, in the *i*-th operation of the second sequence the word splits into parts *a* and *b*, and additionally *x*<=β‰ <=*a* holds. Input Specification: The first line contains a non-empty word *start*, the second line contains a non-empty word *end*. The words consist of lowercase Latin letters. The number of letters in word *start* equals the number of letters in word *end* and is at least 2 and doesn't exceed 1000 letters. The third line contains integer *k* (0<=≀<=*k*<=≀<=105) β€” the required number of operations. Output Specification: Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109<=+<=7). Demo Input: ['ab\nab\n2\n', 'ababab\nababab\n1\n', 'ab\nba\n2\n'] Demo Output: ['1\n', '2\n', '0\n'] Note: The sought way in the first sample is: ab  →  a|b  →  ba  →  b|a  →  ab In the second sample the two sought ways are: - ababab  →  abab|ab  →  ababab - ababab  →  ab|abab  →  ababab
1,282
Title: List Of Integers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's denote as *L*(*x*,<=*p*) an infinite sequence of integers *y* such that *gcd*(*p*,<=*y*)<==<=1 and *y*<=&gt;<=*x* (where *gcd* is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of *L*(*x*,<=*p*) are 1-indexed; for example, 9, 13 and 15 are the first, the second and the third elements of *L*(7,<=22), respectively. You have to process *t* queries. Each query is denoted by three integers *x*, *p* and *k*, and the answer to this query is *k*-th element of *L*(*x*,<=*p*). Input Specification: The first line contains one integer *t* (1<=≀<=*t*<=≀<=30000) β€” the number of queries to process. Then *t* lines follow. *i*-th line contains three integers *x*, *p* and *k* for *i*-th query (1<=≀<=*x*,<=*p*,<=*k*<=≀<=106). Output Specification: Print *t* integers, where *i*-th integer is the answer to *i*-th query. Demo Input: ['3\n7 22 1\n7 22 2\n7 22 3\n', '5\n42 42 42\n43 43 43\n44 44 44\n45 45 45\n46 46 46\n'] Demo Output: ['9\n13\n15\n', '187\n87\n139\n128\n141\n'] Note: none
1,283
Title: Candies Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Iahub is playing an uncommon game. Initially, he has *n* boxes, numbered 1, 2, 3, ..., *n*. Each box has some number of candies in it, described by a sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents the number of candies in box *k*. The goal of the game is to move all candies into exactly two boxes. The rest of *n*<=-<=2 boxes must contain zero candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes *i* and *j*, such that *a**i*<=≀<=*a**j*. Then, Iahub moves from box *j* to box *i* exactly *a**i* candies. Obviously, when two boxes have equal number of candies, box number *j* becomes empty. Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves. Input Specification: The first line of the input contains integer *n* (3<=≀<=*n*<=≀<=1000). The next line contains *n* non-negative integers: *a*1,<=*a*2,<=...,<=*a**n* β€” sequence elements. It is guaranteed that sum of all numbers in sequence *a* is up to 106. Output Specification: In case there exists no solution, output -1. Otherwise, in the first line output integer *c* (0<=≀<=*c*<=≀<=106), representing number of moves in your solution. Each of the next *c* lines should contain two integers *i* and *j* (1<=≀<=*i*,<=*j*<=≀<=*n*,<=*i*<=β‰ <=*j*): integers *i*, *j* in the *k*th line mean that at the *k*-th move you will move candies from the *j*-th box to the *i*-th one. Demo Input: ['3\n3 6 9\n', '3\n0 1 0\n', '4\n0 1 1 0\n'] Demo Output: ['2\n2 3\n1 3\n', '-1', '0\n'] Note: For the first sample, after the first move the boxes will contain 3, 12 and 3 candies. After the second move, the boxes will contain 6, 12 and 0 candies. Now all candies are in exactly 2 boxes. For the second sample, you can observe that the given configuration is not valid, as all candies are in a single box and they should be in two boxes. Also, any move won't change the configuration, so there exists no solution. For the third sample, all candies are already in 2 boxes. Hence, no move is needed.
1,284
Title: Arpa and an exam about geometry Time Limit: None seconds Memory Limit: None megabytes Problem Description: Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points *a*,<=*b*,<=*c*. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of *a* is the same as the old position of *b*, and the new position of *b* is the same as the old position of *c*. Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not. Input Specification: The only line contains six integers *a**x*,<=*a**y*,<=*b**x*,<=*b**y*,<=*c**x*,<=*c**y* (|*a**x*|,<=|*a**y*|,<=|*b**x*|,<=|*b**y*|,<=|*c**x*|,<=|*c**y*|<=≀<=109). It's guaranteed that the points are distinct. Output Specification: Print "Yes" if the problem has a solution, "No" otherwise. You can print each letter in any case (upper or lower). Demo Input: ['0 1 1 1 1 0\n', '1 1 0 0 1000 1000\n'] Demo Output: ['Yes\n', 'No\n'] Note: In the first sample test, rotate the page around (0.5, 0.5) by <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9d845923f4d356a48d8ede337db0303821311f0c.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample test, you can't find any solution.
1,285
Title: Third Month Insanity Time Limit: None seconds Memory Limit: None megabytes Problem Description: The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2*N* teams participating in the tournament, numbered from 1 to 2*N*. The tournament lasts *N* rounds, with each round eliminating half the teams. The first round consists of 2*N*<=-<=1 games, numbered starting from 1. In game *i*, team 2Β·*i*<=-<=1 will play against team 2Β·*i*. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game *i* the winner of the previous round's game 2Β·*i*<=-<=1 will play against the winner of the previous round's game 2Β·*i*. Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2*N*<=-<=1 points. For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score. Input Specification: Input will begin with a line containing *N* (2<=≀<=*N*<=≀<=6). 2*N* lines follow, each with 2*N* integers. The *j*-th column of the *i*-th row indicates the percentage chance that team *i* will defeat team *j*, unless *i*<==<=*j*, in which case the value will be 0. It is guaranteed that the *i*-th column of the *j*-th row plus the *j*-th column of the *i*-th row will add to exactly 100. Output Specification: Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10<=-<=9. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer will be considered correct, if . Demo Input: ['2\n0 40 100 100\n60 0 40 40\n0 60 0 45\n0 60 55 0\n', '3\n0 0 100 0 100 0 0 0\n100 0 100 0 0 0 100 100\n0 0 0 100 100 0 0 0\n100 100 0 0 0 0 100 100\n0 100 0 100 0 0 100 0\n100 100 100 100 100 0 0 0\n100 0 100 0 0 100 0 0\n100 0 100 0 100 100 100 0\n', '2\n0 21 41 26\n79 0 97 33\n59 3 0 91\n74 67 9 0\n'] Demo Output: ['1.75\n', '12\n', '3.141592\n'] Note: In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
1,286
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's consider the following game. We have a rectangular field *n*<=Γ—<=*m* in size. Some squares of the field contain chips. Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right. The player may choose a chip and make a move with it. The move is the following sequence of actions. The chosen chip is marked as the current one. After that the player checks whether there are more chips in the same row (or in the same column) with the current one that are pointed by the arrow on the current chip. If there is at least one chip then the closest of them is marked as the new current chip and the former current chip is removed from the field. After that the check is repeated. This process can be repeated several times. If a new chip is not found, then the current chip is removed from the field and the player's move ends. By the end of a move the player receives several points equal to the number of the deleted chips. By the given initial chip arrangement determine the maximum number of points that a player can receive during one move. Also determine the number of such moves. Input Specification: The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*,<=*n*<=Γ—<=*m*<=≀<=5000). Then follow *n* lines containing *m* characters each β€” that is the game field description. "." means that this square is empty. "L", "R", "U", "D" mean that this square contains a chip and an arrow on it says left, right, up or down correspondingly. It is guaranteed that a field has at least one chip. Output Specification: Print two numbers β€” the maximal number of points a player can get after a move and the number of moves that allow receiving this maximum number of points. Demo Input: ['4 4\nDRLD\nU.UL\n.UUR\nRDDL\n', '3 5\n.D...\nRRRLL\n.U...\n'] Demo Output: ['10 1', '6 2'] Note: In the first sample the maximum number of points is earned by the chip in the position (3, 3). You can see its progress at the following picture: All other chips earn fewer points.
1,287
Title: Businessmen Problems Time Limit: None seconds Memory Limit: None megabytes Problem Description: Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies. All elements are enumerated with integers. The ChemForces company has discovered $n$ distinct chemical elements with indices $a_1, a_2, \ldots, a_n$, and will get an income of $x_i$ Berland rubles if the $i$-th element from this list is in the set of this company. The TopChemist company discovered $m$ distinct chemical elements with indices $b_1, b_2, \ldots, b_m$, and it will get an income of $y_j$ Berland rubles for including the $j$-th element from this list to its set. In other words, the first company can present any subset of elements from $\{a_1, a_2, \ldots, a_n\}$ (possibly empty subset), the second company can present any subset of elements from $\{b_1, b_2, \ldots, b_m\}$ (possibly empty subset). There shouldn't be equal elements in the subsets. Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible. Input Specification: The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) Β β€” the number of elements discovered by ChemForces. The $i$-th of the next $n$ lines contains two integers $a_i$ and $x_i$ ($1 \leq a_i \leq 10^9$, $1 \leq x_i \leq 10^9$) Β β€” the index of the $i$-th element and the income of its usage on the exhibition. It is guaranteed that all $a_i$ are distinct. The next line contains a single integer $m$ ($1 \leq m \leq 10^5$) Β β€” the number of chemicals invented by TopChemist. The $j$-th of the next $m$ lines contains two integers $b_j$ and $y_j$, ($1 \leq b_j \leq 10^9$, $1 \leq y_j \leq 10^9$) Β β€” the index of the $j$-th element and the income of its usage on the exhibition. It is guaranteed that all $b_j$ are distinct. Output Specification: Print the maximum total income you can obtain by choosing the sets for both companies in such a way that no element is presented in both sets. Demo Input: ['3\n1 2\n7 2\n3 10\n4\n1 4\n2 4\n3 4\n4 4\n', '1\n1000000000 239\n3\n14 15\n92 65\n35 89\n'] Demo Output: ['24\n', '408\n'] Note: In the first example ChemForces can choose the set ($3, 7$), while TopChemist can choose ($1, 2, 4$). This way the total income is $(10 + 2) + (4 + 4 + 4) = 24$. In the second example ChemForces can choose the only element $10^9$, while TopChemist can choose ($14, 92, 35$). This way the total income is $(239) + (15 + 65 + 89) = 408$.
1,288
Title: Basketball Team Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of *n* players, all of which are GUC students. However, the team might have players belonging to different departments. There are *m* departments in GUC, numbered from 1 to *m*. Herr Wafa's department has number *h*. For each department *i*, Herr Wafa knows number *s**i* β€” how many students who play basketball belong to this department. Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other. Input Specification: The first line contains three integers *n*, *m* and *h* (1<=≀<=*n*<=≀<=100,<=1<=≀<=*m*<=≀<=1000,<=1<=≀<=*h*<=≀<=*m*) β€” the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly. The second line contains a single-space-separated list of *m* integers *s**i* (1<=≀<=*s**i*<=≀<=100), denoting the number of students in the *i*-th department. Note that *s**h* includes Herr Wafa. Output Specification: Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10<=-<=6. Demo Input: ['3 2 1\n2 1\n', '3 2 1\n1 1\n', '3 2 1\n2 2\n'] Demo Output: ['1\n', '-1\n', '0.666667\n'] Note: In the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department. In the second example, there are not enough players. In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team.
1,289
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an integer *m*, and a list of *n* distinct integers between 0 and *m*<=-<=1. You would like to construct a sequence satisfying the properties: - Each element is an integer between 0 and *m*<=-<=1, inclusive. - All prefix products of the sequence modulo *m* are distinct. - No prefix product modulo *m* appears as an element of the input list. - The length of the sequence is maximized. Construct any sequence satisfying the properties above. Input Specification: The first line of input contains two integers *n* and *m* (0<=≀<=*n*<=&lt;<=*m*<=≀<=200<=000)Β β€” the number of forbidden prefix products and the modulus. If *n* is non-zero, the next line of input contains *n* distinct integers between 0 and *m*<=-<=1, the forbidden prefix products. If *n* is zero, this line doesn't exist. Output Specification: On the first line, print the number *k*, denoting the length of your sequence. On the second line, print *k* space separated integers, denoting your sequence. Demo Input: ['0 5\n', '3 10\n2 9 1\n'] Demo Output: ['5\n1 2 4 3 0\n', '6\n3 9 2 9 8 0\n'] Note: For the first case, the prefix products of this sequence modulo *m* are [1, 2, 3, 4, 0]. For the second case, the prefix products of this sequence modulo *m* are [3, 7, 4, 6, 8, 0].
1,290
Title: Mice problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them. The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (*x*1,<=*y*1) and (*x*2,<=*y*2). Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the *i*-th mouse is equal to (*v**i**x*,<=*v**i**y*), that means that the *x* coordinate of the mouse increases by *v**i**x* units per second, while the *y* coordinates increases by *v**i**y* units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap. Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of computer mice on the desk. The second line contains four integers *x*1, *y*1, *x*2 and *y*2 (0<=≀<=*x*1<=≀<=*x*2<=≀<=100<=000), (0<=≀<=*y*1<=≀<=*y*2<=≀<=100<=000)Β β€” the coordinates of the opposite corners of the mousetrap. The next *n* lines contain the information about mice. The *i*-th of these lines contains four integers *r**i**x*, *r**i**y*, *v**i**x* and *v**i**y*, (0<=≀<=*r**i**x*,<=*r**i**y*<=≀<=100<=000, <=-<=100<=000<=≀<=*v**i**x*,<=*v**i**y*<=≀<=100<=000), where (*r**i**x*,<=*r**i**y*) is the initial position of the mouse, and (*v**i**x*,<=*v**i**y*) is its speed. Output Specification: In the only line print minimum possible non-negative number *t* such that if Igor closes the mousetrap at *t* seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such *t*, print -1. Your answer is considered correct if its absolute or relative error doesn't exceed 10<=-<=6. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if . Demo Input: ['4\n7 7 9 8\n3 5 7 5\n7 5 2 4\n3 3 7 8\n6 6 3 2\n', '4\n7 7 9 8\n0 3 -5 4\n5 0 5 4\n9 9 -1 -6\n10 5 -7 -10\n'] Demo Output: ['0.57142857142857139685\n', '-1\n'] Note: Here is a picture of the first sample Points A, B, C, D - start mice positions, segments are their paths. <img class="tex-graphics" src="https://espresso.codeforces.com/9b2a39ff850b63eb3f41de7ce9efc61a192e99b5.png" style="max-width: 100.0%;max-height: 100.0%;"/> Then, at first time when all mice will be in rectangle it will be looks like this: <img class="tex-graphics" src="https://espresso.codeforces.com/bfdaed392636d2b1790e7986ca711c1c3ebe298c.png" style="max-width: 100.0%;max-height: 100.0%;"/> Here is a picture of the second sample <img class="tex-graphics" src="https://espresso.codeforces.com/a49c381e9f3e453fe5be91a972128def69042e45.png" style="max-width: 100.0%;max-height: 100.0%;"/> Points A, D, B will never enter rectangle.
1,291
Title: Gotta Go Fast Time Limit: None seconds Memory Limit: None megabytes Problem Description: You're trying to set the record on your favorite video game. The game consists of *N* levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the *i*-th level in either *F**i* seconds or *S**i* seconds, where *F**i*<=&lt;<=*S**i*, and there's a *P**i* percent chance of completing it in *F**i* seconds. After completing a level, you may decide to either continue the game and play the next level, or reset the game and start again from the first level. Both the decision and the action are instant. Your goal is to complete all the levels sequentially in at most *R* total seconds. You want to minimize the expected amount of time playing before achieving that goal. If you continue and reset optimally, how much total time can you expect to spend playing? Input Specification: The first line of input contains integers *N* and *R* , the number of levels and number of seconds you want to complete the game in, respectively. *N* lines follow. The *i*th such line contains integers *F**i*,<=*S**i*,<=*P**i* (1<=≀<=*F**i*<=&lt;<=*S**i*<=≀<=100,<=80<=≀<=*P**i*<=≀<=99), the fast time for level *i*, the slow time for level *i*, and the probability (as a percentage) of completing level *i* with the fast time. Output Specification: Print the total expected time. Your answer must be correct within an absolute or relative error of 10<=-<=9. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer will be considered correct, if . Demo Input: ['1 8\n2 8 81\n', '2 30\n20 30 80\n3 9 85\n', '4 319\n63 79 89\n79 97 91\n75 87 88\n75 90 83\n'] Demo Output: ['3.14\n', '31.4\n', '314.159265358\n'] Note: In the first example, you never need to reset. There's an 81% chance of completing the level in 2 seconds and a 19% chance of needing 8 seconds, both of which are within the goal time. The expected time is 0.81Β·2 + 0.19Β·8 = 3.14. In the second example, you should reset after the first level if you complete it slowly. On average it will take 0.25 slow attempts before your first fast attempt. Then it doesn't matter whether you complete the second level fast or slow. The expected time is 0.25Β·30 + 20 + 0.85Β·3 + 0.15Β·9 = 31.4.
1,292
Title: Points and Segments (easy) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw *n* distinct points and *m* segments on the *OX* axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment [*l**i*,<=*r**i*] consider all the red points belong to it (*r**i* points), and all the blue points belong to it (*b**i* points); each segment *i* should satisfy the inequality |*r**i*<=-<=*b**i*|<=≀<=1. Iahub thinks that point *x* belongs to segment [*l*,<=*r*], if inequality *l*<=≀<=*x*<=≀<=*r* holds. Iahub gives to you all coordinates of points and segments. Please, help him to find any good drawing. Input Specification: The first line of input contains two integers: *n* (1<=≀<=*n*<=≀<=100) and *m* (1<=≀<=*m*<=≀<=100). The next line contains *n* space-separated integers *x*1,<=*x*2,<=...,<=*x**n* (0<=≀<=*x**i*<=≀<=100) β€” the coordinates of the points. The following *m* lines contain the descriptions of the *m* segments. Each line contains two integers *l**i* and *r**i* (0<=≀<=*l**i*<=≀<=*r**i*<=≀<=100) β€” the borders of the *i*-th segment. It's guaranteed that all the points are distinct. Output Specification: If there is no good drawing for a given test, output a single integer -1. Otherwise output *n* integers, each integer must be 0 or 1. The *i*-th number denotes the color of the *i*-th point (0 is red, and 1 is blue). If there are multiple good drawings you can output any of them. Demo Input: ['3 3\n3 7 14\n1 5\n6 10\n11 15\n', '3 4\n1 2 3\n1 2\n2 3\n5 6\n2 2\n'] Demo Output: ['0 0 0', '1 0 1 '] Note: none
1,293
Title: Jabber ID Time Limit: 0 seconds Memory Limit: 256 megabytes Problem Description: Jabber ID on the national Berland service Β«BabberΒ» has a form &lt;username&gt;@&lt;hostname&gt;[/resource], where - &lt;username&gt; β€” is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of &lt;username&gt; is between 1 and 16, inclusive. - &lt;hostname&gt; β€” is a sequence of word separated by periods (characters Β«.Β»), where each word should contain only characters allowed for &lt;username&gt;, the length of each word is between 1 and 16, inclusive. The length of &lt;hostname&gt; is between 1 and 32, inclusive. - &lt;resource&gt; β€” is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters Β«_Β», the length of &lt;resource&gt; is between 1 and 16, inclusive. The content of square brackets is optional β€” it can be present or can be absent. There are the samples of correct Jabber IDs: [[emailΒ protected]](/cdn-cgi/l/email-protection), [[emailΒ protected]](/cdn-cgi/l/email-protection)/contest. Your task is to write program which checks if given string is a correct Jabber ID. Input Specification: The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive. Output Specification: Print YES or NO. Demo Input: ['[email\xa0protected]\n', '[email\xa0protected]/contest.icpc/12\n'] Demo Output: ['YES\n', 'NO\n'] Note: none
1,294
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya has *n* items lying in a line. The items are consecutively numbered by numbers from 1 to *n* in such a way that the leftmost item has number 1, the rightmost item has number *n*. Each item has a weight, the *i*-th item weights *w**i* kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms β€” the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend *w**i*<=Β·<=*l* energy units (*w**i* is a weight of the leftmost item, *l* is some parameter). If the previous action was the same (left-hand), then the robot spends extra *Q**l* energy units; 1. Take the rightmost item with the right hand and spend *w**j*<=Β·<=*r* energy units (*w**j* is a weight of the rightmost item, *r* is some parameter). If the previous action was the same (right-hand), then the robot spends extra *Q**r* energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input Specification: The first line contains five integers *n*,<=*l*,<=*r*,<=*Q**l*,<=*Q**r* (1<=≀<=*n*<=≀<=105;<=1<=≀<=*l*,<=*r*<=≀<=100;<=1<=≀<=*Q**l*,<=*Q**r*<=≀<=104). The second line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (1<=≀<=*w**i*<=≀<=100). Output Specification: In the single line print a single number β€” the answer to the problem. Demo Input: ['3 4 4 19 1\n42 3 99\n', '4 7 2 3 9\n1 2 3 4\n'] Demo Output: ['576\n', '34\n'] Note: Consider the first sample. As *l* = *r*, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4Β·42 + 4Β·99 + 4Β·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2Β·4) + (7Β·1) + (2Β·3) + (2Β·2 + 9) = 34 energy units.
1,295
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are *n* kinds of beer at Rico's numbered from 1 to *n*. *i*-th kind of beer has *a**i* milliliters of foam on it. Maxim is Mike's boss. Today he told Mike to perform *q* queries. Initially the shelf is empty. In each request, Maxim gives him a number *x*. If beer number *x* is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf. After each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs (*i*,<=*j*) of glasses in the shelf such that *i*<=&lt;<=*j* and where is the greatest common divisor of numbers *a* and *b*. Mike is tired. So he asked you to help him in performing these requests. Input Specification: The first line of input contains numbers *n* and *q* (1<=≀<=*n*,<=*q*<=≀<=2<=Γ—<=105), the number of different kinds of beer and number of queries. The next line contains *n* space separated integers, *a*1,<=*a*2,<=... ,<=*a**n* (1<=≀<=*a**i*<=≀<=5<=Γ—<=105), the height of foam in top of each kind of beer. The next *q* lines contain the queries. Each query consists of a single integer integer *x* (1<=≀<=*x*<=≀<=*n*), the index of a beer that should be added or removed from the shelf. Output Specification: For each query, print the answer for that query in one line. Demo Input: ['5 6\n1 2 3 4 6\n1\n2\n3\n4\n5\n1\n'] Demo Output: ['0\n1\n3\n5\n6\n2\n'] Note: none
1,296
Title: Crash Time Limit: None seconds Memory Limit: None megabytes Problem Description: During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check. Each participant is identified by some unique positive integer *k*, and each sent solution *A* is characterized by two numbers: *x*Β β€” the number of different solutions that are sent before the first solution identical to *A*, and *k* β€” the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same *x*. It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number *x* (*x*<=&gt;<=0) of the participant with number *k*, then the testing system has a solution with number *x*<=-<=1 of the same participant stored somewhere before. During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so. Input Specification: The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=105)Β β€” the number of solutions. Each of the following *n* lines contains two integers separated by space *x* and *k* (0<=≀<=*x*<=≀<=105; 1<=≀<=*k*<=≀<=105)Β β€” the number of previous unique solutions and the identifier of the participant. Output Specification: A single line of the output should contain Β«YESΒ» if the data is in chronological order, and Β«NOΒ» otherwise. Demo Input: ['2\n0 1\n1 1\n', '4\n0 1\n1 2\n1 1\n0 2\n', '4\n0 1\n1 1\n0 1\n0 2\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n'] Note: none
1,297
Title: Exploration plan Time Limit: None seconds Memory Limit: None megabytes Problem Description: The competitors of Bubble Cup X gathered after the competition and discussed what is the best way to get to know the host country and its cities. After exploring the map of Serbia for a while, the competitors came up with the following facts: the country has *V* cities which are indexed with numbers from 1 to *V*, and there are *E* bi-directional roads that connect the cites. Each road has a weight (the time needed to cross that road). There are *N* teams at the Bubble Cup and the competitors came up with the following plan: each of the *N* teams will start their journey in one of the *V* cities, and some of the teams share the starting position. They want to find the shortest time *T*, such that every team can move in these *T* minutes, and the number of different cities they end up in is at least *K* (because they will only get to know the cities they end up in). A team doesn't have to be on the move all the time, if they like it in a particular city, they can stay there and wait for the time to pass. Please help the competitors to determine the shortest time *T* so it's possible for them to end up in at least *K* different cities or print -1 if that is impossible no matter how they move. Note that there can exist multiple roads between some cities. Input Specification: The first line contains four integers: *V*, *E*, *N* and *K* (1<=≀<=<=*V*<=<=≀<=<=600,<= 1<=<=≀<=<=*E*<=<=≀<=<=20000,<= 1<=<=≀<=<=*N*<=<=≀<=<=*min*(*V*,<=200),<= 1<=<=≀<=<=*K*<=<=≀<=<=*N*), number of cities, number of roads, number of teams and the smallest number of different cities they need to end up in, respectively. The second line contains *N* integers, the cities where the teams start their journey. Next *E* lines contain information about the roads in following format: *A**i* *B**i* *T**i* (1<=≀<=*A**i*,<=*B**i*<=≀<=*V*,<= 1<=≀<=*T**i*<=≀<=10000), which means that there is a road connecting cities *A**i* and *B**i*, and you need *T**i* minutes to cross that road. Output Specification: Output a single integer that represents the minimal time the teams can move for, such that they end up in at least *K* different cities or output -1 if there is no solution. If the solution exists, result will be no greater than 1731311. Demo Input: ['6 7 5 4\n5 5 2 2 5\n1 3 3\n1 5 2\n1 6 5\n2 5 4\n2 6 7\n3 4 11\n3 5 3\n'] Demo Output: ['3'] Note: Three teams start from city 5, and two teams start from city 2. If they agree to move for 3 minutes, one possible situation would be the following: Two teams in city 2, one team in city 5, one team in city 3 , and one team in city 1. And we see that there are four different cities the teams end their journey at.
1,298
Title: Strongly Connected Tournament Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is a chess tournament in All-Right-City. *n* players were invited to take part in the competition. The tournament is held by the following rules: 1. Initially, each player plays one game with every other player. There are no ties; 1. After that, the organizers build a complete directed graph with players as vertices. For every pair of players there is exactly one directed edge between them: the winner of their game is the startpoint of this edge and the loser is the endpoint; 1. After that, the organizers build a condensation of this graph. The condensation of this graph is an acyclic complete graph, therefore it has the only Hamiltonian path which consists of strongly connected components of initial graph *A*1<=β†’<=*A*2<=β†’<=...<=β†’<=*A**k*. 1. The players from the first component *A*1 are placed on the first places, the players from the component *A*2 are placed on the next places, and so on. 1. To determine exact place of each player in a strongly connected component, all the procedures from 1 to 5 are repeated recursively inside each component, i.e. for every *i*<==<=1,<=2,<=...,<=*k* players from the component *A**i* play games with each other again, and so on; 1. If a component consists of a single player, then he has no more rivals, his place is already determined and the process stops. The players are enumerated with integers from 1 to *n*. The enumeration was made using results of a previous tournament. It is known that player *i* wins player *j* (*i*<=&lt;<=*j*) with probability *p*. You need to help to organize the tournament. Find the expected value of total number of games played by all the players. It can be shown that the answer can be represented as , where *P* and *Q* are coprime integers and . Print the value of *P*Β·*Q*<=-<=1 modulo 998244353. If you are not familiar with any of the terms above, you can read about them [here](https://en.wikipedia.org/wiki/Strongly_connected_component). Input Specification: The first line of input contains a single integer *n* (2<=≀<=*n*<=≀<=2000)Β β€” the number of players. The second line contains two integers *a* and *b* (1<=≀<=*a*<=&lt;<=*b*<=≀<=100)Β β€” the numerator and the denominator of fraction . Output Specification: In the only line print the expected value of total number of games played by all the players. Print the answer using the format above. Demo Input: ['3\n1 2\n', '3\n4 6\n', '4\n1 2\n'] Demo Output: ['4\n', '142606340\n', '598946623\n'] Note: In the first example the expected value is 4. In the second example the expected value is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/24bad8c170d1a2f751a54ab5a1ba5ce8bea4e73a.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the third example the expected value is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ea8cfdc5095bcc8748d50693206eb4f960a9117a.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
1,299